|
1
|
|
|
""" |
|
2
|
|
|
High level method related functions |
|
3
|
|
|
""" |
|
4
|
|
|
|
|
5
|
1 |
|
from opcua import ua |
|
6
|
1 |
|
from opcua.common import node |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
1 |
|
def call_method(parent, methodid, *args): |
|
10
|
|
|
""" |
|
11
|
|
|
Call an OPC-UA method. methodid is browse name of child method or the |
|
12
|
|
|
nodeid of method as a NodeId object |
|
13
|
|
|
arguments are variants or python object convertible to variants. |
|
14
|
|
|
which may be of different types |
|
15
|
|
|
returns a list of variants which are output of the method |
|
16
|
|
|
""" |
|
17
|
1 |
|
if isinstance(methodid, str): |
|
18
|
1 |
|
methodid = parent.get_child(methodid).nodeid |
|
19
|
1 |
|
elif isinstance(methodid, node.Node): |
|
20
|
1 |
|
methodid = methodid.nodeid |
|
21
|
|
|
|
|
22
|
1 |
|
arguments = [] |
|
23
|
1 |
|
for arg in args: |
|
24
|
1 |
|
if not isinstance(arg, ua.Variant): |
|
25
|
1 |
|
arg = ua.Variant(arg) |
|
26
|
1 |
|
arguments.append(arg) |
|
27
|
|
|
|
|
28
|
1 |
|
result = _call_method(parent.server, parent.nodeid, methodid, arguments) |
|
29
|
|
|
|
|
30
|
1 |
|
if len(result.OutputArguments) == 0: |
|
31
|
|
|
return None |
|
32
|
1 |
|
elif len(result.OutputArguments) == 1: |
|
33
|
1 |
|
return result.OutputArguments[0].Value |
|
34
|
|
|
else: |
|
35
|
|
|
return [var.Value for var in result.OutputArguments] |
|
36
|
|
|
|
|
37
|
|
|
|
|
38
|
1 |
|
def _call_method(server, parentnodeid, methodid, arguments): |
|
39
|
1 |
|
request = ua.CallMethodRequest() |
|
40
|
1 |
|
request.ObjectId = parentnodeid |
|
41
|
1 |
|
request.MethodId = methodid |
|
42
|
1 |
|
request.InputArguments = arguments |
|
43
|
1 |
|
methodstocall = [request] |
|
44
|
1 |
|
results = server.call(methodstocall) |
|
45
|
1 |
|
res = results[0] |
|
46
|
1 |
|
res.StatusCode.check() |
|
47
|
1 |
|
return res |
|
48
|
|
|
|
|
49
|
|
|
|
|
50
|
1 |
|
def uamethod(func): |
|
51
|
|
|
""" |
|
52
|
|
|
Method decorator to automatically convert |
|
53
|
|
|
arguments and output to and from variants |
|
54
|
|
|
""" |
|
55
|
1 |
|
def wrapper(parent, *args): |
|
56
|
1 |
|
if isinstance(parent, ua.NodeId): |
|
57
|
1 |
|
result = func(parent, *[arg.Value for arg in args]) |
|
58
|
|
|
else: |
|
59
|
|
|
self = parent |
|
60
|
|
|
parent = args[0] |
|
61
|
|
|
args = args[1:] |
|
62
|
|
|
result = func(self, parent, *[arg.Value for arg in args]) |
|
63
|
|
|
|
|
64
|
1 |
|
return to_variant(result) |
|
65
|
1 |
|
return wrapper |
|
66
|
|
|
|
|
67
|
|
|
|
|
68
|
1 |
|
def to_variant(*args): |
|
69
|
1 |
|
uaargs = [] |
|
70
|
1 |
|
for arg in args: |
|
71
|
1 |
|
uaargs.append(ua.Variant(arg)) |
|
72
|
1 |
|
return uaargs |
|
73
|
|
|
|
|
74
|
|
|
|
|
75
|
|
|
|