Beispiel #1
0
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)
Beispiel #2
0
async def test_multiple_clients_with_subscriptions(server):
    """
    Tests that multiple clients can subscribe, and when one client disconnects, the other
    still maintains it's subscription
    """
    class SubscriptionHandler:
        def datachange_notification(self, node, val, data):
            pass

    sub_handler = SubscriptionHandler()
    client1 = Client(server.endpoint.geturl())
    client2 = Client(server.endpoint.geturl())

    o = server.nodes.objects
    var = await o.add_variable(3, "some_variable", 1.0)
    async with client1:
        async with client2:
            sub1 = await client1.create_subscription(100, sub_handler)
            sub2 = await client2.create_subscription(100, sub_handler)
            await sub1.subscribe_data_change(var)
            await sub2.subscribe_data_change(var)
            assert sub1.subscription_id in server.iserver.subscription_service.subscriptions
            assert sub2.subscription_id in server.iserver.subscription_service.subscriptions
        # When client2 disconnects, client1 should still keep its subscription.
        assert sub1.subscription_id in server.iserver.subscription_service.subscriptions
        assert sub2.subscription_id not in server.iserver.subscription_service.subscriptions
    assert sub1.subscription_id not in server.iserver.subscription_service.subscriptions
    assert sub2.subscription_id not in server.iserver.subscription_service.subscriptions
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)
Beispiel #4
0
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)
Beispiel #5
0
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
Beispiel #6
0
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()
Beispiel #7
0
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)
Beispiel #8
0
async def main():
    client = Client("opc.tcp://localhost:53530/OPCUA/SimulationServer/")
    client.set_security_string(
        "Basic256Sha256,Sign,certificate-example.der,private-key-example.pem")
    client.session_timeout = 2000
    async with client:
        root = client.nodes.root
        objects = client.nodes.objects
        while True:
            print("childs og objects are: ", await objects.get_children())
            await asyncio.sleep(1)
Beispiel #9
0
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'
Beispiel #10
0
async def test_max_connections_1(opc):
    opc.server.iserver.isession.__class__.max_connections = 1
    port = opc.server.endpoint.port
    if port == port_num:
        # if client we already have one connection
        with pytest.raises(BadMaxConnectionsReached):
            async with Client(f'opc.tcp://127.0.0.1:{port}'):
                pass
    else:
        async with Client(f'opc.tcp://127.0.0.1:{port}'):
            with pytest.raises(BadMaxConnectionsReached):
                async with Client(f'opc.tcp://127.0.0.1:{port}'):
                    pass
    opc.server.iserver.isession.__class__.max_connections = 1000
Beispiel #11
0
    def __init__(self,
                 config: HaConfig,
                 security: Optional[HaSecurityConfig] = None,
                 loop=None) -> None:
        self._config: HaConfig = config
        self._keepalive_task: Dict[KeepAlive, asyncio.Task] = {}
        self._manager_task: Dict[HaManager, asyncio.Task] = {}
        self._reconciliator_task: Dict[Reconciliator, asyncio.Task] = {}
        self._gen_sub: Generator[str, None, None] = self.generate_sub_name()

        self.loop: asyncio.unix_events._UnixSelectorEventLoop = (
            loop or asyncio.get_event_loop())
        self._url_to_reset_lock = asyncio.Lock(loop=self.loop)
        self._ideal_map_lock: asyncio.Lock = asyncio.Lock(loop=self.loop)
        self._client_lock: asyncio.Lock = asyncio.Lock(loop=self.loop)

        self.clients: Dict[Client, ServerInfo] = {}
        self.active_client: Optional[Client] = None
        # full type: Dict[str, SortedDict[str, VirtualSubscription]]
        self.ideal_map: Dict[str, SortedDict] = {}
        self.sub_names: Set[str] = set()
        self.url_to_reset: Set[str] = set()
        self.is_running = False

        if config.ha_mode != HaMode.WARM:
            # TODO
            # Check if transparent redundancy support exist for the server (nodeid=2035)
            # and prevent using HaClient with such servers.
            raise NotImplementedError(
                f"{config.ha_mode} not currently supported by HaClient")

        for url in self.urls:
            c = Client(url,
                       timeout=self._config.request_timeout,
                       loop=self.loop)
            # timeouts for the session and secure channel are in ms
            c.session_timeout = self._config.session_timeout * 1000
            c.secure_channel_timeout = self._config.secure_channel_timeout * 1000
            c.description = self._config.session_name
            server_info = ServerInfo(url)
            self.clients[c] = server_info
            self.ideal_map[url] = SortedDict()

        # security can also be set via the set_security method
        self.security_config: HaSecurityConfig = (security if security else
                                                  HaSecurityConfig())
        self.manager = HaManager(self, self._config.manager_timer)
        self.reconciliator = Reconciliator(self._config.reconciliator_timer,
                                           self)
