Completed
Pull Request — master (#150)
by Olivier
02:30
created

opcua.ua.NodeId.to_string()   D

Complexity

Conditions 10

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 12.0279
Metric Value
cc 10
dl 0
loc 23
ccs 16
cts 22
cp 0.7272
crap 12.0279
rs 4.0396

How to fix   Complexity   

Complexity

Complex classes like opcua.ua.NodeId.to_string() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
implement ua datatypes
3
"""
4 1
import logging
5 1
from enum import Enum
6 1
from datetime import datetime, timedelta, tzinfo, MAXYEAR
7 1
from calendar import timegm
8 1
import sys
9 1
import os
10 1
import uuid
11 1
import struct
12 1
import re
13 1
if sys.version_info.major > 2:
14
    unicode = str
15 1
16 1
from opcua.ua import status_codes
17 1
from opcua.common.uaerrors import UaError
18 1
from opcua.common.uaerrors import UaStatusCodeError
19
from opcua.common.uaerrors import UaStringParsingError
20
21 1
22
logger = logging.getLogger('opcua.uaprotocol')
23
24
25 1
# types that will packed and unpacked directly using struct (string, bytes and datetime are handles as special cases
26
UaTypes = ("Boolean", "SByte", "Byte", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Float", "Double")
27
28 1
29 1
EPOCH_AS_FILETIME = 116444736000000000  # January 1, 1970 as MS file time
30 1
HUNDREDS_OF_NANOSECONDS = 10000000
31
FILETIME_EPOCH_AS_DATETIME = datetime(1601, 1, 1)
32
33 1
34
class UTC(tzinfo):
35
36
    """UTC"""
37 1
38
    def utcoffset(self, dt):
39
        return timedelta(0)
40 1
41
    def tzname(self, dt):
42
        return "UTC"
43 1
44 1
    def dst(self, dt):
45
        return timedelta(0)
46
47
48 1
# method copied from David Buxton <[email protected]> sample code
49 1
def datetime_to_win_epoch(dt):
50 1
    if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None):
51 1
        dt = dt.replace(tzinfo=UTC())
52 1
    ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS)
53
    return ft + (dt.microsecond * 10)
54
55 1
56 1
def win_epoch_to_datetime(epch):
57 1
    try:
58
        return FILETIME_EPOCH_AS_DATETIME + timedelta(microseconds=epch // 10)
59
    except OverflowError:
60
        # FILETIMEs after 31 Dec 9999 can't be converted to datetime
61
        logger.warning("datetime overflow: {}".format(epch))
62
        return datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999)
63
64 1
65
def build_array_format_py2(prefix, length, fmtchar):
66
    return prefix + str(length) + fmtchar
67
68 1
69 1
def build_array_format_py3(prefix, length, fmtchar):
70
    return prefix + str(length) + chr(fmtchar)
71
72 1
73
if sys.version_info.major < 3:
74
    build_array_format = build_array_format_py2
75 1
else:
76
    build_array_format = build_array_format_py3
77
78 1
79 1
def pack_uatype_array_primitive(st, value, length):
80 1
    if length == 1:
81
        return b'\x01\x00\x00\x00' + st.pack(value[0])
82 1
    else:
83
        return struct.pack(build_array_format("<i", length, st.format[1]), length, *value)
84
85 1
86 1
def pack_uatype_array(uatype, value):
87
    if value is None:
88 1
        return b'\xff\xff\xff\xff'
89 1
    length = len(value)
90 1
    if length == 0:
91 1
        return b'\x00\x00\x00\x00'
92 1
    if uatype in uatype2struct:
93 1
        return pack_uatype_array_primitive(uatype2struct[uatype], value, length)
94 1
    b = []
95 1
    b.append(uatype_Int32.pack(length))
96 1
    for val in value:
97 1
        b.append(pack_uatype(uatype, val))
98
    return b"".join(b)
99
100 1
101 1
def pack_uatype(uatype, value):
102 1
    if uatype in uatype2struct:
103
        if value is None:
104 1
            value = 0
105 1
        return uatype2struct[uatype].pack(value)
106 1
    elif uatype == "Null":
107 1
        return b''
108 1
    elif uatype == "String":
109 1
        return pack_string(value)
110 1
    elif uatype in ("CharArray", "ByteString", "Custom"):
111 1
        return pack_bytes(value)
112 1
    elif uatype == "DateTime":
113 1
        return pack_datetime(value)
114
    elif uatype == "ExtensionObject":
115
        # dependency loop: classes in uaprotocol_auto use Variant defined in this file,
116
        # but Variant can contain any object from uaprotocol_auto as ExtensionObject.
117 1
        # Using local import to avoid import loop
118 1
        from opcua.ua.uaprotocol_auto import extensionobject_to_binary
119
        return extensionobject_to_binary(value)
120 1
    else:
121
        return value.to_binary()
122 1
123 1
uatype_Int8 = struct.Struct("<b")
124 1
uatype_SByte = uatype_Int8
125 1
uatype_Int16 = struct.Struct("<h")
126 1
uatype_Int32 = struct.Struct("<i")
127 1
uatype_Int64 = struct.Struct("<q")
128 1
uatype_UInt8 = struct.Struct("<B")
129 1
uatype_Char = uatype_UInt8
130 1
uatype_Byte = uatype_UInt8
131 1
uatype_UInt16 = struct.Struct("<H")
132 1
uatype_UInt32 = struct.Struct("<I")
133 1
uatype_UInt64 = struct.Struct("<Q")
134 1
uatype_Boolean = struct.Struct("<?")
135 1
uatype_Double = struct.Struct("<d")
136
uatype_Float = struct.Struct("<f")
137 1
138
uatype2struct = {
139
    "Int8": uatype_Int8,
140
    "SByte": uatype_SByte,
141
    "Int16": uatype_Int16,
142
    "Int32": uatype_Int32,
143
    "Int64": uatype_Int64,
144
    "UInt8": uatype_UInt8,
145
    "Char": uatype_Char,
146
    "Byte": uatype_Byte,
147
    "UInt16": uatype_UInt16,
148
    "UInt32": uatype_UInt32,
149
    "UInt64": uatype_UInt64,
150
    "Boolean": uatype_Boolean,
151
    "Double": uatype_Double,
152
    "Float": uatype_Float,
153
}
154
155 1
156 1
def unpack_uatype(uatype, data):
157 1
    if uatype in uatype2struct:
158 1
        st = uatype2struct[uatype]
159 1
        return st.unpack(data.read(st.size))[0]
160 1
    elif uatype == "String":
161 1
        return unpack_string(data)
162 1
    elif uatype in ("CharArray", "ByteString", "Custom"):
163 1
        return unpack_bytes(data)
164 1
    elif uatype == "DateTime":
165 1
        return unpack_datetime(data)
166
    elif uatype == "ExtensionObject":
167
        # dependency loop: classes in uaprotocol_auto use Variant defined in this file,
168
        # but Variant can contain any object from uaprotocol_auto as ExtensionObject.
169 1
        # Using local import to avoid import loop
170 1
        from opcua.ua.uaprotocol_auto import extensionobject_from_binary
171
        return extensionobject_from_binary(data)
172 1
    else:
173 1
        glbs = globals()
174 1
        if uatype in glbs:
175 1
            klass = glbs[uatype]
176 1
            if hasattr(klass, 'from_binary'):
177
                return klass.from_binary(data)
178
        raise UaError("can not unpack unknown uatype %s" % uatype)
179
180 1
181 1
def unpack_uatype_array(uatype, data):
182 1
    length = uatype_Int32.unpack(data.read(4))[0]
183
    if length == -1:
184 1
        return None
185 1
    elif length == 0:
186 1
        return []
187 1
    elif uatype in uatype2struct:
188 1
        st = uatype2struct[uatype]
189 1
        if length == 1:
190
            return list(st.unpack(data.read(st.size)))
191 1
        else:
192 1
            arrst = struct.Struct(build_array_format("<", length, st.format[1]))
193
            return list(arrst.unpack(data.read(arrst.size)))
194 1
    else:
195 1
        result = []
196 1
        for _ in range(0, length):
197 1
            result.append(unpack_uatype(uatype, data))
198
        return result
199
200 1
201 1
def pack_datetime(value):
202 1
    epch = datetime_to_win_epoch(value)
203
    return uatype_Int64.pack(epch)
204
205 1
206 1
def unpack_datetime(data):
207 1
    epch = uatype_Int64.unpack(data.read(8))[0]
208
    return win_epoch_to_datetime(epch)
209
210 1
211 1
def pack_string(string):
212 1
    if isinstance(string, unicode):
213 1
        string = string.encode('utf-8')
214 1
    length = len(string)
215 1
    if length == 0:
216 1
        return b'\xff\xff\xff\xff'
217
    return uatype_Int32.pack(length) + string
218 1
219
pack_bytes = pack_string
220
221 1
222 1
def unpack_bytes(data):
223 1
    length = uatype_Int32.unpack(data.read(4))[0]
224 1
    if length == -1:
225 1
        return b''
226
    return data.read(length)
227
228 1
229 1
def py3_unpack_string(data):
230 1
    b = unpack_bytes(data)
231
    return b.decode("utf-8")
232
233 1
234
if sys.version_info.major < 3:
235
    unpack_string = unpack_bytes
236 1
else:
237
    unpack_string = py3_unpack_string
238
239 1
240 1
def test_bit(data, offset):
241 1
    mask = 1 << offset
242
    return data & mask
243
244 1
245 1
def set_bit(data, offset):
246 1
    mask = 1 << offset
247
    return data | mask
248
249 1
250
class _FrozenClass(object):
251
252
    """
253
    make it impossible to add members to a class.
254
    This is a hack since I found out that most bugs are due to misspelling a variable in protocol
255 1
    """
256
    _freeze = False
257 1
258 1
    def __setattr__(self, key, value):
259
        if self._freeze and not hasattr(self, key):
260 1
            raise TypeError("Error adding member '{}' to class '{}', class is frozen, members are {}".format(key, self.__class__.__name__, self.__dict__.keys()))
261
        object.__setattr__(self, key, value)
262 1
263
if "PYOPCUA_NO_TYPO_CHECK" in os.environ:
264
    # typo check is cpu consuming, but it will make debug easy.
265
    # if typo check is not need (in production), please set env PYOPCUA_NO_TYPO_CHECK.
266
    # this will make all uatype class inherit from object intead of _FrozenClass
267
    # and skip the typo check.
268
    FrozenClass = object
269 1
else:
270
    FrozenClass = _FrozenClass
271
272 1
273
class Guid(FrozenClass):
274 1
275 1
    def __init__(self):
276 1
        self.uuid = uuid.uuid4()
277
        self._freeze = True
278 1
279 1
    def to_binary(self):
280
        return self.uuid.bytes
281 1
282
    def __hash__(self):
283
        return hash(self.uuid.bytes)
284 1
285
    @staticmethod
286 1
    def from_binary(data):
287 1
        g = Guid()
288 1
        g.uuid = uuid.UUID(bytes=data.read(16))
289
        return g
290 1
291 1
    def __eq__(self, other):
292
        return isinstance(other, Guid) and self.uuid == other.uuid
293
294 1
295
class StatusCode(FrozenClass):
296
297
    """
298
    :ivar value:
299
    :vartype value: int
300
    :ivar name:
301
    :vartype name: string
302
    :ivar doc:
303
    :vartype doc: string
304
    """
305 1
306 1
    def __init__(self, value=0):
307 1
        self.value = value
308 1
        self.name, self.doc = status_codes.get_name_and_doc(value)
309
        self._freeze = True
310 1
311 1
    def to_binary(self):
312
        return uatype_UInt32.pack(self.value)
313 1
314
    @staticmethod
315 1
    def from_binary(data):
316 1
        val = uatype_UInt32.unpack(data.read(4))[0]
317 1
        sc = StatusCode(val)
318
        return sc
319 1
320
    def check(self):
321
        """
322
        raise en exception if status code is anything else than 0
323
        use is is_good() method if not exception is desired
324 1
        """
325 1
        if self.value != 0:
326
            raise UaStatusCodeError("{}({})".format(self.doc, self.name))
327 1
328
    def is_good(self):
329
        """
330
        return True if status is Good.
331 1
        """
332 1
        if self.value == 0:
333 1
            return True
334
        return False
335 1
336
    def __str__(self):
337 1
        return 'StatusCode({})'.format(self.name)
338
    __repr__ = __str__
339 1
340
    def __eq__(self, other):
341
        return self.value == other.value
342 1
343
    def __ne__(self, other):
344
        return not self.__eq__(other)
345
346 1
347 1
class NodeIdType(Enum):
348 1
    TwoByte = 0
349 1
    FourByte = 1
350 1
    Numeric = 2
351 1
    String = 3
352 1
    Guid = 4
353
    ByteString = 5
354
355 1
356
class NodeId(FrozenClass):
357
358
    """
359
    NodeId Object
360
361
    Args:
362
        identifier: The identifier might be an int, a string, bytes or a Guid
363
        namespaceidx(int): The index of the namespace
364
        nodeidtype(NodeIdType): The type of the nodeid if it cannor be guess or you want something special like twobyte nodeid or fourbytenodeid
365
366
367
    :ivar Identifier:
368
    :vartype Identifier: NodeId
369
    :ivar NamespaceIndex:
370
    :vartype NamespaceIndex: Int
371
    :ivar NamespaceUri:
372
    :vartype NamespaceUri: String
373
    :ivar ServerIndex:
374
    :vartype ServerIndex: Int
375
    """
376 1
377 1
    def __init__(self, identifier=None, namespaceidx=0, nodeidtype=None):
378 1
        self.Identifier = identifier
379 1
        self.NamespaceIndex = namespaceidx
380 1
        self.NodeIdType = nodeidtype
381 1
        self.NamespaceUri = ""
382 1
        self.ServerIndex = 0
383 1
        self._freeze = True
384 1
        if not isinstance(self.NamespaceIndex, int):
385 1
            raise UaError("NamespaceIndex must be an int")
386 1
        if self.Identifier is None:
387 1
            self.Identifier = 0
388 1
            self.NodeIdType = NodeIdType.TwoByte
389 1
            return
390 1
        if self.NodeIdType is None:
391 1
            if isinstance(self.Identifier, int):
392 1
                self.NodeIdType = NodeIdType.Numeric
393 1
            elif isinstance(self.Identifier, str):
394
                self.NodeIdType = NodeIdType.String
395
            elif isinstance(self.Identifier, bytes):
396
                self.NodeIdType = NodeIdType.ByteString
397
            else:
398
                raise UaError("NodeId: Could not guess type of NodeId, set NodeIdType")
399 1
400 1
    def __key(self):
401 1
        if self.NodeIdType in (NodeIdType.TwoByte, NodeIdType.FourByte, NodeIdType.Numeric):  # twobyte, fourbyte and numeric may represent the same node
402
            return self.NamespaceIndex, self.Identifier
403 1
        else:
404
            return self.NodeIdType, self.NamespaceIndex, self.Identifier
405 1
406 1
    def __eq__(self, node):
407
        return isinstance(node, NodeId) and self.__key() == node.__key()
408 1
409 1
    def __ne__(self, other):
410
        return not self.__eq__(other)
411 1
412 1
    def __hash__(self):
413
        return hash(self.__key())
414 1
415 1
    def is_null(self):
416 1
        if self.NamespaceIndex != 0:
417 1
            return False
418 1
        return self.has_null_identifier()
419 1
420 1
    def has_null_identifier(self):
421 1
        if not self.Identifier:
422 1
            return True
423 1
        if self.NodeIdType == NodeIdType.Guid and re.match(b'0.', self.Identifier):
424
            return True
425
        return False
426
427 1
    @staticmethod
428
    def from_string(string):
429 1
        try:
430
            return NodeId._from_string(string)
431 1
        except ValueError as ex:
432 1
            raise UaStringParsingError("Error parsing string {}".format(string), ex)
433 1
434 1
    @staticmethod
435
    def _from_string(string):
436 1
        l = string.split(";")
437
        identifier = None
438 1
        namespace = 0
439 1
        ntype = None
440 1
        srv = None
441 1
        nsu = None
442 1
        for el in l:
443 1
            if not el:
444 1
                continue
445 1
            k, v = el.split("=", 1)
446 1
            k = k.strip()
447 1
            v = v.strip()
448 1
            if k == "ns":
449 1
                namespace = int(v)
450 1
            elif k == "i":
451 1
                ntype = NodeIdType.Numeric
452 1
                identifier = int(v)
453 1
            elif k == "s":
454 1
                ntype = NodeIdType.String
455 1
                identifier = v
456 1
            elif k == "g":
457 1
                ntype = NodeIdType.Guid
458 1
                identifier = v
459
            elif k == "b":
460
                ntype = NodeIdType.ByteString
461 1
                identifier = v
462
            elif k == "srv":
463
                srv = v
464 1
            elif k == "nsu":
465 1
                nsu = v
466
        if identifier is None:
467
            raise UaStringParsingError("Could not find identifier in string: " + string)
468 1
        nodeid = NodeId(identifier, namespace, ntype)
469 1
        nodeid.NamespaceUri = nsu
470 1
        nodeid.ServerIndex = srv
471 1
        return nodeid
472 1
473 1
    def to_string(self):
474
        string = ""
475 1
        if self.NamespaceIndex != 0:
476 1
            string += "ns={};".format(self.NamespaceIndex)
477 1
        ntype = None
478 1
        if self.NodeIdType == NodeIdType.Numeric:
479 1
            ntype = "i"
480 1
        elif self.NodeIdType == NodeIdType.String:
481
            ntype = "s"
482 1
        elif self.NodeIdType == NodeIdType.TwoByte:
483 1
            ntype = "i"
484 1
        elif self.NodeIdType == NodeIdType.FourByte:
485 1
            ntype = "i"
486 1
        elif self.NodeIdType == NodeIdType.Guid:
487 1
            ntype = "g"
488
        elif self.NodeIdType == NodeIdType.ByteString:
489
            ntype = "b"
490
        string += "{}={}".format(ntype, self.Identifier)
491
        if self.ServerIndex:
492 1
            string = "srv=" + str(self.ServerIndex) + string
493 1
        if self.NamespaceUri:
494
            string += "nsu={}".format(self.NamespaceUri)
495 1
        return string
496
497 1
    def __str__(self):
498
        return "{}NodeId({})".format(self.NodeIdType.name, self.to_string())
499 1
    __repr__ = __str__
500 1
501 1
    def to_binary(self):
502
        if self.NodeIdType == NodeIdType.TwoByte:
503 1
            return struct.pack("<BB", self.NodeIdType.value, self.Identifier)
504 1
        elif self.NodeIdType == NodeIdType.FourByte:
505 1
            return struct.pack("<BBH", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
506 1
        elif self.NodeIdType == NodeIdType.Numeric:
507 1
            return struct.pack("<BHI", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
508 1
        elif self.NodeIdType == NodeIdType.String:
509 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
510 1
                pack_string(self.Identifier)
511 1
        elif self.NodeIdType == NodeIdType.ByteString:
512
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
513 1
                pack_bytes(self.Identifier)
514 1
        else:
515
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
516
                self.Identifier.to_binary()
517 1
        #FIXME: Missing NNamespaceURI and ServerIndex
518
519
    @staticmethod
520
    def from_binary(data):
521 1
        nid = NodeId()
522
        encoding = ord(data.read(1))
523 1
        nid.NodeIdType = NodeIdType(encoding & 0b00111111)
524 1
525 1
        if nid.NodeIdType == NodeIdType.TwoByte:
526
            nid.Identifier = ord(data.read(1))
527 1
        elif nid.NodeIdType == NodeIdType.FourByte:
528 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3))
529 1
        elif nid.NodeIdType == NodeIdType.Numeric:
530 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6))
531 1
        elif nid.NodeIdType == NodeIdType.String:
532 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
533 1
            nid.Identifier = unpack_string(data)
534 1
        elif nid.NodeIdType == NodeIdType.ByteString:
535 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
536 1
            nid.Identifier = unpack_bytes(data)
537 1
        elif nid.NodeIdType == NodeIdType.Guid:
538 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
539 1
            nid.Identifier = Guid.from_binary(data)
540 1
        else:
541 1
            raise UaError("Unknown NodeId encoding: " + str(nid.NodeIdType))
542
543
        if test_bit(encoding, 7):
544
            nid.NamespaceUri = unpack_string(data)
545 1
        if test_bit(encoding, 6):
546
            nid.ServerIndex = uatype_UInt32.unpack(data.read(4))[0]
547 1
548
        return nid
549
550 1
551
class TwoByteNodeId(NodeId):
552
553 1
    def __init__(self, identifier):
554
        NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte)
555 1
556 1
557
class FourByteNodeId(NodeId):
558
559 1
    def __init__(self, identifier, namespace=0):
560
        NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte)
561 1
562 1
563
class NumericNodeId(NodeId):
564
565 1
    def __init__(self, identifier, namespace=0):
566
        NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric)
567 1
568 1
569
class ByteStringNodeId(NodeId):
570
571 1
    def __init__(self, identifier, namespace=0):
572
        NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString)
573 1
574 1
575
class GuidNodeId(NodeId):
576
577 1
    def __init__(self, identifier, namespace=0):
578
        NodeId.__init__(self, identifier, namespace, NodeIdType.Guid)
579 1
580 1
581
class StringNodeId(NodeId):
582
583 1
    def __init__(self, identifier, namespace=0):
584
        NodeId.__init__(self, identifier, namespace, NodeIdType.String)
585 1
586 1
587
ExpandedNodeId = NodeId
588
589 1
590
class QualifiedName(FrozenClass):
591
592 1
    '''
593
    A string qualified with a namespace index.
594
    '''
595
596
    def __init__(self, name="", namespaceidx=0):
597
        if not isinstance(namespaceidx, int):
598 1
            raise UaError("namespaceidx must be an int")
599 1
        self.NamespaceIndex = namespaceidx
600
        self.Name = name
601 1
        self._freeze = True
602 1
603 1
    def to_string(self):
604
        return "{}:{}".format(self.NamespaceIndex, self.Name)
605 1
606 1
    @staticmethod
607
    def from_string(string):
608 1
        if ":" in string:
609
            try:
610 1
                idx, name = string.split(":", 1)
611 1
                idx = int(idx)
612 1
            except (TypeError, ValueError) as ex:
613 1
                raise UaStringParsingError("Error parsing string {}".format(string), ex)
614 1
        else:
615 1
            idx = 0
616
            name = string
617 1
        return QualifiedName(name, idx)
618 1
619 1
    def to_binary(self):
620
        packet = []
621 1
        packet.append(uatype_UInt16.pack(self.NamespaceIndex))
622 1
        packet.append(pack_string(self.Name))
623 1
        return b''.join(packet)
624 1
625 1
    @staticmethod
626
    def from_binary(data):
627 1
        obj = QualifiedName()
628
        obj.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
629 1
        obj.Name = unpack_string(data)
630 1
        return obj
631 1
632 1
    def __eq__(self, bname):
633
        return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex
634 1
635 1
    def __ne__(self, other):
636
        return not self.__eq__(other)
637 1
638
    def __str__(self):
639
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
640 1
641
    __repr__ = __str__
642
643 1
644
class LocalizedText(FrozenClass):
645
646 1
    '''
647
    A string qualified with a namespace index.
648
    '''
649
650
    def __init__(self, text=""):
651
        self.Encoding = 0
652 1
        self.Text = text
653 1
        if isinstance(self.Text, unicode):
654 1
            self.Text = self.Text.encode('utf-8')
655 1
        if self.Text:
656 1
            self.Encoding |= (1 << 1)
657 1
        self.Locale = b''
658 1
        self._freeze = True
659 1
660 1
    def to_binary(self):
661
        packet = []
662 1
        if self.Locale:
663 1
            self.Encoding |= (1 << 0)
664 1
        if self.Text:
665
            self.Encoding |= (1 << 1)
666 1
        packet.append(uatype_UInt8.pack(self.Encoding))
667 1
        if self.Locale:
668 1
            packet.append(pack_bytes(self.Locale))
669 1
        if self.Text:
670
            packet.append(pack_bytes(self.Text))
671 1
        return b''.join(packet)
672 1
673 1
    @staticmethod
674
    def from_binary(data):
675 1
        obj = LocalizedText()
676
        obj.Encoding = ord(data.read(1))
677 1
        if obj.Encoding & (1 << 0):
678 1
            obj.Locale = unpack_bytes(data)
679 1
        if obj.Encoding & (1 << 1):
680
            obj.Text = unpack_bytes(data)
681 1
        return obj
682 1
683 1
    def to_string(self):
684
        # FIXME: use local
685 1
        return self.Text.decode()
686
687
    def __str__(self):
688
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
689 1
            'Locale:' + str(self.Locale) + ', ' + \
690
            'Text:' + str(self.Text) + ')'
691
    __repr__ = __str__
692
693 1
    def __eq__(self, other):
694
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
695 1
            return True
696 1
        return False
697 1
698 1
    def __ne__(self, other):
699
        return not self.__eq__(other)
700 1
701 1
702
class ExtensionObject(FrozenClass):
703
704 1
    '''
705
706
    Any UA object packed as an ExtensionObject
707
708
709
    :ivar TypeId:
710
    :vartype TypeId: NodeId
711
    :ivar Body:
712
    :vartype Body: bytes
713
714
    '''
715
716
    def __init__(self):
717
        self.TypeId = NodeId()
718 1
        self.Encoding = 0
719 1
        self.Body = b''
720 1
        self._freeze = True
721 1
722 1
    def to_binary(self):
723
        packet = []
724 1
        if self.Body:
725 1
            self.Encoding |= (1 << 0)
726 1
        packet.append(self.TypeId.to_binary())
727 1
        packet.append(pack_uatype('UInt8', self.Encoding))
728 1
        if self.Body:
729 1
            packet.append(pack_uatype('ByteString', self.Body))
730 1
        return b''.join(packet)
731 1
732 1
    @staticmethod
733
    def from_binary(data):
734 1
        obj = ExtensionObject()
735
        obj.TypeId = NodeId.from_binary(data)
736
        obj.Encoding = unpack_uatype('UInt8', data)
737
        if obj.Encoding & (1 << 0):
738
            obj.Body = unpack_uatype('ByteString', data)
739
        return obj
740
741
    @staticmethod
742
    def from_object(obj):
743 1
        ext = ExtensionObject()
744
        oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__))
745
        ext.TypeId = FourByteNodeId(oid)
746
        ext.Body = obj.to_binary()
747
        return ext
748
749
    def __str__(self):
750
        return 'ExtensionObject(' + 'TypeId:' + str(self.TypeId) + ', ' + \
751 1
            'Encoding:' + str(self.Encoding) + ', ' + str(len(self.Body)) + ' bytes)'
752
753
    __repr__ = __str__
754
755 1
756
class VariantType(Enum):
757
758 1
    '''
759
    The possible types of a variant.
760
761
    :ivar Null:
762
    :ivar Boolean:
763
    :ivar SByte:
764
    :ivar Byte:
765
    :ivar Int16:
766
    :ivar UInt16:
767
    :ivar Int32:
768
    :ivar UInt32:
769
    :ivar Int64:
770
    :ivar UInt64:
771
    :ivar Float:
772
    :ivar Double:
773
    :ivar String:
774
    :ivar DateTime:
775
    :ivar Guid:
776
    :ivar ByteString:
777
    :ivar XmlElement:
778
    :ivar NodeId:
779
    :ivar ExpandedNodeId:
780
    :ivar StatusCode:
781
    :ivar QualifiedName:
782
    :ivar LocalizedText:
783
    :ivar ExtensionObject:
784
    :ivar DataValue:
785
    :ivar Variant:
786
    :ivar DiagnosticInfo:
787
788
789
790
    '''
791
    Null = 0
792
    Boolean = 1
793 1
    SByte = 2
794 1
    Byte = 3
795 1
    Int16 = 4
796 1
    UInt16 = 5
797 1
    Int32 = 6
798 1
    UInt32 = 7
799 1
    Int64 = 8
800 1
    UInt64 = 9
801 1
    Float = 10
802 1
    Double = 11
803 1
    String = 12
804 1
    DateTime = 13
805 1
    Guid = 14
806 1
    ByteString = 15
807 1
    XmlElement = 16
808 1
    NodeId = 17
809 1
    ExpandedNodeId = 18
810 1
    StatusCode = 19
811 1
    QualifiedName = 20
812 1
    LocalizedText = 21
813 1
    ExtensionObject = 22
814 1
    DataValue = 23
815 1
    Variant = 24
816 1
    DiagnosticInfo = 25
817 1
818 1
819
class VariantTypeCustom(object):
820
    def __init__(self, val):
821 1
        self.name = "Custom"
822 1
        self.value = val
823 1
        if self.value > 0b00111111:
824 1
            raise UaError("Cannot create VariantType. VariantType must be %s > x > %s", 0b111111, 25)
825 1
826 1
    def __str__(self):
827
        return "VariantType.Custom:{}".format(self.value)
828 1
    __repr__ = __str__
829
830 1
    def __eq__(self, other):
831
        return self.value == other.value
832 1
833 1
834
class Variant(FrozenClass):
835
836 1
    """
837
    Create an OPC-UA Variant object.
838
    if no argument a Null Variant is created.
839
    if not variant type is given, attemps to guess type from python type
840
    if a variant is given as value, the new objects becomes a copy of the argument
841
842
    :ivar Value:
843
    :vartype Value: Any supported type
844
    :ivar VariantType:
845
    :vartype VariantType: VariantType
846
    """
847
848
    def __init__(self, value=None, varianttype=None, dimensions=None):
849
        self.Value = value
850 1
        self.VariantType = varianttype
851 1
        self.Dimensions = dimensions
852 1
        self._freeze = True
853 1
        if isinstance(value, Variant):
854 1
            self.Value = value.Value
855 1
            self.VariantType = value.VariantType
856 1
        if self.VariantType is None:
857 1
            self.VariantType = self._guess_type(self.Value)
858 1
        if self.Dimensions is None and type(self.Value) in (list, tuple):
859 1
            dims = get_shape(self.Value)
860 1
            if len(dims) > 1:
861 1
                self.Dimensions = dims
862 1
863 1
    def __eq__(self, other):
864
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
865 1
            return True
866 1
        return False
867 1
868 1
    def __ne__(self, other):
869
        return not self.__eq__(other)
870 1
871 1
    def _guess_type(self, val):
872
        if isinstance(val, (list, tuple)):
873 1
            error_val = val
874 1
        while isinstance(val, (list, tuple)):
875 1
            if len(val) == 0:
876 1
                raise UaError("could not guess UA type of variable {}".format(error_val))
877 1
            val = val[0]
878
        if val is None:
879 1
            return VariantType.Null
880 1
        elif isinstance(val, bool):
881 1
            return VariantType.Boolean
882 1
        elif isinstance(val, float):
883 1
            return VariantType.Double
884 1
        elif isinstance(val, int):
885 1
            return VariantType.Int64
886 1
        elif type(val) in (str, unicode):
887 1
            return VariantType.String
888 1
        elif isinstance(val, bytes):
889 1
            return VariantType.ByteString
890 1
        elif isinstance(val, datetime):
891 1
            return VariantType.DateTime
892 1
        else:
893 1
            if isinstance(val, object):
894
                try:
895 1
                    return getattr(VariantType, val.__class__.__name__)
896 1
                except AttributeError:
897 1
                    return VariantType.ExtensionObject
898 1
            else:
899 1
                raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
900
901
    def __str__(self):
902
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
903 1
    __repr__ = __str__
904 1
905 1
    def to_binary(self):
906
        b = []
907 1
        encoding = self.VariantType.value & 0b111111
908 1
        if type(self.Value) in (list, tuple):
909 1
            if self.Dimensions is not None:
910 1
                encoding = set_bit(encoding, 6)
911 1
            encoding = set_bit(encoding, 7)
912 1
            b.append(uatype_UInt8.pack(encoding))
913 1
            b.append(pack_uatype_array(self.VariantType.name, flatten(self.Value)))
914 1
            if self.Dimensions is not None:
915 1
                b.append(pack_uatype_array("Int32", self.Dimensions))
916 1
        else:
917 1
            b.append(uatype_UInt8.pack(encoding))
918
            b.append(pack_uatype(self.VariantType.name, self.Value))
919 1
920 1
        return b"".join(b)
921
922 1
    @staticmethod
923
    def from_binary(data):
924 1
        dimensions = None
925
        encoding = ord(data.read(1))
926 1
        int_type = encoding & 0b00111111
927 1
        if int_type > 25:
928 1
            vtype = VariantTypeCustom(int_type)
929 1
        else:
930 1
            vtype = VariantType(int_type)
931
        if vtype == VariantType.Null:
932 1
            return Variant(None, vtype, encoding)
933 1
        if test_bit(encoding, 7):
934 1
            value = unpack_uatype_array(vtype.name, data)
935 1
        else:
936 1
            value = unpack_uatype(vtype.name, data)
937
        if test_bit(encoding, 6):
938 1
            dimensions = unpack_uatype_array("Int32", data)
939 1
            value = reshape(value, dimensions)
940 1
941 1
        return Variant(value, vtype, dimensions)
942
943 1
944
def reshape(flat, dims):
945
    subdims = dims[1:]
946 1
    subsize = 1
947 1
    for i in subdims:
948 1
        if i == 0:
949 1
            i = 1
950 1
        subsize *= i
951 1
    while dims[0] * subsize > len(flat):
952 1
        flat.append([])
953 1
    if not subdims or subdims == [0]:
954 1
        return flat
955 1
    return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)]
956 1
957 1
958
def _split_list(l, n):
959
    n = max(1, n)
960 1
    return [l[i:i + n] for i in range(0, len(l), n)]
961
962
963
def flatten_and_get_shape(mylist):
964
    dims = []
965 1
    dims.append(len(mylist))
966
    while isinstance(mylist[0], (list, tuple)):
967
        dims.append(len(mylist[0]))
968
        mylist = [item for sublist in mylist for item in sublist]
969
        if len(mylist) == 0:
970
            break
971
    return mylist, dims
972
973
974
def flatten(mylist):
975
    if len(mylist) == 0:
976 1
        return mylist
977 1
    while isinstance(mylist[0], (list, tuple)):
978 1
        mylist = [item for sublist in mylist for item in sublist]
979 1
        if len(mylist) == 0:
980 1
            break
981 1
    return mylist
982 1
983 1
984
def get_shape(mylist):
985
    dims = []
986 1
    while isinstance(mylist, (list, tuple)):
987 1
        dims.append(len(mylist))
988 1
        if len(mylist) == 0:
989 1
            break
990 1
        mylist = mylist[0]
991 1
    return dims
992 1
993 1
994
class XmlElement(FrozenClass):
995
    '''
996 1
    An XML element encoded as an UTF-8 string.
997
    '''
998
    def __init__(self, binary=None):
999
        if binary is not None:
1000 1
            self._binary_init(binary)
1001
            self._freeze = True
1002
            return
1003
        self.Value = []
1004
        self._freeze = True
1005
1006
    def to_binary(self):
1007
        return pack_string(self.Value)
1008 1
1009
    @staticmethod
1010
    def from_binary(data):
1011 1
        return XmlElement(data)
1012
1013
    def _binary_init(self, data):
1014
        self.Value = unpack_string(data)
1015 1
1016
    def __str__(self):
1017
        return 'XmlElement(Value:' + str(self.Value) + ')'
1018 1
1019
    __repr__ = __str__
1020
1021 1
1022
1023
1024
class DataValue(FrozenClass):
1025
1026 1
    '''
1027
    A value with an associated timestamp, and quality.
1028
    Automatically generated from xml , copied and modified here to fix errors in xml spec
1029
1030
    :ivar Value:
1031
    :vartype Value: Variant
1032
    :ivar StatusCode:
1033
    :vartype StatusCode: StatusCode
1034
    :ivar SourceTimestamp:
1035
    :vartype SourceTimestamp: datetime
1036
    :ivar SourcePicoSeconds:
1037
    :vartype SourcePicoSeconds: int
1038
    :ivar ServerTimestamp:
1039
    :vartype ServerTimestamp: datetime
1040
    :ivar ServerPicoseconds:
1041
    :vartype ServerPicoseconds: int
1042
1043
    '''
1044
1045
    def __init__(self, variant=None, status=None):
1046
        self.Encoding = 0
1047 1
        if not isinstance(variant, Variant):
1048 1
            variant = Variant(variant)
1049 1
        self.Value = variant
1050 1
        if status is None:
1051 1
            self.StatusCode = StatusCode()
1052 1
        else:
1053 1
            self.StatusCode = status
1054
        self.SourceTimestamp = None  # DateTime()
1055 1
        self.SourcePicoseconds = None
1056 1
        self.ServerTimestamp = None  # DateTime()
1057 1
        self.ServerPicoseconds = None
1058 1
        self._freeze = True
1059 1
1060 1
    def to_binary(self):
1061
        packet = []
1062 1
        if self.Value:
1063 1
            self.Encoding |= (1 << 0)
1064 1
        if self.StatusCode:
1065 1
            self.Encoding |= (1 << 1)
1066 1
        if self.SourceTimestamp:
1067 1
            self.Encoding |= (1 << 2)
1068 1
        if self.ServerTimestamp:
1069 1
            self.Encoding |= (1 << 3)
1070 1
        if self.SourcePicoseconds:
1071 1
            self.Encoding |= (1 << 4)
1072 1
        if self.ServerPicoseconds:
1073
            self.Encoding |= (1 << 5)
1074 1
        packet.append(uatype_UInt8.pack(self.Encoding))
1075
        if self.Value:
1076 1
            packet.append(self.Value.to_binary())
1077 1
        if self.StatusCode:
1078 1
            packet.append(self.StatusCode.to_binary())
1079 1
        if self.SourceTimestamp:
1080 1
            packet.append(pack_datetime(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
1081 1
        if self.ServerTimestamp:
1082 1
            packet.append(pack_datetime(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
1083 1
        if self.SourcePicoseconds:
1084 1
            packet.append(uatype_UInt16.pack(self.SourcePicoseconds))
1085 1
        if self.ServerPicoseconds:
1086
            packet.append(uatype_UInt16.pack(self.ServerPicoseconds))
1087 1
        return b''.join(packet)
1088
1089 1
    @staticmethod
1090
    def from_binary(data):
1091 1
        encoding = ord(data.read(1))
1092
        if encoding & (1 << 0):
1093 1
            value = Variant.from_binary(data)
1094 1
        else:
1095 1
            value = None
1096
        if encoding & (1 << 1):
1097
            status = StatusCode.from_binary(data)
1098 1
        else:
1099 1
            status = None
1100
        obj = DataValue(value, status)
1101
        obj.Encoding = encoding
1102 1
        if obj.Encoding & (1 << 2):
1103 1
            obj.SourceTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1104 1
        if obj.Encoding & (1 << 3):
1105 1
            obj.ServerTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1106 1
        if obj.Encoding & (1 << 4):
1107 1
            obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1108 1
        if obj.Encoding & (1 << 5):
1109
            obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1110 1
        return obj
1111
1112 1
    def __str__(self):
1113
        s = 'DataValue(Value:{}'.format(self.Value)
1114 1
        if self.StatusCode is not None:
1115
            s += ', StatusCode:{}'.format(self.StatusCode)
1116
        if self.SourceTimestamp is not None:
1117
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
1118
        if self.ServerTimestamp is not None:
1119
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
1120
        if self.SourcePicoseconds is not None:
1121
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
1122
        if self.ServerPicoseconds is not None:
1123
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
1124
        s += ')'
1125
        return s
1126
1127
    __repr__ = __str__
1128
1129 1
1130
1131