def uals(): parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result") add_common_args(parser) parser.add_argument("-l", dest="long_format", const=3, nargs="?", type=int, help="use a long listing format") parser.add_argument("-d", "--depth", default=1, type=int, help="Browse depth") args = parse_args(parser) if args.long_format is None: args.long_format = 1 client = Client(args.url, timeout=args.timeout) _configure_client_with_args(client, args) client.connect() try: node = get_node(client, args) print("Browsing node {0} at {1}\n".format(node, args.url)) if args.long_format == 0: _lsprint_0(node, args.depth - 1) elif args.long_format == 1: _lsprint_1(node, args.depth - 1) else: _lsprint_long(node, args.depth - 1) finally: client.disconnect() sys.exit(0) print(args)
def uaread(): parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node") add_common_args(parser) parser.add_argument("-a", "--attribute", dest="attribute", type=int, default=ua.AttributeIds.Value, help="Set attribute to read") parser.add_argument("-t", "--datatype", dest="datatype", default="python", choices=['python', 'variant', 'datavalue'], help="Data type to return") args = parse_args(parser, requirenodeid=True) client = Client(args.url, timeout=args.timeout) client.connect() try: node = get_node(client, args) attr = node.get_attribute(args.attribute) if args.datatype == "python": print(attr.Value.Value) elif args.datatype == "variant": print(attr.Value) else: print(attr) finally: client.disconnect() sys.exit(0) print(args)
class TestClient(unittest.TestCase, CommonTests): ''' Run common tests on client side Of course we need a server so we start a server in another process using python Process module Tests that can only be run on client side must be defined here ''' @classmethod def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://localhost:%d' % port_num1) add_server_methods(self.srv) self.srv.start() # start client self.clt = Client('opc.tcp://localhost:%d' % port_num1) self.clt.connect() self.opc = self.clt @classmethod def tearDownClass(self): self.clt.disconnect() # stop the server in its own process self.srv.stop() def test_service_fault(self): request = ua.ReadRequest() request.TypeId = ua.FourByteNodeId(999) # bad type! with self.assertRaises(Exception): self.clt.bclient._send_request(request)
def wrapper(self): try: client = Client(URL) client.connect() func(self, client) finally: client.disconnect()
def test_basic256_encrypt_feil(self): # FIXME: how to make it feil??? clt = Client(self.uri_crypto) with self.assertRaises(ua.UaError): clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.None_ )
def get_endpoints(uri): client = Client(uri, timeout=2) client.connect_and_get_server_endpoints() edps = client.connect_and_get_server_endpoints() for i, ep in enumerate(edps, start=1): logger.info('Endpoint %s:', i) for (n, v) in endpoint_to_strings(ep): logger.info(' %s: %s', n, v) logger.info('') return edps
def opcua_init(request): client = Client( request.get('url', 'opc.tcp://localhost:4841'), timeout=request.get('timeout', 10) ) client.set_security_string(request.get('security', '')) client.connect() return client
class HelloClient: def __init__(self, endpoint): self.client = Client(endpoint) def __enter__(self): self.client.connect() return self.client def __exit__(self, exc_type, exc_val, exc_tb): self.client.disconnect()
def test_find_servers2(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: servers = client.find_servers() new_app_uri1 = "urn:freeopcua:python:server:test_discovery1" self.srv.application_uri = new_app_uri1 self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0) new_app_uri2 = "urn:freeopcua:python:test_discovery2" self.srv.application_uri = new_app_uri2 self.srv.register_to_discovery(self.discovery.endpoint.geturl(), period=0) time.sleep(0.1) # let server register registration new_servers = client.find_servers() self.assertEqual(len(new_servers) - len(servers) , 2) self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers]) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filer new_servers = client.find_servers(["urn:freeopcua:python:server"]) self.assertEqual(len(new_servers) - len(servers) , 0) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filer new_servers = client.find_servers(["urn:freeopcua:python"]) self.assertEqual(len(new_servers) - len(servers) , 2) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) finally: client.disconnect()
def test_find_servers2(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: servers = client.find_servers() # Use 2 different RegistrationServices, as it does not allow duplicate registrations. with RegistrationService() as regService1, RegistrationService() as regService2: # Register to server with uri1 new_app_uri1 = "urn:freeopcua:python:server:test_discovery1" self.srv.application_uri = new_app_uri1 regService1.register_to_discovery(self.srv, self.discovery.endpoint.geturl(), period=0) # Register to server with uri2 new_app_uri2 = "urn:freeopcua:python:test_discovery2" self.srv.application_uri = new_app_uri2 regService2.register_to_discovery(self.srv, self.discovery.endpoint.geturl(), period=0) # Check for 2 registrations time.sleep(0.1) # let server register registration new_servers = client.find_servers() self.assertEqual(len(new_servers) - len(servers) , 2) self.assertFalse(new_app_uri1 in [s.ApplicationUri for s in servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in servers]) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filter new_servers = client.find_servers(["urn:freeopcua:python:server"]) self.assertEqual(len(new_servers) - len(servers) , 0) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertFalse(new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filter new_servers = client.find_servers(["urn:freeopcua:python"]) self.assertEqual(len(new_servers) - len(servers) , 2) self.assertTrue(new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue(new_app_uri2 in [s.ApplicationUri for s in new_servers]) finally: client.disconnect()
def uasubscribe(): parser = argparse.ArgumentParser(description="Subscribe to a node and print results") add_common_args(parser) parser.add_argument("-t", "--eventtype", dest="eventtype", default="datachange", choices=['datachange', 'event'], help="Event type to subscribe to") args = parse_args(parser, requirenodeid=False) if args.eventtype == "datachange": _require_nodeid(parser, args) else: # FIXME: this is broken, someone may have written i=84 on purpose if args.nodeid == "i=84" and args.path == "": args.nodeid = "i=2253" client = Client(args.url, timeout=args.timeout) client.set_security_string(args.security) client.connect() try: node = get_node(client, args) handler = SubHandler() sub = client.create_subscription(500, handler) if args.eventtype == "datachange": sub.subscribe_data_change(node) else: sub.subscribe_events(node) embed() finally: client.disconnect() sys.exit(0) print(args)
def test_basic128Rsa15_encrypt(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic128Rsa15,SignAndEncrypt,examples/certificate-example.der,examples/private-key-example.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect()
def test_basic256(self): clt = Client(self.uri_crypto) try: clt.set_security_string("Basic256,Sign,examples/example-certificate.der,examples/example-private-key.pem") clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect()
def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://*****:*****@localhost:%d' % port_num1) self.clt.connect() self.opc = self.clt # start anonymous client self.ro_clt = Client('opc.tcp://localhost:%d' % port_num1) self.ro_clt.connect()
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 opc_snd_plc(): url = "opc.tcp://192.168.10.1:4840" rev_nodeid = 'ns=3;s="OPCUA_REV"."srm_mqtt_sub"' rev_flg_nodeid = 'ns=3;s="OPCUA_REV"."srm_mqtt_sub_flg"' with Client(url=url) as client: # 发送到PLC节点ID rev_srm_mqtt_sub = client.get_node(rev_nodeid) rev_srm_mqtt_sub_flg = client.get_node(rev_flg_nodeid) # 初始化同步PLC的数据 # 发送给PLC rev_srm_mqtt_sub_flg_value = rev_srm_mqtt_sub_flg.get_value() while True: # 发送PLC消息 rev_srm_mqtt_sub_value = q_opc.get() rev_srm_mqtt_sub.set_value( ua.DataValue( ua.Variant(rev_srm_mqtt_sub_value, ua.VariantType.String))) if rev_srm_mqtt_sub_flg_value >= 32767: rev_srm_mqtt_sub_flg_value = -32768 else: rev_srm_mqtt_sub_flg_value = rev_srm_mqtt_sub_flg_value + 1 rev_srm_mqtt_sub_flg.set_value( ua.DataValue( ua.Variant(rev_srm_mqtt_sub_flg_value, ua.VariantType.Int16))) q_opc.task_done()
def setUpClass(self): # start our own server self.srv = Server() self.srv.set_endpoint('opc.tcp://*****:*****@localhost:%d' % port_num1, timeout=10) self.clt.connect() self.opc = self.clt # start anonymous client self.ro_clt = Client('opc.tcp://localhost:%d' % port_num1) self.ro_clt.connect()
def __init__(self, name, endPointAddress, nameSpaceUri=None, browseRootNodeIdentifier=None): # ---------- Setup ----------- self.name = name self.logger = logging.getLogger(self.name) self.endPointAddress = endPointAddress self.nameSpaceUri = nameSpaceUri self.nameSpaceIndex = None self.browseRootNodeIdentifier = browseRootNodeIdentifier self.rootNodeId = None self.client = Client(self.endPointAddress, timeout=2) self.sub = None self.subscriptions = {}
def main(): config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'wtc.cfg')) opcnodes = [] with Client("opc.tcp://10.0.146.94:40843/freeopcua/server/") as client: client.connect() wtc = client.get_objects_node().get_child("0:WTC") wtc_items = wtc.get_children() qual = 0 for item in wtc_items: opcnodes.append( wtc.get_child( item.get_browse_name().to_string()).get_child("0:state")) if item.get_browse_name().to_string() == "0:CPU27/AS_EGRESS_REP": val = item.get_child("0:sample_quality") opcnodes.append(val) qual = val data = json.dumps(qual.get_value()) print("HTTP/1.1 200 Ok") print("Content-type: application/json") print("Content-length: " + str(len(data))) print() print(data) exit(0)
def connect(self, opc_name, init_status): self.client = Client(self.url) CRED = '\33[31m' CGREEN = '\33[32m' CEND = '\033[0m' try: self.client.connect() except socket.error: connect_status = False print(opc_name + CRED + " disconnected" + CEND) time.sleep(1) else: if init_status: print(opc_name + CGREEN + " connected" + CEND) connect_status = True return connect_status
def start_server_and_client(cls): cls.srv = Server() cls.srv.set_endpoint('opc.tcp://localhost:{0:d}'.format(port_num1)) cls.srv.start() cls.clt = Client('opc.tcp://localhost:{0:d}'.format(port_num1)) cls.clt.connect()
def connect(self) -> bool: """ Connect driver. : returns: True if connection stablished False if not """ try: self._connection = Client(self.url) self._connection.connect() except Exception as e: self.sendDebugInfo(f'Error connecting to server at {self.url}.') return False self.handler = SubHandler() self.subscription = self._connection.create_subscription(self.rpi, self.handler) return True
def opc_rev_plc(): url = "opc.tcp://192.168.10.1:4840" snd_nodeid = 'ns=3;s="OPCUA_SND"."srm_mqtt_pub"' snd_flg_nodeid = 'ns=3;s="OPCUA_SND"."srm_mqtt_pub_flg"' with Client(url=url) as client: # 接收自PLC节点ID snd_srm_mqtt_pub = client.get_node(snd_nodeid) snd_srm_mqtt_pub_flg = client.get_node(snd_flg_nodeid) # 初始化同步PLC的数据 # 接收自PLC # snd_srm_mqtt_pub_value = snd_srm_mqtt_pub.get_value() snd_srm_mqtt_pub_flg_value = snd_srm_mqtt_pub_flg.get_value() snd_srm_mqtt_pub_flg_value_old = snd_srm_mqtt_pub_flg_value while True: time.sleep(0.1) # 接收PLC消息 snd_srm_mqtt_pub_value = snd_srm_mqtt_pub.get_value() snd_srm_mqtt_pub_flg_value = snd_srm_mqtt_pub_flg.get_value() if snd_srm_mqtt_pub_value == '': pass elif snd_srm_mqtt_pub_flg_value != snd_srm_mqtt_pub_flg_value_old: print("PLC: " + snd_srm_mqtt_pub_value) if q_speak.empty(): q_speak.put(snd_srm_mqtt_pub_value) else: pass snd_srm_mqtt_pub_flg_value_old = snd_srm_mqtt_pub_flg_value
def test_find_servers2(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: servers = client.find_servers() # Use 2 different RegistrationServices, as it does not allow duplicate registrations. with RegistrationService() as regService1, RegistrationService( ) as regService2: # Register to server with uri1 new_app_uri1 = "urn:freeopcua:python:server:test_discovery1" self.srv.set_application_uri(new_app_uri1) regService1.register_to_discovery( self.srv, self.discovery.endpoint.geturl(), period=0) # Register to server with uri2 new_app_uri2 = "urn:freeopcua:python:test_discovery2" self.srv.set_application_uri(new_app_uri2) regService2.register_to_discovery( self.srv, self.discovery.endpoint.geturl(), period=0) # Check for 2 registrations time.sleep(0.1) # let server register registration new_servers = client.find_servers() self.assertEqual(len(new_servers) - len(servers), 2) self.assertFalse( new_app_uri1 in [s.ApplicationUri for s in servers]) self.assertFalse( new_app_uri2 in [s.ApplicationUri for s in servers]) self.assertTrue( new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue( new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filter new_servers = client.find_servers( ["urn:freeopcua:python:server"]) self.assertEqual(len(new_servers) - len(servers), 0) self.assertTrue( new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertFalse( new_app_uri2 in [s.ApplicationUri for s in new_servers]) # now do a query with filter new_servers = client.find_servers(["urn:freeopcua:python"]) self.assertEqual(len(new_servers) - len(servers), 2) self.assertTrue( new_app_uri1 in [s.ApplicationUri for s in new_servers]) self.assertTrue( new_app_uri2 in [s.ApplicationUri for s in new_servers]) finally: client.disconnect()
def test_basic256sha56_encrypt_success(self): clt = Client(self.uri_crypto) try: clt.set_security(security_policies.SecurityPolicyBasic256Sha256, '../examples/certificate-example.der', '../examples/private-key-example.pem', None, ua.MessageSecurityMode.SignAndEncrypt ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect()
class OPCClient: def __init__(self, url="opc.tcp://127.0.0.1:48402/freeopcua/server/"): self.url = url self.client = Client(self.url) def get_value(self, count): num = 2 list_value = list() while num < count + 2: list_value.append( self.client.get_node(f'ns=2; i={num}').get_value()) num += 1 return list_value def run(self): self.client.connect() print(f'Client connected to {self.url}')
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 login(self): # Init local registers for key, val in self.variables.items(): self.registers[key] = {} self.registers[key]["min"] = None self.registers[key]["max"] = None self.registers[key]["register_timestamp"] = None # Create session try: self.client = Client(self.opc_url) self.client.connect() except Exception as e: raise Exception( "OPC/UA server is not available. Please check connectivity by cmd tools" ) logging.info("Client connected to a OPC/UA server" + str(self.opc_url))
def connect(self, uri): self.disconnect() logger.info("Connecting to %s with parameters %s, %s, %s, %s", uri, self.security_mode, self.security_policy, self.certificate_path, self.private_key_path) self.client = Client(uri) 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 self.save_security_settings(uri)
def uadiscover(): parser = argparse.ArgumentParser( description= "Performs OPC UA discovery and prints information on servers and endpoints." ) add_minimum_args(parser) parser.add_argument( "-n", "--network", action="store_true", help="Also send a FindServersOnNetwork request to server") #parser.add_argument("-s", #"--servers", #action="store_false", #help="send a FindServers request to server") #parser.add_argument("-e", #"--endpoints", #action="store_false", #help="send a GetEndpoints request to server") args = parse_args(parser) client = Client(args.url, timeout=args.timeout) if args.network: print("Performing discovery at {0}\n".format(args.url)) for i, server in enumerate( client.connect_and_find_servers_on_network(), start=1): print('Server {0}:'.format(i)) #for (n, v) in application_to_strings(server): #print(' {}: {}'.format(n, v)) print('') print("Performing discovery at {0}\n".format(args.url)) for i, server in enumerate(client.connect_and_find_servers(), start=1): print('Server {0}:'.format(i)) for (n, v) in application_to_strings(server): print(' {0}: {1}'.format(n, v)) print('') for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1): print('Endpoint {0}:'.format(i)) for (n, v) in endpoint_to_strings(ep): print(' {0}: {1}'.format(n, v)) print('') sys.exit(0)
def start_server(self, endpoint): self._server = UAServer() self._server.endpoint = 48400 # enpoint not supported yet #self._server.endpoint = endpoint self._server.start() #self._server.set_server_name("OpcUa Modeler Server") time.sleep(0.2) self._client = Client(endpoint) self._client.connect() self.nodes = self._client.nodes self.get_node = self._client.get_node self.get_namespace_array = self._client.get_namespace_array # now remove freeopcua namespace, not necessary when modeling and # ensures correct idx for exported nodesets ns_node = self._client.get_node(ua.NodeId(ua.ObjectIds.Server_NamespaceArray)) nss = ns_node.get_value()
def setUpClass(cls): # start our own server cls.srv = Server() cls.srv.set_endpoint('opc.tcp://127.0.0.1:{0:d}'.format(port_num1)) add_server_methods(cls.srv) add_server_custom_enum_struct(cls.srv) cls.srv.start() # start admin client # long timeout since travis (automated testing) can be really slow cls.clt = Client('opc.tcp://[email protected]:{0:d}'.format(port_num1), timeout=10) cls.clt.connect() cls.opc = cls.clt # start anonymous client cls.ro_clt = Client('opc.tcp://127.0.0.1:{0:d}'.format(port_num1)) cls.ro_clt.connect()
def uageneratestructs(): parser = argparse.ArgumentParser( description= "Generate a Python module from the xml structure definition (.bsd)") add_common_args(parser, require_node=True) parser.add_argument( "-o", "--output", dest="output_path", required=True, type=str, default=None, help="The python file to be generated.", ) args = parse_args(parser, requirenodeid=True) client = Client(args.url, timeout=args.timeout) _configure_client_with_args(client, args) client.connect() try: node = get_node(client, args) generators, _ = client.load_type_definitions([node]) generators[0].save_to_file(args.output_path, True) finally: client.disconnect() sys.exit(0)
def uahistoryread(): parser = argparse.ArgumentParser(description="Read history of a node") add_common_args(parser) parser.add_argument( "--starttime", default="", help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time" ) parser.add_argument( "--endtime", default="", help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time" ) args = parse_args(parser, requirenodeid=True) client = Client(args.url, timeout=args.timeout) client.set_security_string(args.security) client.connect() try: node = get_node(client, args) starttime = str_to_datetime(args.starttime) endtime = str_to_datetime(args.endtime) print( "Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime) ) print_history(node.read_raw_history(starttime, endtime)) finally: client.disconnect() sys.exit(0)
def getSubModel(endpointStr, subModel_NodeId): client = Client(endpointStr) try: client.connect() # nsarray = client.get_node(ua.NodeId(2255, 0)) # nsList = nsarray.get_value() # i=-1 # for entry in nsList: # i = i + 1 # if entry == "http://acplt.org/openaas/": # nsopenaas_subModelType = i # # break # if i!= -1: # print("Looking for AAS at entry point %s,%s" % (subModel_NodeId)) path = client.get_node(subModel_NodeId) print("path is %s" % path) subModelInst = subModel.fromOPCUANodes(node=path) for pvsContainer in subModelInst.PropertyValueStatementContainers: print(pvsContainer.Name) finally: client.disconnect() return subModel
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_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_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 test_nocrypto(self): clt = Client(self.uri_no_crypto) clt.connect() try: clt.get_objects_node().get_children() finally: clt.disconnect()
def __init__(self, config_file='./start.cfg'): """ Constructor for create object """ # --------------------------------------------------------------------- # File parameters: # --------------------------------------------------------------------- # Open config file: self._config_file = config_file config = ConfigParser.ConfigParser() config.read([self._config_file]) # A. Telegram: self._telegram_token = config.get(u'Telegram', u'token') self._telegram_group = config.get(u'Telegram', u'group') # B. Command self._node_command = { 'alarm_mask': config.get(u'command', u'alarm_mask'), 'version_check': config.get(u'command', u'version_check'), } # C. Alarms self._alarms_file = config.get(u'alarm', u'file') self._load_alarms() # D. Robot: self._robot_name = config.get(u'robot', u'name') self._robot_address = config.get(u'robot', u'address') print(u'Read config file %s for Robot: %s' % ( self._robot_name, self._config_file)) try: self._robot_port = config.get(u'robot', u'port') except: self._robot_port = 4840 self._uri = u'opc.tcp://%s:%s' % ( self._robot_address, self._robot_port) # Create and connect as client: self._client = Client(self._uri) try: self._client.connect() except: raise self.RobotConnectionError(self)
def test_get_endpointr(self): client = Client("opc.tcp://" + os.environ['TEST_IP'] + ":" + os.environ['TEST_PORT']) client.connect() endpoints = client.get_endpoints() print(endpoints) client.disconnect()
def uasubscribe(): parser = argparse.ArgumentParser(description="Subscribe to a node and print results") add_common_args(parser) parser.add_argument("-t", "--eventtype", dest="eventtype", default="datachange", choices=['datachange', 'event'], help="Event type to subscribe to") args = parse_args(parser, requirenodeid=False) if args.eventtype == "datachange": _require_nodeid(parser, args) else: # FIXME: this is broken, someone may have written i=84 on purpose if args.nodeid == "i=84" and args.path == "": args.nodeid = "i=2253" client = Client(args.url, timeout=args.timeout, security_policy=args.security) client.connect() try: node = get_node(client, args) handler = SubHandler() sub = client.create_subscription(500, handler) if args.eventtype == "datachange": sub.subscribe_data_change(node) else: sub.subscribe_events(node) embed() finally: client.disconnect() sys.exit(0) print(args)
def cambiar_valor(server,nodo,tiemp,TFD,TFRS,RGTFD,RGTFRS,RGRS,RT,SP,EC,EE,logger): client = Client(server) try: client.connect()#conecta el servidor var=client.get_node("ns=1;s="+nodo)#se obtiene el primer nodo variable2=var.get_children() tamano=np.size(variable2) datetime_object = datetime.strptime(tiemp, '%d/%m/%Y %H:%M:%S') if tamano>0: variable2[0].set_value(datetime_object) variable2[1].set_value(TFD) variable2[2].set_value(TFRS) variable2[3].set_value(RGTFD) variable2[4].set_value(RGTFRS) variable2[5].set_value(RGRS) variable2[6].set_value(RT) variable2[7].set_value(SP) variable2[8].set_value(EC) variable2[9].set_value(EE) else: logger.warning("No se encuentra el nodo en el servidor opc") client.disconnect() except: logger.error("No se puede conectar con el servidor opc")
def cambiar_valor2(server,nodo,avg_fv,median_fv,std_fv,moda_fv,perc50_fv,mom2_fv,mom3_fv,mom4_fv,skew1_fv,skew2_fv,skew3_fv,kurt_fv,logger): client = Client(server) try: client.connect()#conecta el servidor var=client.get_node("ns=1;s="+nodo)#se obtiene el primer nodo variable2=var.get_children() tamano=np.size(variable2) #datetime_object = datetime.strptime(tiemp, '%d/%m/%Y %H:%M:%S') if tamano>0: variable2[10].set_value(avg_fv) variable2[11].set_value(median_fv) variable2[12].set_value(std_fv) variable2[13].set_value(moda_fv) variable2[14].set_value(perc50_fv) variable2[15].set_value(mom2_fv) variable2[16].set_value(mom3_fv) variable2[17].set_value(mom4_fv) variable2[18].set_value(skew1_fv) variable2[19].set_value(skew2_fv) variable2[20].set_value(skew3_fv) variable2[21].set_value(kurt_fv) else: logger.warning("No se encuentra el nodo en el servidor opc") client.disconnect() except: logger.error("No se puede conectar con el servidor opc")
def getSubModel(endpointStr, subModel_NodeId): client = Client(endpointStr) subModel = None try: client.connect() # nsarray = client.get_node(ua.NodeId(2255, 0)) # nsList = nsarray.get_value() # i=-1 # for entry in nsList: # i = i + 1 # if entry == "http://acplt.org/openaas/": # nsopenaas_subModelType = i # # break # if i!= -1: # print("Looking for AAS at entry point %s,%s" % (subModel_NodeId)) path = client.get_node(subModel_NodeId) print("path is %s" % path) print("1") subModelInst = subModel.fromOPCUANodes( path) #in line 259, classmethod of 'subModel' exists print("2") #no print out of "2" during tests for statement in subModelInst.statements: print(statement.Name) finally: client.disconnect() return subModel
def uasubscribe(): parser = argparse.ArgumentParser(description="Subscribe to a node and print results") add_common_args(parser) parser.add_argument("-t", "--eventtype", dest="eventtype", default="datachange", choices=['datachange', 'event'], help="Event type to subscribe to") args = parser.parse_args() if args.nodeid == "i=84" and args.path == "": parser.print_usage() print("uaread: error: The NodeId or BrowsePath of a variable is required") sys.exit(1) logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) client = Client(args.url, timeout=args.timeout) client.connect() try: node = client.get_node(args.nodeid) if args.path: node = node.get_child(args.path.split(",")) handler = SubHandler() sub = client.create_subscription(500, handler) if args.eventtype == "datachange": sub.subscribe_data_change(node) else: sub.subscribe_events(node) embed() finally: client.disconnect() sys.exit(0) print(args)
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 test_context_manager(self): """ Context manager calls connect() and disconnect() """ state = [0] def increment_state(self, *args, **kwargs): state[0] += 1 # create client and replace instance methods with dummy methods client = Client('opc.tcp://dummy_address:10000') client.connect = increment_state.__get__(client) client.disconnect = increment_state.__get__(client) assert state[0] == 0 with client: # test if client connected self.assertEqual(state[0], 1) # test if client disconnected self.assertEqual(state[0], 2)
def register_to_discovery(self, url, period=60): """ Register to a OPC-UA Discovery server. Registering must be renewed at least every 10 minutes, so this method will use our asyncio thread to re-register every period seconds """ self._discovery_period = period self._discovery_client = Client(url) self._discovery_client.connect() self.iserver.loop.call_soon(self._renew_registration)
def uadiscover(): parser = argparse.ArgumentParser( description="Performs OPC UA discovery and prints information on servers and endpoints." ) add_minimum_args(parser) parser.add_argument( "-n", "--network", action="store_true", help="Also send a FindServersOnNetwork request to server" ) # parser.add_argument("-s", # "--servers", # action="store_false", # help="send a FindServers request to server") # parser.add_argument("-e", # "--endpoints", # action="store_false", # help="send a GetEndpoints request to server") args = parse_args(parser) client = Client(args.url, timeout=args.timeout) if args.network: print("Performing discovery at {}\n".format(args.url)) for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1): print("Server {}:".format(i)) # for (n, v) in application_to_strings(server): # print(' {}: {}'.format(n, v)) print("") print("Performing discovery at {}\n".format(args.url)) for i, server in enumerate(client.connect_and_find_servers(), start=1): print("Server {}:".format(i)) for (n, v) in application_to_strings(server): print(" {}: {}".format(n, v)) print("") for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1): print("Endpoint {}:".format(i)) for (n, v) in endpoint_to_strings(ep): print(" {}: {}".format(n, v)) print("") sys.exit(0)
def test_basic256_encrypt_success(self): clt = Client(self.uri_crypto) try: clt.set_security(security_policies.SecurityPolicyBasic256, 'examples/certificate-example.der', 'examples/private-key-example.pem', None, ua.MessageSecurityMode.SignAndEncrypt ) clt.connect() self.assertTrue(clt.get_objects_node().get_children()) finally: clt.disconnect()
def __init__(self, address:str, port:int=502, interval:float=3): super().__init__() self.address=address self.port=port self.interval=interval self.handler=OPCPLC.Handler(self) self.subscription=None self.objects=None self.tagbynodeid={} self.client = Client("opc.tcp://"+self.address+":"+str(self.port)+"/") self.create("")
def uadiscover(): parser = argparse.ArgumentParser(description="Performs OPC UA discovery and prints information on servers and endpoints.") add_minimum_args(parser) args = parser.parse_args() logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) client = Client(args.url, timeout=args.timeout) for i, server in enumerate(client.find_all_servers(), start=1): print('Server {}:'.format(i)) for (n, v) in application_to_strings(server): print(' {}: {}'.format(n, v)) print('') client = Client(args.url, timeout=args.timeout) for i, ep in enumerate(client.get_server_endpoints()): print('Endpoint {}:'.format(i)) for (n, v) in endpoint_to_strings(ep): print(' {}: {}'.format(n, v)) print('') sys.exit(0)
def uahistoryread(): parser = argparse.ArgumentParser(description="Read history of a node") add_common_args(parser) parser.add_argument("--starttime", default="", help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time") parser.add_argument("--endtime", default="", help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time") args = parser.parse_args() if args.nodeid == "i=84" and args.path == "": parser.print_usage() print("uahistoryread: error: A NodeId or BrowsePath is required") sys.exit(1) logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) client = Client(args.url, timeout=args.timeout) client.connect() try: node = client.get_node(args.nodeid) if args.path: node = node.get_child(args.path.split(",")) starttime = str_to_datetime(args.starttime) endtime = str_to_datetime(args.endtime) print("Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime)) print_history(node.read_raw_history(starttime, endtime)) finally: client.disconnect() sys.exit(0)
def uals(): parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result") add_common_args(parser) #parser.add_argument("-l", #dest="long_format", #default=ua.AttributeIds.Value, #help="use a long listing format") parser.add_argument("-d", "--depth", default=1, type=int, help="Browse depth") 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() try: node = client.get_node(args.nodeid) if args.path: node = node.get_child(args.path.split(",")) print("Browsing node {} at {}\n".format(node, args.url)) _lsprint(client, node.nodeid, args.depth - 1) finally: client.disconnect() sys.exit(0) print(args)
def uasubscribe(): parser = argparse.ArgumentParser(description="Subscribe to a node and print results") add_common_args(parser) parser.add_argument("-t", "--eventtype", dest="eventtype", default="datachange", choices=['datachange', 'event'], help="Event type to subscribe to") args = parse_args(parser, requirenodeid=True) client = Client(args.url, timeout=args.timeout) client.connect() try: node = get_node(client, args) handler = SubHandler() sub = client.create_subscription(500, handler) if args.eventtype == "datachange": sub.subscribe_data_change(node) else: sub.subscribe_events(node) embed() finally: client.disconnect() sys.exit(0) print(args)