async def opc(request):
    """
    Fixture for tests that should run for both `Server` and `Client`
    :param request:
    :return:
    """
    if request.param == 'client':
        srv = Server()
        await srv.init()
        srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num}')
        await add_server_methods(srv)
        await srv.start()
        # start client
        # long timeout since travis (automated testing) can be really slow
        clt = Client(f'opc.tcp://[email protected]:{port_num}', timeout=10)
        await clt.connect()
        yield Opc(clt, srv)
        await clt.disconnect()
        await srv.stop()
    elif request.param == 'server':
        # start our own server
        srv = Server()
        await srv.init()
        srv.set_endpoint(f'opc.tcp://127.0.0.1:{port_num1}')
        await add_server_methods(srv)
        await srv.start()
        yield Opc(srv, srv)
        # stop the server
        await srv.stop()
    else:
        raise ValueError("invalid internal test config")
Beispiel #13
0
async def main():
    url = 'opc.tcp://CX-385DB1:4840'
    # url = 'opc.tcp://commsvr.com:51234/UA/CAS_UA_Server'
    async with Client(url=url) as client:
        # 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()
        root = await root.get_children()

        # 'main.xxx' is the node name, 4 is the namespace (ns) , E.G. in uaexpert/objects/plcbeckhoff/MAIN/o_rxd
        O_RXD = client.get_node(ua.NodeId('MAIN.O_RXD', 4))
        M_RXD = client.get_node(ua.NodeId('MAIN.M_RXD', 4))
        M_RIF = client.get_node(ua.NodeId('MAIN.M_RIF', 4))
        M_FOOD = client.get_node(ua.NodeId('MAIN.M_FOOD', 4))

        out = await O_RXD.get_value()
        print('RXD out is {v} '.format(v=out))

        dt = 0.2
        while True:
            await M_RXD.set_attribute(ua.AttributeIds.Value, ua.DataValue(True))
            time.sleep(dt)
            await M_RXD.set_attribute(ua.AttributeIds.Value, ua.DataValue(False))
            time.sleep(dt)
            await M_RIF.set_attribute(ua.AttributeIds.Value, ua.DataValue(True))
            time.sleep(dt)
            await M_RIF.set_attribute(ua.AttributeIds.Value, ua.DataValue(False))
            time.sleep(dt)
            await M_FOOD.set_attribute(ua.AttributeIds.Value, ua.DataValue(True))
            time.sleep(dt)
            await M_FOOD.set_attribute(ua.AttributeIds.Value, ua.DataValue(False))
            time.sleep(dt)
Beispiel #14
0
async def _uageneratestructs():
    parser = argparse.ArgumentParser(
        description=
        "Generate a Python module from the xml structure definition (.bsd), the node argument is typically a children of i=93"
    )
    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)
    await _configure_client_with_args(client, args)
    await client.connect()
    try:
        node = await get_node(client, args)
        generators, _ = await client.load_type_definitions([node])
        generators[0].save_to_file(args.output_path, True)
    finally:
        await client.disconnect()
async def admin_client():
    # start admin client
    # long timeout since travis (automated testing) can be really slow
    clt = Client(f'opc.tcp://[email protected]:{port_num}', timeout=10)
    await clt.connect()
    yield clt
    await clt.disconnect()
