Completed
Push — master ( 9ea27a...e48fac )
by Olivier
04:09
created

QualifiedName.__lt__()   A

Complexity

Conditions 3

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 5.667

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
dl 0
loc 7
ccs 1
cts 3
cp 0.3333
crap 5.667
rs 9.4285
c 1
b 0
f 0
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 __lt__(self, other):
734
        if not isinstance(other, QualifiedName):
735
            raise TypeError("Cannot compare QualifiedName and {}".format(other))
736 1
        if self.NamespaceIndex == other.NamespaceIndex:
737
            return self.Name < other.Name
738
        else:
739
            return self.NamespaceIndex < other.NamespaceIndex
740 1
741
    def __str__(self):
742 1
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
743 1
744 1
    __repr__ = __str__
745 1
746
747 1
class LocalizedText(FrozenClass):
748 1
749
    '''
750
    A string qualified with a namespace index.
751 1
    '''
752
753
    def __init__(self, text=None):
754
        self.Encoding = 0
755
        self.Text = text
756
        if isinstance(self.Text, unicode):
757
            self.Text = self.Text.encode('utf-8')
758
        if self.Text:
759
            self.Encoding |= (1 << 1)
760
        self.Locale = None 
761
        self._freeze = True
762
763
    def to_binary(self):
764
        packet = []
765 1
        if self.Locale:
766 1
            self.Encoding |= (1 << 0)
767 1
        if self.Text:
768 1
            self.Encoding |= (1 << 1)
769 1
        packet.append(uatype_UInt8.pack(self.Encoding))
770
        if self.Locale:
771 1
            packet.append(pack_bytes(self.Locale))
772 1
        if self.Text:
773 1
            packet.append(pack_bytes(self.Text))
774 1
        return b''.join(packet)
775 1
776 1
    @staticmethod
777 1
    def from_binary(data):
778 1
        obj = LocalizedText()
779 1
        obj.Encoding = ord(data.read(1))
780
        if obj.Encoding & (1 << 0):
781 1
            obj.Locale = unpack_bytes(data)
782
        if obj.Encoding & (1 << 1):
783
            obj.Text = unpack_bytes(data)
784
        return obj
785
786
    def to_string(self):
787
        # FIXME: use local
788
        if self.Text is None:
789
            return ""
790 1
        return self.Text.decode('utf-8')
791
792
    def __str__(self):
793
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
794
            'Locale:' + str(self.Locale) + ', ' + \
795
            'Text:' + str(self.Text) + ')'
796
    __repr__ = __str__
797
798 1
    def __eq__(self, other):
799
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
800
            return True
801
        return False
802 1
803
    def __ne__(self, other):
804
        return not self.__eq__(other)
805 1 View Code Duplication
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
806
807
class ExtensionObject(FrozenClass):
808
809
    '''
810
811
    Any UA object packed as an ExtensionObject
812
813
814
    :ivar TypeId:
815
    :vartype TypeId: NodeId
816
    :ivar Body:
817
    :vartype Body: bytes
818
819
    '''
820
821
    def __init__(self):
822
        self.TypeId = NodeId()
823
        self.Encoding = 0
824
        self.Body = b''
825
        self._freeze = True
826
827
    def to_binary(self):
828
        packet = []
829
        if self.Body:
830
            self.Encoding |= (1 << 0)
831
        packet.append(self.TypeId.to_binary())
832
        packet.append(pack_uatype('UInt8', self.Encoding))
833
        if self.Body:
834
            packet.append(pack_uatype('ByteString', self.Body))
835
        return b''.join(packet)
836
837
    @staticmethod
838
    def from_binary(data):
839
        obj = ExtensionObject()
840 1
        obj.TypeId = NodeId.from_binary(data)
841 1
        obj.Encoding = unpack_uatype('UInt8', data)
842 1
        if obj.Encoding & (1 << 0):
843 1
            obj.Body = unpack_uatype('ByteString', data)
844 1
        return obj
845 1
846 1
    @staticmethod
847 1
    def from_object(obj):
848 1
        ext = ExtensionObject()
849 1
        oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__))
850 1
        ext.TypeId = FourByteNodeId(oid)
851 1
        ext.Body = obj.to_binary()
852 1
        return ext
853 1
854 1
    def __str__(self):
855 1
        return 'ExtensionObject(' + 'TypeId:' + str(self.TypeId) + ', ' + \
856 1
            'Encoding:' + str(self.Encoding) + ', ' + str(len(self.Body)) + ' bytes)'
857 1
858 1
    __repr__ = __str__
