Completed
Pull Request — master (#149)
by Denis
02:39
created

opcua.ua.NodeId.__key()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

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