예제 #1
1
   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:
예제 #2
0
파일: opc.py 프로젝트: rraabb/smap
    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")
예제 #3
0
파일: supervisor.py 프로젝트: holalluis/mbr
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]
예제 #4
0
파일: supervisor.py 프로젝트: icra/mbr
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]
예제 #5
0
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()
예제 #6
0
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()
예제 #7
0
파일: opc.py 프로젝트: tarunsmalviya/smap
    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")
예제 #8
0
 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)
예제 #9
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)
예제 #10
0
    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:
예제 #11
0
    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
예제 #12
0
    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()
예제 #13
0
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"])
예제 #14
0
파일: consumers.py 프로젝트: DevArslan/MON
    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()
예제 #15
0
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
예제 #16
0
 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 
예제 #17
0
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
예제 #18
0
    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
예제 #19
0
 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
예제 #20
0
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
예제 #21
0
파일: pythonprog.py 프로젝트: chrylarson/WM
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
예제 #22
0
def checkICONICS_Simulator():
    opc = OpenOPC.client()
    opc.connect(IconicsSim)

    j=0
    for i in tagset:
        print i, ": ", opc[i]
        j = j+1

    opc.close()
예제 #23
0
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返回状态结果集
예제 #25
0
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
예제 #26
0
    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')
예제 #27
0
def pubService():
    opc = OpenOPC.client()
    opc.connect('Matrikon.OPC.Simulation.1')
    while True:
        opcData = opc.read(opc.list('Configured Aliases.testEmir'))
        msgs = []
        for i in opcData:
            alias, item = i[0].split(".")
            msgs.append(("/plcNetwork/dev0/get/" + alias + "/" + item + "/",
                         i[1], 0, False))

        publish.multiple(msgs, hostname="###")
        time.sleep(0.5)
    opc.close()
예제 #28
0
 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 opc_write():
    opc = OpenOPC.client()  #创建客户端
    opc.connect(u'PCAuto.OPCServer', 'localhost')  #读取opc
    pointName=request.values["pointName"]      #获取坐取按钮信息
    pointValue=request.values["pointValue"]
    opc.write((str(pointName), float(pointValue)))  #写入opc值
    time.sleep(1)
    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返回状态结果集
예제 #30
0
    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
예제 #31
0
    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')
예제 #32
0
 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
예제 #33
0
 def __init__(self, conn_cfg, use_alt_host=False):
     if use_alt_host:
         self.opc_host = conn_cfg["OPC_HOST_ALT"]
     else:
         self.opc_host = conn_cfg["OPC_HOST"]
     self.client = OpenOPC.client(client_name="PyOPC")
     self.landmark_path = conn_cfg[
         "LANDMARK_PATH"]  # Path to known/expected value, for health checks
     self.expected_landmark_val = conn_cfg[
         "EXPECTED_LANDMARK_VAL"]  # Value to compare landmark observation against
     self.heartbeat_path = conn_cfg[
         "HEARTBEAT_PATH"]  # Path to constantly changing value, for health checks
     self.landmark = None
     self.heartbeats = deque(maxlen=2)
     self.aliasing_possible = False  # Indicates if heartbeat scan is too slow and could alias signal
     self.last_integrity_timestamp = None
def AddItemsCSV(OPCserver, CSVname, taglist):
    """
    Connect OPCserver
    Extract a value of the value
    of the taglist and append them to
    liste and to csv
    taglist: list with name of all items
    liste: list of item value
    """

    attach = []  #Initialize attach

    try:
        opc = OpenOPC.client()  #Connection with the OPC Server
        opc.connect(OPCserver)
    except:
        print("No connection to Server")

    try:
        v = opc.read(tags=taglist)  #Reading tags from OPC
        str(v)
    except:
        print("Unable to read tags")

    try:

        # Create a line with the values from the tag

        for i in range(len(v)):
            (name, val, qual, time) = v[i]
            if val == '':
                val = 0
            attach.insert(i, val)
        attach.insert(0, time)
    except:
        print('Unable to create a row')

    #Writing the line to the CSV file

    try:
        b = open(CSVname, 'ab')
        a = csv.writer(b)
        a.writerow(attach)
        b.close()
    except:
        print('Unable to write in CSV')
예제 #35
0
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
예제 #36
0
 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
예제 #37
0
    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
예제 #38
0
 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.
