Completed
Push — master ( 4bbb48...d16ca4 )
by Olivier
11:53 queued 09:32
created

client-events.task()   A

Complexity

Conditions 2

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 15
nop 0
dl 0
loc 22
rs 9.65
c 0
b 0
f 0
1
import asyncio
2
import logging
3
from asyncua import Client
4
5
logging.basicConfig(level=logging.INFO)
6
_logger = logging.getLogger(__name__)
7
8
9
class SubHandler:
10
    """
11
    Subscription Handler. To receive events from server for a subscription
12
    data_change and event methods are called directly from receiving thread.
13
    Do not do expensive, slow or network operation there. Create another
14
    thread if you need to do such a thing
15
    """
16
    def event_notification(self, event):
17
        _logger.info("New event received: %r", event)
18
19
20
async def main():
21
    url = "opc.tcp://localhost:4840/freeopcua/server/"
22
    # url = "opc.tcp://admin@localhost:4840/freeopcua/server/"  #connect using a user
23
    async with Client(url=url) as client:
24
        # Client has a few methods to get proxy to UA nodes that should always be in address space such as Root or Objects
25
        _logger.info("Objects node is: %r", client.nodes.root)
26
27
        # Now getting a variable node using its browse path
28
        obj = await client.nodes.root.get_child(["0:Objects", "2:MyObject"])
29
        _logger.info("MyObject is: %r", obj)
30
31
        myevent = await client.nodes.root.get_child(["0:Types", "0:EventTypes", "0:BaseEventType", "2:MyFirstEvent"])
32
        _logger.info("MyFirstEventType is: %r", myevent)
33
34
        msclt = SubHandler()
35
        sub = await client.create_subscription(100, msclt)
36
        handle = await sub.subscribe_events(obj, myevent)
37
        await asyncio.sleep(10)
38
        await sub.unsubscribe(handle)
39
        await sub.delete()
40
41
42
if __name__ == "__main__":
43
    asyncio.run(main())
44