Passed
Push — dev ( 14d7ed...583b67 )
by Olivier
02:20
created

opcua.ua.NodeId.__init__()   C

Complexity

Conditions 7

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

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