Beispiel #16
0
async 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)
    await _configure_client_with_args(client, args)
    try:
        async with client:
            node = await get_node(client, args)
            print(f"Browsing node {node} at {args.url}\n")
            if args.long_format == 0:
                await _lsprint_0(node, args.depth - 1)
            elif args.long_format == 1:
                await _lsprint_1(node, args.depth - 1)
            else:
                await _lsprint_long(node, args.depth - 1)
    except (OSError, concurrent.futures._base.TimeoutError) as e:
        print(e)
        sys.exit(1)
    sys.exit(0)
Beispiel #17
0
async 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)
    await _configure_client_with_args(client, args)
    await client.connect()
    try:
        node = await get_node(client, args)
        handler = SubHandler()
        sub = await client.create_subscription(500, handler)
        if args.eventtype == "datachange":
            await sub.subscribe_data_change(node)
        else:
            await sub.subscribe_events(node)
        print("Type Ctr-C to exit")
        while True:
            time.sleep(1)
    finally:
        await client.disconnect()
Beispiel #18
0
async def test_basic256(srv_crypto):
    clt = Client(uri_crypto)
    await clt.set_security_string(
        f"Basic256Sha256,Sign,{EXAMPLE_PATH}certificate-example.der,{EXAMPLE_PATH}private-key-example.pem"
    )
    async with clt:
        assert await clt.get_objects_node().get_children()
Beispiel #19
0
async 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)
    await _configure_client_with_args(client, args)
    if args.certificate:
        await client.load_client_certificate(args.certificate)
    if args.private_key:
        await client.load_private_key(args.private_key)

    try:
        async with client:
            mynode = await get_node(client, args)
    except (OSError, concurrent.futures.TimeoutError) as e:
        print(e)
        sys.exit(1)

    sys.exit(0)
async def test_basic256_encrypt(srv_crypto_all_certs):
    clt = Client(uri_crypto)
    await clt.set_security_string(
        f"Basic256Sha256,SignAndEncrypt,{EXAMPLE_PATH}certificate-example.der,{EXAMPLE_PATH}private-key-example.pem"
    )
    async with clt:
        assert await clt.nodes.objects.get_children()
Beispiel #21
0
async 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)
    await _configure_client_with_args(client, args)
    await client.connect()
    try:
        node = await get_node(client, args)
        print("Browsing node {0} at {1}\n".format(node, args.url))
        if args.long_format == 0:
            await _lsprint_0(node, args.depth - 1)
        elif args.long_format == 1:
            await _lsprint_1(node, args.depth - 1)
        else:
            _lsprint_long(node, args.depth - 1)
    finally:
        await client.disconnect()
async def main_mirror_client_2(shared):
    #this client runs on an (local) mirror server together with main_mirror_client_1 and is connected to the virtual device server

    url = 'opc.tcp://localhost:4841/virtual/server/'

    async with Client(url=url) as client:

        uri = 'http://examples.freeopcua.github.io'
        idx = await client.get_namespace_index(uri)

        sensor_value = await client.nodes.root.get_child(
            ["0:Objects", f"{idx}:Component", f"{idx}:SensorValue"])
        command_id = await client.nodes.root.get_child(
            ["0:Objects", f"{idx}:Component", f"{idx}:CommandID"])

        while True:
            await asyncio.sleep(update_period_s)
            #write sensor value to virtual device
            await sensor_value.write_value(shared.sensor_value)
            new_sensor_value = await sensor_value.read_value()
            print("[Mirror_Client2] Write to virtual ", sensor_value,
                  new_sensor_value)
            #read command id from virtual device
            shared.command_id = await command_id.read_value()
            print("[Mirror_Client2] Read from virtual ", command_id,
                  shared.command_id)
