1
|
|
|
''' |
2
|
|
|
Show 3 different examples for creating an object: |
3
|
|
|
1) create a basic object |
4
|
|
|
2) create a new object type and a instance of the new object type |
5
|
|
|
3) import a new object from xml address space and create a instance of the new object type |
6
|
|
|
''' |
7
|
|
|
import sys |
8
|
|
|
sys.path.insert(0, "..") |
9
|
|
|
import asyncio |
10
|
|
|
|
11
|
|
|
import asyncua |
12
|
|
|
|
13
|
|
|
from asyncua import ua, Server |
14
|
|
|
|
15
|
|
|
|
16
|
|
|
async def main(): |
17
|
|
|
|
18
|
|
|
# setup our server |
19
|
|
|
server = Server() |
20
|
|
|
await server.init() |
21
|
|
|
|
22
|
|
|
server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/") |
23
|
|
|
|
24
|
|
|
# setup our own namespace, not really necessary but should as spec |
25
|
|
|
uri = "http://examples.freeopcua.github.io" |
26
|
|
|
idx = await server.register_namespace(uri) |
27
|
|
|
|
28
|
|
|
# Example 1 - create a basic object |
29
|
|
|
#------------------------------------------------------------------------------- |
30
|
|
|
myobj = await server.nodes.objects.add_object(idx, "MyObject") |
31
|
|
|
#------------------------------------------------------------------------------- |
32
|
|
|
|
33
|
|
|
# Example 2 - create a new object type and a instance of the new object type |
34
|
|
|
#------------------------------------------------------------------------------- |
35
|
|
|
mycustomobj_type = await server.nodes.base_object_type.add_object_type(idx, "MyCustomObjectType") |
36
|
|
|
await mycustomobj_type.add_variable(0, "var_should_be_there_after_instantiate", 1.0) # demonstrates instantiate |
37
|
|
|
|
38
|
|
|
myobj = await server.nodes.objects.add_object(idx, "MyCustomObjectA", mycustomobj_type.nodeid) |
39
|
|
|
#------------------------------------------------------------------------------- |
40
|
|
|
|
41
|
|
|
# Example 3 - import a new object from xml address space and create a instance of the new object type |
42
|
|
|
#------------------------------------------------------------------------------- |
43
|
|
|
# Import customobject type |
44
|
|
|
await server.import_xml('customobject.xml') |
45
|
|
|
|
46
|
|
|
# get nodeid of custom object type by one of the following 2 ways: |
47
|
|
|
# 1) Use node ID |
48
|
|
|
# 3) Or As child from BaseObjectType |
49
|
|
|
myobject1_type_nodeid = ua.NodeId.from_string('ns=%d;i=2' % idx) |
50
|
|
|
myobject2_type_nodeid = (await server.nodes.base_object_type.get_child([f"{idx}:MyCustomObjectType"])).nodeid |
51
|
|
|
|
52
|
|
|
# populating our address space |
53
|
|
|
myobj = await server.nodes.objects.add_object(idx, "MyCustomObjectB", myobject2_type_nodeid) |
54
|
|
|
#------------------------------------------------------------------------------- |
55
|
|
|
|
56
|
|
|
# starting! |
57
|
|
|
async with server: |
58
|
|
|
while True: |
59
|
|
|
await asyncio.sleep(1) |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
if __name__ == "__main__": |
63
|
|
|
asyncio.run(main()) |
64
|
|
|
|