Completed
Pull Request — master (#579)
by
unknown
06:23
created

uasubscribe()   D

Complexity

Conditions 8

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
dl 0
loc 38
ccs 0
cts 27
cp 0
crap 72
rs 4
c 1
b 0
f 0
1
import logging
2
import sys
3
import argparse
4
from datetime import datetime, timedelta
5
import math
6
import time
7
8
try:
9
    from IPython import embed
10
except ImportError:
11
    import code
12
13
    def embed():
14
        code.interact(local=dict(globals(), **locals()))
15
16
from opcua import ua
17
from opcua import Client
18
from opcua import Server
19
from opcua import Node
20
from opcua import uamethod
21
22
23
def add_minimum_args(parser):
24
    parser.add_argument("-u",
25
                        "--url",
26
                        help="URL of OPC UA server (for example: opc.tcp://example.org:4840)",
27
                        default='opc.tcp://localhost:4840',
28
                        metavar="URL")
29
    parser.add_argument("-v",
30
                        "--verbose",
31
                        dest="loglevel",
32
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
33
                        default='WARNING',
34
                        help="Set log level")
35
    parser.add_argument("--timeout",
36
                        dest="timeout",
37
                        type=int,
38
                        default=1,
39
                        help="Set socket timeout (NOT the diverse UA timeouts)")
40
41
42
def add_common_args(parser, default_node='i=84', require_node=False):
43
    add_minimum_args(parser)
44
    parser.add_argument("-n",
45
                        "--nodeid",
46
                        help="Fully-qualified node ID (for example: i=85). Default: root node",
47
                        default=default_node,
48
                        required=require_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("{0}: 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
        path = args.path.split(",")
89
        if node.nodeid == ua.NodeId(84, 0) and path[0] == "0:Root":
90
            # let user specify root if not node given
91
            path = path[1:]
92
        node = node.get_child(path)
93
    return node
94
95 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
96
def uaread():
97
    parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node")
98
    add_common_args(parser)
99
    parser.add_argument("-a",
100
                        "--attribute",
101
                        dest="attribute",
102
                        type=int,
103
                        default=ua.AttributeIds.Value,
104
                        help="Set attribute to read")
105
    parser.add_argument("-t",
106
                        "--datatype",
107
                        dest="datatype",
108
                        default="python",
109
                        choices=['python', 'variant', 'datavalue'],
110
                        help="Data type to return")
111
112
    args = parse_args(parser, requirenodeid=True)
113
114
    client = Client(args.url, timeout=args.timeout)
115
    client.set_security_string(args.security)
116
    client.connect()
117
    try:
118
        node = get_node(client, args)
119
        attr = node.get_attribute(args.attribute)
120
        if args.datatype == "python":
121
            print(attr.Value.Value)
122
        elif args.datatype == "variant":
123
            print(attr.Value)
124
        else:
125
            print(attr)
126
    finally:
127
        client.disconnect()
128
    sys.exit(0)
129
    print(args)
130
131
132
def _args_to_array(val, array):
133
    if array == "guess":
134
        if "," in val:
135
            array = "true"
136
    if array == "true":
137
        val = val.split(",")
138
    return val
139
140
141
def _arg_to_bool(val):
142
    return val in ("true", "True")
143
144
145
def _arg_to_variant(val, array, ptype, varianttype=None):
146
    val = _args_to_array(val, array)
147
    if isinstance(val, list):
148
        val = [ptype(i) for i in val]
149
    else:
150
        val = ptype(val)
151
    if varianttype:
152
        return ua.Variant(val, varianttype)
153
    else:
154
        return ua.Variant(val)
155
156
157
def _val_to_variant(val, args):
158
    array = args.array
159
    if args.datatype == "guess":
160
        if val in ("true", "True", "false", "False"):
161
            return _arg_to_variant(val, array, _arg_to_bool)
162
        try:
163
            return _arg_to_variant(val, array, int)
164
        except ValueError:
165
            try:
166
                return _arg_to_variant(val, array, float)
167
            except ValueError:
168
                return _arg_to_variant(val, array, str)
169
    elif args.datatype == "bool":
170
        if val in ("1", "True", "true"):
171
            return ua.Variant(True, ua.VariantType.Boolean)
172
        else:
173
            return ua.Variant(False, ua.VariantType.Boolean)
174
    elif args.datatype == "sbyte":
175
        return _arg_to_variant(val, array, int, ua.VariantType.SByte)
176
    elif args.datatype == "byte":
177
        return _arg_to_variant(val, array, int, ua.VariantType.Byte)
178
    #elif args.datatype == "uint8":
179
        #return _arg_to_variant(val, array, int, ua.VariantType.Byte)
180
    elif args.datatype == "uint16":
181
        return _arg_to_variant(val, array, int, ua.VariantType.UInt16)
182
    elif args.datatype == "uint32":
183
        return _arg_to_variant(val, array, int, ua.VariantType.UInt32)
184
    elif args.datatype == "uint64":
185
        return _arg_to_variant(val, array, int, ua.VariantType.UInt64)
186
    #elif args.datatype == "int8":
187
        #return ua.Variant(int(val), ua.VariantType.Int8)
188
    elif args.datatype == "int16":
189
        return _arg_to_variant(val, array, int, ua.VariantType.Int16)
190
    elif args.datatype == "int32":
191
        return _arg_to_variant(val, array, int, ua.VariantType.Int32)
192
    elif args.datatype == "int64":
193
        return _arg_to_variant(val, array, int, ua.VariantType.Int64)
194
    elif args.datatype == "float":
195
        return _arg_to_variant(val, array, float, ua.VariantType.Float)
196
    elif args.datatype == "double":
197
        return _arg_to_variant(val, array, float, ua.VariantType.Double)
198
    elif args.datatype == "string":
199
        return _arg_to_variant(val, array, str, ua.VariantType.String)
200
    elif args.datatype == "datetime":
201
        raise NotImplementedError
202
    elif args.datatype == "Guid":
203
        return _arg_to_variant(val, array, bytes, ua.VariantType.Guid)
204
    elif args.datatype == "ByteString":
205
        return _arg_to_variant(val, array, bytes, ua.VariantType.ByteString)
206
    elif args.datatype == "xml":
207
        return _arg_to_variant(val, array, str, ua.VariantType.XmlElement)
208
    elif args.datatype == "nodeid":
209
        return _arg_to_variant(val, array, ua.NodeId.from_string, ua.VariantType.NodeId)
210
    elif args.datatype == "expandednodeid":
211
        return _arg_to_variant(val, array, ua.ExpandedNodeId.from_string, ua.VariantType.ExpandedNodeId)
212
    elif args.datatype == "statuscode":
213
        return _arg_to_variant(val, array, int, ua.VariantType.StatusCode)
214
    elif args.datatype in ("qualifiedname", "browsename"):
215
        return _arg_to_variant(val, array, ua.QualifiedName.from_string, ua.VariantType.QualifiedName)
216
    elif args.datatype == "LocalizedText":
217
        return _arg_to_variant(val, array, ua.LocalizedText, ua.VariantType.LocalizedText)
218
219
220
def uawrite():
221
    parser = argparse.ArgumentParser(description="Write attribute of a node, per default write value of node")
222
    add_common_args(parser)
223
    parser.add_argument("-a",
224
                        "--attribute",
225
                        dest="attribute",
226
                        type=int,
227
                        default=ua.AttributeIds.Value,
228
                        help="Set attribute to read")
229
    parser.add_argument("-l",
230
                        "--list",
231
                        "--array",
232
                        dest="array",
233
                        default="guess",
234
                        choices=["guess", "true", "false"],
235
                        help="Value is an array")
236
    parser.add_argument("-t",
237
                        "--datatype",
238
                        dest="datatype",
239
                        default="guess",
240
                        choices=["guess", 'byte', 'sbyte', 'nodeid', 'expandednodeid', 'qualifiedname', 'browsename', 'string', 'float', 'double', 'int16', 'int32', "int64", 'uint16', 'uint32', 'uint64', "bool", "string", 'datetime', 'bytestring', 'xmlelement', 'statuscode', 'localizedtext'],
241
                        help="Data type to return")
242
    parser.add_argument("value",
243
                        help="Value to be written",
244
                        metavar="VALUE")
245
    args = parse_args(parser, requirenodeid=True)
246
247
    client = Client(args.url, timeout=args.timeout)
248
    client.set_security_string(args.security)
249
    client.connect()
250
    try:
251
        node = get_node(client, args)
252
        val = _val_to_variant(args.value, args)
253
        node.set_attribute(args.attribute, ua.DataValue(val))
254
    finally:
255
        client.disconnect()
256
    sys.exit(0)
257
    print(args)
258
259 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
260
def uals():
261
    parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result")
262
    add_common_args(parser)
263
    parser.add_argument("-l",
264
                        dest="long_format",
265
                        const=3,
266
                        nargs="?",
267
                        type=int,
268
                        help="use a long listing format")
269
    parser.add_argument("-d",
270
                        "--depth",
271
                        default=1,
272
                        type=int,
273
                        help="Browse depth")
274
275
    args = parse_args(parser)
276
    if args.long_format is None:
277
        args.long_format = 1
278
279
    client = Client(args.url, timeout=args.timeout)
280
    client.set_security_string(args.security)
281
    client.connect()
282
    try:
283
        node = get_node(client, args)
284
        print("Browsing node {0} at {1}\n".format(node, args.url))
285
        if args.long_format == 0:
286
            _lsprint_0(node, args.depth - 1)
287
        elif args.long_format == 1:
288
            _lsprint_1(node, args.depth - 1)
289
        else:
290
            _lsprint_long(node, args.depth - 1)
291
    finally:
292
        client.disconnect()
293
    sys.exit(0)
294
    print(args)
295
296
297
def _lsprint_0(node, depth, indent=""):
298
    if not indent:
299
        print("{0:30} {1:25}".format("DisplayName", "NodeId"))
300
        print("")
301
    for desc in node.get_children_descriptions():
302
        print("{0}{1:30} {2:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string()))
303
        if depth:
304
            _lsprint_0(Node(node.server, desc.NodeId), depth - 1, indent + "  ")
305
306
307
def _lsprint_1(node, depth, indent=""):
308
    if not indent:
309
        print("{0:30} {1:25} {2:25} {3:25}".format("DisplayName", "NodeId", "BrowseName", "Value"))
310
        print("")
311
312
    for desc in node.get_children_descriptions():
313
        if desc.NodeClass == ua.NodeClass.Variable:
314
            val = Node(node.server, desc.NodeId).get_value()
315
            print("{0}{1:30} {2!s:25} {3!s:25}, {4!s:3}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string(), val))
316
        else:
317
            print("{0}{1:30} {2!s:25} {3!s:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string()))
318
        if depth:
319
            _lsprint_1(Node(node.server, desc.NodeId), depth - 1, indent + "  ")
320
321
322
def _lsprint_long(pnode, depth, indent=""):
323
    if not indent:
324
        print("{0:30} {1:25} {2:25} {3:10} {4:30} {5:25}".format("DisplayName", "NodeId", "BrowseName", "DataType", "Timestamp", "Value"))
325
        print("")
326
    for node in pnode.get_children():
327
        attrs = node.get_attributes([ua.AttributeIds.DisplayName,
328
                                     ua.AttributeIds.BrowseName,
329
                                     ua.AttributeIds.NodeClass,
330
                                     ua.AttributeIds.WriteMask,
331
                                     ua.AttributeIds.UserWriteMask,
332
                                     ua.AttributeIds.DataType,
333
                                     ua.AttributeIds.Value])
334
        name, bname, nclass, mask, umask, dtype, val = [attr.Value.Value for attr in attrs]
335
        update = attrs[-1].ServerTimestamp
336
        if nclass == ua.NodeClass.Variable:
337
            print("{0}{1:30} {2:25} {3:25} {4:10} {5!s:30} {6!s:25}".format(indent, name.to_string(), node.nodeid.to_string(), bname.to_string(), dtype.to_string(), update, val))
338
        else:
339
            print("{0}{1:30} {2:25} {3:25}".format(indent, name.to_string(), bname.to_string(), node.nodeid.to_string()))
340
        if depth:
341
            _lsprint_long(node, depth - 1, indent + "  ")
342
343
344
class SubHandler(object):
345
346
    def datachange_notification(self, node, val, data):
347
        print("New data change event", node, val, data)
348
349
    def event_notification(self, event):
350
        print("New event", event)
351
352
353
def uasubscribe():
354
    parser = argparse.ArgumentParser(description="Subscribe to a node and print results")
355
    add_common_args(parser)
356
    parser.add_argument("-t",
357
                        "--eventtype",
358
                        dest="eventtype",
359
                        default="datachange",
360
                        choices=['datachange', 'timeordatachange', 'event'],
361
                        help="Event type to subscribe to")
362
363
    args = parse_args(parser, requirenodeid=False)
364
    if args.eventtype == "datachange" or args.eventtype == "timeordatachange":
365
        _require_nodeid(parser, args)
366
    else:
367
        # FIXME: this is broken, someone may have written i=84 on purpose
368
        if args.nodeid == "i=84" and args.path == "":
369
            args.nodeid = "i=2253"
370
371
    client = Client(args.url, timeout=args.timeout)
372
    client.set_security_string(args.security)
373
    client.connect()
374
    try:
375
        node = get_node(client, args)
376
        handler = SubHandler()
377
        sub = client.create_subscription(500, handler)
378
        if args.eventtype == "datachange":
379
            sub.subscribe_data_change(node)
380
        elif args.eventtype == "timeordatachange":
381
            sub.subscribe_data_timestamp_change(node)
382
        else:
383
            sub.subscribe_events(node)
384
        print("Type Ctr-C to exit")
385
        while True:
386
            time.sleep(1)
387
    finally:
388
        client.disconnect()
389
    sys.exit(0)
390
    print(args)
391
392
393
def application_to_strings(app):
394
    result = []
395
    result.append(('Application URI', app.ApplicationUri))
396
    optionals = [
397
        ('Product URI', app.ProductUri),
398
        ('Application Name', app.ApplicationName.to_string()),
399
        ('Application Type', str(app.ApplicationType)),
400
        ('Gateway Server URI', app.GatewayServerUri),
401
        ('Discovery Profile URI', app.DiscoveryProfileUri),
402
    ]
403
    for (n, v) in optionals:
404
        if v:
405
            result.append((n, v))
406
    for url in app.DiscoveryUrls:
407
        result.append(('Discovery URL', url))
408
    return result  # ['{}: {}'.format(n, v) for (n, v) in result]
409
410
411
def cert_to_string(der):
412
    if not der:
413
        return '[no certificate]'
414
    try:
415
        from opcua.crypto import uacrypto
416
    except ImportError:
417
        return "{0} bytes".format(len(der))
418
    cert = uacrypto.x509_from_der(der)
419
    return uacrypto.x509_to_string(cert)
420
421
422
def endpoint_to_strings(ep):
423
    result = [('Endpoint URL', ep.EndpointUrl)]
424
    result += application_to_strings(ep.Server)
425
    result += [
426
        ('Server Certificate', cert_to_string(ep.ServerCertificate)),
427
        ('Security Mode', str(ep.SecurityMode)),
428
        ('Security Policy URI', ep.SecurityPolicyUri)]
429
    for tok in ep.UserIdentityTokens:
430
        result += [
431
            ('User policy', tok.PolicyId),
432
            ('  Token type', str(tok.TokenType))]
433
        if tok.IssuedTokenType or tok.IssuerEndpointUrl:
434
            result += [
435
                ('  Issued Token type', tok.IssuedTokenType),
436
                ('  Issuer Endpoint URL', tok.IssuerEndpointUrl)]
437
        if tok.SecurityPolicyUri:
438
            result.append(('  Security Policy URI', tok.SecurityPolicyUri))
439
    result += [
440
        ('Transport Profile URI', ep.TransportProfileUri),
441
        ('Security Level', ep.SecurityLevel)]
442
    return result
443
444
445
def uaclient():
446
    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")
447
    add_common_args(parser)
448
    parser.add_argument("-c",
449
                        "--certificate",
450
                        help="set client certificate")
451
    parser.add_argument("-k",
452
                        "--private_key",
453
                        help="set client private key")
454
    args = parse_args(parser)
455
456
    client = Client(args.url, timeout=args.timeout)
457
    client.set_security_string(args.security)
458
    if args.certificate:
459
        client.load_client_certificate(args.certificate)
460
    if args.private_key:
461
        client.load_private_key(args.private_key)
462
    client.connect()
463
    try:
464
        root = client.get_root_node()
465
        objects = client.get_objects_node()
466
        mynode = get_node(client, args)
467
        embed()
468
    finally:
469
        client.disconnect()
470
    sys.exit(0)
471
472
473
def uaserver():
474
    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")
475
    # we setup a server, this is a bit different from other tool so we do not reuse common arguments
476
    parser.add_argument("-u",
477
                        "--url",
478
                        help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840",
479
                        default='opc.tcp://0.0.0.0:4840',
480
                        metavar="URL")
481
    parser.add_argument("-v",
482
                        "--verbose",
483
                        dest="loglevel",
484
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
485
                        default='WARNING',
486
                        help="Set log level")
487
    parser.add_argument("-x",
488
                        "--xml",
489
                        metavar="XML_FILE",
490
                        help="Populate address space with nodes defined in XML")
491
    parser.add_argument("-p",
492
                        "--populate",
493
                        action="store_true",
494
                        help="Populate address space with some sample nodes")
495
    parser.add_argument("-c",
496
                        "--disable-clock",
497
                        action="store_true",
498
                        help="Disable clock, to avoid seeing many write if debugging an application")
499
    parser.add_argument("-s",
500
                        "--shell",
501
                        action="store_true",
502
                        help="Start python shell instead of randomly changing node values")
503
    parser.add_argument("--certificate",
504
                        help="set server certificate")
505
    parser.add_argument("--private_key",
506
                        help="set server private key")
507
    args = parser.parse_args()
508
    logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))
509
510
    server = Server()
511
    server.set_endpoint(args.url)
512
    if args.certificate:
513
        server.load_certificate(args.certificate)
514
    if args.private_key:
515
        server.load_private_key(args.private_key)
516
    server.disable_clock(args.disable_clock)
517
    server.set_server_name("FreeOpcUa Example Server")
518
    if args.xml:
519
        server.import_xml(args.xml)
520
    if args.populate:
521
        @uamethod
522
        def multiply(parent, x, y):
523
            print("multiply method call with parameters: ", x, y)
524
            return x * y
525
526
        uri = "http://examples.freeopcua.github.io"
527
        idx = server.register_namespace(uri)
528
        objects = server.get_objects_node()
529
        myobj = objects.add_object(idx, "MyObject")
530
        mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7)
531
        mywritablevar.set_writable()    # Set MyVariable to be writable by clients
532
        myvar = myobj.add_variable(idx, "MyVariable", 6.7)
533
        myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9])
534
        myprop = myobj.add_property(idx, "MyProperty", "I am a property")
535
        mymethod = myobj.add_method(idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double])
