|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import argparse |
| 5 | +from opcua import ua, Client |
| 6 | + |
| 7 | + |
| 8 | +def add_common_args(parser, nodeid_required=True): |
| 9 | + parser.add_argument("-u", |
| 10 | + "--url", |
| 11 | + help="URL of OPC UA server (for example: opc.tcp://example.org:4840)", |
| 12 | + default='opc.tcp://localhost:4841', |
| 13 | + metavar="URL") |
| 14 | + parser.add_argument("-n", |
| 15 | + "--nodeid", |
| 16 | + help="Fully-qualified node ID (for example: i=85). Default: root node", |
| 17 | + default='i=84', |
| 18 | + required=nodeid_required, |
| 19 | + #required=True, |
| 20 | + metavar="NODE") |
| 21 | + parser.add_argument("-p", |
| 22 | + "--path", |
| 23 | + help="Comma separated browse path to the node starting at nodeid (for example: 3:Mybject,3:MyVariable)", |
| 24 | + default='', |
| 25 | + metavar="BROWSEPATH") |
| 26 | + parser.add_argument("-i", |
| 27 | + "--namespace", |
| 28 | + help="Default namespace", |
| 29 | + type=int, |
| 30 | + default=0, |
| 31 | + metavar="NAMESPACE") |
| 32 | + |
| 33 | + parser.add_argument("-v", |
| 34 | + "--verbose", |
| 35 | + dest="loglevel", |
| 36 | + choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], |
| 37 | + default='WARNING', |
| 38 | + help="Set log level") |
| 39 | + |
| 40 | + |
| 41 | +def get_node(client, args): |
| 42 | + node = client.get_node(args.nodeid) |
| 43 | + if args.path: |
| 44 | + node = node.get_child(args.path.split(",")) |
| 45 | + |
| 46 | + |
| 47 | +def uaread(): |
| 48 | + parser = argparse.ArgumentParser(description="Read attribute of a node") |
| 49 | + add_common_args(parser) |
| 50 | + parser.add_argument("-a", |
| 51 | + "--attribute", |
| 52 | + dest="attribute", |
| 53 | + type=int, |
| 54 | + #default="VALUE", |
| 55 | + #choices=['VALUE', 'NODEID', 'BROWSENAME', 'ERROR', 'CRITICAL'], |
| 56 | + default=ua.AttributeIds.Value, |
| 57 | + help="Set attribute to read") |
| 58 | + parser.add_argument("-t", |
| 59 | + "--datatype", |
| 60 | + dest="datatype", |
| 61 | + default="python", |
| 62 | + choices=['python', 'variant', 'datavalue'], |
| 63 | + help="Data type to return") |
| 64 | + |
| 65 | + args = parser.parse_args() |
| 66 | + logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel)) |
| 67 | + |
| 68 | + client = Client(args.url) |
| 69 | + client.connect() |
| 70 | + try: |
| 71 | + node = client.get_node(args.nodeid) |
| 72 | + if args.path: |
| 73 | + node = node.get_child(args.path.split(",")) |
| 74 | + attr = node.get_attribute(args.attribute) |
| 75 | + if args.datatype == "python": |
| 76 | + print(attr.Value.Value) |
| 77 | + elif args.datatype == "variant": |
| 78 | + print(attr.Value) |
| 79 | + else: |
| 80 | + print(attr) |
| 81 | + finally: |
| 82 | + client.disconnect() |
| 83 | + sys.exit(0) |
| 84 | + print(args) |
| 85 | + |
| 86 | + |
| 87 | + |
0 commit comments