859 1
860 1
861 1
class VariantType(Enum):
862 1
863 1
    '''
864 1
    The possible types of a variant.
865 1
866
    :ivar Null:
867
    :ivar Boolean:
868 1
    :ivar SByte:
869 1
    :ivar Byte:
870 1
    :ivar Int16:
871 1
    :ivar UInt16:
872 1
    :ivar Int32:
873 1
    :ivar UInt32:
874
    :ivar Int64:
875 1
    :ivar UInt64:
876
    :ivar Float:
877 1
    :ivar Double:
878
    :ivar String:
879 1
    :ivar DateTime:
880 1
    :ivar Guid:
881
    :ivar ByteString:
882
    :ivar XmlElement:
883 1
    :ivar NodeId:
884
    :ivar ExpandedNodeId:
885
    :ivar StatusCode:
886
    :ivar QualifiedName:
887
    :ivar LocalizedText:
888
    :ivar ExtensionObject:
889
    :ivar DataValue:
890
    :ivar Variant:
891
    :ivar DiagnosticInfo:
892
893
894
895
    '''
896
    Null = 0
897 1
    Boolean = 1
898 1
    SByte = 2
899 1
    Byte = 3
900 1
    Int16 = 4
901 1
    UInt16 = 5
902 1
    Int32 = 6
903 1
    UInt32 = 7
904 1
    Int64 = 8
905 1
    UInt64 = 9
906 1
    Float = 10
907 1
    Double = 11
908 1
    String = 12
909 1
    DateTime = 13
910 1
    Guid = 14
911
    ByteString = 15
912 1
    XmlElement = 16
913 1
    NodeId = 17
914 1
    ExpandedNodeId = 18
915 1
    StatusCode = 19
916
    QualifiedName = 20
917 1
    LocalizedText = 21
918 1
    ExtensionObject = 22
919
    DataValue = 23
920 1
    Variant = 24
921 1
    DiagnosticInfo = 25
922 1
923 1
924 1
class VariantTypeCustom(object):
925
    def __init__(self, val):
926 1
        self.name = "Custom"
927 1
        self.value = val
928 1
        if self.value > 0b00111111:
929 1
            raise UaError("Cannot create VariantType. VariantType must be {} > x > {}, received {}".format(0b111111, 25, val))
930 1
931 1
    def __str__(self):
932 1
        return "VariantType.Custom:{}".format(self.value)
933 1
    __repr__ = __str__
934 1
935 1
    def __eq__(self, other):
936 1
        return self.value == other.value
937 1
938 1
939 1
class Variant(FrozenClass):
940 1
941
    """
942 1
    Create an OPC-UA Variant object.
943 1
    if no argument a Null Variant is created.
944 1
    if not variant type is given, attemps to guess type from python type
945 1
    if a variant is given as value, the new objects becomes a copy of the argument
946 1
947
    :ivar Value:
948
    :vartype Value: Any supported type
949
    :ivar VariantType:
950 1
    :vartype VariantType: VariantType
951 1
    """
952 1
953
    def __init__(self, value=None, varianttype=None, dimensions=None):
954 1
        self.Value = value
955 1
        self.VariantType = varianttype
956 1
        self.Dimensions = dimensions
957 1
        self._freeze = True
958 1
        if isinstance(value, Variant):
959 1
            self.Value = value.Value
960 1
            self.VariantType = value.VariantType
961 1
        if self.VariantType is None:
962 1
            self.VariantType = self._guess_type(self.Value)
963 1
        if self.Dimensions is None and type(self.Value) in (list, tuple):
964 1
            dims = get_shape(self.Value)
965
            if len(dims) > 1:
966 1
                self.Dimensions = dims
967 1
968
    def __eq__(self, other):
969 1
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
970
            return True
971 1
        return False
972
973 1
    def __ne__(self, other):
974 1
        return not self.__eq__(other)
975 1
976 1
    def _guess_type(self, val):
977 1
        if isinstance(val, (list, tuple)):
978
            error_val = val
979 1
        while isinstance(val, (list, tuple)):
980 1
            if len(val) == 0:
981 1
                raise UaError("could not guess UA type of variable {}".format(error_val))
982 1
            val = val[0]
983 1
        if val is None:
984
            return VariantType.Null
985 1
        elif isinstance(val, bool):
986 1
            return VariantType.Boolean
987 1
        elif isinstance(val, float):
988 1
            return VariantType.Double
989
        elif isinstance(val, int):
990 1
            return VariantType.Int64
991
        elif type(val) in (str, unicode):
992
            return VariantType.String
993 1
        elif isinstance(val, bytes):
994 1
            return VariantType.ByteString
995 1
        elif isinstance(val, datetime):
996 1
            return VariantType.DateTime
997 1
        else:
998 1
            if isinstance(val, object):
999 1
                try:
1000 1
                    return getattr(VariantType, val.__class__.__name__)
1001 1
                except AttributeError:
1002 1
                    return VariantType.ExtensionObject
1003 1
            else:
1004 1
                raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
1005
1006
    def __str__(self):
1007 1
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
1008
    __repr__ = __str__