예제 #39
0
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")

    # MySQL

    user = '******'
    password = ''
    host = '127.0.0.1'
    database = 'mbr'

    print(" - Connecting to MySQL...")
    try:
        config = {
            'user': user,
            'password': password,
            'host': host,
            'database': database,
            'raise_on_warnings': True
        }
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor()
        print('Success! connection established')
        # analise if cursor is defined
        assert isinstance(cursor, object)
        return [opc, cursor]
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(f'unable to connect to MySQL server on {host}')
예제 #40
0
def connect(serveurName, taglist):
    """
    Connexion serveur OPC
    serveurName: name of the OPC server
    taglist: list with name of item
    return list of item information
    """      
    try:
        # Connexion serveur
        opc = OpenOPC.client()
        u= opc.connect(serveurName)
	# Read item list
	v = opc.read(taglist)
	# Close socket
	opc.close()
    except:
        print "Error - No connection to OPC server !!!"
	
    return v
    def create_client(self):
        """Create a new OpenOPC client instance in the Pyro server"""

        opc_obj = OpenOPC.client(opc_class)
        opc_obj._open_serv = self
        opc_obj._open_self = opc_obj
        opc_obj._open_host = opc_gate_host
        opc_obj._open_port = opc_gate_port

        uri = self._pyroDaemon.register(opc_obj)
        opc_obj._open_guid = uri.asString()

        self._opc_objects[opc_obj._open_guid] = opc_obj
        self._init_times[opc_obj._open_guid] =  time.time()
        self._last_times[opc_obj._open_guid] =  time.time()

        servicemanager.LogInfoMsg('\n\nCreate client %s' % opc_obj._open_guid)

        return Pyro4.Proxy(uri)
예제 #42
0
 def query_handler(call):
     answer = ''
     if call.data == '3':
         try:
             opc1 = OpenOPC.client()
             opc1.connect(tagsValue[0])
             # tag1 = opc1.list("COM4.TRM_202(adr=104)T_слой_Ср_р-ра.Оперативные параметры")[3]
             answer = opc1.read(tagsValue, update=1, include_error=True)
             print(answer)
             opc1.close()
             count = 0
             while count < len(tagsValue):
                 bot.send_message(
                     call.message.chat.id,
                     "{0:_^20} {1:>10.2f}".format(tg_lst[tagsValue[count]],
                                                  answer[count][1]))
                 count += 1
         except ConnectionError as err:
             print(err)
예제 #43
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
예제 #44
0
    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 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)
예제 #46
0
파일: connect.py 프로젝트: holalluis/mbr
import MySQLdb

# Libraries for time
import time

while True:
    try:
        # Create a variable for the time
        localtime = time.asctime(time.localtime(time.time()))

        # Connect to the DB ("host", "username", "password", "db_name")
        host = "localhost"  # Where the host is (local or internet)
        username = "******"  # user name to get into the DB
        password = "******"  # Password to get into the DB
        db_name = "prova"  # DB name
        db = MySQLdb.connect(host, username, password, db_name)  # Connect and name it DB

        # Create the object cursor to execute the SQL command
        cursor = db.cursor()
        break
    except MySQLdb.Error:
        print "Error connectant a la base de dades. Try again!"


# Connect to the OPC server
import OpenOPC  # Imports the OpenOPC library

opc = OpenOPC.client()  # Opens the client
server = "Matrikon.OPC.Simulation"  # Choose the server
opc.connect(server)  # Connect to server
예제 #47
0
파일: OPC-Tool.py 프로젝트: pski07/OPC-Tool
	def create_instance(self):
		'''creats OPC client'''
		self.opc = OpenOPC.client()
		self.status = 'Created OPC Instance'
예제 #48
0
=================== """

import sys
from os import path

if __name__ == '__main__':
    sys.path[0:0] = ['..',]

from Control.GPCVariablesConfig import EPA_Vars, GPC_SysVars, GPC_StateVars
from ReadWriteDataTest.handleConfig import readConfigJob, readGPCConfig
import ReadWriteDataTest.config as GPCConfig
import OpenOPC

GPCConf = readGPCConfig(path.join('..','ReadWriteDataTest',GPCConfig.GPCConfFile))
OPCServer = GPCConf[0]["Global"]["OPCServer"]
opc = OpenOPC.client()
opc.connect(OPCServer)

#Set the Valves into automatic mode.
# This need sto be done first otherwise some other settings will be ignored.
variables = [('HMI_VanneVM1enAuto_S01',1),
             ('HMI_VanneVM1enAuto_S02',1),
             ('HMI_VanneVM1enAuto_S03',1),]
opc.write(variables)

#Set all the other variables that need to have a specific value at startup.
variables = []
for sti in EPA_Vars:
    variables.extend([(vi['OPC'],0) for vi in EPA_Vars[sti] if vi['OPC'].endswith('_Index')])

for sti in GPC_SysVars:
예제 #49
0
 def get_opc(self):
     print "Get opc server "
     opc = OpenOPC.client() 
     all = opc.servers()
     opc.close()
     return all
# -*- 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
예제 #51
0
 def __init__(self):
     self.client = OpenOPC.client()
     self.client.connect(OPC_SERVER)
예제 #52
0
 def __init__(self):
     QtCore.QThread.__init__(self)
     self.opc = OpenOPC.client()
     self.exiting = False
     self.items = []
예제 #53
0
파일: opc.py 프로젝트: bapowell/OpenOPC
   
# 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

if action not in ['servers'] and not health_only:
   try:
      opc.connect(opc_server, opc_host)
   except OpenOPC.OPCError, error_msg:
      if opc_mode == 'open': error_msg = error_msg[0]
      print "Connect to OPC server '%s' on '%s' failed - %s" % (opc_server, opc_host, error_msg)
      exit()

# Perform requested action...