async def main(): """ Main task of this Client-Subscription example. """ client = Client(url='opc.tcp://localhost:4840/freeopcua/server/') async with client: idx = await client.get_namespace_index( uri="http://examples.freeopcua.github.io") var = await client.nodes.objects.get_child( [f"{idx}:MyObject", f"{idx}:MyVariable"]) handler = SubscriptionHandler() # We create a Client Subscription. subscription = await client.create_subscription(500, handler) nodes = [ var, client.get_node(ua.ObjectIds.Server_ServerStatus_CurrentTime), ] # We subscribe to data changes for two nodes (variables). await subscription.subscribe_data_change(nodes) # We let the subscription run for ten seconds await asyncio.sleep(10) # We delete the subscription (this un-subscribes from the data changes of the two variables). # This is optional since closing the connection will also delete all subscriptions. await subscription.delete() # After one second we exit the Client context manager - this will close the connection. await asyncio.sleep(1)
async def opcua_client(): """ -handles connect/disconnect/reconnect/subscribe/unsubscribe -connection-monitoring with cyclic read of the service-level """ client = Client(url=server_url) handler = SubscriptionHandler() subscription = None case = 0 subscription_handle_list = [] idx = 0 while 1: if case == 1: #connect print("connecting...") try: await client.connect() await client.load_type_definitions() idx = await client.get_namespace_index("http://andreas-heine.net/UA") print("connected!") case = 2 except: print("connection error!") case = 1 await asyncio.sleep(5) elif case == 2: #subscribe all nodes and events print("subscribing nodes and events...") try: variable_list = await client.get_node("ns=2;i=6").get_children() # added for performance test with 100 quick and randomly changing variables subscription = await client.create_subscription(50, handler) subscription_handle_list = [] if nodes_to_subscribe: for node in nodes_to_subscribe + variable_list: # added for performance test with 100 quick and randomly changing variables # for node in nodes_to_subscribe: handle = await subscription.subscribe_data_change(client.get_node(node)) subscription_handle_list.append(handle) if events_to_subscribe: for event in events_to_subscribe: handle = await subscription.subscribe_events(event[0], event[1]) subscription_handle_list.append(handle) print("subscribed!") case = 3 except: print("subscription error") case = 4 await asyncio.sleep(0) elif case == 3: #running => read cyclic the service level if it fails disconnect and unsubscribe => wait 5s => connect try: if users == set(): datachange_notification_queue.clear() event_notification_queue.clear() service_level = await client.get_node("ns=0;i=2267").get_value() if service_level >= 200: case = 3 else: case = 4 await asyncio.sleep(5)
async def writeY(data): client = Client(data['opcUrl']) client.name = "TOTO" client.application_uri = "urn:freeopcua:clientasync" async with client: struct = client.get_node( "ns=4;s=|var|CODESYS Control Win V3 x64.Application.GVL.intYPos") await struct.write_value(data['yPos'], ua.VariantType.Int16)
async def execute(opc_server_url=None, subscription_nodes=None, polling_interval=1000): """ Create the client and start listening to the nodes Param: opc_server_url - the url to the opc ua server (example: opc.tcp://milo.digitalpetri.com:62541/milo) subscription_nodes - list of nodes to subscribe on polling_interval - polling interval to the opc ua server in milliseconds """ client = Client(url=opc_server_url) async with client: # Create the subscription handler handler = SubscriptionHandler() # We create a Client Subscription. subscription = await client.create_subscription(polling_interval, handler) # Set current time of server for time based storage nodes = [client.get_node(ua.ObjectIds.Server_ServerStatus_CurrentTime)] for node in subscription_nodes: nodes.append(client.get_node(node)) # We subscribe to data changes for two nodes (variables). await subscription.subscribe_data_change(nodes) stop_running = False while not stop_running: _logger.info("Start running loop for " + str(constants.MAX_SUBSCRIPTION_RUN_INTERVAL) + " seconds") # We let the subscription run for the MAX_SUBSCRIPTION_RUN_INTERVAL await asyncio.sleep(constants.MAX_SUBSCRIPTION_RUN_INTERVAL) if constants.STOP_AFTER_INTERVAL: stop_running = True # We delete the subscription (this un-subscribes from the data changes of the two variables). # This is optional since closing the connection will also delete all subscriptions. await subscription.delete() # After one second we exit the Client context manager - this will close the connection. await asyncio.sleep(1)
async def read(data): client = Client(data['opcUrl']) client.name = "TOTO" client.application_uri = "urn:freeopcua:clientasync" async with client: struct = client.get_node( "ns=4;s=|var|CODESYS Control Win V3 x64.Application.GVL.stringStatus" ) readVal = await struct.read_value() return readVal
async def opcua_client(): """ -handles connect/disconnect/reconnect/subscribe/unsubscribe -connection-monitoring with cyclic read of the service-level """ client = Client(url=server_url) handler = SubscriptionHandler() subscription = None case = 0 subscription_handle_list = [] idx = 0 while 1: if case == 1: #connect print("connecting...") try: await client.connect() print("connected!") case = 2 except: print("connection error!") case = 1 await asyncio.sleep(2) elif case == 2: #subscribe all nodes and events print("subscribing nodes and events...") try: subscription = await client.create_subscription(200, handler) subscription_handle_list = [] if nodes_to_subscribe: for node in nodes_to_subscribe: handle = await subscription.subscribe_data_change( client.get_node(node)) subscription_handle_list.append(handle) if events_to_subscribe: for event in events_to_subscribe: handle = await subscription.subscribe_events( event[0], event[1]) subscription_handle_list.append(handle) print("subscribed!") case = 3 except: print("subscription error") case = 4 await asyncio.sleep(0) elif case == 3: #running => read cyclic the service level if it fails disconnect and unsubscribe => wait 5s => connect try: service_level = await client.get_node("ns=0;i=2267" ).get_value() if service_level >= 200: case = 3 else: case = 4 await asyncio.sleep(2)
async def connectUa(data): client = Client(data['opcUrl']) client.name = "TOTO" client.application_uri = "urn:freeopcua:clientasync" try: async with client: struct = client.get_node( ua.ObjectIds.Server_ServerStatus_CurrentTime) time = await struct.read_value() return time except: return 'failed'
def _nodes_to_add( self, url: str, sub_name: str, client: Client, vs_real: VirtualSubscription, vs_ideal: VirtualSubscription, ) -> List[Optional[asyncio.Task]]: tasks = [] real_sub = self.name_to_subscription[url].get(sub_name) monitoring = vs_real.monitoring node_to_add = set(vs_ideal.nodes) - set(vs_real.nodes) if node_to_add: _logger.info(f"Adding {len(node_to_add)} Nodes") # hack to group subscription by NodeAttributes attr_to_nodes = defaultdict(list) for node in node_to_add: node_attr = vs_ideal.nodes[node] node_obj = client.get_node(node) attr_to_nodes[node_attr].append(node_obj) for node_attr, nodes_obj in attr_to_nodes.items(): # some servers are sensitive to the number of MI per request for batch_nodes_obj in batch(nodes_obj, self.BATCH_MI_SIZE): task = asyncio.create_task( real_sub.subscribe_data_change( batch_nodes_obj, *astuple(node_attr), monitoring=monitoring, ) ) nodes = [n.nodeid.to_string() for n in batch_nodes_obj] task.add_done_callback( partial( self.add_to_map, url, Method.ADD_MI, sub_name=sub_name, nodes=nodes, node_attr=node_attr, monitoring=monitoring, ) ) tasks.append(task) self.hook_mi_request( url=url, sub_name=sub_name, nodes=node_to_add, action=Method.ADD_MI ) return tasks
async def main(): url = 'opc.tcp://localhost:4840/freeopcua/server/' client = Client(url=url) # client.set_security_string() async with client: uri = 'http://examples.freeopcua.github.io' idx = await client.get_namespace_index(uri) var = await client.nodes.objects.get_child([f"{idx}:MyObject", f"{idx}:MyVariable"]) handler = SubscriptionHandler() subscription = await client.create_subscription(500, handler) nodes = [ var, client.get_node(ua.ObjectIds.Server_ServerStatus_CurrentTime), ] await subscription.subscribe_data_change(nodes) await asyncio.sleep(10)
async def clone_and_subscribe(client: Client, node_dict: dict, server_node: Node, sub_handler: SubscriptionHandler, subscription_obj: Subscription, server_object: Server, method_handler): namespace_array = await client.get_namespace_array() mapping_list = await clone_nodes(node_dict, server_node, namespace_array, server_object, method_handler) subscribe_with_handler_from_list(sub_handler, mapping_list) var_nodes = [ client.get_node(elem['original_id']) for elem in mapping_list if elem['type'] == 'Variable' ] sub_node_lists = [ var_nodes[x:x + 50] for x in range(0, len(var_nodes), 50) ] for node_list in sub_node_lists: await subscription_obj.subscribe_data_change(node_list) return mapping_list
async def readSubscribed(data): oldVals = data['oldVals'] oldData = [] for val in oldVals: dataOld = {'NodeID': val['NodeID'], 'Value': val['Value']} oldData.append(dataOld) client = Client(data['opcUrl']) client.name = "TOTO" client.application_uri = "urn:freeopcua:clientasync" async with client: for i in range(290): returnVal = [] for nodeID in oldData: struct = client.get_node(nodeID['NodeID']) readVal = await struct.read_value() data = {'NodeID': nodeID['NodeID'], 'Value': str(readVal)} returnVal.append(data) for i in returnVal: if i not in oldData: return returnVal asyncio.sleep(0.1) return
import sys sys.path.insert(0, "..") import time import logging from IPython import embed from asyncua import Client from asyncua import ua if __name__ == "__main__": logging.basicConfig(level=logging.WARN) client = Client("opc.tcp://asyncua.demo-this.com:51210/UA/SampleServer") try: client.connect() root = client.get_root_node() objects = client.get_objects_node() struct = client.get_node("ns=2;i=10239") struct_array = client.get_node("ns=2;i=10323") before = struct.read_value() before_array = struct_array.read_value() client.load_type_definitions( ) # scan server for custom structures and import them after = struct.read_value() after_array = struct_array.read_value() embed() finally: client.disconnect()
import sys sys.path.insert(0, "..") import time import logging from IPython import embed from asyncua import Client from asyncua import ua if __name__ == "__main__": logging.basicConfig(level=logging.WARN) client = Client("opc.tcp://asyncua.demo-this.com:51210/UA/SampleServer") try: client.connect() root = client.get_root_node() objects = client.get_objects_node() struct = client.get_node("ns=2;i=10239") before = struct.read_value() client.load_type_definitions( ) # scan server for custom structures and import them after = struct.read_value() embed() finally: client.disconnect()
if __name__ == "__main__": #from IPython import embed logging.basicConfig(level=logging.WARN) client = Client("opc.tcp://192.168.56.100:49320/OPCUA/SimulationServer/") #client = Client("opc.tcp://192.168.56.100:4840/OPCUA/SimulationServer/") #client = Client("opc.tcp://*****:*****@localhost:53530/OPCUA/SimulationServer/") try: client.connect() root = client.nodes.root print("Root is", root) print("childs of root are: ", root.get_children()) print("name of root is", root.read_browse_name()) objects = client.nodes.objects print("childs og objects are: ", objects.get_children()) tag1 = client.get_node("ns=2;s=Channel1.Device1.Tag1") print("tag1 is: {0} with value {1} ".format(tag1, tag1.read_value())) tag2 = client.get_node("ns=2;s=Channel1.Device1.Tag2") print("tag2 is: {0} with value {1} ".format(tag2, tag2.read_value())) handler = SubHandler() sub = client.create_subscription(500, handler) handle1 = sub.subscribe_data_change(tag1) handle2 = sub.subscribe_data_change(tag2) from IPython import embed embed() sub.unsubscribe(handle1) sub.unsubscribe(handle2) sub.delete()
async def _serial_poller_async(tpp): """Poll OPCUA agent data. Args: tpp: TargetDataPoints object Returns: target_datapoints: TargetDataPoints object """ # Initialize key variables connected = False # Test for validity if isinstance(tpp, TargetPollingPoints) is False: return None if isinstance(tpp.target, OPCUAauth) is False: return None if tpp.valid is False: return None # Create URL for polling ip_target = tpp.target.ip_target ip_port = tpp.target.ip_port username = tpp.target.username password = tpp.target.password url = 'opc.tcp://{}:{}'.format(ip_target, ip_port) # Intialize data gathering target_datapoints = TargetDataPoints(ip_target) # Create a client object to connect to OPCUA server client = Client(url=url) client.set_user(username) client.set_password(password) # Connect try: await client.connect() connected = True except: log_message = ( 'Authentication for polling target {} is incorrect'.format(url)) log.log2warning(51011, log_message) pass if connected is True: for point in tpp.data: # Make sure we have the right data type if isinstance(point, PollingPoint) is False: log_message = ('''\ Invalid polling point {} for OPC UA URL {}'''.format(point, url)) log.log2info(51012, log_message) continue # Get data address = point.address try: node = client.get_node(address) value = await node.read_value() except BadNodeIdUnknown: log_message = ('''\ OPC UA node {} not found on server {}'''.format(address, url)) log.log2warning(51015, log_message) continue except: _exception = sys.exc_info() log_message = ('OPC UA server communication error') log.log2exception(51014, _exception, message=log_message) log_message = ('''\ Cannot get value from polling point {} for OPC UA URL {}\ '''.format(address, url)) log.log2info(51013, log_message) continue # Create datapoint if bool(point.multiplier) is True: if is_numeric(value) is True and (is_numeric(point.multiplier) is True): value = value * point.multiplier else: value = 0 datapoint = DataPoint(address, value) datapoint.add(DataPointMetadata('OPCUA Server', ip_target)) target_datapoints.add(datapoint) # Disconnect client await client.disconnect() return target_datapoints