def reconnect(self): """ reconnect """ log.info("reconnect...") info = "" if self._lock.locked() == False: #self.reconnecting = 1 self._lock.acquire() try: #self.opc = OpenOPC.open_client(self.host, self.port) #self.opc.connect(self.provider, self.host) if self.mode == 'dcom': self.opc = OpenOPC.client("Graybox.OPC.DAWrapper", self.host) else: self.opc = OpenOPC.open_client(self.host, self.port) info = self.opc.servers() info = info + self.opc.info() for group in self.groups: self.create_group(group, self.groups[group]) #self.reconnecting = 0 except Exception, e: # release the lock info = "excetp: %s"%(e.message) log.error(info) log.error(traceback.format_exc()) #self.reconnecting = 0 finally:
def connect(self): """ connect """ self._lock.acquire() self._lock.release() try: #print self.host #print self.opc_host #print self.opc_server #self.opc = OpenOPC.open_client(self.host, self.port) if self.mode == 'dcom': self.opc = OpenOPC.client("Graybox.OPC.DAWrapper", self.host) else: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.opc_server, self.opc_host) info = self.opc.servers() print info except OPCError, oe: log.debug(str(oe)) raise Exception(oe.message)
def connect(): global opc global list opc = None list = None if debug: print "Connecting..." r.set("connected", "BAD") while list is None: try: if debug: print "Connection Attempt {" opc = OpenOPC.open_client(opc_server) opc.connect(opc_server_name, opc_server) list = opc.list('Brave.calendar.opc_group') if debug: print "}" r.set("connected", "OK") r.set("opc_server", plc) r.set("opc_server_name", opc_server_name) r.set("plc", plc) r.set("redis_server", redis_server) except Exception as e: if debug: print e try: ping(opc_server, c=1) print {'error': 'Cannot connect to ' + opc_server_name, 'val': 0} except Exception as e: if debug: print e print {'error': 'Cannot connect to network', 'val': 0} pass pass finally: time.sleep(poll_rate)
def device_connect(job_data): """Connect the device to OPC server.""" try: global connection if connection: logger.warn("connection exists, closing it...") connection = None logger.warn("connection closed done.") # Connection retries for i in range(CONNECTION_RETRY): try: connection = OpenOPC.open_client( host=job_data["job"]["machine-details"] ["connectivity-parameters"]["machine-ip"]) connection.connect( opc_server=job_data["job"]["machine-details"] ["connectivity-parameters"]["opcda-server-name"]) break except: if i == CONNECTION_RETRY - 1: raise logger.error( "Connection failed to %s, retry to connect...", job_data["job"]["machine-details"] ["connectivity-parameters"]["machine-ip"]) time.sleep(i + 1) except Exception as err: logger.error("Connection failed. Error: %s", str(err)) raise Exception(msg.ERR_MSG_FAIL_TO_CONNECT)
def do_read(self): logger.info('Doing read') try: if not self.pyro_connected: self.opc = OpenOPC.open_client(self.pyro_host, self.pyro_port) self.opc.connect(self.opc_server, self.opc_host) self.pyro_connected = True self.com_connected = True if not self.com_connected: self.opc.connect(self.opc_server, self.opc_host) self.com_connected = True self.success = True data = self.opc.read(self.items.keys(), group='opcdmn', size=self.group_size, pause=self.tx_pause, source=self.data_source, update=self.update_rate, timeout=self.timeout, sync=self.sync, include_error=True) for row in data: logger.debug(str(row)) self._update(row) except OpenOPC.TimeoutError, error_msg: logger.error(error_msg[0]) self.success = False
def connect(self): self._lock.acquire() self._lock.release() try: #print self.host #print self.opc_host #print self.opc_server #self.opc = OpenOPC.open_client(self.host, self.port) if self.mode == 'dcom': self.opc = OpenOPC.client("Graybox.OPC.DAWrapper", self.host) else: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.opc_server, self.opc_host) #info = self.opc.servers() #print info except OPCError, oe: log.debug( str(oe) ) raise Exception(oe.message)
def reconnect(self): """ reconnect """ log.info("reconnect...") info = "" if self._lock.locked() == False: #self.reconnecting = 1 self._lock.acquire() try: #self.opc = OpenOPC.open_client(self.host, self.port) #self.opc.connect(self.provider, self.host) if self.mode == 'dcom': self.opc = OpenOPC.client("Graybox.OPC.DAWrapper", self.host) else: self.opc = OpenOPC.open_client(self.host, self.port) info = self.opc.servers() info = info + self.opc.info() for group in self.groups: self.create_group(group, self.groups[group]) #self.reconnecting = 0 except Exception, e: # release the lock info = "excetp: %s" % (e.message) log.error(info) log.error(traceback.format_exc()) #self.reconnecting = 0 finally:
def colectInfo(self): self.log.Info(self.opcInfoList) while True: try: for i in range(len(self.opcInfoList)): opchost=self.opcInfoList[i]['opchost'] opcserver=self.opcInfoList[i]['opcserver'] ItemList=self.opcInfoList[i]['ItemList'] opc = OpenOPC.open_client(opchost) opc.connect(opcserver, opchost) for j in range(len(ItemList)): ItemList[j]['value'] = opc.read(ItemList[j]['Item']) self.opcInfoList[i]['ItemList'] = ItemList #存入日期 dateInfo=datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S') self.opcInfoList[i]['Date'] = dateInfo opc.close() self.log.Info(self.opcInfoList) #存入数据信息管理模块 self.sysTopInfo.setInfoByKey("opcInfoList", self.opcInfoList) except Exception, e: self.log.Info(traceback.print_exc()) self.log.Info(e) time.sleep(60)
def connect(self): print "attempting OPC connection to", self.opc_name self.opc = OpenOPC.open_client(host=self.opc_host) self.opc.connect(self.opc_name, self.opc_host) if self.points is None: pointlist = self.opc.list(recursive=True, flat=True) self.points = self.parse_pointlist(pointlist) props = self.opc.properties(self.points.keys()) print "loaded", len(props), "properties" points = {} for point, pid, key, val in props: key = key.decode().encode('ascii', 'ignore') key = key.replace(' ', '') if isinstance(val, unicode) or isinstance(val, str): val = val.encode('ascii', 'ignore') name = self.make_path(point) if not name in points: points[name] = self.points[point] if not exclude(key): points[name]['OpcDA/' + key] = str(val) # try to make some sense out of the metadata for name, meta in points.iteritems(): unit = str(meta.get('OpcDA/' + self.unit_tag, 'None')) dtype = meta.get('OpcDA/ItemCanonicalDataType', None) if not dtype: print "no datatype tag in", name continue dtype = 'double' if not self.get_timeseries(name): name = name.decode().encode('ascii', 'ignore') self.add_timeseries(name, unit, data_type=dtype) self.set_metadata(name, points[name]) vals = self.opc.read(self.points.keys(), group="smap-points-group") self.updater = task.LoopingCall(self.update).start(self.rate)
def connect(self): logger.debug("connect...............") try: if conf["Use_Wrapper"] == True: logger.debug(conf["DAWrapper"]) self.opc_client = OpenOPC.client(conf["DAWrapper"], conf["HOST"]) else: logger.debug(conf["PROVIDER"]) self.opc_client = OpenOPC.open_client(conf["HOST"], conf["PORT"]) self.opc_client.connect(conf["PROVIDER"], conf["OPC_HOST"]) self.connected = 1 except Exception as ex: logger.debug(ex) self.connected = 0
def connect(self): print "attempting OPC connection to", self.opc_name self.opc = OpenOPC.open_client(host=self.opc_host) self.opc.connect(self.opc_name, self.opc_host) if self.points is None: pointlist = self.opc.list(recursive=True, flat=True) self.points = self.parse_pointlist(pointlist) props = self.opc.properties(self.points.keys()) print "loaded", len(props), "properties" points = {} for point, pid, key, val in props: key = key.decode().encode('ascii','ignore') key = key.replace(' ','') if isinstance(val, unicode) or isinstance(val, str): val = val.encode('ascii','ignore') name = self.make_path(point) if not name in points: points[name] = self.points[point] if not exclude(key): points[name]['OpcDA/' + key] = str(val) # try to make some sense out of the metadata for name, meta in points.iteritems(): unit = str(meta.get('OpcDA/' + self.unit_tag, 'None')) dtype = meta.get('OpcDA/ItemCanonicalDataType', None) if not dtype: print "no datatype tag in", name continue dtype = 'double' if not self.get_timeseries(name): name = name.decode().encode('ascii','ignore') self.add_timeseries(name, unit, data_type=dtype) self.set_metadata(name, points[name]) vals = self.opc.read(self.points.keys(), group="smap-points-group") self.updater = task.LoopingCall(self.update).start(self.rate)
def OPCCommand(self): ''' You will also need to add the following to your config file: opc: server: 10.0.1.107 name: OPC SERVER NAME tags: ["OPC-SERVER.Brightness_1.Brightness", "OPC-SERVER.TAGNAME"] tagcounter: OPC-SERVER.tag_which_is_int_that_tells_frame_has_changed This also requires the server you are connecting to be running the OpenOPC gateway service. It comes bundled with OpenOPC. To get it to route over the network you also have to set the windows environment variable OPC_GATE_HOST to the actual of the IP address of the server it's running on instead of 'localhost' otherwise the interface doesn't bind and you won't be able to connect via linux. ''' try: import OpenOPC except: raise Exception('Requires OpenOPC plugin') from SimpleSeer.realtime import ChannelManager opc_settings = self.session.opc if opc_settings.has_key('name') and opc_settings.has_key('server'): self.log.info('Trying to connect to OPC Server[%s]...' % opc_settings['server']) try: opc_client = OpenOPC.open_client(opc_settings['server']) except: ex = 'Cannot connect to server %s, please verify it is up and running' % opc_settings['server'] raise Exception(ex) self.log.info('...Connected to server %s' % opc_settings['server']) self.log.info('Mapping OPC connection to server name: %s' % opc_settings['name']) opc_client.connect(opc_settings['name']) self.log.info('Server [%s] mapped' % opc_settings['name']) if opc_settings.has_key('tagcounter'): tagcounter = int(opc_client.read(opc_settings['tagcounter'])[0]) counter = tagcounter self.log.info('Polling OPC Server for triggers') while True: tagcounter = int(opc_client.read(opc_settings['tagcounter'])[0]) if tagcounter != counter: self.log.info('Trigger Received') data = dict() for tag in opc_settings.get('tags'): tagdata = opc_client.read(tag) if tagdata: self.log.info('Read tag[%s] with value: %s' % (tag, tagdata[0])) data[tag] = tagdata[0] self.log.info('Publishing data to PUB/SUB OPC channel') ChannelManager().publish('opc/', data) counter = tagcounter
def __init__(self,canNum,modNum,host=hostDefault,srvName=srvNameDefault): self.canNum = canNum self.modNum = modNum #connect to OPC Server self.opc = OpenOPC.open_client(host) self.opc.connect(srvName,host) time.sleep(waittimeDefault) assert self.opc.ping()
def open(self, *args, **kw): self.debug('opening OPC communicator') self.handle = OpenOPC.open_client(self.address) if self.handle is not None: self.handle.connect(self.server_name) self.simulation = False return True
def Connect(self, RemoteHost="dcspc", RemotePort=7766, OPCHost="epdt120", OPCServer="OPC20CanOpen+"): self.RemoteHost = RemoteHost self.RemotePort = RemotePort self.OPCHost = OPCHost self.OPCServer = OPCServer print "Connectining to OPC server " + self.OPCServer + " on " + self.RemoteHost self.OPC = OpenOPC.open_client(self.RemoteHost, self.RemotePort) self.OPC.connect(self.OPCServer, self.OPCHost) print "Connected\nWaiting for OPC server to read all values from devices ..." time.sleep(10)
def OPCconnect(): opc = OpenOPC.client() #opc = OpenOPC.open_client('localhost') opc = OpenOPC.open_client(wm_global.OpcClientName) opc.servers() # opc.connect('KEPware.KEPServerEx.V4') opc.connect(wm_global.OpcServerName) return opc
def device_connect(): global connection_handler, event job_name = event["job"]["properties"][0]["name"] job_version = event["job"]["properties"][0]["version"] try: connection_handler = OpenOPC.open_client(event["job"]["machine-details"]["connectivity-parameters"]["machine-ip"]) connection_handler.connect(event["job"]["machine-details"]["connectivity-parameters"]["opcda-server-name"]) except: post_to_user(job_name, job_version, "error", msg.ERR_MSG_FAIL_TO_CONNECT) else: return connection_handler
def checkopc2(taglist, opc): #检查opc print(taglist) d = readconf() if opc == "": #最初opc为空 try: #c尝试第一次连接 opc = OpenOPC.open_client(d["opcserverip"]) opc.connect(d["opcservername"]) opc.read(taglist) except Exception, e: printlog("Failed to connect opc:" + str(e)) print("Failed to connect opc:" + str(e)) opc = ""
def animate_graph(self, i): opc = OpenOPC.open_client('localhost') opc.connect('Kepware.KEPServerEX.V6', 'localhost') t1 = opc.read('Channel1.Device1.T') rh1 = opc.read('Channel1.Device1.RH') #Temp t1_data_raw = open("Temperature-01.txt", "r") pullDataRaw = t1_data_raw.read() dataListRaw = pullDataRaw.split('\n') dataListRaw_len = len(dataListRaw) if len(dataListRaw) == 6: dataListRaw.pop(0) t1_data_raw.close() newDataList = '\n'.join(dataListRaw) t1_data_raw = open("Temperature-01.txt", "w") t1_data_raw.write(newDataList) t1_data_raw.close() t1_data = open("Temperature-01.txt", "a") t1_data.write( str(float(t1[0]) / 100) + '**' + str(float(rh1[0]) / 100) + '**' + str(t1[2]) + '\n') t1_data.close() else: t1_data_raw.close() t1_data = open("Temperature-01.txt", "a") t1_data.write( str(float(t1[0]) / 100) + '**' + str(float(rh1[0]) / 100) + '**' + str(t1[2]) + '\n') t1_data.close() pullData = open("Temperature-01.txt", "r").read() dataList = pullData.split('\n') xList = [] yList = [] jList = [] for eachLine in dataList: if len(eachLine) > 1: y, j, x = eachLine.split('**') xList.append(x) yList.append(float(y)) jList.append(float(j)) a.clear() a.plot(xList, yList) b.clear() b.plot(xList, jList)
def connect(self): _lock.acquire() _lock.release() try: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.provider,self.host) except Exception, e: raise Exception(e.message)
def connect(self): _lock.acquire() _lock.release() try: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.provider, self.host) except Exception, e: raise Exception(e.message)
def push(): logger.info("User request: push") global event,busy job_name = event["job"]["properties"][0]["name"] job_version = event["job"]["properties"][0]["version"] try: opc = OpenOPC.open_client(event["job"]["machine-details"]["connectivity-parameters"]["machine-ip"]) server = opc.servers() opc.close() except Exception as err: logger.info(msg.ERR_MSG_FAIL_SERVER_NAME %(str(err))) post_to_user(job_name, job_version, "error", msg.ERR_MSG_FAIL_SERVER_NAME %(str(err))) else: post_to_user(job_name, job_version, "info", msg.INF_MSG_SERVER_NAME + str(server)) busy = False
def getData(collection): import time global items print collection client = OpenOPC.open_client(collection['opc_server_ip']) client.connect(collection['opc_name']) items = collection['opc_items'] arr = [] for name, value, quality,create_time in client.read(items): collect_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) arr.append({"quality":quality,"project_id":collection['project_id'],"name":name,"value":value,"create_time":create_time,"collect_time":collect_time}) #写日志 client.close() return {"data":arr,"success":"true"}
def _opc_client(self): """Create OPC client""" if system == 'Linux': self.opc = OpenOPC.open_client(self.opc_server_host, self.opc_server_port) self.opc.connect(opc_server=self.opc_server_name) elif system == 'Windows': try: self.opc = OpenOPC.client() self.opc.connect(opc_server=self.opc_server_name, opc_host=self.opc_server_host) except Exception as e: raise e self.logger.info('OPC client created successfully')
def push(job_data): """Send the list of servers to users through the IoT topic.""" logger.info("User request: push") try: opc = OpenOPC.open_client(host=job_data["job"]["machine-details"] ["connectivity-parameters"]["machine-ip"]) server = opc.servers() opc.close() post_to_user("info", msg.INF_MSG_SERVER_NAME.format(server)) except Exception as err: logger.info(msg.ERR_MSG_FAIL_SERVER_NAME.format(err)) post_to_user("error", msg.ERR_MSG_FAIL_SERVER_NAME.format(err))
def sensor_reading(self): while True: opc = OpenOPC.open_client('localhost') opc.connect('Kepware.KEPServerEX.V6', 'localhost') t1 = opc.read('Channel1.Device1.T') rh1 = opc.read('Channel1.Device1.RH') t2 = opc.read('Channel1.Device2.T') rh2 = opc.read('Channel1.Device2.RH') t3 = opc.read('Channel1.Device3.T') rh3 = opc.read('Channel1.Device3.RH') T1 = float(t1[0]) / 100 RH1 = float(rh1[0]) / 100 T2 = float(t2[0]) / 100 RH2 = float(rh2[0]) / 100 T3 = float(t3[0]) / 100 RH3 = float(rh3[0]) / 100 if RH1 > 75.0: self.sensor1_RH_text.config(bg='red') else: self.sensor1_RH_text.config(bg='white') if RH2 > 75.0: self.sensor2_RH_text.config(bg='red') else: self.sensor2_RH_text.config(bg='white') if RH3 > 75.0: self.sensor3_RH_text.config(bg='red') else: self.sensor3_RH_text.config(bg='white') self.sensor1_temp_text.delete('0.0', END) self.sensor1_temp_text.insert(0.0, T1) self.sensor1_RH_text.delete('0.0', END) self.sensor1_RH_text.insert(0.0, RH1) self.sensor2_temp_text.delete('0.0', END) self.sensor2_temp_text.insert(0.0, T2) self.sensor2_RH_text.delete('0.0', END) self.sensor2_RH_text.insert(0.0, RH2) self.sensor3_temp_text.delete('0.0', END) self.sensor3_temp_text.insert(0.0, T3) self.sensor3_RH_text.delete('0.0', END) self.sensor3_RH_text.insert(0.0, RH3) time.sleep(3)
def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() # print "{} wrote:".format(self.client_address[0]) print self.data taglist = [self.data] opcConnect = OpenOPC.open_client(gateway) opcConnect.connect(opcServer, opcHost) tags = opcConnect.read(taglist) opcConnect.close() for i in range(len(tags)): (tag, reading, condition, time) = tags[i] print "%s %s %s %s"%(tag, reading, condition, time) self.request.sendall(str(tags[i]))
def __init__(self, master): self.master = master self.master.geometry("800x550") self.master.title("Industrial SCADA System") opc = OpenOPC.open_client('localhost') opc.connect('Kepware.KEPServerEX.V6', 'localhost') # backgroundimage self.image = Image.open("temp1.jpg") self.photo = ImageTk.PhotoImage(self.image) self.label = Label(image=self.photo) self.label.image = self.photo # keep a reference! self.label.place(x=0, y=0, relwidth=1, relheight=1) self.label1 = Label(master, text="SENSOR 01 TEMPERATURE TREND", bg="MediumPurple2") self.label1.grid(row=0, column=0, sticky=N + S + E + W) self.label1.config(font=("Arial", 15)) canvas = FigureCanvasTkAgg(fig, master) canvas.get_tk_widget().grid(row=1, column=0) self.anim = animation.FuncAnimation(fig, self.animate_graph, interval=3000, repeat=True) self.label2 = Label(master, text="SENSOR 01 RH TREND", bg="MediumPurple2") self.label2.grid(row=2, column=0, sticky=N + S + E + W) self.label2.config(font=("Arial", 15)) self.label2 = Label(master, bg="MediumPurple4") self.label2.grid(row=3, column=0, sticky=N + S + E + W) self.label2.config(font=("Arial", 15)) self.MainMenuButton = Button(master, text="Main Menu", width=20, command=self.SCADA_menu, bg="dark turquoise", fg="white smoke") self.MainMenuButton.grid(row=4, column=0)
def connect(self, host=None, opc_server=None): """ Создание объекта OPC клиента. @param host: Хост OPC сервера для возможности удаленного подключения (через DCOM) к OPC серверу. Если не определен, то берется из описания компонента. @param opc_server: Имя OPC сервера. Если не определен, то берется из описания компонента. @return: Объект OPC сервера. """ if host is None: host = self.getHost() if opc_server is None: opc_server = self.getOPCServer() if type(host) not in (None.__class__, str, unicode): log.error(u'Не корректный тип хоста OPC сервера <%s>' % type(host)) return None is_local_opc = self.is_localhost(host) if is_local_opc: log.info(u'OPC сервер находится локально') opc = OpenOPC.client() else: log.info(u'OPC сервер находится на <%s>' % host) opc = OpenOPC.open_client(host) if opc is None: log.error(u'Не возможно создать объект клиента OPC. Хост <%s>' % host) return None # Список серверов OPC servers = opc.servers() if opc_server not in servers: log.warning(u'Сервер <%s> не найден среди %s' % (opc_server, servers)) self.disconnect(opc) return None # Соедиенение с сервером opc.connect(opc_server) return opc
def create_opc_client(self, opc_host=None): """ Создание объекта OPC клиента. @param opc_host: Хост OPC сервера для возможности удаленного подключения (через DCOM) к OPC серверу. Если не определен, то считается что OPC сервер находится локально. @return: Объект OPC сервера. """ if type(opc_host) not in (None.__class__, str, unicode): msg = u'Не корректный тип хоста OPC сервера <%s>' % type(opc_host) log.error(msg) journal.write_msg(msg) return None is_local_opc = (opc_host is None) or (type(opc_host) in (str, unicode) and opc_host.lower().strip() in ('localhost', '127.0.0.1')) if is_local_opc: log.info(u'OPC сервер находится локально') opc = OpenOPC.client() else: log.info(u'OPC сервер находится на <%s>' % opc_host) opc = OpenOPC.open_client(opc_host) return opc
def data_logging(): while True: time.sleep(2) opc = OpenOPC.open_client('localhost') opc.connect('Kepware.KEPServerEX.V6', 'localhost') # t1= opc.read('Channel1.Device1._System._SecondsInError') # rh1= opc.read('Channel1.Device1._System._SecondsInError') t1 = opc.read('Channel1.Device1.T') rh1 = opc.read('Channel1.Device1.RH') t2 = opc.read('Channel2.Device1.T') rh2 = opc.read('Channel2.Device1.RH') t3 = opc.read('Channel3.Device1.T') rh3 = opc.read('Channel3.Device1.RH') T1 = float(t1[0]) / 100 RH1 = float(rh1[0]) / 100 time_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') #time_now=datetime.now() print(time_now) #print(str(time_now) + " Temperature : " + str(x[1]) + " RH : " +str(x[2])) mydb = mysql.connector.connect(host="localhost", user="******", passwd="root", database="SCADA") #print (mydb) mycursor = mydb.cursor() #mycursor.execute("CREATE TABLE sensor1 (time DATETIME, temperature DECIMAL(8,2),rh DECIMAL(8,2))") #mycursor.execute("CREATE TABLE sensor2 (time DATETIME PRIMARY KEY, temperature FLOAT(3,2),rh FLOAT(3,2))") #mycursor.execute("CREATE TABLE sensor3 (time DATETIME PRIMARY KEY, temperature FLOAT(3,2),rh FLOAT(3,2))") sql = ( "INSERT INTO sensor1 (time, temperature,rh) VALUES (%s, %s, %s)") val = (time_now, T1, RH1) mycursor.execute(sql, val) mydb.commit()
def __init__(self, ip=None, port=None): if 'connection' in config: user_ip = input( 'Введите адрес openOPC Gateway в формате "ip:port". Сейчас установлено: {}:{}(enter) \n> ' .format(config["connection"]['ip'], config["connection"]['port'])) if user_ip != '': splited = user_ip.split(':') if len(splited) == 2: ip = splited[0] port = splited[1] config.save() else: print('Формат не распознан, использую значения из конфига') else: if 'connection' in config: if ip is None: ip = config["connection"]['ip'] if port is None: port = config["connection"]['port'] print('Использую значения из конфига') else: print('Неверно введен ip') exit(0) try: self.opc = OpenOPC.open_client(ip, port) except: log.debug(traceback.format_exc()) log.critical( "Ошибка подключения к openOPC Gateway. Проверьте состояние сервиса zzzOpenOPCService" ) raise SystemExit self.server_name = "" self.structure = {} self.client = self.opc #OpenOPC.client() self.servers = self.opc.servers()
def _start(self): logger.debug('opc plugin connecting starting......') self.gateway = self.entity.get_property(self.plugin_node, 'server address').value self.opc_host = self.gateway self.opc_serv = self.entity.get_property(self.plugin_node, 'server name').value try: self.opc = OpenOPC.open_client(self.gateway) self.opc.connect(self.opc_serv, self.opc_host) self.connected = True logger.info('opc plugin connect server success') except BaseException: logger.exception('connect opc server failed, %s' % self.gateway) self.opc = None self.connected = False if self.connected: self._main = threading.Thread(target=self._plugin_main, args=(None, )) self._main.setDaemon(True) self.is_stop = False self._main.start()
def recreateGroup(self): _lock.acquire() _lock.release() info = "" if self.reconnecting == 0: self.reconnecting = 1 try: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.provider, self.host) info = self.opc.servers() info = info + self.opc.info() for group in self.groups: self.createGroupByWS2(group) self.reconnecting = 0 except Exception, e: # release the lock info = "excetp: %s" % (e) log.error(info) log.error(traceback.format_exc()) self.reconnecting = 0
def recreateGroup(self): _lock.acquire() _lock.release() info = "" if self.reconnecting == 0: self.reconnecting = 1 try: self.opc = OpenOPC.open_client(self.host, self.port) self.opc.connect(self.provider, self.host) info = self.opc.servers() info = info + self.opc.info() for group in self.groups: self.createGroupByWS2(group) self.reconnecting = 0 except Exception, e: # release the lock info = "excetp: %s"%(e) log.error(info) log.error(traceback.format_exc()) self.reconnecting = 0
def _initConnnect(self): try: self.opc = OpenOPC.open_client(self.ip, self.port) self.opc.connect(self.opcname) # print self.opc_connected except IOError as e: self.logger.info('... FAILED to connect to OPC Server:{0}'.format( self.opcname)) self.opc_connected = False raise e else: self.logger.info('... Success to connect to OPC Server:{0}'.format( self.opcname)) self.opc_connected = True # return the opc connect status # if not connect reconnectxx if self.opc_connected: return True else: time.sleep(5)
def main(): opc_client = OpenOPC.open_client(conf["HOST"], conf["PORT"]) opc_client.connect(conf["PROVIDER"], conf["OPC_HOST"]) #info = opc_client.servers() #print info tags = conf["TAGS"] # ["Digi.cool_system.A1", "Digi.cool_system.A11"] group = conf["GROUP"] v = opc_client.read(tags=tags, group=group, update=100) while True: data = opc_client.read(group=group, update=100) for item in data: update(item) time.sleep(conf["INTERVAL"])
#opc_client = OpenOPC.client("Graybox.OPC.DAWrapper", "127.0.0.1") GATEWAY_HOST = conf["GATEWAY_HOST"] GATEWAY_PORT = conf["GATEWAY_PORT"] OPC_SERVER = conf["OPC_SERVER"] OPC_HOST = conf["OPC_HOST"] UPDATE = conf["UPDATE"] t1 = time.time() print "t1,",t1-t0 opc_client = OpenOPC.open_client(GATEWAY_HOST, GATEWAY_PORT) t2 = time.time() print t2 - t1 opc_client.connect(OPC_SERVER, OPC_HOST) t3 = time.time() print t3 - t2 #info = opc_client.servers() #print info #tags = ["Digi.cool_system.A1", "Digi.cool_system.A11"]
from project import settings setup_environ(settings) # import models and choices from project.web.models import Asset, COLLECTOR_CHOICES choices = dict(COLLECTOR_CHOICES) # loop through the OPC servers, connecting to each one and # creating the asset objects we need based off of the data itemcount = 0 for plant in choices: for server in choices[plant]: # ('192.168.141.204', 'APCOLLECTCMC') try: opc = OpenOPC.open_client(server[0]) opc.connect(kepware) except: print 'Connection to %s (%s) failed!' % (server[0], kepware) break eoc_list = opc.list("*.EOC", flat=True) for item in eoc_list: parts = item.split('.') # pop the EOC string off the list and put together our components tag = parts.pop() name = parts[-1] path = '.'.join(parts[:-1])
import OpenOPC import time import calendar import ConfigParser from optparse import OptionParser import psycopg2 cfg = ConfigParser.RawConfigParser() cfg.read('srv.cfg') host = cfg.get('SERVER_INFO', 'host') server = cfg.get('SERVER_INFO', 'server') var = cfg.items('VARIABLES') opc = OpenOPC.open_client(host) opc.connect(server) db=cfg.get('DATA_BASE_INFO','dbname'); db_host=cfg.get('DATA_BASE_INFO','host'); db_user=cfg.get('DATA_BASE_INFO','user'); db_pass=cfg.get('DATA_BASE_INFO','password'); conn = psycopg2.connect('dbname='+db+' host='+db_host+' user='******' password='******'State'] print "#################################################" print "Protocolo: %s" % dict(opc.info())['Protocol'] print "OPC Host: %s" % dict(opc.info())['OPC Host'] print "OPC Server: %s" % dict(opc.info())['OPC Server'] print "Status OPC: %s" % state
def connect_local(self, svr_name, host="localhost"): opc_client = OpenOPC.open_client(host) opc_client.connect(svr_name) return opc_client
def connect_local(self, svr_name): opc_client = OpenOPC.open_client('localhost') opc_client.connect(svr_name) return opc_client
parser.add_argument( '--output', '-o', help="Enables output saving, in specified file") #Path to output.txt parser.add_argument('--server', '-s', help="Name of OPC Server", default="Matrikon.OPC.Simulation.1") #OPC Server Name args = parser.parse_args() if args.command is None: print("Command for Controller not specified") sys.exit(0) # Create OpenOPC client and connect to Matrikon OPC server opc = OpenOPC.open_client() opc.connect(args.server) print("Connected to " + args.server) status_tag = "EPSimServer.EnergyPlus.Status" status = int(read_status()) print(args.mapping) if args.command == "setup": setup() elif args.command == "run": mapping = {} run(args.mapping, args.output) elif args.command == "reset": reset() elif args.command == "kill": kill()
def Read_tags(json_data): logs = {} #accessing result class returnData = DATA_RESULT() returnData.error = False try: # validate json data if 'ipaddress' in json_data and 'server' in json_data and 'group' in json_data and 'tags' in json_data: #accesing input json data assert json_data['ipaddress'] != '' ipaddress = json_data['ipaddress'] assert json_data['server'] != '' server = json_data['server'] assert json_data['group'] != '' group = json_data['group'] assert json_data['tags'] != '' tags = json_data['tags'] else: raise KeyError( "Please check!,kindly input in proper json formatted") #validate input data returnData = ValidateData(ipaddress, tags) if returnData.error: #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData #connection opc = OpenOPC.open_client(ipaddress) opc.connect(server) #read tags values = opc.read(tags, group=group, update=1) #connection close opc.remove(group) opc.close() result = [] #result into dictionary for variable in values: parameter = {} parameter["parameter"] = variable[0] #validate parameter value if (type(variable[1]) == float): parameter["value"] = round(variable[1], 3) else: parameter["value"] = variable[1] parameter["quality"] = variable[2] parameter["timestamp"] = variable[3] result.append(parameter) #return valid data returnData.data = result returnData.error = False returnData.errormessage = None return returnData except OpenOPC.TimeoutError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "TimeoutError occured" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except KeyError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Please check!,kindly input in proper json formatted" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except AssertionError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Kindly Check!, your json input values" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except UnboundLocalError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Kindly Check!, your json input format" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData
def Write_MultipleTag(json_data): logs = {} #accessing result class returnData = DATA_RESULT() returnData.error = True try: # validate json data if 'ipaddress' in json_data and 'server' in json_data and 'tags' in json_data and 'values_to_write' in json_data: #accesing input json data assert json_data['ipaddress'] != '' ipaddress = json_data['ipaddress'] assert json_data['server'] != '' server = json_data['server'] assert json_data['tags'] != '' tags = json_data['tags'] assert json_data['values_to_write'] != '' values = json_data['values_to_write'] else: raise KeyError( "Please check!,kindly input in proper json formatted") #validate input data returnData = ValidateData(ipaddress, tags) if returnData.error: #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData #connection opc = OpenOPC.open_client(ipaddress) opc.connect(server) zip_data = zip(tags, values) #read tags values = opc.write(list(zip_data), include_error=True) #connection close opc.close() result = [] #result into dictionary for item in values: parameter = {} parameter["parameter"] = item[0] parameter["Write_Result"] = item[1] parameter["Description"] = item[2] result.append(parameter) #return valid data returnData.data = result returnData.error = False returnData.errormessage = None return returnData except OpenOPC.TimeoutError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "TimeoutError occured" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except KeyError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Please check!,kindly input in proper json formatted" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except AssertionError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Kindly Check!, your json input values" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData except UnboundLocalError: #return valid data returnData.data = None returnData.error = True returnData.errormessage = "Kindly Check!, your json input format" #store logs into DB logs['CreateAt'] = datetime.now() logs['Error_Log'] = returnData.errormessage operations().insert_logs('OPCDA', 'Logs', logs) return returnData
def run(path, mapping_path, server, eplus_config, default): with open(mapping_path, 'r') as f: s = f.read() mapping = json.loads(s) opc = OpenOPC.open_client() opc.connect(server) print("Connected to: " + server) #Default EnergyPlus Version to 8-4-0 pyEp.set_eplus_dir(default) path_to_buildings = path buildings = [] command = "" prev_command = "" while True: command, _, _ = opc_read('EPSimServer.EnergyPlus.Status', opc) command = int(command) print(command) if command is not prev_command: if command is 0: #setup print("Setup") builder = pyEp.socket_builder(path_to_buildings) configs = builder.build() #[port, building_folder_path, idf] #Setup EnergyPlus instances for each building for config in configs: building_path = config[1] building_name = os.path.normpath(building_path).split( os.sep)[-1] print(building_name) #Set weather file and EnergyPlus version weather_file = eplus_config[building_name][0] eplus_path = None print(weather_file) if len(eplus_config[building_name] ) > 1 and eplus_config[building_name][1] is not '': eplus_path = eplus_config[building_name][1] print(eplus_path) ep = pyEp.ep_process('localhost', config[0], building_path, weather_file, eplus_path) output = find_output_group(building_name, mapping) output_rdy = find_output_rdy(building_name, mapping) input = find_input_group(building_name, mapping) input_rdy = find_input_rdy(building_name, mapping) ts = find_ts_tag(building_name, mapping) buildings.append( Building(building_name, ep, output, input, input_rdy, output_rdy, ts)) opc.write((ts, 0)) opc.write((input_rdy, 0)) opc.write((output_rdy, 0)) print("E+ Iniitalized, Waiting for Start Signal") elif command is 2: print("EnergyPlus Simulation finished") elif command is 3: #reset print("Reset") for building in buildings: building.ep.close() delay.sleep(1) buildings = [] delay.sleep(1) elif command is 4: #close print("Closing") for building in buildings: building.ep.close() opc.remove(opc.groups()) opc.close() break sys.exit(0) elif command is 1: for building in buildings: building_name = building.name ep = building.ep input_group = building.input_group #OPC group for easy reading from tags output_rdy = building.output_rdy input_rdy = building.input_rdy timestep_tag = building.timestep print(building_name) outputs = ep.decode_packet_simple(ep.read()) print("Writing Outputs") output_mapping = map_outputs( building_name, outputs, mapping) # Mapping is in (k, v) of TagNames, Value for tag, value in output_mapping: opc.write((tag, value)) #Notify controller that outputs are ready opc.write((output_rdy, 1)) print("Waiting for new inputs") #Wait for controller to write new inputs inputs_ready = int(opc_read(input_rdy, opc)[0]) while inputs_ready is not 1: inputs_ready = int(opc_read(input_rdy, opc)[0]) temp_command, _, _ = opc_read( 'EPSimServer.EnergyPlus.Status', opc) temp_command = int(temp_command) if temp_command is not command: print("Got Interrupt") break print("Sending inputs to EnergyPlus") inputs = opc_read(input_group, opc) # [(name, value, status, time)] #print(inputs) setpoints = [sp for (_, sp, _, _) in inputs] input_mapping = map_inputs( building_name, inputs, mapping ) #input_mapping is a list of the values of the tags, in order time, _, _ = opc_read(timestep_tag, opc) encoded_packet = ep.encode_packet_simple(input_mapping, time) ep.write(encoded_packet) inputs_ready = opc.write((input_rdy, 0)) prev_command = command
if action == 'sessions': print ' %-38s %-18s %-18s' % ('Remote Client', 'Start Time', 'Last Transaction') try: for guid, host, init_time, tx_time in OpenOPC.get_sessions(open_host, open_port): print ' %-38s %-18s %-18s' % (host, time2str(init_time), time2str(tx_time)) except: error_msg = sys.exc_info()[1] print "Cannot connect to OpenOPC service at %s:%s - %s" % (open_host, open_port, error_msg) exit() # Connect to OpenOPC service (Open mode) if opc_mode == 'open': try: opc = OpenOPC.open_client(open_host, open_port) except: error_msg = sys.exc_info()[1] print "Cannot connect to OpenOPC Gateway Service at %s:%s - %s" % (open_host, open_port, error_msg) exit() # Dispatch to COM class (DCOM mode) else: try: opc = OpenOPC.client(opc_class, client_name) except OpenOPC.OPCError, error_msg: print "Failed to initialize an OPC Automation Class from the search list '%s' - %s" % (opc_class, error_msg) exit() # Connect to OPC server
def mainloop(rectime = 5): lastrun = False # previous cycle run value lastalarm = False # previous cycle alarm value safealarmvals = [alarmtags[key][2] for key in alarmkeys] lastalarmvals = safealarmvals cycles = 1 ncols = len(senslist) + 1 # add 1 for timestamp b = {} for bc in bcycles: b[bc] = ['NaN'] * ncols def printmsg(msg): global ab currenttime = strftime('%Y%m%d %H:%M:%S', localtime()) #print(currenttime + ' - ' + msg) if len(ab) == ablength: ab = ab[:-1] ab = [currenttime + ' - ' + msg] + ab def getsrv(): srv=[i.strip() for i in subprocess.check_output(['net','start']).split('\r\n')] return(srv) opcsrvname = 'OpenOPC Gateway Service' # check running services def checksrv(): wsrv = getsrv() while opcsrvname not in wsrv: printmsg('OpenOPC gateway service not running. Attempting to start.') subprocess.call(['net','stop','zzzOpenOPCService']) subprocess.call(['net','start','zzzOpenOPCService']) wsrv = getsrv() checksrv() opc = OpenOPC.open_client(gateway_host) printmsg('Creating OPC client instance...') opc.connect(opc_server, opc_host) printmsg('OPC server connected.') def statchk(): # print furnace stats rawd = {key.split('.')[-1]: val for key, val, stat, t in opc.read(stattags.keys())} eud = {} for key, fmt, scale, offset in senslist: eud[key]=[fmt %((offset+float(rawd[key]))*scale)] return(rawd, eud) def writesens(eud): dailylog = strftime('%Y%m%d') + '.csv' logpath = os.path.join(savedir, dailylog) if (not os.path.exists(logpath)): try: logfile = open(logpath, mode = 'w') logfile.write(sensheader + '\n') logfile.close() except: printmsg('Unable to write to log file.') return() sensdata = [strftime('%X')] for key, fmt, scale, offset in senslist: sensdata+=eud[key] if (len(sensdata)==(len(senslist)+1)): # only write log if we have all data fields try: logfile = open(logpath, mode = 'a') logfile.write(','.join(sensdata)+'\n') logfile.close() except: printmsg('Unable to write to log file.') pass def mailalert(body, to = to, subject = subject): smtpserv = smtplib.SMTP(smtphost, 587) smtpserv.ehlo() smtpserv.starttls() smtpserv.ehlo smtpserv.login(mailuser, mailpass) header = 'To:' + to + '\n' + 'From: ' + mailuser + '\n' + 'Subject: ' + subject + '\n' msg = header + body smtpserv.sendmail(mailuser, to, msg) smtpserv.close() def runchk(d): run=d['Run_step']>0 if(run==True and lastrun==False): # send message run started try: mailalert(subject='Run #' + str(d['Run_number']) + ' has started.', body='') printmsg('Start message sent.') except: printmsg('Unable to send start message.') pass if(run==False and lastrun==True): # send message run ended try: mailalert(subject='Run #' + str(d['Run_number']-1) + ' has finished.', body='') printmsg('Stop message sent.') except: printmsg('Unable to send end message.') pass return(run) def alarmchk(d): alarm=bool(d['Fault']) alarms = opc.read(alarmkeys) alarmd = {} alarmvals = [] alarmtxtlist = [] for i in alarms: key, val, stat, t = i alarmd[key] = val if not alarmtags[key][2] == val: alarmtxtlist.append(alarmtags[key][1]) for key in alarmkeys: alarmvals += [alarmd[key]] alarmtext = '\nThe following alarms are active: \n' + '\n'.join(alarmtxtlist) if((alarm==True and lastalarm==False) or ((alarmvals != lastalarmvals) and (alarmvals != safealarmvals))): # send message alarm triggered try: mailalert(body = alarmtext) printmsg('Alarm message sent.') except: printmsg('Unable to send alarm message.') pass if((alarm==False and lastalarm==True) and (alarmvals == safealarmvals)): # send message alarm cleared try: mailalert(subject='Furnace interlock cleared.', body='All alarms cleared.') printmsg('Alarm cleared message sent.') except: printmsg('Unable to send clear message.') pass return(alarm, alarmvals) def printstats(eud): t = PrettyTable(['Time'] + [key for key, fmt, scale, offset in senslist]) for bc in bcycles[::-1]: if int(bc) == 1: b[bc] = [strftime('%X')] + [eud[k][0] for k in [key for key, fmt, scale, offset in senslist]] elif cycles % int(bc) == 0: b[bc] = b[bcycles[bcycles.index(bc)-1]] # propagate value down list t.add_row(b[bc]) cls() t.border = False print t print 'Last 8 messages:' for alm in ab[::-1]: print alm printmsg('Alarm loop started.') try: while True: try: rd, ed = statchk() lastrun=runchk(rd) lastalarm, lastalarmvals=alarmchk(rd) if cycles % rectime == 0: writesens(ed) if cycles == max([int(c) for c in bcycles]): cycles = 1 printstats(ed) cycles = cycles + 1 except: cycles = 1 checksrv() opc = OpenOPC.open_client(gateway_host) opc.connect(opc_server, opc_host) pass gc.collect() sleep(1) except KeyboardInterrupt: printmsg('Ctrl-C pressed. Exiting loop.') try: rd, ed = statchk() printstats(ed) except: pass opc.close()
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' from django.core.management import setup_environ from project import settings setup_environ(settings) # import models from project.web.models import Asset bad_quality = [] last_collector = '' num_checked = 0 for asset in Asset.objects.filter(check_enabled=True).order_by('collector'): if asset.collector != last_collector: print "Creating a new OPC client for %s... " % asset.collector, try: opc = OpenOPC.open_client(asset.collector) opc.connect(kepware) except: print "failed to connect to %s!" % asset.collector break print "success!" print "Retrieving properties for %s... " % asset.full_path(), status = opc.properties(asset.full_path(), id=3) print status if status == "Bad": bad_quality.append(asset) asset.bad_count += 1 asset.quality = status