536
537
    server.start()
538
    try:
539
        if args.shell:
540
            embed()
541
        elif args.populate:
542
            count = 0
543
            while True:
544
                time.sleep(1)
545
                myvar.set_value(math.sin(count / 10))
546
                myarrayvar.set_value([math.sin(count / 10), math.sin(count / 100)])
547
                count += 1
548
        else:
549
            while True:
550
                time.sleep(1)
551
    finally:
552
        server.stop()
553
    sys.exit(0)
554
555
556
def uadiscover():
557
    parser = argparse.ArgumentParser(description="Performs OPC UA discovery and prints information on servers and endpoints.")
558
    add_minimum_args(parser)
559
    parser.add_argument("-n",
560
                        "--network",
561
                        action="store_true",
562
                        help="Also send a FindServersOnNetwork request to server")
563
    #parser.add_argument("-s",
564
                        #"--servers",
565
                        #action="store_false",
566
                        #help="send a FindServers request to server")
567
    #parser.add_argument("-e",
568
                        #"--endpoints",
569
                        #action="store_false",
570
                        #help="send a GetEndpoints request to server")
571
    args = parse_args(parser)
572
573
    client = Client(args.url, timeout=args.timeout)
574
575
    if args.network:
576
        print("Performing discovery at {0}\n".format(args.url))