1009
1010
    def to_binary(self):
1011
        b = []
1012 1
        encoding = self.VariantType.value & 0b111111
1013
        if type(self.Value) in (list, tuple):
1014
            if self.Dimensions is not None:
1015
                encoding = set_bit(encoding, 6)
1016
            encoding = set_bit(encoding, 7)
1017
            b.append(uatype_UInt8.pack(encoding))
1018
            b.append(pack_uatype_array(self.VariantType.name, flatten(self.Value)))
1019
            if self.Dimensions is not None:
1020
                b.append(pack_uatype_array("Int32", self.Dimensions))
1021
        else:
1022
            b.append(uatype_UInt8.pack(encoding))
1023 1
            b.append(pack_uatype(self.VariantType.name, self.Value))
1024 1
1025 1
        return b"".join(b)
1026 1
1027 1
    @staticmethod
1028 1
    def from_binary(data):
1029 1
        dimensions = None
1030 1
        encoding = ord(data.read(1))
1031
        int_type = encoding & 0b00111111
1032
        vtype = DataType_to_VariantType(int_type)
1033 1
        if vtype == VariantType.Null:
1034 1
            return Variant(None, vtype, encoding)
1035 1
        if test_bit(encoding, 7):
1036 1
            value = unpack_uatype_array(vtype.name, data)
1037 1
        else:
1038 1
            value = unpack_uatype(vtype.name, data)
1039 1
        if test_bit(encoding, 6):
1040 1
            dimensions = unpack_uatype_array("Int32", data)
1041
            value = reshape(value, dimensions)
1042
1043 1 View Code Duplication
        return Variant(value, vtype, dimensions)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1044
1045
1046
def reshape(flat, dims):
1047 1
    subdims = dims[1:]
1048
    subsize = 1
1049
    for i in subdims:
1050
        if i == 0:
1051
            i = 1
1052
        subsize *= i
1053
    while dims[0] * subsize > len(flat):
1054
        flat.append([])
1055 1
    if not subdims or subdims == [0]:
1056
        return flat
1057
    return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)]
1058 1
1059
1060
def _split_list(l, n):
1061
    n = max(1, n)
1062 1
    return [l[i:i + n] for i in range(0, len(l), n)]
1063
1064
1065 1
def flatten_and_get_shape(mylist):
1066
    dims = []
1067
    dims.append(len(mylist))
1068 1
    while isinstance(mylist[0], (list, tuple)):
1069
        dims.append(len(mylist[0]))
1070
        mylist = [item for sublist in mylist for item in sublist]
1071 1
        if len(mylist) == 0:
1072
            break
1073
    return mylist, dims
1074
1075
1076
def flatten(mylist):
1077
    if len(mylist) == 0:
1078
        return mylist
1079
    while isinstance(mylist[0], (list, tuple)):
1080
        mylist = [item for sublist in mylist for item in sublist]
1081
        if len(mylist) == 0:
1082
            break
1083
    return mylist
1084
1085
1086
def get_shape(mylist):
1087
    dims = []
1088
    while isinstance(mylist, (list, tuple)):
1089
        dims.append(len(mylist))
1090
        if len(mylist) == 0:
1091
            break
1092 1
        mylist = mylist[0]
1093 1
    return dims
1094 1
1095 1
1096 1
class XmlElement(FrozenClass):
1097 1
    '''
1098 1
    An XML element encoded as an UTF-8 string.
1099
    '''
1100 1
    def __init__(self, binary=None):
1101 1
        if binary is not None:
1102 1
            self._binary_init(binary)
1103 1
            self._freeze = True
1104 1
            return
1105 1
        self.Value = []
1106
        self._freeze = True
1107 1
1108 1
    def to_binary(self):
1109 1
        return pack_string(self.Value)
1110 1
1111 1
    @staticmethod
1112 1
    def from_binary(data):
1113 1
        return XmlElement(data)
1114 1
1115 1
    def _binary_init(self, data):
1116 1
        self.Value = unpack_string(data)
1117 1
1118
    def __str__(self):
1119 1
        return 'XmlElement(Value:' + str(self.Value) + ')'
1120
1121 1
    __repr__ = __str__
1122 1
1123 1
1124 1
class DataValue(FrozenClass):
1125 1
1126 1
    '''
1127 1
    A value with an associated timestamp, and quality.
1128 1
    Automatically generated from xml , copied and modified here to fix errors in xml spec
1129 1
1130 1
    :ivar Value:
1131
    :vartype Value: Variant
1132 1
    :ivar StatusCode:
1133
    :vartype StatusCode: StatusCode
1134 1
    :ivar SourceTimestamp:
1135
    :vartype SourceTimestamp: datetime
1136 1
    :ivar SourcePicoSeconds:
1137
    :vartype SourcePicoSeconds: int
1138 1
    :ivar ServerTimestamp:
1139 1
    :vartype ServerTimestamp: datetime
1140 1
    :ivar ServerPicoseconds:
1141
    :vartype ServerPicoseconds: int
1142
1143 1
    '''
