Completed
Push — master ( cc3a89...7074ac )
by Olivier
04:03
created

int_to_EventNotifier()   A

Complexity

Conditions 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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