Completed
Pull Request — master (#217)
by Olivier
04:14
created

Variant.from_binary()   A

Complexity

Conditions 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0582

Importance

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