Completed
Pull Request — master (#115)
by Alexander
04:04
created

opcua.ua.ExtensionObject.__str__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

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