Completed
Pull Request — master (#133)
by Denis
02:28
created

Event.fill_default_fields()   A

Complexity

Conditions 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

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