1
|
|
|
import logging |
2
|
|
|
import sys |
3
|
|
|
import argparse |
4
|
|
|
from datetime import datetime |
5
|
|
|
from enum import Enum |
6
|
|
|
import math |
7
|
|
|
import time |
8
|
|
|
|
9
|
|
|
try: |
10
|
|
|
from IPython import embed |
11
|
|
|
except ImportError: |
12
|
|
|
import code |
13
|
|
|
|
14
|
|
|
def embed(): |
15
|
|
|
code.interact(local=dict(globals(), **locals())) |
16
|
|
|
|
17
|
|
|
from opcua import ua |
18
|
|
|
from opcua import Client |
19
|
|
|
from opcua import Server |
20
|
|
|
from opcua import Node |
21
|
|
|
from opcua import uamethod |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
def add_minimum_args(parser): |
25
|
|
|
parser.add_argument("-u", |
26
|
|
|
"--url", |
27
|
|
|
help="URL of OPC UA server (for example: opc.tcp://example.org:4840)", |
28
|
|
|
default='opc.tcp://localhost:4840', |
29
|
|
|
metavar="URL") |
30
|
|
|
parser.add_argument("-v", |
31
|
|
|
"--verbose", |
32
|
|
|
dest="loglevel", |
33
|
|
|
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], |
34
|
|
|
default='WARNING', |
35
|
|
|
help="Set log level") |
36
|
|
|
parser.add_argument("--timeout", |
37
|
|
|
dest="timeout", |
38
|
|
|
type=int, |
39
|
|
|
default=1, |
40
|
|
|
help="Set socket timeout (NOT the diverse UA timeouts)") |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
def add_common_args(parser, default_node='i=84'): |
44
|
|
|
add_minimum_args(parser) |
45
|
|
|
parser.add_argument("-n", |
46
|
|
|
"--nodeid", |
47
|
|
|
help="Fully-qualified node ID (for example: i=85). Default: root node", |
48
|
|
|
default=default_node, |
49
|
|
|
metavar="NODE") |
50
|
|
|
parser.add_argument("-p", |
51
|
|
|
"--path", |
52
|
|
|
help="Comma separated browse path to the node starting at NODE (for example: 3:Mybject,3:MyVariable)", |
53
|
|
|
default='', |
54
|
|
|
metavar="BROWSEPATH") |
55
|
|
|
parser.add_argument("-i", |
56
|
|
|
"--namespace", |
57
|
|
|
help="Default namespace", |
58
|
|
|
type=int, |
59
|
|
|
default=0, |
60
|
|
|
metavar="NAMESPACE") |
61
|
|
|
parser.add_argument("--security", |
62
|
|
|
help="Security settings, for example: Basic256,SignAndEncrypt,cert.der,pk.pem[,server_cert.der]. Default: None", |
63
|
|
|
default='') |
64
|
|
|
|
65
|
|
|
|
66
|
|
|
def _require_nodeid(parser, args): |
67
|
|
|
# check that a nodeid has been given explicitly, a bit hackish... |
68
|
|
|
if args.nodeid == "i=84" and args.path == "": |
69
|
|
|
parser.print_usage() |
70
|
|
|
print("{}: error: A NodeId or BrowsePath is required".format(parser.prog)) |
71
|
|
|
sys.exit(1) |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
def parse_args(parser, requirenodeid=False): |
75
|
|
|
args = parser.parse_args() |
76
|
|
|
logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) |
77
|
|
|
if args.url and '://' not in args.url: |
78
|
|
|
logging.info("Adding default scheme %s to URL %s", ua.OPC_TCP_SCHEME, args.url) |
79
|
|
|
args.url = ua.OPC_TCP_SCHEME + '://' + args.url |
80
|
|
|
if requirenodeid: |
81
|
|
|
_require_nodeid(parser, args) |
82
|
|
|
return args |
83
|
|
|
|
84
|
|
|
|
85
|
|
|
def get_node(client, args): |
86
|
|
|
node = client.get_node(args.nodeid) |
87
|
|
|
if args.path: |
88
|
|
|
node = node.get_child(args.path.split(",")) |
89
|
|
|
return node |
90
|
|
|
|
91
|
|
|
|
92
|
|
|
def uaread(): |
93
|
|
|
parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node") |
94
|
|
|
add_common_args(parser) |
95
|
|
|
parser.add_argument("-a", |
96
|
|
|
"--attribute", |
97
|
|
|
dest="attribute", |
98
|
|
|
type=int, |
99
|
|
|
default=ua.AttributeIds.Value, |
100
|
|
|
help="Set attribute to read") |
101
|
|
|
parser.add_argument("-t", |
102
|
|
|
"--datatype", |
103
|
|
|
dest="datatype", |
104
|
|
|
default="python", |
105
|
|
|
choices=['python', 'variant', 'datavalue'], |
106
|
|
|
help="Data type to return") |
107
|
|
|
|
108
|
|
|
args = parse_args(parser, requirenodeid=True) |
109
|
|
|
|
110
|
|
|
client = Client(args.url, timeout=args.timeout) |
111
|
|
|
client.set_security_string(args.security) |
112
|
|
|
client.connect() |
113
|
|
|
try: |
114
|
|
|
node = get_node(client, args) |
115
|
|
|
attr = node.get_attribute(args.attribute) |
116
|
|
|
if args.datatype == "python": |
117
|
|
|
print(attr.Value.Value) |
118
|
|
|
elif args.datatype == "variant": |
119
|
|
|
print(attr.Value) |
120
|
|
|
else: |
121
|
|
|
print(attr) |
122
|
|
|
finally: |
123
|
|
|
client.disconnect() |
124
|
|
|
sys.exit(0) |
125
|
|
|
print(args) |
126
|
|
|
|
127
|
|
|
|
128
|
|
|
def _args_to_array(val, array): |
129
|
|
|
if array == "guess": |
130
|
|
|
if "," in val: |
131
|
|
|
array = "true" |
132
|
|
|
if array == "true": |
133
|
|
|
val = val.split(",") |
134
|
|
|
return val |
135
|
|
|
|
136
|
|
|
|
137
|
|
|
def _arg_to_bool(val): |
138
|
|
|
if val in ("true", "True"): |
139
|
|
|
return True |
140
|
|
|
else: |
141
|
|
|
return False |
142
|
|
|
|
143
|
|
|
|
144
|
|
|
def _arg_to_variant(val, array, ptype, varianttype=None): |
145
|
|
|
val = _args_to_array(val, array) |
146
|
|
|
if isinstance(val, list): |
147
|
|
|
val = [ptype(i) for i in val] |
148
|
|
|
else: |
149
|
|
|
val = ptype(val) |
150
|
|
|
if varianttype: |
151
|
|
|
return ua.Variant(val, varianttype) |
152
|
|
|
else: |
153
|
|
|
return ua.Variant(val) |
154
|
|
|
|
155
|
|
|
|
156
|
|
|
def _val_to_variant(val, args): |
157
|
|
|
array = args.array |
158
|
|
|
if args.datatype == "guess": |
159
|
|
|
if val in ("true", "True", "false", "False"): |
160
|
|
|
return _arg_to_variant(val, array, _arg_to_bool) |
161
|
|
|
try: |
162
|
|
|
return _arg_to_variant(val, array, int) |
163
|
|
|
except ValueError: |
164
|
|
|
try: |
165
|
|
|
return _arg_to_variant(val, array, float) |
166
|
|
|
except ValueError: |
167
|
|
|
return _arg_to_variant(val, array, str) |
168
|
|
|
elif args.datatype == "bool": |
169
|
|
|
if val in ("1", "True", "true"): |
170
|
|
|
return ua.Variant(True, ua.VariantType.Boolean) |
171
|
|
|
else: |
172
|
|
|
return ua.Variant(False, ua.VariantType.Boolean) |
173
|
|
|
elif args.datatype == "sbyte": |
174
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.SByte) |
175
|
|
|
elif args.datatype == "byte": |
176
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.Byte) |
177
|
|
|
#elif args.datatype == "uint8": |
178
|
|
|
#return _arg_to_variant(val, array, int, ua.VariantType.Byte) |
179
|
|
|
elif args.datatype == "uint16": |
180
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.UInt16) |
181
|
|
|
elif args.datatype == "uint32": |
182
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.UInt32) |
183
|
|
|
elif args.datatype == "uint64": |
184
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.UInt64) |
185
|
|
|
#elif args.datatype == "int8": |
186
|
|
|
#return ua.Variant(int(val), ua.VariantType.Int8) |
187
|
|
|
elif args.datatype == "int16": |
188
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.Int16) |
189
|
|
|
elif args.datatype == "int32": |
190
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.Int32) |
191
|
|
|
elif args.datatype == "int64": |
192
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.Int64) |
193
|
|
|
elif args.datatype == "float": |
194
|
|
|
return _arg_to_variant(val, array, float, ua.VariantType.Float) |
195
|
|
|
elif args.datatype == "double": |
196
|
|
|
return _arg_to_variant(val, array, float, ua.VariantType.Double) |
197
|
|
|
elif args.datatype == "string": |
198
|
|
|
return _arg_to_variant(val, array, str, ua.VariantType.String) |
199
|
|
|
elif args.datatype == "datetime": |
200
|
|
|
raise NotImplementedError |
201
|
|
|
elif args.datatype == "Guid": |
202
|
|
|
return _arg_to_variant(val, array, bytes, ua.VariantType.Guid) |
203
|
|
|
elif args.datatype == "ByteString": |
204
|
|
|
return _arg_to_variant(val, array, bytes, ua.VariantType.ByteString) |
205
|
|
|
elif args.datatype == "xml": |
206
|
|
|
return _arg_to_variant(val, array, str, ua.VariantType.XmlElement) |
207
|
|
|
elif args.datatype == "nodeid": |
208
|
|
|
return _arg_to_variant(val, array, ua.NodeId.from_string, ua.VariantType.NodeId) |
209
|
|
|
elif args.datatype == "expandednodeid": |
210
|
|
|
return _arg_to_variant(val, array, ua.ExpandedNodeId.from_string, ua.VariantType.ExpandedNodeId) |
211
|
|
|
elif args.datatype == "statuscode": |
212
|
|
|
return _arg_to_variant(val, array, int, ua.VariantType.StatusCode) |
213
|
|
|
elif args.datatype in ("qualifiedname", "browsename"): |
214
|
|
|
return _arg_to_variant(val, array, ua.QualifiedName.from_string, ua.VariantType.QualifiedName) |
215
|
|
|
elif args.datatype == "LocalizedText": |
216
|
|
|
return _arg_to_variant(val, array, ua.LocalizedText, ua.VariantType.LocalizedText) |
217
|
|
|
|
218
|
|
|
|
219
|
|
|
def uawrite(): |
220
|
|
|
parser = argparse.ArgumentParser(description="Write attribute of a node, per default write value of node") |
221
|
|
|
add_common_args(parser) |
222
|
|
|
parser.add_argument("-a", |
223
|
|
|
"--attribute", |
224
|
|
|
dest="attribute", |
225
|
|
|
type=int, |
226
|
|
|
default=ua.AttributeIds.Value, |
227
|
|
|
help="Set attribute to read") |
228
|
|
|
parser.add_argument("-l", |
229
|
|
|
"--list", |
230
|
|
|
"--array", |
231
|
|
|
dest="array", |
232
|
|
|
default="guess", |
233
|
|
|
choices=["guess", "true", "false"], |
234
|
|
|
help="Value is an array") |
235
|
|
|
parser.add_argument("-t", |
236
|
|
|
"--datatype", |
237
|
|
|
dest="datatype", |
238
|
|
|
default="guess", |
239
|
|
|
choices=["guess", 'byte', 'sbyte', 'nodeid', 'expandednodeid', 'qualifiedname', 'browsename', 'string', 'float', 'double', 'int16', 'int32', "int64", 'uint16', 'uint32', 'uint64', "bool", "string", 'datetime', 'bytestring', 'xmlelement', 'statuscode', 'localizedtext'], |
240
|
|
|
help="Data type to return") |
241
|
|
|
parser.add_argument("value", |
242
|
|
|
help="Value to be written", |
243
|
|
|
metavar="VALUE") |
244
|
|
|
args = parse_args(parser, requirenodeid=True) |
245
|
|
|
|
246
|
|
|
client = Client(args.url, timeout=args.timeout) |
247
|
|
|
client.set_security_string(args.security) |
248
|
|
|
client.connect() |
249
|
|
|
try: |
250
|
|
|
node = get_node(client, args) |
251
|
|
|
val = _val_to_variant(args.value, args) |
252
|
|
|
node.set_attribute(args.attribute, ua.DataValue(val)) |
253
|
|
|
finally: |
254
|
|
|
client.disconnect() |
255
|
|
|
sys.exit(0) |
256
|
|
|
print(args) |
257
|
|
|
|
258
|
|
|
|
259
|
|
|
def uals(): |
260
|
|
|
parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result") |
261
|
|
|
add_common_args(parser) |
262
|
|
|
parser.add_argument("-l", |
263
|
|
|
dest="long_format", |
264
|
|
|
const=3, |
265
|
|
|
nargs="?", |
266
|
|
|
type=int, |
267
|
|
|
help="use a long listing format") |
268
|
|
|
parser.add_argument("-d", |
269
|
|
|
"--depth", |
270
|
|
|
default=1, |
271
|
|
|
type=int, |
272
|
|
|
help="Browse depth") |
273
|
|
|
|
274
|
|
|
args = parse_args(parser) |
275
|
|
|
if args.long_format is None: |
276
|
|
|
args.long_format = 1 |
277
|
|
|
|
278
|
|
|
client = Client(args.url, timeout=args.timeout) |
279
|
|
|
client.set_security_string(args.security) |
280
|
|
|
client.connect() |
281
|
|
|
try: |
282
|
|
|
node = get_node(client, args) |
283
|
|
|
print("Browsing node {} at {}\n".format(node, args.url)) |
284
|
|
|
if args.long_format == 0: |
285
|
|
|
_lsprint_0(node, args.depth - 1) |
286
|
|
|
elif args.long_format == 1: |
287
|
|
|
_lsprint_1(node, args.depth - 1) |
288
|
|
|
else: |
289
|
|
|
_lsprint_long(node, args.depth - 1) |
290
|
|
|
finally: |
291
|
|
|
client.disconnect() |
292
|
|
|
sys.exit(0) |
293
|
|
|
print(args) |
294
|
|
|
|
295
|
|
|
|
296
|
|
|
def _lsprint_0(node, depth, indent=""): |
297
|
|
|
if not indent: |
298
|
|
|
print("{:30} {:25}".format("DisplayName", "NodeId")) |
299
|
|
|
print("") |
300
|
|
|
for desc in node.get_children_descriptions(): |
301
|
|
|
print("{}{:30} {:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string())) |
302
|
|
|
if depth: |
303
|
|
|
_lsprint_0(Node(node.server, desc.NodeId), depth - 1, indent + " ") |
304
|
|
|
|
305
|
|
|
|
306
|
|
|
def _lsprint_1(node, depth, indent=""): |
307
|
|
|
if not indent: |
308
|
|
|
print("{:30} {:25} {:25} {:25}".format("DisplayName", "NodeId", "BrowseName", "Value")) |
309
|
|
|
print("") |
310
|
|
|
|
311
|
|
|
for desc in node.get_children_descriptions(): |
312
|
|
|
if desc.NodeClass == ua.NodeClass.Variable: |
313
|
|
|
val = Node(node.server, desc.NodeId).get_value() |
314
|
|
|
print("{}{:30} {!s:25} {!s:25}, {!s:3}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string(), val)) |
315
|
|
|
else: |
316
|
|
|
print("{}{:30} {!s:25} {!s:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string())) |
317
|
|
|
if depth: |
318
|
|
|
_lsprint_1(Node(node.server, desc.NodeId), depth - 1, indent + " ") |
319
|
|
|
|
320
|
|
|
|
321
|
|
|
def _lsprint_long(pnode, depth, indent=""): |
322
|
|
|
if not indent: |
323
|
|
|
print("{:30} {:25} {:25} {:10} {:30} {:25}".format("DisplayName", "NodeId", "BrowseName", "DataType", "Timestamp", "Value")) |
324
|
|
|
print("") |
325
|
|
|
for node in pnode.get_children(): |
326
|
|
|
attrs = node.get_attributes([ua.AttributeIds.DisplayName, |
327
|
|
|
ua.AttributeIds.BrowseName, |
328
|
|
|
ua.AttributeIds.NodeClass, |
329
|
|
|
ua.AttributeIds.WriteMask, |
330
|
|
|
ua.AttributeIds.UserWriteMask, |
331
|
|
|
ua.AttributeIds.DataType, |
332
|
|
|
ua.AttributeIds.Value]) |
333
|
|
|
name, bname, nclass, mask, umask, dtype, val = [attr.Value.Value for attr in attrs] |
334
|
|
|
update = attrs[-1].ServerTimestamp |
335
|
|
|
if nclass == ua.NodeClass.Variable: |
336
|
|
|
print("{}{:30} {:25} {:25} {:10} {!s:30} {!s:25}".format(indent, name.to_string(), node.nodeid.to_string(), bname.to_string(), dtype.to_string(), update, val)) |
337
|
|
|
else: |
338
|
|
|
print("{}{:30} {:25} {:25}".format(indent, name.to_string(), bname.to_string(), node.nodeid.to_string())) |
339
|
|
|
if depth: |
340
|
|
|
_lsprint_long(node, depth - 1, indent + " ") |
341
|
|
|
|
342
|
|
|
|
343
|
|
|
class SubHandler(object): |
344
|
|
|
|
345
|
|
|
def datachange_notification(self, node, val, data): |
346
|
|
|
print("New data change event", node, val, data) |
347
|
|
|
|
348
|
|
|
def event_notification(self, event): |
349
|
|
|
print("New event", event) |
350
|
|
|
|
351
|
|
|
|
352
|
|
|
def uasubscribe(): |
353
|
|
|
parser = argparse.ArgumentParser(description="Subscribe to a node and print results") |
354
|
|
|
add_common_args(parser) |
355
|
|
|
parser.add_argument("-t", |
356
|
|
|
"--eventtype", |
357
|
|
|
dest="eventtype", |
358
|
|
|
default="datachange", |
359
|
|
|
choices=['datachange', 'event'], |
360
|
|
|
help="Event type to subscribe to") |
361
|
|
|
|
362
|
|
|
args = parse_args(parser, requirenodeid=False) |
363
|
|
|
if args.eventtype == "datachange": |
364
|
|
|
_require_nodeid(parser, args) |
365
|
|
|
else: |
366
|
|
|
# FIXME: this is broken, someone may have written i=84 on purpose |
367
|
|
|
if args.nodeid == "i=84" and args.path == "": |
368
|
|
|
args.nodeid = "i=2253" |
369
|
|
|
|
370
|
|
|
client = Client(args.url, timeout=args.timeout) |
371
|
|
|
client.set_security_string(args.security) |
372
|
|
|
client.connect() |
373
|
|
|
try: |
374
|
|
|
node = get_node(client, args) |
375
|
|
|
handler = SubHandler() |
376
|
|
|
sub = client.create_subscription(500, handler) |
377
|
|
|
if args.eventtype == "datachange": |
378
|
|
|
sub.subscribe_data_change(node) |
379
|
|
|
else: |
380
|
|
|
sub.subscribe_events(node) |
381
|
|
|
embed() |
382
|
|
|
finally: |
383
|
|
|
client.disconnect() |
384
|
|
|
sys.exit(0) |
385
|
|
|
print(args) |
386
|
|
|
|
387
|
|
|
|
388
|
|
|
def application_to_strings(app): |
389
|
|
|
result = [] |
390
|
|
|
result.append(('Application URI', app.ApplicationUri)) |
391
|
|
|
optionals = [ |
392
|
|
|
('Product URI', app.ProductUri), |
393
|
|
|
('Application Name', app.ApplicationName.to_string()), |
394
|
|
|
('Application Type', str(app.ApplicationType)), |
395
|
|
|
('Gateway Server URI', app.GatewayServerUri), |
396
|
|
|
('Discovery Profile URI', app.DiscoveryProfileUri), |
397
|
|
|
] |
398
|
|
|
for (n, v) in optionals: |
399
|
|
|
if v: |
400
|
|
|
result.append((n, v)) |
401
|
|
|
for url in app.DiscoveryUrls: |
402
|
|
|
result.append(('Discovery URL', url)) |
403
|
|
|
return result # ['{}: {}'.format(n, v) for (n, v) in result] |
404
|
|
|
|
405
|
|
|
|
406
|
|
|
def cert_to_string(der): |
407
|
|
|
if not der: |
408
|
|
|
return '[no certificate]' |
409
|
|
|
try: |
410
|
|
|
from opcua.crypto import uacrypto |
411
|
|
|
except ImportError: |
412
|
|
|
return "{} bytes".format(len(der)) |
413
|
|
|
cert = uacrypto.x509_from_der(der) |
414
|
|
|
return uacrypto.x509_to_string(cert) |
415
|
|
|
|
416
|
|
|
|
417
|
|
|
def endpoint_to_strings(ep): |
418
|
|
|
result = [('Endpoint URL', ep.EndpointUrl)] |
419
|
|
|
result += application_to_strings(ep.Server) |
420
|
|
|
result += [ |
421
|
|
|
('Server Certificate', cert_to_string(ep.ServerCertificate)), |
422
|
|
|
('Security Mode', str(ep.SecurityMode)), |
423
|
|
|
('Security Policy URI', ep.SecurityPolicyUri)] |
424
|
|
|
for tok in ep.UserIdentityTokens: |
425
|
|
|
result += [ |
426
|
|
|
('User policy', tok.PolicyId), |
427
|
|
|
(' Token type', str(tok.TokenType))] |
428
|
|
|
if tok.IssuedTokenType or tok.IssuerEndpointUrl: |
429
|
|
|
result += [ |
430
|
|
|
(' Issued Token type', tok.IssuedTokenType), |
431
|
|
|
(' Issuer Endpoint URL', tok.IssuerEndpointUrl)] |
432
|
|
|
if tok.SecurityPolicyUri: |
433
|
|
|
result.append((' Security Policy URI', tok.SecurityPolicyUri)) |
434
|
|
|
result += [ |
435
|
|
|
('Transport Profile URI', ep.TransportProfileUri), |
436
|
|
|
('Security Level', ep.SecurityLevel)] |
437
|
|
|
return result |
438
|
|
|
|
439
|
|
|
|
440
|
|
|
def uaclient(): |
441
|
|
|
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") |
442
|
|
|
add_common_args(parser) |
443
|
|
|
parser.add_argument("-c", |
444
|
|
|
"--certificate", |
445
|
|
|
help="set client certificate") |
446
|
|
|
parser.add_argument("-k", |
447
|
|
|
"--private_key", |
448
|
|
|
help="set client private key") |
449
|
|
|
args = parse_args(parser) |
450
|
|
|
|
451
|
|
|
client = Client(args.url, timeout=args.timeout) |
452
|
|
|
client.set_security_string(args.security) |
453
|
|
|
if args.certificate: |
454
|
|
|
client.load_client_certificate(args.certificate) |
455
|
|
|
if args.private_key: |
456
|
|
|
client.load_private_key(args.private_key) |
457
|
|
|
client.connect() |
458
|
|
|
try: |
459
|
|
|
root = client.get_root_node() |
460
|
|
|
objects = client.get_objects_node() |
461
|
|
|
mynode = get_node(client, args) |
462
|
|
|
embed() |
463
|
|
|
finally: |
464
|
|
|
client.disconnect() |
465
|
|
|
sys.exit(0) |
466
|
|
|
|
467
|
|
|
|
468
|
|
|
def uaserver(): |
469
|
|
|
parser = argparse.ArgumentParser(description="Run an example OPC-UA server. By importing xml definition and using uawrite command line, it is even possible to expose real data using this server") |
470
|
|
|
# we setup a server, this is a bit different from other tool so we do not reuse common arguments |
471
|
|
|
parser.add_argument("-u", |
472
|
|
|
"--url", |
473
|
|
|
help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840", |
474
|
|
|
default='opc.tcp://0.0.0.0:4840', |
475
|
|
|
metavar="URL") |
476
|
|
|
parser.add_argument("-v", |
477
|
|
|
"--verbose", |
478
|
|
|
dest="loglevel", |
479
|
|
|
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], |
480
|
|
|
default='WARNING', |
481
|
|
|
help="Set log level") |
482
|
|
|
parser.add_argument("-x", |
483
|
|
|
"--xml", |
484
|
|
|
metavar="XML_FILE", |
485
|
|
|
help="Populate address space with nodes defined in XML") |
486
|
|
|
parser.add_argument("-p", |
487
|
|
|
"--populate", |
488
|
|
|
action="store_true", |
489
|
|
|
help="Populate address space with some sample nodes") |
490
|
|
|
parser.add_argument("-c", |
491
|
|
|
"--disable-clock", |
492
|
|
|
action="store_true", |
493
|
|
|
help="Disable clock, to avoid seeing many write if debugging an application") |
494
|
|
|
parser.add_argument("-s", |
495
|
|
|
"--shell", |
496
|
|
|
action="store_true", |
497
|
|
|
help="Start python shell instead of randomly changing node values") |
498
|
|
|
parser.add_argument("--certificate", |
499
|
|
|
help="set server certificate") |
500
|
|
|
parser.add_argument("--private_key", |
501
|
|
|
help="set server private key") |
502
|
|
|
args = parser.parse_args() |
503
|
|
|
logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) |
504
|
|
|
|
505
|
|
|
server = Server() |
506
|
|
|
server.set_endpoint(args.url) |
507
|
|
|
if args.certificate: |
508
|
|
|
server.load_certificate(args.certificate) |
509
|
|
|
if args.private_key: |
510
|
|
|
server.load_private_key(args.private_key) |
511
|
|
|
server.disable_clock(args.disable_clock) |
512
|
|
|
server.set_server_name("FreeOpcUa Example Server") |
513
|
|
|
if args.xml: |
514
|
|
|
server.import_xml(args.xml) |
515
|
|
|
if args.populate: |
516
|
|
|
@uamethod |
517
|
|
|
def multiply(parent, x, y): |
518
|
|
|
print("multiply method call with parameters: ", x, y) |
519
|
|
|
return x * y |
520
|
|
|
|
521
|
|
|
uri = "http://examples.freeopcua.github.io" |
522
|
|
|
idx = server.register_namespace(uri) |
523
|
|
|
objects = server.get_objects_node() |
524
|
|
|
myobj = objects.add_object(idx, "MyObject") |
525
|
|
|
mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7) |
526
|
|
|
mywritablevar.set_writable() # Set MyVariable to be writable by clients |
527
|
|
|
myvar = myobj.add_variable(idx, "MyVariable", 6.7) |
528
|
|
|
myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9]) |
529
|
|
|
myprop = myobj.add_property(idx, "MyProperty", "I am a property") |
530
|
|
|
mymethod = myobj.add_method(idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double]) |
531
|
|
|
|
532
|
|
|
server.start() |
533
|
|
|
try: |
534
|
|
|
if args.shell: |
535
|
|
|
embed() |
536
|
|
|
elif args.populate: |
537
|
|
|
count = 0 |
538
|
|
|
while True: |
539
|
|
|
time.sleep(1) |
540
|
|
|
myvar.set_value(math.sin(count / 10)) |
541
|
|
|
myarrayvar.set_value([math.sin(count / 10), math.sin(count / 100)]) |
542
|
|
|
count += 1 |
543
|
|
|
else: |
544
|
|
|
while True: |
545
|
|
|
time.sleep(1) |
546
|
|
|
finally: |
547
|
|
|
server.stop() |
548
|
|
|
sys.exit(0) |
549
|
|
|
|
550
|
|
|
|
551
|
|
|
def uadiscover(): |
552
|
|
|
parser = argparse.ArgumentParser(description="Performs OPC UA discovery and prints information on servers and endpoints.") |
553
|
|
|
add_minimum_args(parser) |
554
|
|
|
parser.add_argument("-n", |
555
|
|
|
"--network", |
556
|
|
|
action="store_true", |
557
|
|
|
help="Also send a FindServersOnNetwork request to server") |
558
|
|
|
#parser.add_argument("-s", |
559
|
|
|
#"--servers", |
560
|
|
|
#action="store_false", |
561
|
|
|
#help="send a FindServers request to server") |
562
|
|
|
#parser.add_argument("-e", |
563
|
|
|
#"--endpoints", |
564
|
|
|
#action="store_false", |
565
|
|
|
#help="send a GetEndpoints request to server") |
566
|
|
|
args = parse_args(parser) |
567
|
|
|
|
568
|
|
|
client = Client(args.url, timeout=args.timeout) |
569
|
|
|
|
570
|
|
|
if args.network: |
571
|
|
|
print("Performing discovery at {}\n".format(args.url)) |
572
|
|
|
for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1): |
573
|
|
|
print('Server {}:'.format(i)) |
574
|
|
|
#for (n, v) in application_to_strings(server): |
575
|
|
|
#print(' {}: {}'.format(n, v)) |
576
|
|
|
print('') |
577
|
|
|
|
578
|
|
|
print("Performing discovery at {}\n".format(args.url)) |
579
|
|
|
for i, server in enumerate(client.connect_and_find_servers(), start=1): |
580
|
|
|
print('Server {}:'.format(i)) |
581
|
|
|
for (n, v) in application_to_strings(server): |
582
|
|
|
print(' {}: {}'.format(n, v)) |
583
|
|
|
print('') |
584
|
|
|
|
585
|
|
|
for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1): |
586
|
|
|
print('Endpoint {}:'.format(i)) |
587
|
|
|
for (n, v) in endpoint_to_strings(ep): |
588
|
|
|
print(' {}: {}'.format(n, v)) |
589
|
|
|
print('') |
590
|
|
|
|
591
|
|
|
sys.exit(0) |
592
|
|
|
|
593
|
|
|
|
594
|
|
|
def print_history(o): |
595
|
|
|
if isinstance(o, ua.HistoryData): |
596
|
|
|
print("{:30} {:10} {}".format('Source timestamp', 'Status', 'Value')) |
597
|
|
|
for d in o.DataValues: |
598
|
|
|
print("{:30} {:10} {}".format(str(d.SourceTimestamp), d.StatusCode.name, d.Value)) |
599
|
|
|
|
600
|
|
|
|
601
|
|
|
def str_to_datetime(s): |
602
|
|
|
if not s: |
603
|
|
|
return datetime.utcnow() |
604
|
|
|
# FIXME: try different datetime formats |
605
|
|
|
for fmt in ["%Y-%m-%d", "%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"]: |
606
|
|
|
try: |
607
|
|
|
return datetime.strptime(s, fmt) |
608
|
|
|
except ValueError: |
609
|
|
|
pass |
610
|
|
|
|
611
|
|
|
|
612
|
|
|
def uahistoryread(): |
613
|
|
|
parser = argparse.ArgumentParser(description="Read history of a node") |
614
|
|
|
add_common_args(parser) |
615
|
|
|
parser.add_argument("--starttime", |
616
|
|
|
default="", |
617
|
|
|
help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time") |
618
|
|
|
parser.add_argument("--endtime", |
619
|
|
|
default="", |
620
|
|
|
help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time") |
621
|
|
|
|
622
|
|
|
args = parse_args(parser, requirenodeid=True) |
623
|
|
|
|
624
|
|
|
client = Client(args.url, timeout=args.timeout) |
625
|
|
|
client.set_security_string(args.security) |
626
|
|
|
client.connect() |
627
|
|
|
try: |
628
|
|
|
node = get_node(client, args) |
629
|
|
|
starttime = str_to_datetime(args.starttime) |
630
|
|
|
endtime = str_to_datetime(args.endtime) |
631
|
|
|
print("Reading raw history of node {} at {}; start at {}, end at {}\n".format(node, args.url, starttime, endtime)) |
632
|
|
|
print_history(node.read_raw_history(starttime, endtime)) |
633
|
|
|
finally: |
634
|
|
|
client.disconnect() |
635
|
|
|
sys.exit(0) |
636
|
|
|
|