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): 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 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): """ 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 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 _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 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 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 init(self): config_filename = 'main.conf' self.config = ConfigParser.ConfigParser() file_handle = open(config_filename) self.config.readfp(file_handle) self.opc_classname = self.config.get('opc', 'classname') self.opc_servers = self.config.get('opc', 'servers') self.opc_host = self.config.get('opc', 'host') self.logger.info('Opc Class: ' + self.opc_classname) self.logger.info('Opc Servers: ' + self.opc_servers) self.logger.info('Opc Host: ' + self.opc_host) self.preferences = {} self.preferences['show_root'] = mTools.str_to_bool( self.config.get('preferences', 'show_root')) self.opc = OpenOPC.client() result = self.opc.connect(self.opc_servers, self.opc_host) #result = False if result: self.logger.info('... Successfully connected to OPC server') return True else: self.logger.error('... FAILED to connect to OPC Server') time.sleep(5) self.init()
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(): ''' return 2 connection objects: "opc" and "cursor" ''' # PLC plc='Matrikon.OPC.Simulation.1' try: print "+------------+" print "| | - Connecting to PLC...", opc=OpenOPC.client() opc.connect(plc) print " Success!" except: print "Error connecting to OPC" print "| Connecting |" # MYSQL server='127.0.0.1' user='******' pasw='' dbName='mbr' try: print "| | - Connecting to MySQL...", db=MySQLdb.connect(server,user,pasw,dbName) cursor = db.cursor() print " Success!" except: print "Error connecting to MySQL" print "+------------+" return [opc,cursor]
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 pubService(): items = [ '[OPC_Sample]Program:MainProgram.OUTPUT1', '[OPC_Sample]Program:MainProgram.OUTPUT2', '[OPC_Sample]Program:MainProgram.INPUT' ] while True: try: opc = OpenOPC.client() opc.connect('RSLinx OPC Server') opcData = opc.read(items) except: print "pubService OPC exception" else: msgs = [] for i in opcData: msgs.append(("opcsample/get/" + i[0] + "/", i[1], 0, False)) try: publish.multiple(msgs, hostname="***.eercan.com", auth={ 'username': "******", 'password': "******" }) except: print "pubService MQTT exception, sleeping 5 sec" time.sleep(5) time.sleep(1) opc.close()
def connect(self): print "attempting OPC connection to", self.opc_name self.opc = OpenOPC.client() self.opc.connect(self.opc_name, self.opc_host) props = self.opc.properties(self.points.keys()) print "loaded", len(props), "properties" points = {} for point, pid, key, val in props: 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/Item Canonical DataType', None) if not dtype: print "no datatype tag in", name continue if dtype.startswith('VT_R'): dtype = 'double' elif dtype.startswith('VT_U') or dtype.startswith('VT_I'): dtype = 'long' else: print "skipping", name, "since cannot find data type" continue if not self.get_timeseries(name): 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")
def connect(): ''' return 2 connection objects: "opc" and "cursor" ''' # PLC plc = 'OMRON.OpenDataServer.1' try: print "+------------+" print "| | - Connecting to PLC...", opc = OpenOPC.client() opc.connect(plc) print " Success!" except: print "Error connecting to OPC" print "| Connecting |" # MYSQL server = '127.0.0.1' user = '******' pasw = '' dbName = 'mbr' try: print "| | - Connecting to MySQL...", db = MySQLdb.connect(server, user, pasw, dbName) cursor = db.cursor() print " Success!" except: print "Error connecting to MySQL" print "+------------+" return [opc, cursor]
def connect(self): print "attempting OPC connection to", self.opc_name self.opc = OpenOPC.client() self.opc.connect(self.opc_name, self.opc_host) props = self.opc.properties(self.points.keys()) print "loaded", len(props), "properties" points = {} for point, pid, key, val in props: 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/Item Canonical DataType", None) if not dtype: print "no datatype tag in", name continue if dtype.startswith("VT_R"): dtype = "double" elif dtype.startswith("VT_U") or dtype.startswith("VT_I"): dtype = "long" else: print "skipping", name, "since cannot find data type" continue if not self.get_timeseries(name): 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")
def connectOPC(self, event): eventValue = event.get("text").split(',') nameServer = eventValue[0] nameTag = eventValue[1] print(nameServer, nameTag) con = psycopg2.connect( "host='localhost' dbname='postgres' user='******' password='******'" ) cur = con.cursor() pywintypes.datetime = pywintypes.TimeType opc = OpenOPC.client() opc.connect(nameServer) tag = nameTag ID = 0 cur.execute(f"delete from orders") while True: value = opc.read(tag) cur.execute(f"INSERT INTO orders VALUES({ID},{value[0]});") print(value) con.commit() sleep(5) ID += 1 con.close()
def subService(): try: opc = OpenOPC.client() opc.connect('RSLinx OPC Server') except: print "subService OPC Connect exception" def on_connect(client, userdata, flags, rc): print("MQTT Connected with result code " + str(rc)) client.subscribe("opcsample/set/#") def on_message(client, userdata, msg): topicParse = msg.topic.split("/") opc.write((topicParse[-2:][0], msg.payload)) print "set: " + topicParse[-2:][0] + ": " + msg.payload client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message try: client.username_pw_set("***", "***") client.connect("***.eercan.com", 1883, 60) except: print "subService MQTT Connect exception" client.loop_forever() opc.close()
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 main(): opc_client = OpenOPC.client( "Graybox.OPC.DAWrapper", "127.0.0.1") #OpenOPC.open_client(conf["HOST"], conf["PORT"]) print conf["PROVIDER"] print conf["OPC_HOST"] 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) print data for item in data: #update( item ) print item time.sleep(conf["INTERVAL"])
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 create_app(): # Funcao responsavel por inicializar a aplicacao REST app = Flask(__name__) app.threaded = False __register_blueprints(app) app.opc = OpenOPC.client() return app
def jobWriteOPC(TVpairs,opcserver='OPCManager.DA.XML-DA.Server.DA',client_name=None): opc = OpenOPC.client(client_name=client_name) opc.connect(opcserver) sleep(0.7) status = opc.write(TVpairs) sleep(0.7) opc.close() return status
def get_opc_info(self, opc_server): print "Get opc server infomation" opc = OpenOPC.client() opc.connect(opc_server) all = opc.info() opc.close() return all
def get_opc_info(self,opc_server): print "Get opc server infomation" opc = OpenOPC.client() opc.connect(opc_server) all = opc.info() opc.close() return all
def OLGA_connect(serverIP='127.0.0.1',modelPrefix='Sim.ServerDemo.'): #Create Data Access Object from OPC server model = modelPrefix; # turn his into a class da = OpenOPC.client() id = 'SPT.OLGAOPCServer.7' da.connect(id) time.sleep(1) #OLGA_restart_time(da,True) return da
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 __init__(self, servername) -> None: super().__init__() self.__opc = OpenOPC.client() try: self.__opc.connect(servername) except OpenOPC.OPCError: self.__opc.close() print("cannot connect to opc") raise exception_.OPCError
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 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 checkICONICS_Simulator(): opc = OpenOPC.client() opc.connect(IconicsSim) j=0 for i in tagset: print i, ": ", opc[i] j = j+1 opc.close()
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 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 readopc(tags): pywintypes.datetime = pywintypes.TimeType opc = OpenOPC.client() opc.connect('Matrikon.OPC.Simulation.1') try: data = opc.read(tags, group='Group0', update=1) except OpenOPC.TimeoutError: print("TimeoutError occured") return data
def conexion_OPC(): # Conexion con el servidor del controlador MPC = Client("opc.tcp://Labo6:16700/") # Creacion objeto OPC-UA MPC.connect() # Conexion Controlador MPC.load_type_definitions() # Conexión con el servidor RTO RTO = Client("opc.tcp://Labo6:16701/") # Creacion objeto OPC-UA RTO.connect() # Conexion Controlador RTO.load_type_definitions() # Conexion con los demas servidores SCADA = OpenOPC.client() # Creacion objeto OPC-DA PID1 = OpenOPC.client() # Creacion objeto OPC-DA PID2 = OpenOPC.client() # Creacion objeto OPC-DA SCADA.connect("LecturaOPC.1.0") PID1.connect("OPC.PID ISA (CreaOPC).1") PID2.connect("OPC.PID ISA 2 (CreaOPC).1") return [MPC, SCADA, PID1, PID2, RTO]
def opc_status(): opc = OpenOPC.client() #创建客户端 opc.connect(u'PCAuto.OPCServer', 'localhost') #读取opcserver lista = ["ZLJ2_ManOn.PV", "ZLJ2_Run.PV", "ZLJ2_ManAuto.PV", "ZLJ3_ManOn.PV", "ZLJ3_Run.PV", "ZLJ3_ManAuto.PV"] listStatus = [] opcList = opc.read(lista) #读取整个流程参数 0停止和手动 1启动和自动 for line in opcList: collection = {} collection[line[0]] = line[1] listStatus.append(collection) return jsonify(listStatus) #f返回状态结果集
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 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 __init__(self): pywintypes.datetime = pywintypes.TimeType self.opc = OpenOPC.client() if self.opc.servers()[0]: self.opc.connect(self.opc.servers()[0]) self.server = self.opc.servers()[0] print('OPC Server Conectado') print('Servidor: {}'.format(self.opc.servers()[0])) else: print('Nenhum servidor encontrado')
def inactive_cleanup(exit_event): while True: exit_event.wait(60.0) if exit_event.is_set(): try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) for server, oid, ctime, xtime in all_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) except Exception as e: servicemanager.LogInfoMsg('\n\nException %s happen when stop opc gateway service' % e) finally: exit_event.clear() return else: try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) if len(all_sessions) > max_clients: stale_sessions = sorted(all_sessions, key=lambda s: s[3])[:-max_clients] else: stale_sessions = [s for s in all_sessions if time.time() - s[3] > (inactive_timeout * 60)] for server, oid, ctime, xtime in stale_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) time.sleep(1) except Exception as e: servicemanager.LogInfoMsg('\n\nException %s happen when cleanup timeout session' % e)
def inactive_cleanup(exit_event): while True: exit_event.wait(60.0) if exit_event.is_set(): all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) for oid, ip, ctime, xtime in all_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) exit_event.clear() return else: try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) except Pyro.errors.ProtocolError: all_sessions = [] if len(all_sessions) > max_clients: stale_sessions = sorted(all_sessions, key=lambda s: s[3])[:-max_clients] else: stale_sessions = [ s for s in all_sessions if time.time() - s[3] > (inactive_timeout * 60) ] for oid, ip, ctime, xtime in stale_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) time.sleep(1)
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 _init_OPC(self, opcserver='CoDeSys.OPC.02', opcclientName='OPCClient.GPCSys'): try: # opc client instance can not be stored here as this will be run in the main thread during initialisation. # opc connection will faile later if run from the scheduler job (which will be in an other thread) opc = OpenOPC.client() except: raise ValueError('OPC-Client could not be instantiated') if opcserver in opc.servers(): self.opcServer = opcserver try: opc.connect(self.opcServer) except: raise ValueError('OPC-Server: "%s" could not be connected'%(self.opcServer,)) if self.Variables.has_key('OPC_Group'): opcGrp = self.Variables['OPC_Group'] opcVMap = {} opcVars = set() opcServVars = set() for sti in self.Variables.keys(): if sti in ["OPC_Group",]: continue stg = lambda vi: ''.join(vi.split('_',2)[:2]) vmapi = dict([(sti+':.'+vi['OPC'],GPC_Stations[stg(vi['OPC'])]+':'+vi['GPC']) for vi in self.Variables[sti]]) opcVMap.update(vmapi) opcVars.update(vmapi.keys()) opcServVars.update(opc.list(sti+"*", flat=True)) opcVMap.update(dict([reversed(i) for i in opcVMap.items()])) else: opcGrp = self.Variables.keys()[0] opcVars = set([opcGrp+':.'+vi for vi in self.Variables[opcGrp]]) opcServVars = set(opc.list(opcGrp+"*", flat=True)) if opcVars <= opcServVars: self.opcGrp = opcGrp self.opcVars = opcVars self.opcVarsDict = dict() try: #only if variable mapping available store it self.opcVMap = opcVMap self.gpcVars = [opcVMap[vi] for vi in opcVars] except: self.gpcVars = self.opcVars else: raise ValueError('Not all needed Variables are listed by the OPC Server\n missing: %s' % (opcVars - opcServVars,)) self.opcclientName = opcclientName self.readLock = False self.writeLock = False self.connTrys = 0 self.connMaxTrys = 3 #Could come from config opc.close() else: raise ValueError('OPC Server is not accessible: %s' % opcserver)
def get_opc_list(self,opc_server,browe_option): print "Initial to get all OPC item from ",opc_server opc = OpenOPC.client() opc.connect(opc_server) #all = opc.list() if browe_option: #Flat == True all = opc.list('*',flat = True) print "------------------------" for t in all: print t opc.close() return all # rerturn all opc server else: return all
def readOPC(self,server,tag_read): opc = OpenOPC.client() opc.connect(server) result = opc.read(tag_read,timeout=7000) del self.global_list[server]['value'][:] # delete all item self.global_list[server]['value'] = result check_time_out = 0 run_proc = True try: while run_proc: # reset tag timeout if check_time_out > 3: check_time_out = 0 tag_read = [] del_tag = [] for t in self.global_list[server]['tag']: time_out = self.global_list[server]['tag'][t]-1 print "Tag %s timeout %s " % (t,time_out) if time_out > 0 : self.global_list[server]['tag'][t]=time_out tag_read.append(t) else: del_tag.append(t) # delete tag from servie for t in del_tag: del self.global_list[server]['tag'][t] #print "OPC thread service update between 2 second \r\n Try to set new value in global_list : ", #print self.global_list time.sleep(2) if len(tag_read)>0: result = opc.read(tag_read,timeout=7000) #print result del self.global_list[server]['value'][:] # delete all item self.global_list[server]['value'] = result check_time_out +=1 else: run_proc = False # exit process del self.global_list[server] # delete all tag and server except Exception,err: print "interrupt exit with thread opc : ",err
def jobReadOPC(Tags,opcserver='OPCManager.DA.XML-DA.Server.DA',client_name=None): opc = OpenOPC.client(client_name=client_name) opc.connect(opcserver) sleep(0.7) opcIn = [] for i in xrange(2): try: opcIn = opc.read(Tags,timeout=1000) break except OpenOPC.TimeoutError: print "%s: TimeoutError" % (client_name,) opc.close() sleep(1) opc.connect(opcserver) sleep(0.7) opc.close() return opcIn
def _connect_OPC(self): try: self.opc except AttributeError: # opc client instance can now be stored as this is done within the job thread. # later cals will be issued from the same thread. try: self.opc = OpenOPC.client(client_name=self.opcclientName) except OpenOPC.OPCError as e: raise ValueError('OpenOPC.OPCError: %s\n Error during OPC client instantiation' % e) try: self.opc.info() #This raises an exception if the OPC-Server is not connected. conn = True except: conn = False if not conn: self.opc.connect(self.opcServer) sleep(0.3) #To be sure connection is done on OPC server side.
def create_client(self): """Create a new OpenOPC instance in the Pyro server""" opc_obj = OpenOPC.client(opc_class) base_obj = Pyro.core.ObjBase() base_obj.delegateTo(opc_obj) uri = self.getDaemon().connect(base_obj) opc_obj._open_serv = self opc_obj._open_self = base_obj opc_obj._open_host = self.getDaemon().hostname opc_obj._open_port = self.getDaemon().port opc_obj._open_guid = uri.objectID remote_ip = self.getLocalStorage().caller.addr[0] try: remote_name = socket.gethostbyaddr(remote_ip)[0] self._remote_hosts[uri.objectID] = '%s (%s)' % (remote_ip, remote_name) except socket.herror: self._remote_hosts[uri.objectID] = '%s' % (remote_ip) self._init_times[uri.objectID] = time.time() self._tx_times[uri.objectID] = time.time() return Pyro.core.getProxyForURI(uri)
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 inactive_cleanup(exit_event): while True: exit_event.wait(60.0) if exit_event.is_set(): all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) for oid, ip, ctime, xtime in all_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) exit_event.clear() return else: try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) except Pyro.errors.ProtocolError: all_sessions = [] if len(all_sessions) > max_clients: stale_sessions = sorted(all_sessions, key=lambda s: s[3])[:-max_clients] else: stale_sessions = [s for s in all_sessions if time.time()-s[3] > (inactive_timeout*60)] for oid, ip, ctime, xtime in stale_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) time.sleep(1)
#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])
health_only = False # Establish signal handler for keyboard interrupts sh = SigHandler() signal.signal(signal.SIGINT,sh) if os.name == 'nt': signal.signal(signal.SIGBREAK,sh) signal.signal(signal.SIGTERM,sh) # ACTION: List active sessions in OpenOPC service 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()
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()
# -*- coding: utf-8 -*- from __future__ import print_function import time from Model import Model from PlantOPC import PlantOPC import OpenOPC import numpy import matplotlib.pyplot as plt opc = OpenOPC.client() # Cria o cliente OPC; o servidor é o RSLinx opc.connect('RSLinx OPC Server') # Essa string não muda; conecta ao RSLinx init_pos = (opc.read('[CLP_AB]position',update=1)[0]) pC = numpy.array([0.5, 0.6, 0.7, 0.5 + 0.4j, 0.5 - 0.4j]) Ki = 0.183111320328469 Kp = numpy.array([0.007993734748865, 0.009705988539721, -0.004630469582507, -0.000426479250745]) # Kalman Matrices n = 4 Ak = numpy.matrix([[0.993175847266250, 0.0997676389875316, 0.00447446153612418, 0.000154491807255262], [-0.266442692060039, 0.989506934720158, 0.0794137333776907, 0.00441443534842949], [-7.61331011046535, -0.371277877313592, 0.407916221277208, 0.0776985503560236], [-134.001998512554, -9.45851595845769, -10.6078657460473, 0.377727256243161]]) Bk = numpy.matrix([0.674742463375352, 3.50238796155364, -32.6963528822316, -364.795682866366]).transpose() Ck = numpy.matrix([1.0, 0.0, 0.0, 0.0]) Q = 0.01 ** 2 * numpy.eye(4) R = 0.4 ** 2 epsilon = 0.3 Ts = 0.1
def get_opc(self): print "Get opc server " opc = OpenOPC.client() all = opc.servers() opc.close() return all