Beispiel #23
0
async def test_find_servers2(server, discovery_server):
    client = Client(discovery_server.endpoint.geturl())
    async with client:
        servers = await client.find_servers()
        new_app_uri1 = 'urn:freeopcua:python:server:test_discovery1'
        await server.set_application_uri(new_app_uri1)
        await server.register_to_discovery(discovery_server.endpoint.geturl(),
                                           period=0)
        new_app_uri2 = 'urn:freeopcua:python:test_discovery2'
        await server.set_application_uri(new_app_uri2)
        await server.register_to_discovery(discovery_server.endpoint.geturl(),
                                           period=0)
        await asyncio.sleep(0.1)  # let server register registration
        new_servers = await client.find_servers()
        assert len(new_servers) - len(servers) == 2
        assert new_app_uri1 not in [s.ApplicationUri for s in servers]
        assert new_app_uri2 not in [s.ApplicationUri for s in servers]
        assert new_app_uri1 in [s.ApplicationUri for s in new_servers]
        assert new_app_uri2 in [s.ApplicationUri for s in new_servers]
        # now do a query with filer
        new_servers = await client.find_servers(
            ['urn:freeopcua:python:server'])
        assert len(new_servers) - len(servers) == 0
        assert new_app_uri1 in [s.ApplicationUri for s in new_servers]
        assert new_app_uri2 not in [s.ApplicationUri for s in new_servers]
        # now do a query with filer
        new_servers = await client.find_servers(['urn:freeopcua:python'])
        assert len(new_servers) - len(servers) == 2
        assert new_app_uri1 in [s.ApplicationUri for s in new_servers]
        assert new_app_uri2 in [s.ApplicationUri for s in new_servers]
async def main():
    # setup our serverclone_and_subscribe(client_node, server_node, sub_handler)
    client = Client(url=PLC_url)
    cloud_cert = '/credentials/cloud_cert.der'
    cloud_private_key = '/credentials/cloud_private_key.pem'
    server_cert = '/credentials/PLC_cert.der'
    await client.set_security(SecurityPolicyBasic256Sha256,
                              certificate=cloud_cert,
                              private_key=cloud_private_key,
                              server_certificate=server_cert)
    await client.connect()

    # client2 = Client(url=PLC_url_2)
    #
    # await client2.connect()

    node_1_client = client.nodes.objects
    # node_2_client = client2.nodes.objects

    await produce_full_bridge_yaml(
        [
            # {'nodes': node_2_client, 'name': 'plc_2', 'url': PLC_url_2},
            {
                'nodes': node_1_client,
                'name': 'plc_1',
                'url': PLC_url,
                'bridge_certificate': cloud_cert,
                'bridge_private_key': cloud_private_key,
                'server_certificate': server_cert
            },
        ],
        '/appdata/test_yaml/test.yaml')
Beispiel #25
0
async def main():
    # url = 'opc.tcp://192.168.2.64:4840'
    url = 'opc.tcp://localhost:4840/freeopcua/server/'
    # url = 'opc.tcp://commsvr.com:51234/UA/CAS_UA_Server'
    try:
        async with Client(url=url) as client:
            # 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()
            _logger.info('Objects node is: %r', root)

            # Node objects have methods to read and write node attributes as well as browse or populate address space
            _logger.info('Children of root are: %r', await root.get_children())

            uri = 'http://examples.freeopcua.github.io'
            idx = await client.get_namespace_index(uri)
            # get a specific node knowing its node id
            # var = client.get_node(ua.NodeId(1002, 2))
            # var = client.get_node("ns=3;i=2002")
            var = await root.get_child(
                ["0:Objects", f"{idx}:MyObject", f"{idx}:MyVariable"])
            print("My variable", var, await var.get_value())
            # 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
    except Exception:
        _logger.exception('error')
Beispiel #26
0
async 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)
    await client.set_security_string(args.security)
    await client.connect()

    try:
        node = await get_node(client, args)
        attr = await node.read_attribute(args.attribute)
        if args.datatype == "python":
            print(attr.Value.Value)
        elif args.datatype == "variant":
            print(attr.Value)
        else:
            print(attr)
    finally:
        await client.disconnect()