1144 1
1145
    def __init__(self, variant=None, status=None):
1146
        self.Encoding = 0
1147 1
        if not isinstance(variant, Variant):
1148 1
            variant = Variant(variant)
1149 1
        self.Value = variant
1150 1
        if status is None:
1151 1
            self.StatusCode = StatusCode()
1152 1
        else:
1153 1
            self.StatusCode = status
1154
        self.SourceTimestamp = None  # DateTime()
1155 1
        self.SourcePicoseconds = None
1156
        self.ServerTimestamp = None  # DateTime()
1157 1
        self.ServerPicoseconds = None
1158
        self._freeze = True
1159 1
1160
    def to_binary(self):
1161
        packet = []
1162
        if self.Value:
1163
            self.Encoding |= (1 << 0)
1164
        if self.StatusCode:
1165
            self.Encoding |= (1 << 1)
1166
        if self.SourceTimestamp:
1167
            self.Encoding |= (1 << 2)
1168
        if self.ServerTimestamp:
1169
            self.Encoding |= (1 << 3)
1170
        if self.SourcePicoseconds:
1171
            self.Encoding |= (1 << 4)
1172
        if self.ServerPicoseconds:
1173
            self.Encoding |= (1 << 5)
1174 1
        packet.append(uatype_UInt8.pack(self.Encoding))
1175
        if self.Value:
1176
            packet.append(self.Value.to_binary())
1177
        if self.StatusCode:
1178
            packet.append(self.StatusCode.to_binary())
1179
        if self.SourceTimestamp:
1180
            packet.append(pack_datetime(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
1181
        if self.ServerTimestamp:
1182
            packet.append(pack_datetime(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
1183
        if self.SourcePicoseconds:
1184
            packet.append(uatype_UInt16.pack(self.SourcePicoseconds))
1185
        if self.ServerPicoseconds:
1186
            packet.append(uatype_UInt16.pack(self.ServerPicoseconds))
1187
        return b''.join(packet)
1188
1189
    @staticmethod
1190
    def from_binary(data):
1191
        encoding = ord(data.read(1))
1192
        if encoding & (1 << 0):
1193
            value = Variant.from_binary(data)
1194
        else:
1195
            value = None
1196
        if encoding & (1 << 1):
1197
            status = StatusCode.from_binary(data)
1198
        else:
1199
            status = None
1200
        obj = DataValue(value, status)
1201
        obj.Encoding = encoding
1202
        if obj.Encoding & (1 << 2):
1203
            obj.SourceTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1204
        if obj.Encoding & (1 << 3):
1205
            obj.ServerTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1206
        if obj.Encoding & (1 << 4):
1207
            obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1208
        if obj.Encoding & (1 << 5):
1209
            obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1210
        return obj
1211
1212
    def __str__(self):
1213
        s = 'DataValue(Value:{}'.format(self.Value)
1214
        if self.StatusCode is not None:
1215
            s += ', StatusCode:{}'.format(self.StatusCode)
1216
        if self.SourceTimestamp is not None:
1217
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
1218
        if self.ServerTimestamp is not None:
1219
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
1220
        if self.SourcePicoseconds is not None:
1221
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
1222
        if self.ServerPicoseconds is not None:
1223
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
1224
        s += ')'
1225
        return s
1226
1227
    __repr__ = __str__
1228
1229
1230
def DataType_to_VariantType(int_type):
1231
    """
1232
    Takes a NodeId or int and return a VariantType
1233
    This is only supported if int_type < 63 due to VariantType encoding
1234
    """
1235
    if isinstance(int_type, NodeId):
1236
        int_type = int_type.Identifier
1237
1238
    if int_type <= 25:
1239
        return VariantType(int_type)
1240
    else:
1241
        return VariantTypeCustom(int_type)
1242
1243
1244
def int_to_AccessLevel(level):
1245
    """
1246
    take an int and return a list of AccessLevel Enum
1247
    """
1248
    res = []
1249
    for val in AccessLevel:
1250
        test_bit(level, val.value)
1251
        res.append(val)
1252
    return res
1253
1254
1255
def int_to_WriteMask(level):
1256
    """
1257
    take an int and return a list of WriteMask Enum
1258
    """
1259
    res = []
1260
    for val in WriteMask:
1261
        test_bit(level, val.value)
1262
        res.append(val)
1263
    return res
1264
1265
1266
def int_to_EventNotifier(level):
1267
    """
1268
    take an int and return a list of EventNotifier Enum
1269
    """
1270
    res = []
1271
    for val in EventNotifier:
1272
        test_bit(level, val.value)
1273
        res.append(val)
1274
    return res
1275