577
        for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1):
578
            print('Server {0}:'.format(i))
579
            #for (n, v) in application_to_strings(server):
580
                #print('  {}: {}'.format(n, v))
581
            print('')
582
583
    print("Performing discovery at {0}\n".format(args.url))
584
    for i, server in enumerate(client.connect_and_find_servers(), start=1):
585
        print('Server {0}:'.format(i))
586
        for (n, v) in application_to_strings(server):
587
            print('  {0}: {1}'.format(n, v))
588
        print('')
589
590
    for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1):
591
        print('Endpoint {0}:'.format(i))
592
        for (n, v) in endpoint_to_strings(ep):
593
            print('  {0}: {1}'.format(n, v))
594
        print('')
595
596
    sys.exit(0)
597
598
599
def print_history(o):
600
    print("{0:30} {1:10} {2}".format('Source timestamp', 'Status', 'Value'))
601
    for d in o:
602
        print("{0:30} {1:10} {2}".format(str(d.SourceTimestamp), d.StatusCode.name, d.Value.Value))
603
604
605
def str_to_datetime(s, default=None):
606
    if not s:
607
        if default is not None:
608
            return default
609
        return datetime.utcnow()
610
    # FIXME: try different datetime formats
611
    for fmt in ["%Y-%m-%d", "%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"]:
612
        try:
613
            return datetime.strptime(s, fmt)
614
        except ValueError:
615
            pass
616
617
618
def uahistoryread():
619
    parser = argparse.ArgumentParser(description="Read history of a node")
620
    add_common_args(parser)
621
    parser.add_argument("--starttime",
622
                        default=None,
623
                        help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time - one day")
624
    parser.add_argument("--endtime",
625
                        default=None,
626
                        help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time")
627
    parser.add_argument("-e",
628
                        "--events",
629
                        action="store_true",
630
                        help="Read event history instead of data change history")
631
    parser.add_argument("-l",
632
                        "--limit",
633
                        type=int,
634
                        default=10,
635
                        help="Maximum number of notfication to return")
636
637
    args = parse_args(parser, requirenodeid=True)
638
639
    client = Client(args.url, timeout=args.timeout)
640
    client.set_security_string(args.security)
641
    client.connect()
642
    try:
643
        node = get_node(client, args)
644
        starttime = str_to_datetime(args.starttime, datetime.utcnow() - timedelta(days=1))
645
        endtime = str_to_datetime(args.endtime, datetime.utcnow())
646
        print("Reading raw history of node {0} at {1}; start at {2}, end at {3}\n".format(node, args.url, starttime, endtime))
647
        if args.events:
648
            evs = node.read_event_history(starttime, endtime, numvalues=args.limit)
649
            for ev in evs:
650
                print(ev)
651
        else:
652
            print_history(node.read_raw_history(starttime, endtime, numvalues=args.limit))
653
    finally:
654
        client.disconnect()
655
    sys.exit(0)
656
657
658
def uacall():
659
    parser = argparse.ArgumentParser(description="Call method of a node")
660
    add_common_args(parser)
661
    parser.add_argument("-m",
662
                        "--method",
663
                        dest="method",
664
                        type=int,
665
                        default=None,
666
                        help="Set method to call. If not given then (single) method of the selected node is used.")
667
    parser.add_argument("-l",
668
                        "--list",
669
                        "--array",
670
                        dest="array",
671
                        default="guess",
672
                        choices=["guess", "true", "false"],
673
                        help="Value is an array")
674
    parser.add_argument("-t",
675
                        "--datatype",
676
                        dest="datatype",
677
                        default="guess",
678
                        choices=["guess", 'byte', 'sbyte', 'nodeid', 'expandednodeid', 'qualifiedname', 'browsename', 'string', 'float', 'double', 'int16', 'int32', "int64", 'uint16', 'uint32', 'uint64', "bool", "string", 'datetime', 'bytestring', 'xmlelement', 'statuscode', 'localizedtext'],
679
                        help="Data type to return")
680
    parser.add_argument("value",
681
                        help="Value to use for call to method, if any",
682
                        nargs="?",
683
                        metavar="VALUE")
684
685
    args = parse_args(parser, requirenodeid=True)
686
687
    client = Client(args.url, timeout=args.timeout)
688
    client.set_security_string(args.security)
689
    client.connect()
690
    try:
691
        node = get_node(client, args)
692
        # val must be a tuple in order to enable method calls without arguments
693
        if ( args.value is None ):
694
            val = () #empty tuple
695
        else:
696
            val = (_val_to_variant(args.value, args),) # tuple with one element
697
698
        # determine method to call: Either explicitly given or automatically select the method of the selected node.
699
        methods = node.get_methods()
700
        method_id = None
701
        #print( "methods=%s" % (methods) )
702
703
        if ( args.method is None ):
704
            if ( len( methods ) == 0 ):
705
                raise ValueError( "No methods in selected node and no method given" )
706
            elif ( len( methods ) == 1 ):
707
                method_id = methods[0]
708
            else:
709
                raise ValueError( "Selected node has {0:d} methods but no method given. Provide one of {1!s}".format(*(methods)) )
710
        else:
711
            for m in methods:
712
                if ( m.nodeid.Identifier == args.method ):
713
                    method_id = m.nodeid
714
                    break
715
716
        if ( method_id is None):
717
            # last resort:
718
            method_id = ua.NodeId( identifier=args.method )#, namespaceidx=? )#, nodeidtype=?): )
719
720
        #print( "method_id=%s\nval=%s" % (method_id,val) )
721
722
        result_variants = node.call_method( method_id, *val )
723
        print( "resulting result_variants={0!s}".format(result_variants) )
724
    finally:
725
        client.disconnect()
726
    sys.exit(0)
727
    print(args)
728
729
730
def uageneratestructs():
731
    parser = argparse.ArgumentParser(description="Generate a Python module from the xml structure definition (.bsd)")
732
    add_common_args(parser, require_node=True)
733
    parser.add_argument("-o",
734
                        "--output",
735
                        dest="output_path",
736
                        required=True,
737
                        type=str,
738
                        default=None,
739
                        help="The python file to be generated.",
740
                        )
741
    args = parse_args(parser, requirenodeid=True)
742
743
    client = Client(args.url, timeout=args.timeout)
744
    client.set_security_string(args.security)
745
    client.connect()
746
    try:
747
        node = get_node(client, args)
748
        generators, _ = client.load_type_definitions([node])
749
        generators[0].save_to_file(args.output_path, True)
750
    finally:
751
        client.disconnect()
752
    sys.exit(0)
753