Beispiel #27
0
async def run():
    url = "opc.tcp://localhost:4840/Larouex-Industrial-Manufacturing/Server"

    map_telemetry_file = MapTelemetry(Log)
    map_telemetry_file.load_file()
    map_telemetry_data = map_telemetry_file.data

    config_file = Config(Log)
    config_file_data = config_file.data

    async with Client(url=url) as client:
        idx = await client.get_namespace_index(map_telemetry_data["NameSpace"])
        print(idx)

        while True:
            await asyncio.sleep(config_file_data["ClientFrequencyInSeconds"])

            for node in map_telemetry_data["Nodes"]:
                print(node["Name"])
                for variable in node["Variables"]:
                    print(variable["DisplayName"])
                    print(variable["TelemetryName"])
                    read_node = client.get_node(variable["NodeId"])
                    val = await read_node.get_value()
                    print(val)
Beispiel #28
0
async def read(url):
	print("######################debug: read() started")

	
	async with Client(url=url) as client:
		root = client.get_root_node()
		program = await root.get_child(['0:Objects', '0:Server', '4:CODESYS Control Win V3 x64', '3:Resources', '4:Application', '3:Programs', '4:PLC_PRG'])
		vars = await program.get_children()
	
		var_test = client.get_node("ns=4;s=|var|CODESYS Control Win V3 x64.Application.PLC_PRG.int_var")
		print('{}: \t {}' .format("teste", await var_test.get_value()))
		##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

		while True:
			for var in vars:
				var_output_test= await var.read_value()
				print('{}: \t {}' .format((await var.get_display_name())._text, await var.read_value()))
				print("test", var_output_test)
			await asyncio.sleep(1)
			print("-----------------------------------------------------")
			#input_var= input()
			#print( input_var)
				
	
		_logger.info('Objects node is: %r', root)
		print(program)
		_logger.info('Children of root are: %r', await root.get_children())
	
		print(await root.get_children())
Beispiel #29
0
async def main():
    global _Running
    try:
        async with Client(url="opc.tcp://192.168.0.102:4840/") as client:
            announcement('Connected')
            _State = client.get_node("ns=2;i=2")
            Vib_Data_List = await client.nodes.root.get_child(
                ["0:Objects", "2:MyACC", "2:Data_List"])
            CT_Threshold = await client.nodes.root.get_child(
                ["0:Objects", "2:MyACC", "2:CT_Threshold"])
            #CT_Data_List =await client.nodes.root.get_child(["0:Objects","2:MyACC","2:CT_Data_List"])
            await CT_Threshold.write_value(3200)
            # Check data change
            handler = SubHandler()
            sub = await client.create_subscription(500, handler)
            handle = await sub.subscribe_data_change(Vib_Data_List)
            while True:
                try:
                    await _State.write_value(3)
                    await asyncio.sleep(10)
                except Exception as e:
                    print(e)
                    break
    except Exception as e:
        print(e)
    finally:
        if _Running:
            announcement('Disconnected')
        else:
            await _State.set_value(0)
        announcement('End')
Beispiel #30
0
async def browse_nodes_children(Server_URL, NodeId):
    """Explora los hijos directos del NodeId provisto

    Args:
        Server_URL (string): Dirección del servidor OPC-UA
        NodeId (string): Identificador del nodo de interés

    Returns:
        list: Nodos hijos
    """
    async with Client(url=Server_URL, timeout=60*60) as client:
        node = client.get_node(NodeId)
        children = await node.get_children()
        Nodes = [None]*len(children)
        Nodes_Names = [None]*len(children)
        Nodes_with_children = [0]*len(children)
        if children:
            for i, child in enumerate(children):
                browse_name = await child.read_display_name()
                Nodes[i] = child
                Nodes_Names[i] = browse_name.Text
                if await child.get_children():
                    Nodes_with_children[i] = 1
                # print(f'{Nodes[i]}\t|\t{Nodes_Names[i]}\t{Nodes_with_children[i]}')
        return [Nodes, Nodes_Names, Nodes_with_children]