def conn_opc(): # OPCサーバに接続 cl = Client("opc.tcp://192.168.10.5:51110/CogentDataHub/DataAccess") # クライアント証明書のapplication_uri cl.application_uri = "urn:desktop-i50i89m:Cogent DataHub" # policy設定 print("secPolicy: " + str(secPolicy)) if secPolicy != policies[0]: # None以外の場合SecurityPolicyを設定 mode = ua.MessageSecurityMode.SignAndEncrypt pc = getattr(security_policies, 'SecurityPolicy' + secPolicy) # 第二引数:クライアント証明書 cl.set_security( pc, "/Users/watarium/PycharmProjects/opcua/OPCUA_CL.der", "/Users/watarium/PycharmProjects/opcua/OPCUAClient.pem", "/Users/watarium/PycharmProjects/opcua/OPCUAServer.der", mode) # 認証設定 if setCert == certs[1]: # user/pass cl.set_user("admin") cl.set_password("1234") elif setCert == certs[2]: # certificate cl.load_private_key( "/Users/watarium/PycharmProjects/opcua/OPCUAClient.pem") cl.load_client_certificate( "/Users/watarium/PycharmProjects/opcua/OPCUA_CL.der") try: # 接続 print("Policy: {0}, Certificate: {1}".format(secPolicy, setCert)) print("---------------------Connection start-----------------------") cl.connect() sleep(5) # 情報取得 ep = cl.get_endpoints() print(ep[0].Server.ApplicationUri) root = cl.get_root_node() print("Objects node is: ", root) print(cl.get_namespace_array()) print(cl.get_namespace_index('urn:win-9hi38ajrojd:Cogent DataHub')) #これがうまくいかなかった(2019/06/27) #node = cl.get_node('ns=1;s=xxxxx') #print(node.get_value()) #node.set_attribute(ua.AttributeIds.Value, 1) # 切断 cl.disconnect() print("-------------------Connection Success!!!--------------------") except Exception as e: print("---------------------Connection Faild!!---------------------") print(e) cl.disconnect()
def OPC_Connect(): client = Client("opc.tcp://DESKTOP-G25O981:4840") client.connect() root = client.get_root_node() objects = client.get_root_node() return objects
def uaclient(): parser = argparse.ArgumentParser(description="Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable") add_common_args(parser) parser.add_argument("-c", "--certificate", help="set client certificate") parser.add_argument("-k", "--private_key", help="set client private key") args = parser.parse_args() logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) client = Client(args.url, timeout=args.timeout) client.connect() if args.certificate: client.load_certificate(args.certificate) if args.private_key: client.load_certificate(args.private_key) try: root = client.get_root_node() objects = client.get_objects_node() mynode = client.get_node(args.nodeid) if args.path: mynode = mynode.get_child(args.path.split(",")) embed() finally: client.disconnect() sys.exit(0)
def main_c(): # url = "opc.tcp://127.0.0.1:12345/" # # url = "opc.tcp://127.0.0.1:12346/test" # c = Client(url) # try: # c.connect() # root = c.get_root_node() # print("\r\nBrower:") # brower_child2(root.get_child(["0:Objects"]), -1, ["Server"]) # except Exception as e: # print("Client Exception:", e) # finally: # c.disconnect() url = "opc.tcp://127.0.0.1:12345/" # url = "opc.tcp://127.0.0.1:12346/test" c = Client(url) try: c.connect() root = c.get_root_node() print("\r\nBrower:") brower_child2(root.get_child(["0:Objects"]), -1, ["Server"]) except Exception as e: print("Client Exception:", e) finally: c.disconnect()
def start_loop(self): interrupted = False while not interrupted: client_sigvib_server = None try: client_sigvib_server = Client(CLIENT_SIGVIB_SERVER) client_sigvib_server.connect() self.root_sig_vib = client_sigvib_server.get_root_node() logger.info("Started Sigmatek Vibration loop") while True: # Send vibration if timeout is reached or difference exceeds 0.005m/s self.fetch_vibration_x() self.fetch_vibration_y() time.sleep(INTERVAL) except KeyboardInterrupt: logger.info("KeyboardInterrupt, gracefully closing") if client_sigvib_server: client_sigvib_server.disconnect() pr_client.disconnect() interrupted = True except Exception as e: logger.warning( "Exception Sigmatek Vibration loop, Reconnecting in 60 seconds: {}" .format(e)) time.sleep(60)
def start_loop(self): interrupted = False while not interrupted: client_sigshelf_server = None try: client_sigshelf_server = Client(CLIENT_SIGSHELF_SERVER) client_sigshelf_server.connect() self.root_sig_shelf = client_sigshelf_server.get_root_node() logger.info("Started Sigmatek Shelf loop") while True: self.fetch_shelf_data() time.sleep(INTERVAL) except KeyboardInterrupt: logger.info("KeyboardInterrupt, gracefully closing") if client_sigshelf_server: client_sigshelf_server.disconnect() pr_client.disconnect() interrupted = True except Exception as e: logger.warning( "Exception Sigmatek Shelf loop, Reconnecting in 60 seconds: {}" .format(e)) time.sleep(60)
def start_loop(self): interrupted = False while not interrupted: client_pixtend_server = None try: client_pixtend_server = Client(CLIENT_PIXTEND_SERVER) client_pixtend_server.connect() self.root_pixtend = client_pixtend_server.get_root_node() logger.info("Started PiXtend loop") while True: # upsert_panda_state() self.fetch_conbelt_state() self.fetch_conbelt_dist() # self.fetch_light_state() #TODO doesn't work right now # self.fetch_belt_state() #TODO what is that metric? time.sleep(INTERVAL) except KeyboardInterrupt: logger.info("KeyboardInterrupt, gracefully closing") if client_pixtend_server: client_pixtend_server.disconnect() pr_client.disconnect() interrupted = True except Exception as e: logger.warning( "Exception PiXtend loop, Reconnecting in 60 seconds: {}". format(e)) time.sleep(60)
def main(): client = Client("opc.tcp://localhost:4840/freeopcua/server/") try: client.connect() # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects root = client.get_root_node() print("Objects node is: ", root) print("Children of root are: ", root.get_children()) msclt = SubHandler() sub = client.create_subscription(100, msclt) ## subscribe to events myevent = root.get_child( ["0:Types", "0:EventTypes", "0:BaseEventType", "2:ThresholdEvent"]) print("MyFirstEventType is: ", myevent) handle = sub.subscribe_events(obj, myevent) myevent2 = root.get_child( ["0:Types", "0:EventTypes", "0:BaseEventType"]) print("MyFirstEventType is: ", myevent2) handle = sub.subscribe_events(obj, myevent2) while True: sleep(0.1) sub.unsubscribe(handle) sub.delete() finally: client.disconnect()
def uaclient(): parser = argparse.ArgumentParser( description= "Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable" ) add_common_args(parser) parser.add_argument("-c", "--certificate", help="set client certificate") parser.add_argument("-k", "--private_key", help="set client private key") args = parse_args(parser) client = Client(args.url, timeout=args.timeout) client.set_security_string(args.security) if args.certificate: client.load_client_certificate(args.certificate) if args.private_key: client.load_private_key(args.private_key) client.connect() try: root = client.get_root_node() objects = client.get_objects_node() mynode = get_node(client, args) embed() finally: client.disconnect() sys.exit(0)
def uaclient(): parser = argparse.ArgumentParser(description="Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable") add_common_args(parser) parser.add_argument("-c", "--certificate", help="set client certificate") parser.add_argument("-k", "--private_key", help="set client private key") args = parse_args(parser) client = Client(args.url, timeout=args.timeout) _configure_client_with_args(client, args) if args.certificate: client.load_client_certificate(args.certificate) if args.private_key: client.load_private_key(args.private_key) client.connect() try: root = client.get_root_node() objects = client.get_objects_node() mynode = get_node(client, args) embed() finally: client.disconnect() sys.exit(0)
def run(): configs = get_configs() patterns = configs["measures"].split(":") tout = configs["connection_timeout"].strip() timeout = 1 if len(tout) <= 0 else int(tout) client = Client(configs["connection"], timeout=timeout) try: client.connect() measures = [] root = client.get_root_node() collect_measures(measures, patterns, root) for x in root.get_children(): print x.get_browse_name().Name for m in measures: print m time.sleep(30) except Exception as ex: print ex finally: client.disconnect()
def _start_OPCUA_client(): # Set OPC UA server address and port or use defaults client = Client("opc.tcp://%s:%s/freeopcua/server/" % (OPCUA_HOST, OPCUA_PORT)) client.connect() root = client.get_root_node() imms = root.get_child(["0:Objects", "2:IMMS"]) while True: run_OPCUA_write_updates(imms) time.sleep(.2) # lets sleep a bit, to not utilize our CPU for 100% with this thread
def main_c(): url = "opc.tcp://127.0.0.1:4840/freeopcua/server/" #url = "opc.tcp://localhost:49320" c = Client(url) try: c.connect() root = c.get_root_node() print("\r\nBrower:") brower_child2(root.get_child(["0:Objects"]), -1, ["Server"]) except Exception as e: print("Client Exception:", e) finally: c.disconnect()
def clientOPCUA(h): r = '' global host global port url = "opc.tcp://" + host[h] + ":" + port[h] + "/server/" try: client = Client(url) client.connect() r = client.get_root_node() except Exception as e: r = '' pass return r
def start_uaprogramm(self, name, serverurl, port, uamethod="start_demoprogramm"): """ ruft die UA Methode über den im Docker erzeugten Client auf """ # Suche, ob der Container existiert clientname = name + "client" self._refresh_registry() container = self.registry.get(clientname) if container: connectstring = "opc.tcp://" + serverurl + ":" + port + "/freeopcua/server/" client = Client(connectstring) # client = Client("opc.tcp://admin@localhost:4840/freeopcua/server/") try: client.connect() client.load_type_definitions() # # Der Client verfügt über einige Methoden, um einen Proxy für UA-Knoten abzurufen, # die sich immer im Adressraum befinden sollten, z. B. Root oder Objects root = client.get_root_node() print("Root node is: ", root) objects = client.get_objects_node() print("Objects node is: ", objects) # Knotenobjekte verfügen über Methoden zum Lesen und Schreiben von Knotenattributen sowie zum Duchsuchen # des Adressraums print("Children of root are: ", root.get_children()) # Der Adressraum idx uri = "http://freeopcua.github.io" idx = client.get_namespace_index(uri) # Jetzt wird ein variabler Knoten über den Suchpfad abgerufen myvar = root.get_child([ "0:Objects", "{}:MyObject".format(idx), "{}:MyVariable".format(idx) ]) obj = root.get_child(["0:Objects", "{}:MyObject".format(idx)]) # Aufrufen unserer übergebenen Methode res = obj.call_method(uamethod.format(idx)) finally: client.disconnect()
def test_udf_call_builtins(self): client = Client("opc.tcp://localhost:4840") try: client.connect() root = client.get_root_node() objects = client.get_objects_node() obj = root.get_child(["0:Objects", "2:DataProcPlugin"]) print("\nSet UDF to udf_call_builtins.py and wait for 10 secs") ret = obj.call_method("2:set_udf_file", "udf_call_builtins.py") self.assertEqual(ret, ['0', 'Success']) time.sleep(10) except BaseException: self.assertTrue(False) finally: client.disconnect()
class UaClient(object): def __init__(self, server_ip): self.server_ip = server_ip self.client = Client(self.server_ip) print('Try to connect', self.server_ip) self.client.connect() print('Connected!') self.root = self.client.get_root_node() self.device = self.root.get_child(['0:Objects', '2:device']) self.device_obj = Device(self.device) self.device_id = self.device.get_child(['2:device_id']).get_value() self.location_x = self.device.get_child(['2:location_x']) self.location_y = self.device.get_child(['2:location_y']) self.direction = self.device.get_child(['2:direction']) self.status = self.device.get_child(['2:status']) self.network_condition = self.device.get_child(['2:network_condition']) handler = SubHandler(self) sub = self.client.create_subscription(500, handler) sub.subscribe_data_change(self.location_x) sub.subscribe_data_change(self.location_y) sub.subscribe_data_change(self.direction) sub.subscribe_data_change(self.network_condition) sub.subscribe_data_change(self.status) def go_front(self): self.device.call_method('2:go_front') def go_back(self): self.device.call_method('2:go_back') def turn_left(self): self.device.call_method('2:turn_left') def turn_right(self): self.device.call_method('2:turn_right') def go_to(self, target_x, target_y): self.device.call_method('2:go_to', target_x, target_y) def get_status(self): return Device(self.device).get_status() def disconnect(self): self.client.disconnect()
class ProductClass: def __init__(self): self.url = URL self.ua_c = None self.root_node = None self.s7_root_node = None self.mod_root_node = None self.redis_c = None self.nodes_list = None # ua client def ua_client(self): self.ua_c = Client(url=self.url) try: self.ua_c.connect() self.root_node = self.ua_c.get_root_node().get_child( ["0:Objects", "1:WinCC", "1:@LOCALMACHINE::"]) self.s7_root_node = self.root_node.get_child( ["1:SIMATIC S7-1200, S7-1500 Channel"]) self.mod_root_node = self.root_node.get_child(["1:Modbus TCPIP"]) self.get_nodes([self.s7_root_node, self.mod_root_node]) except Exception as e: print(e) logger.warning(e) finally: self.ua_c.disconnect() # 获取节点 def get_nodes(self, nodes=[]): #index = 1 while len(nodes): node = nodes.pop() c_name = node.get_node_class().name b_name = node.get_browse_name().Name if c_name == "Variable": if ua.AccessLevel.CurrentRead in node.get_access_level(): # yield node # R1.set(index, str(node)) R1.sadd('nodes', str(node)) # index += 1 # logger.debug(f"节点遍历{round(index / 4187 * 100, 1)}%") elif c_name == "Object" and b_name not in [ "WNTS01", "WNTS02", "WNTS03" ]: for i in node.get_children(): nodes.append(i) else: continue
def download_xst(subband: int, integration_time_s: int, url: str = 'localhost', port: int = 50000): """ Download cross correlation statistics Args: subband (int): Subband number integration_time_s (int): Integration time in seconds url (str): URL to connect to, defaults to 'localhost' port (str): Port to connect to, defaults to 50000 Returns: Tuple[datetime.datetime, np.ndarray, int]: UTC time, visibilities (shape n_ant x n_ant), RCU mode Raises: RuntimeError: if in mixed RCU mode """ client = Client("opc.tcp://{}:{}/".format(url, port), timeout=1000) client.connect() client.load_type_definitions() objects = client.get_objects_node() idx = client.get_namespace_index(DEFAULT_URI) obj = client.get_root_node().get_child( ["0:Objects", "{}:StationMetrics".format(idx), "{}:RCU".format(idx)]) obstime, visibilities_opc, rcu_modes = obj.call_method( "{}:record_cross".format(idx), subband, integration_time_s) client.close_session() client.close_secure_channel() rcu_modes_on = set([mode for mode in rcu_modes if mode != '0']) if len(rcu_modes_on) == 1: rcu_mode = int(rcu_modes_on.pop()) elif len(rcu_modes_on) == 0: rcu_mode = 0 else: raise RuntimeError( "Multiple nonzero RCU modes are used, that's not supported yet") assert (len(visibilities_opc) == 2) # Real and complex part visibilities = np.array(visibilities_opc)[0] + 1j * np.array( visibilities_opc[1]) return obstime, visibilities, rcu_mode
def start(): address = args['address'] server_url = "opc.tcp://{}/mp_opua_test/".format(address) client = Client(server_url) try: # Start the client client.connect() # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects root = client.get_root_node() print("Objects node is: ", root) # Node objects have methods to read and write node attributes as well as browse or populate address space print("Children of root are: ", root.get_children()) finally: client.disconnect()
def main(): client = Client("opc.tcp://*****:*****@localhost:4840/freeopcua/server/") #connect using a user try: client.connect() # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects root = client.get_root_node() print("Objects node is: ", root) # Node objects have methods to read and write node attributes as well as browse or populate address space print("Children of root are: ", root.get_children()) # get a specific node knowing its node id #var = client.get_node(ua.NodeId(1002, 2)) #var = client.get_node("ns=3;i=2002") #print(var) #var.get_data_value() # get value of node as a DataValue object #var.get_value() # get value of node as a python builtin #var.set_value(ua.Variant([23], ua.VariantType.Int64)) #set node value using explicit data type #var.set_value(3.9) # set node value using implicit data type # Now getting a variable node using its browse path obj = root.get_child(["0:Objects", "2:Parameters"]) # parameters temp_param = root.get_child( ["0:Objects", "2:Parameters", "2:Temperature"]) pres_param = root.get_child( ["0:Objects", "2:Parameters", "2:Pressure"]) time_param = root.get_child(["0:Objects", "2:Parameters", "2:Time"]) print("Node is: ", obj) while True: print("Temperature is: ", temp_param.get_value()) print("Pressure is: ", pres_param.get_value()) print("Time is: ", time_param.get_value()) time.sleep(1) # Stacked myvar access # print("myvar is: ", root.get_children()[0].get_children()[1].get_variables()[0].get_value()) finally: client.disconnect()
def run(self): print('Thread running') url = "opc.tcp://10.8.0.14:4840" client = Client(url) client.connect() print("Client Connected") client.load_type_definitions() #while True: root = client.get_root_node() print("Root 노드: ", root) objects = client.get_objects_node() print("오브젝트: ", objects) print("Children of root are: ", objects.get_children())
def test_1_set_udf_enabled(self): client = Client("opc.tcp://localhost:4840") try: client.connect() root = client.get_root_node() objects = client.get_objects_node() obj = root.get_child(["0:Objects", "2:DataProcPlugin"]) print("\nDisable UDF and wait for 10 secs") ret = obj.call_method("2:set_udf_enabled", "false") self.assertEqual(ret, ['0', 'Success']) time.sleep(10) print("\nRe-enable UDF and wait for 10 secs") ret = obj.call_method("2:set_udf_enabled", "true") self.assertEqual(ret, ['0', 'Success']) time.sleep(10) except BaseException: self.assertTrue(False) finally: client.disconnect()
def test_0_ua_client(self): client = Client("opc.tcp://localhost:4840") try: client.connect() root = client.get_root_node() print("Root node is: ", root.__dict__) print("Children of root are: ", root.get_children()) objects = client.get_objects_node() print("Objects node is: ", objects) print("Children of objects are: ", objects.get_children()) obj = root.get_child(["0:Objects", "2:DataProcPlugin"]) print("dataprocplugin obj is ", obj) except BaseException: self.assertTrue( False, msg="Error checking DataProcPlugin in OPC-UA registry") finally: client.disconnect()
def main(): srv_url = "opc.tcp://127.0.0.1:XXXX/FearFactory/supervision_unit/" client = Client(srv_url) client.connect() root = client.get_root_node() objs = client.get_objects_node() # Subscribe to the main board event_obj = root.get_child("2:MainBoard") handler = SubscriptionHandler() subscription = client.create_subscription(500, handler) event_type = root.get_child( ["0:Types", "0:EventTypes", "0:BaseEventType", "2:MainBoardNotif"]) hilt = subscription.subscribe_events(event_obj, event_type) #subscription.unsubscribe(hilt) #subscription.delete() # Uncomment if you want to interact with server using IPython embed()
def lambda_handler(event, context): """ Handler for the AWS Lambda function. :param event: AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type. :param context: The AWS Lambda event context. To learn more about what is included in the context, see https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html. """ logger.debug('Handling event: %s', json.dumps(event)) client = Client(SERVER_URL) try: client.connect() root = client.get_root_node() logger.debug("Root node is: %s", root) objects = client.get_objects_node() logger.debug("Objects node is: %s", objects) # Node objects have methods to read and write node attributes as well as browse or populate address space logger.debug("Children of root are: %s", root.get_children()) logger.debug('Creating subscription...') subscription_handler = SubscriptionHandler() subscription = client.create_subscription(500, subscription_handler) logger.info('Finished creating subscription to %s', SERVER_URL) logger.debug('Subscribing to data changes...') variable = root.get_child(["0:Objects", "2:MyObject", "2:MyVariable"]) handle = subscription.subscribe_data_change(variable) logger.info('Subscribed to %s', handle) while True: time.sleep(1) finally: client.disconnect()
def main_c(url_p): url = url_p # url = "opc.tcp://127.0.0.1:12346/test" c = Client(url) rs = [] try: try: c.connect() except Exception as e: print('e====', e) return "连接错误", rs root = c.get_root_node() print("\r\nBrower:") rs = brower_child2(root.get_child(["0:Objects"]), -1, ["Server"]) # print('rs====',rs) except Exception as e: print("Client Exception:", e) # c.disconnect() return "opcua client 错误", rs finally: c.disconnect() return "查询成功", rs
def start_loop(self): interrupted = False while not interrupted: client_panda_server = None try: client_panda_server = Client(CLIENT_PANDA_SERVER) client_panda_server.connect() self.root_panda = client_panda_server.get_root_node() logger.info("Started Panda loop") while True: self.fetch_panda_state() time.sleep(INTERVAL) except KeyboardInterrupt: logger.info("KeyboardInterrupt, gracefully closing") if client_panda_server: client_panda_server.disconnect() interrupted = True except Exception as e: # Suppressing warning, as the panda runs only occasionally # logger.warning("Exception Panda loop, Reconnecting in 60 seconds.", e) time.sleep(60)
class OpcuaSubClient(): def __init__(self, sub_handler=SubHandler): self.server_uri = "opc.tcp://localhost:4840" self.client = Client(self.server_uri) self.is_connect = False self.sub = None self.root = None self.sub_handler = sub_handler() self.handle = None self.connect() def connect(self): try: self.client.connect() self.is_connect = True self.root = self.client.get_root_node() self.sub = self.client.create_subscription(1000, self.sub_handler) except Exception as e: self.is_connect = False raise e def dis_connect(self): if self.is_connect: self.client.disconnect() self.is_connect = False self.root = None self.sub = None def subscribe(self, qualified_list): val_node = self.root.get_child(qualified_list) if val_node: self.handle = self.sub.subscribe_data_change(val_node) def unsubscribe(self): if self.handle: self.sub.unsubscribe(self.handle)
class OpcUaConnector(Thread, Connector): def __init__(self, gateway, config, connector_type): self._connector_type = connector_type self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0} super().__init__() self.__gateway = gateway self.__server_conf = config.get("server") self.__interest_nodes = [] self.__available_object_resources = {} self.__show_map = self.__server_conf.get("showMap", False) self.__previous_scan_time = 0 for mapping in self.__server_conf["mapping"]: if mapping.get("deviceNodePattern") is not None: self.__interest_nodes.append( {mapping["deviceNodePattern"]: mapping}) else: log.error( "deviceNodePattern in mapping: %s - not found, add property deviceNodePattern to processing this mapping", dumps(mapping)) if "opc.tcp" not in self.__server_conf.get("url"): opcua_url = "opc.tcp://" + self.__server_conf.get("url") else: opcua_url = self.__server_conf.get("url") self.client = Client( opcua_url, timeout=self.__server_conf.get("timeoutInMillis", 4000) / 1000) if self.__server_conf["identity"]["type"] == "cert.PEM": try: ca_cert = self.__server_conf["identity"].get("caCert") private_key = self.__server_conf["identity"].get("privateKey") cert = self.__server_conf["identity"].get("cert") security_mode = self.__server_conf["identity"].get( "mode", "SignAndEncrypt") policy = self.__server_conf["security"] if cert is None or private_key is None: log.exception( "Error in ssl configuration - cert or privateKey parameter not found" ) raise security_string = policy + ',' + security_mode + ',' + cert + ',' + private_key if ca_cert is not None: security_string = security_string + ',' + ca_cert self.client.set_security_string(security_string) except Exception as e: log.exception(e) if self.__server_conf["identity"].get("username"): self.client.set_user( self.__server_conf["identity"].get("username")) if self.__server_conf["identity"].get("password"): self.client.set_password( self.__server_conf["identity"].get("password")) self.setName( self.__server_conf.get( "name", 'OPC-UA ' + ''.join(choice(ascii_lowercase) for _ in range(5))) + " Connector") self.__opcua_nodes = {} self._subscribed = {} self.data_to_send = [] self.__sub_handler = SubHandler(self) self.__stopped = False self.__connected = False self.daemon = True def is_connected(self): return self.__connected def open(self): self.__stopped = False self.start() log.info("Starting OPC-UA Connector") def run(self): while not self.__connected: try: self.__connected = self.client.connect() try: self.client.load_type_definitions() except Exception as e: log.debug(e) log.debug("Error on loading type definitions.") log.debug(self.client.get_namespace_array()[-1]) log.debug( self.client.get_namespace_index( self.client.get_namespace_array()[-1])) except ConnectionRefusedError: log.error( "Connection refused on connection to OPC-UA server with url %s", self.__server_conf.get("url")) time.sleep(10) except OSError: log.error( "Connection refused on connection to OPC-UA server with url %s", self.__server_conf.get("url")) time.sleep(10) except Exception as e: log.debug("error on connection to OPC-UA server.") log.error(e) time.sleep(10) else: self.__connected = True log.info("OPC-UA connector %s connected to server %s", self.get_name(), self.__server_conf.get("url")) self.__opcua_nodes["root"] = self.client.get_objects_node() self.__opcua_nodes["objects"] = self.client.get_objects_node() if not self.__server_conf.get("disableSubscriptions", False): self.__sub = self.client.create_subscription( self.__server_conf.get("subCheckPeriodInMillis", 500), self.__sub_handler) else: self.__sub = False self.__scan_nodes_from_config() self.__previous_scan_time = time.time() * 1000 log.debug('Subscriptions: %s', self.subscribed) log.debug("Available methods: %s", self.__available_object_resources) while not self.__stopped: try: time.sleep(.1) self.__check_connection() if not self.__connected and not self.__stopped: self.client.connect() elif not self.__stopped: if self.__server_conf.get( "disableSubscriptions", False ) and time.time( ) * 1000 - self.__previous_scan_time > self.__server_conf.get( "scanPeriodInMillis", 60000): self.__scan_nodes_from_config() self.__previous_scan_time = time.time() * 1000 if self.data_to_send: self.__gateway.send_to_storage(self.get_name(), self.data_to_send.pop()) if self.__stopped: self.close() break except (KeyboardInterrupt, SystemExit): self.close() raise except ConnectionRefusedError: log.error( "Connection refused on connection to OPC-UA server with url %s", self.__server_conf.get("url")) time.sleep(10) except Exception as e: self.close() log.exception(e) def __check_connection(self): try: node = self.client.get_root_node() node.get_children() self.__connected = True except ConnectionRefusedError: self.__connected = False self._subscribed = {} self.__sub = None except OSError: self.__connected = False self._subscribed = {} self.__sub = None except TimeoutError: self.__connected = False self._subscribed = {} self.__sub = None except AttributeError: self.__connected = False self._subscribed = {} self.__sub = None except Exception as e: self.__connected = False self._subscribed = {} self.__sub = None log.exception(e) def close(self): self.__stopped = True if self.__connected: self.client.disconnect() self.__connected = False log.info('%s has been stopped.', self.get_name()) def get_name(self): return self.name def on_attributes_update(self, content): log.debug(content) try: for server_variables in self.__available_object_resources[ content["device"]]['variables']: for attribute in content["data"]: for variable in server_variables: if attribute == variable: server_variables[variable].set_value( content["data"][variable]) except Exception as e: log.exception(e) def server_side_rpc_handler(self, content): try: for method in self.__available_object_resources[ content["device"]]['methods']: rpc_method = content["data"].get("method") if rpc_method is not None and method.get( rpc_method) is not None: arguments_from_config = method["arguments"] arguments = content["data"].get( "params") if content["data"].get( "params") is not None else arguments_from_config try: if type(arguments) is list: result = method["node"].call_method( method[rpc_method], *arguments) elif arguments is not None: result = method["node"].call_method( method[rpc_method], arguments) else: result = method["node"].call_method( method[rpc_method]) self.__gateway.send_rpc_reply( content["device"], content["data"]["id"], { content["data"]["method"]: result, "code": 200 }) log.debug("method %s result is: %s", method[rpc_method], result) except Exception as e: log.exception(e) self.__gateway.send_rpc_reply(content["device"], content["data"]["id"], { "error": str(e), "code": 500 }) else: log.error("Method %s not found for device %s", rpc_method, content["device"]) self.__gateway.send_rpc_reply( content["device"], content["data"]["id"], { "error": "%s - Method not found" % (rpc_method), "code": 404 }) except Exception as e: log.exception(e) def __scan_nodes_from_config(self): try: if self.__interest_nodes: for device_object in self.__interest_nodes: for current_device in device_object: try: device_configuration = device_object[ current_device] devices_info_array = self.__search_general_info( device_configuration) for device_info in devices_info_array: if device_info is not None and device_info.get( "deviceNode") is not None: self.__search_nodes_and_subscribe( device_info) self.__save_methods(device_info) self.__search_attribute_update_variables( device_info) else: log.error( "Device node is None, please check your configuration." ) log.debug( "Current device node is: %s", str( device_configuration.get( "deviceNodePattern"))) break except Exception as e: log.exception(e) log.debug(self.__interest_nodes) except Exception as e: log.exception(e) def __search_nodes_and_subscribe(self, device_info): information_types = { "attributes": "attributes", "timeseries": "telemetry" } for information_type in information_types: for information in device_info["configuration"][information_type]: information_key = information["key"] config_path = TBUtility.get_value(information["path"], get_tag=True) information_path = self._check_path(config_path, device_info["deviceNode"]) information["path"] = '${%s}' % information_path information_nodes = [] self.__search_node(device_info["deviceNode"], information_path, result=information_nodes) for information_node in information_nodes: if information_node is not None: information_value = information_node.get_value() log.debug( "Node for %s \"%s\" with path: %s - FOUND! Current values is: %s", information_type, information_key, information_path, str(information_value)) if device_info.get("uplink_converter") is None: configuration = { **device_info["configuration"], "deviceName": device_info["deviceName"], "deviceType": device_info["deviceType"] } if device_info["configuration"].get( 'converter') is None: converter = OpcUaUplinkConverter(configuration) else: converter = TBUtility.check_and_import( self._connector_type, configuration) device_info["uplink_converter"] = converter else: converter = device_info["uplink_converter"] self.subscribed[information_node] = { "converter": converter, "path": information_path, "config_path": config_path } if not device_info.get( information_types[information_type]): device_info[ information_types[information_type]] = [] converted_data = converter.convert( (config_path, information_path), information_value) self.statistics['MessagesReceived'] += 1 self.data_to_send.append(converted_data) self.statistics['MessagesSent'] += 1 if self.__sub is None: self.__sub = self.client.create_subscription( self.__server_conf.get( "subCheckPeriodInMillis", 500), self.__sub_handler) if self.__sub: self.__sub.subscribe_data_change(information_node) log.debug("Added subscription to node: %s", str(information_node)) log.debug("Data to ThingsBoard: %s", converted_data) else: log.error( "Node for %s \"%s\" with path %s - NOT FOUND!", information_type, information_key, information_path) def __save_methods(self, device_info): try: if self.__available_object_resources.get( device_info["deviceName"]) is None: self.__available_object_resources[ device_info["deviceName"]] = {} if self.__available_object_resources[ device_info["deviceName"]].get("methods") is None: self.__available_object_resources[ device_info["deviceName"]]["methods"] = [] if device_info["configuration"].get("rpc_methods"): node = device_info["deviceNode"] for method_object in device_info["configuration"][ "rpc_methods"]: method_node_path = self._check_path( method_object["method"], node) methods = [] self.__search_node(node, method_node_path, True, result=methods) for method in methods: if method is not None: node_method_name = method.get_display_name().Text self.__available_object_resources[ device_info["deviceName"]]["methods"].append({ node_method_name: method, "node": node, "arguments": method_object.get("arguments") }) else: log.error( "Node for method with path %s - NOT FOUND!", method_node_path) except Exception as e: log.exception(e) def __search_attribute_update_variables(self, device_info): try: if device_info["configuration"].get("attributes_updates"): node = device_info["deviceNode"] device_name = device_info["deviceName"] if self.__available_object_resources.get(device_name) is None: self.__available_object_resources[device_name] = {} if self.__available_object_resources[device_name].get( "variables") is None: self.__available_object_resources[device_name][ "variables"] = [] for attribute_update in device_info["configuration"][ "attributes_updates"]: attribute_path = self._check_path( attribute_update["attributeOnDevice"], node) attribute_nodes = [] self.__search_node(node, attribute_path, result=attribute_nodes) for attribute_node in attribute_nodes: if attribute_node is not None: self.__available_object_resources[device_name][ "variables"].append({ attribute_update["attributeOnThingsBoard"]: attribute_node }) else: log.error( "Attribute update node with path \"%s\" - NOT FOUND!", attribute_path) except Exception as e: log.exception(e) def __search_general_info(self, device): result = [] match_devices = [] self.__search_node(self.__opcua_nodes["root"], TBUtility.get_value(device["deviceNodePattern"], get_tag=True), result=match_devices) for device_node in match_devices: if device_node is not None: result_device_dict = { "deviceName": None, "deviceType": None, "deviceNode": device_node, "configuration": deepcopy(device) } name_pattern_config = device["deviceNamePattern"] name_expression = TBUtility.get_value(name_pattern_config, get_tag=True) if "${" in name_pattern_config and "}" in name_pattern_config: log.debug("Looking for device name") name_path = self._check_path(name_expression, device_node) device_name_node = [] self.__search_node(device_node, name_path, result=device_name_node) device_name_node = device_name_node[0] if device_name_node is not None: device_name_from_node = device_name_node.get_value() full_device_name = name_pattern_config.replace( "${" + name_expression + "}", str(device_name_from_node)).replace( name_expression, str(device_name_from_node)) else: log.error( "Device name node not found with expression: %s", name_expression) return else: full_device_name = name_expression result_device_dict["deviceName"] = full_device_name log.debug("Device name: %s", full_device_name) if device.get("deviceTypePattern"): device_type_expression = TBUtility.get_value( device["deviceTypePattern"], get_tag=True) if "${" in device_type_expression and "}" in device_type_expression: type_path = self._check_path(device_type_expression, device_node) device_type_node = [] self.__search_node(device_node, type_path, result=device_type_node) device_type_node = device_type_node[0] if device_type_node is not None: device_type = device_type_node.get_value() full_device_type = device_type_expression.replace( "${" + device_type_expression + "}", device_type).replace(device_type_expression, device_type) else: log.error( "Device type node not found with expression: %s", device_type_expression) full_device_type = "default" else: full_device_type = device_type_expression result_device_dict["deviceType"] = full_device_type log.debug("Device type: %s", full_device_type) else: result_device_dict["deviceType"] = "default" result.append(result_device_dict) else: log.error( "Device node not found with expression: %s", TBUtility.get_value(device["deviceNodePattern"], get_tag=True)) return result def __search_node(self, current_node, fullpath, search_method=False, result=[]): fullpath_pattern = regex.compile(fullpath) try: for child_node in current_node.get_children(): new_node = self.client.get_node(child_node) new_node_path = '\\\\.'.join( char.split(":")[1] for char in new_node.get_path(200000, True)) if self.__show_map: log.debug("SHOW MAP: Current node path: %s", new_node_path) new_node_class = new_node.get_node_class() # regex_fullmatch = re.fullmatch(fullpath, new_node_path.replace('\\\\.', '.')) or new_node_path.replace('\\\\', '\\') == fullpath regex_fullmatch = regex.fullmatch(fullpath_pattern, new_node_path.replace('\\\\.', '.')) or \ new_node_path.replace('\\\\', '\\') == fullpath.replace('\\\\', '\\') or \ new_node_path.replace('\\\\', '\\') == fullpath regex_search = fullpath_pattern.fullmatch(new_node_path.replace('\\\\.', '.'), partial=True) or \ new_node_path.replace('\\\\', '\\') in fullpath.replace('\\\\', '\\') # regex_search = re.search(new_node_path, fullpath.replace('\\\\', '\\')) if regex_fullmatch: if self.__show_map: log.debug( "SHOW MAP: Current node path: %s - NODE FOUND", new_node_path.replace('\\\\', '\\')) result.append(new_node) elif regex_search: if self.__show_map: log.debug( "SHOW MAP: Current node path: %s - NODE FOUND", new_node_path) if new_node_class == ua.NodeClass.Object: if self.__show_map: log.debug("SHOW MAP: Search in %s", new_node_path) self.__search_node(new_node, fullpath, result=result) elif new_node_class == ua.NodeClass.Variable: log.debug("Found in %s", new_node_path) result.append(new_node) elif new_node_class == ua.NodeClass.Method and search_method: log.debug("Found in %s", new_node_path) result.append(new_node) except Exception as e: log.exception(e) def _check_path(self, config_path, node): if re.search("^root", config_path.lower()) is None: node_path = '\\\\.'.join( char.split(":")[1] for char in node.get_path(200000, True)) if config_path[-3:] != '\\.': information_path = node_path + '\\\\.' + config_path.replace( '\\', '\\\\') else: information_path = node_path + config_path.replace( '\\', '\\\\') else: information_path = config_path return information_path[:] @property def subscribed(self): return self._subscribed
class ClientController: def __init__(self, view): self.ui = view self.client = None self._connected = False self.address_list = ["opc.tcp://10.42.0.2:4840/OPCUAproject"] self.security_mode = None self.security_policy = None self.certificate_path = None self.private_key_path = None self.ui.closeEvent = self.closeEvent for addr in self.address_list: self.ui.addressComboBox.addItem(addr) self.tree_ui = TreeWidget(self.ui.treeView) self.attrs_ui = AttrsWidget(self.ui.attrView) #self.refs_ui = RefsWidget(self.ui.refView) self.subscription_window = SubscriptionWindow() self.log_window = LogWindow() self.datachange_ui = DataChangeUI(self, self.subscription_window) #self.ui.treeView.selectionModel().selectionChanged.connect(lambda sel: self.show_refs(sel)) self.ui.treeView.selectionModel().selectionChanged.connect( lambda sel: self.show_attrs(sel)) # self.ui.endpointsButton.clicked.connect(lambda : self.get_endpoints()) # self.ui.connSettingsButton.clicked.connect(lambda : self.show_connection_dialog()) # self.ui.connectButton.clicked.connect(lambda : self.connect()) # self.ui.disconnectButton.clicked.connect(lambda: self.disconnect()) # self.ui.readButton.clicked.connect(lambda : self.read_value()) # self.ui.writeButton.clicked.connect(lambda : self.show_write_dialog()) # self.ui.showReferencesButton.clicked.connect(lambda : self.show_refs_dialog()) # self.ui.showSubscriptionsButton.clicked.connect(lambda : self.show_subs_dialog()) # self.ui.showLogsButton.clicked.connect(lambda : self.show_logs_dialog()) self.ui.actionQuery_endpoints.triggered.connect( lambda: self.get_endpoints()) self.ui.actionConnection_settings.triggered.connect( lambda: self.show_connection_dialog()) self.ui.actionConnect.triggered.connect(lambda: self.connect()) self.ui.actionDisconnect.triggered.connect(lambda: self.disconnect()) self.ui.actionRead.triggered.connect(lambda: self.read_value()) self.ui.actionWrite.triggered.connect(lambda: self.show_write_dialog()) self.ui.actionReferences.triggered.connect( lambda: self.show_refs_dialog()) self.ui.actionSubscriptions.triggered.connect( lambda: self.show_subs_dialog()) self.ui.actionLogs.triggered.connect(lambda: self.show_logs_dialog()) def closeEvent(self, event): self.disconnect() def get_endpoints(self): uri = self.ui.addressComboBox.currentText() client = Client(uri, timeout=2) try: edps = client.connect_and_get_server_endpoints() for i, ep in enumerate(edps, start=1): self.log_window.ui.logTextEdit.append('Endpoint %s:' % i) for (n, v) in endpoint_to_strings(ep): self.log_window.ui.logTextEdit.append(' %s: %s' % (n, v)) self.log_window.ui.logTextEdit.append('') except Exception as ex: self.log_window.ui.logTextEdit.append(str(ex)) raise return edps def show_connection_dialog(self): dia = ConnectionDialog(self, self.ui.addressComboBox.currentText()) #dia.security_mode = self.security_mode #dia.security_policy = self.security_policy #dia.certificate_path = self.certificate_path #dia.private_key_path = self.private_key_path ret = dia.exec_() if ret: #self.security_mode = dia.security_mode #self.security_policy = dia.security_policy self.certificate_path = dia.certificate_path self.private_key_path = dia.private_key_path def show_write_dialog(self): node = self.get_current_node() if node.get_node_class() == ua.NodeClass.Variable: dia = WriteDialog(node, self.log_window.ui.logTextEdit) ret = dia.exec_() else: self.log_window.ui.logTextEdit.append( "Only Variable can be written") def connect(self): self.disconnect() uri = self.ui.addressComboBox.currentText() self.log_window.ui.logTextEdit.append( "Connecting to %s with parameters %s, %s, %s, %s" % (uri, self.security_mode, self.security_policy, self.certificate_path, self.private_key_path)) try: self.client = Client(uri) self.client.application_uri = "urn:opcua:python:client" if self.security_mode is not None and self.security_policy is not None: self.client.set_security(getattr( crypto.security_policies, 'SecurityPolicy' + self.security_policy), self.certificate_path, self.private_key_path, mode=getattr(ua.MessageSecurityMode, self.security_mode)) self.client.connect() self._connected = True except Exception as ex: self.log_window.ui.logTextEdit.append(str(ex)) try: self.client.uaclient._uasocket._thread.isAlive() self.tree_ui.set_root_node(self.client.get_root_node()) self.ui.treeView.setFocus() except Exception as ex: print("Connection error") def _reset(self): self.client = None self._connected = False self.datachange_ui._datachange_sub = {} self.datachange_ui._subs_dc = {} def disconnect(self): try: if self._connected: self.log_window.ui.logTextEdit.append( "Disconnecting from server") self._connected = False if self.client: if self.datachange_ui._datachange_sub: sub_ids = list(self.datachange_ui._datachange_sub.keys()) for sub_id in sub_ids: self.datachange_ui.delete_subscription(sub_id) self.client.disconnect() self._reset() except Exception as ex: self.log_window.ui.logTextEdit.append(str(ex)) finally: self.tree_ui.clear() #self.refs_ui.clear() self.attrs_ui.clear() self.datachange_ui.clear() def show_attrs(self, selection): if isinstance(selection, QItemSelection): if not selection.indexes(): # no selection return node = self.get_current_node() if node: self.attrs_ui.show_attrs(node) '''def show_refs(self, selection): if isinstance(selection, QItemSelection): if not selection.indexes(): # no selection return node = self.get_current_node() if node: self.refs_ui.show_refs(node)''' def show_refs_dialog(self): self.references_window = ReferencesWindow(self) self.references_window.show() def show_subs_dialog(self): self.subscription_window.show() def show_logs_dialog(self): self.log_window.show() def get_current_node(self, idx=None): return self.tree_ui.get_current_node(idx) def read_value(self): node = self.get_current_node() try: self.attrs_ui.show_attrs(node) if node.get_node_class() == ua.NodeClass.Variable: value = node.get_value() data = "Node: %s, Value: %s" % (node.get_browse_name(), value) self.log_window.ui.logTextEdit.append(data) except Exception as ex: self.log_window.ui.logTextEdit.append(str(ex))
class UaClient(object): """ OPC-Ua client specialized for the need of GUI client return exactly whant GUI needs, no customization possible """ def __init__(self): self.client = None self._connected = False self._subscription = None def connect(self, uri): self.disconnect() print("Connecting to ", uri) self.client = Client(uri) self.client.connect() self._connected = True print("Connected, root is: ", self.client.get_root_node()) print(self.get_root_attrs()) def disconnect(self): if self._connected: print("Disconnecting from server") self._connected = False self._subscription = None self.client.disconnect() self.client = None def subscribe(self, node, handler): if not self._subscription: self._subscription = self.client.create_subscription(500, handler) self._subscription.subscribe_data_change(node) def get_root_attrs(self): return self.get_node_attrs(self.client.get_root_node()) def get_node_attrs(self, node): if not type(node) is Node: node = self.client.get_node(node) attrs = node.get_attributes([AttributeIds.DisplayName, AttributeIds.BrowseName, AttributeIds.NodeId]) return [node] + [attr.Value.Value.to_string() for attr in attrs] def get_children(self, node): descs = node.get_children_descriptions() children = [] for desc in descs: children.append([self.client.get_node(desc.NodeId), desc.DisplayName.to_string(), desc.BrowseName.to_string(), desc.NodeId.to_string()]) return children def get_all_attrs(self, node): names = [] vals = [] for name, val in ua.AttributeIds.__dict__.items(): if not name.startswith("_"): names.append(name) vals.append(val) attrs = node.get_attributes(vals) res = {} for idx, name in enumerate(names): if attrs[idx].StatusCode.is_good(): res[name] = attrs[idx].Value.Value return res def get_all_refs(self, node): return node.get_children_descriptions(refs=ObjectIds.References)
def run(): logger.info("Modular Input mi_opcua_subscription command: %s" % sys.argv) if len(sys.argv) > 1: try: if sys.argv[1] == "--scheme": do_scheme() elif sys.argv[1] == "--validate-arguments": validate_arguments() elif sys.argv[1] == "--test": test() else: usage() except Exception as ex: logger.critical(ex) else: logger.info("Modular Input mi_opcua_subscription Starts data collection.") configs = get_config() stanza = configs["name"] # server_uri = configs["server_uri"] # sessionKey = configs["session_key"] # userName = "******" # make this modular input as application context only. patterns = configs["measures"].split(":") tout = configs["connection_timeout"].strip() timeout = 1 if len(tout) <= 0 else int(tout) ct = configs["collect_duration"].strip() duration = 1000 if len(ct) <=0 else int(ct) conn = configs["connection"] ## "opc.tcp://ec2-54-190-162-94.us-west-2.compute.amazonaws.com:49320" if configs.has_key("username"): username = configs["username"].strip() if len(username)>0: password = configs["password"].strip() conn = "%s?username=%s&password=%s" % (conn, username, password) client = Client(conn, timeout=timeout) try: client.connect() measures = [] root = client.get_root_node() node.collect_measures(measures, patterns, root) subscribers = [] for m in measures: try: subscribers.append(m[len(m)-1]) except: logger.warn("The node of %s is invalid to subscribe." % m) handler = SubHandler(stanza) sub = client.create_subscription(duration, handler) dchandle = sub.subscribe_data_change(subscribers) def signal_handler(signal, frame): logger.info('Press Ctrl+C') if signal in [signal.SIGABRT, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]: sub.unsubscribe(dchandle) sub.delete() client.disconnect() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGABRT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGQUIT, signal_handler) signal.pause() except Exception as ex: logger.critical(ex) finally: sub.unsubscribe(dchandle) sub.delete() client.disconnect() logger.info("---- end of sub opc ua ----")
class UaClient(object): """ OPC-Ua client specialized for the need of GUI client return exactly whant GUI needs, no customization possible """ def __init__(self): self.client = None self._connected = False self._datachange_sub = None self._event_sub = None self._subs_dc = {} self._subs_ev = {} def connect(self, uri): self.disconnect() print("Connecting to ", uri) self.client = Client(uri) self.client.connect() self._connected = True def disconnect(self): if self._connected: print("Disconnecting from server") self._subs_dc = {} self._subs_ev = {} self._connected = False self._subscription = None self.client.disconnect() self.client = None def subscribe_datachange(self, node, handler): if not self._datachange_sub: self._datachange_sub = self.client.create_subscription(500, handler) handle = self._datachange_sub.subscribe_data_change(node) self._subs_dc[node.nodeid] = handle return handle def unsubscribe_datachange(self, node): self._datachange_sub.unsubscribe(self._subs_dc[node.nodeid]) def subscribe_events(self, node, handler): if not self._event_sub: print("subscirbing with handler: ", handler, dir(handler)) self._event_sub = self.client.create_subscription(500, handler) handle = self._event_sub.subscribe_events(node) self._subs_ev[node.nodeid] = handle return handle def unsubscribe_events(self, node): self._event_sub.unsubscribe(self._subs_ev[node.nodeid]) def get_root_node_and_desc(self): node = self.client.get_root_node() attrs = node.get_attributes([ua.AttributeIds.DisplayName, ua.AttributeIds.BrowseName, ua.AttributeIds.NodeId, ua.AttributeIds.NodeClass]) desc = ua.ReferenceDescription() desc.DisplayName = attrs[0].Value.Value desc.BrowseName = attrs[1].Value.Value desc.NodeId = attrs[2].Value.Value desc.NodeClass = attrs[3].Value.Value desc.TypeDefinition = ua.TwoByteNodeId(ua.ObjectIds.FolderType) return node, desc def get_node_attrs(self, node): if not isinstance(node, Node): node = self.client.get_node(node) attrs = node.get_attributes([ua.AttributeIds.DisplayName, ua.AttributeIds.BrowseName, ua.AttributeIds.NodeId]) return node, [attr.Value.Value.to_string() for attr in attrs] def get_children(self, node): descs = node.get_children_descriptions() children = [] for desc in descs: children.append((self.client.get_node(desc.NodeId), desc)) return children def get_all_attrs(self, node): names = [] vals = [] for name, val in ua.AttributeIds.__dict__.items(): if not name.startswith("_"): names.append(name) vals.append(val) attrs = node.get_attributes(vals) res = [] for idx, name in enumerate(names): if attrs[idx].StatusCode.is_good(): res.append((name, attrs[idx])) res.sort() return res def get_all_refs(self, node): return node.get_children_descriptions(refs=ua.ObjectIds.References)
class NodeXMLExporter: def __init__(self): self.nodes = [] self.namespaces = {} self.visited = [] self.client = None self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) def iterater_over_child_nodes(self, node): self.nodes.append(node) self.logger.debug("Add %s" % node) # iterate over all referenced nodes (31), only hierarchical references (33) for child in node.get_children(refs=33): if child not in self.nodes: self.iterater_over_child_nodes(child) def export_xml(self, namespaces=None, output_file="export.xml"): if namespaces: self.logger.info("Export only NS %s" % namespaces) nodes = [node for node in self.nodes if node.nodeid.NamespaceIndex in namespaces] else: nodes = self.nodes self.logger.info("Export nodes to %s" % output_file) exp = XmlExporter(self.client) exp.build_etree(nodes) exp.write_xml(output_file) self.logger.info("Export finished") def import_nodes(self, server_url="opc.tcp://localhost:16664"): from opcua.crypto import security_policies import types from opcua.ua.uaprotocol_hand import CryptographyNone self.client = Client(server_url) # Fix symmetric_key_size (not 0) of securityPolicy sec_policy = security_policies.SecurityPolicy() sec_policy.symmetric_key_size = 8 self.client.security_policy = sec_policy # Fix signature method of CryptographyNone def signature(self, data): return None fixed_signature = types.MethodType(signature, CryptographyNone) self.client.security_policy.asymmetric_cryptography.signature = fixed_signature try: self.client.connect() except Exception as e: self.logger.error("No connection established", e) self.logger.error(e) self.logger.error("Exiting ...") sys.exit() self.logger.info("Client connected to %s" % server_url) for ns in self.client.get_namespace_array(): self.namespaces[self.client.get_namespace_index(ns)] = ns root = self.client.get_root_node() self.logger.info("Starting to collect nodes. This may take some time ...") self.iterater_over_child_nodes(root) self.logger.info("All nodes collected") def statistics(self): types = {} for node in self.nodes: try: node_class = str(node.get_node_class()) ns = node.nodeid.NamespaceIndex if ns not in types: types[ns] = {} if node_class not in types[ns]: types[ns][node_class] = 1 else: types[ns][node_class] += 1 except Exception as e: self.logger.info("some error with %s: %s" % (node,e)) for ns in types: self.logger.info("NS%d (%s)" % (ns, self.namespaces[ns])) for type in types[ns]: self.logger.info("\t%s:\t%d" % (type, types[ns][type])) self.logger.info("\tTOTAL in namespace: %d" % len(self.nodes))
if __name__ == "__main__": logging.basicConfig(level=logging.WARN) #logger = logging.getLogger("KeepAlive") #logger.setLevel(logging.DEBUG) client = Client("opc.tcp://192.168.157.244:40840") # client = Client("opc.tcp://admin@localhost:4840/freeopcua/server/") #connect using a user try: client.connect() client.load_type_definitions( ) # load definition of server specific structures/extension objects # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects root = client.get_root_node() print("Root node is: ", root) objects = client.get_objects_node() #for t in obje print("Objects node is: ", objects) # Node objects have methods to read and write node attributes as well as browse or populate address space print("Children of root are: ", root.get_children()) # get a specific node knowing its node id #var = client.get_node(ua.NodeId(1002, 2)) #var = client.get_node("ns=3;i=2002") #print(var) #var.get_data_value() # get value of node as a DataValue object #var.get_value() # get value of node as a python builtin #var.set_value(ua.Variant([23], ua.VariantType.Int64)) #set node value using explicit data type
def data_change(self, handle, node, val, attr): print("Python: New data change event", handle, node, val, attr) def event(self, handle, event): print("Python: New event", handle, event) if __name__ == "__main__": #from IPython import embed logging.basicConfig(level=logging.WARN) client = Client("opc.tcp://*****:*****@localhost:53530/OPCUA/SimulationServer/") try: client.connect() root = client.get_root_node() print("Root is", root) print("childs of root are: ", root.get_children()) print("name of root is", root.get_browse_name()) objects = client.get_objects_node() print("childs og objects are: ", objects.get_children()) myfloat = client.get_node("ns=4;s=Float") mydouble = client.get_node("ns=4;s=Double") myint64 = client.get_node("ns=4;s=Int64") myuint64 = client.get_node("ns=4;s=UInt64") myint32 = client.get_node("ns=4;s=Int32") myuint32 = client.get_node("ns=4;s=UInt32") var = client.get_node(ua.NodeId("Random1", 5)) print("var is: ", var) print("value of var is: ", var.get_value())
def event_notification(self, event): try: print("Python: New event", event) except: print("event_notification failed") def publish_callback(self, publishresult): pass if __name__ == "__main__": vals = {} workerRunning = True client = Client("opc.tcp://localhost:4841", timeout=0.3) client.connect() print("Children of Objects are:") for n in client.get_root_node().get_child("0:Objects").get_children(): b = 1==int(n.get_attribute(ua.AttributeIds.WriteMask).Value.Value) if b: print(n.get_browse_name()) v = n.get_value() if type(v)==float: print("Adding writable float",n.get_browse_name()) labelFloat = QLineEdit(str(n.get_browse_name())) labelFloat.setReadOnly(True) inputFloat = QLineEdit(str(v)) def buttonPressed(inputFloat=inputFloat, n=n): try: n.set_value(float(inputFloat.text())) except: pass