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

opcua.ua.win_epoch_to_datetime()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.5
Metric Value
cc 2
dl 0
loc 7
ccs 3
cts 6
cp 0.5
crap 2.5
rs 9.4285
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"):
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"):
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
    @staticmethod
279
    def from_binary(data):
280 1
        g = Guid()
281 1
        g.uuid = uuid.UUID(bytes=data.read(16))
282 1
        return g
283
284 1
    def __eq__(self, other):
285 1
        return isinstance(other, Guid) and self.uuid == other.uuid
286
287
288 1
class StatusCode(FrozenClass):
289
290
    """
291
    :ivar value:
292
    :vartype value: int
293
    :ivar name:
294
    :vartype name: string
295
    :ivar doc:
296
    :vartype doc: string
297
    """
298
299 1
    def __init__(self, value=0):
300 1
        self.value = value
301 1
        self.name, self.doc = status_codes.get_name_and_doc(value)
302 1
        self._freeze = True
303
304 1
    def to_binary(self):
305 1
        return uatype_UInt32.pack(self.value)
306
307 1
    @staticmethod
308
    def from_binary(data):
309 1
        val = uatype_UInt32.unpack(data.read(4))[0]
310 1
        sc = StatusCode(val)
311 1
        return sc
312
313 1
    def check(self):
314
        """
315
        raise en exception if status code is anything else than 0
316
        use is is_good() method if not exception is desired
317
        """
318 1
        if self.value != 0:
319 1
            raise UAStatusCodeError("{}({})".format(self.doc, self.name))
320
321 1
    def is_good(self):
322
        """
323
        return True if status is Good.
324
        """
325 1
        if self.value == 0:
326 1
            return True
327 1
        return False
328
329 1
    def __str__(self):
330
        return 'StatusCode({})'.format(self.name)
331 1
    __repr__ = __str__
332
333
334 1
class NodeIdType(Enum):
335 1
    TwoByte = 0
336 1
    FourByte = 1
337 1
    Numeric = 2
338 1
    String = 3
339 1
    Guid = 4
340 1
    ByteString = 5
341
342
343 1
class NodeId(FrozenClass):
344
345
    """
346
    NodeId Object
347
348
    Args:
349
        identifier: The identifier might be an int, a string, bytes or a Guid
350
        namespaceidx(int): The index of the namespace
351
        nodeidtype(NodeIdType): The type of the nodeid if it cannor be guess or you want something special like twobyte nodeid or fourbytenodeid
352
353
354
    :ivar Identifier:
355
    :vartype Identifier: NodeId
356
    :ivar NamespaceIndex:
357
    :vartype NamespaceIndex: Int
358
    :ivar NamespaceUri:
359
    :vartype NamespaceUri: String
360
    :ivar ServerIndex:
361
    :vartype ServerIndex: Int
362
    """
363
364 1
    def __init__(self, identifier=None, namespaceidx=0, nodeidtype=None):
365 1
        self.Identifier = identifier
366 1
        self.NamespaceIndex = namespaceidx
367 1
        self.NodeIdType = nodeidtype
368 1
        self.NamespaceUri = ""
369 1
        self.ServerIndex = 0
370 1
        self._freeze = True
371 1
        if self.Identifier is None:
372 1
            self.Identifier = 0
373 1
            self.NodeIdType = NodeIdType.TwoByte
374 1
            return
375 1
        if self.NodeIdType is None:
376 1
            if isinstance(self.Identifier, int):
377 1
                self.NodeIdType = NodeIdType.Numeric
378 1
            elif isinstance(self.Identifier, str):
379 1
                self.NodeIdType = NodeIdType.String
380
            elif isinstance(self.Identifier, bytes):
381
                self.NodeIdType = NodeIdType.ByteString
382
            else:
383
                raise UAError("NodeId: Could not guess type of NodeId, set NodeIdType")
384
385 1
    def __key(self):
386 1
        if self.NodeIdType in (NodeIdType.TwoByte, NodeIdType.FourByte, NodeIdType.Numeric):  # twobyte, fourbyte and numeric may represent the same node
387 1
            return self.NamespaceIndex, self.Identifier
388
        else:
389 1
            return self.NodeIdType, self.NamespaceIndex, self.Identifier
390
391 1
    def __eq__(self, node):
392 1
        return isinstance(node, NodeId) and self.__key() == node.__key()
393
394 1
    def __hash__(self):
395 1
        return hash(self.__key())
396
397 1
    @staticmethod
398
    def from_string(string):
399 1
        l = string.split(";")
400 1
        identifier = None
401 1
        namespace = 0
402 1
        ntype = None
403 1
        srv = None
404 1
        nsu = None
405 1
        for el in l:
406 1
            if not el:
407 1
                continue
408 1
            k, v = el.split("=")
409 1
            k = k.strip()
410 1
            v = v.strip()
411 1
            if k == "ns":
412 1
                namespace = int(v)
413 1
            elif k == "i":
414 1
                ntype = NodeIdType.Numeric
415 1
                identifier = int(v)
416 1
            elif k == "s":
417 1
                ntype = NodeIdType.String
418 1
                identifier = v
419 1
            elif k == "g":
420
                ntype = NodeIdType.Guid
421
                identifier = v
422 1
            elif k == "b":
423
                ntype = NodeIdType.ByteString
424
                identifier = v
425 1
            elif k == "srv":
426 1
                srv = v
427
            elif k == "nsu":
428
                nsu = v
429 1
        if identifier is None:
430
            raise UAError("Could not parse nodeid string: " + string)
431 1
        nodeid = NodeId(identifier, namespace, ntype)
432 1
        nodeid.NamespaceUri = nsu
433 1
        nodeid.ServerIndex = srv
434 1
        return nodeid
435
436 1
    def to_string(self):
437 1
        string = ""
438 1
        if self.NamespaceIndex != 0:
439 1
            string += "ns={};".format(self.NamespaceIndex)
440 1
        ntype = None
441 1
        if self.NodeIdType == NodeIdType.Numeric:
442
            ntype = "i"
443 1
        elif self.NodeIdType == NodeIdType.String:
444 1
            ntype = "s"
445 1
        elif self.NodeIdType == NodeIdType.TwoByte:
446 1
            ntype = "i"
447 1
        elif self.NodeIdType == NodeIdType.FourByte:
448 1
            ntype = "i"
449
        elif self.NodeIdType == NodeIdType.Guid:
450
            ntype = "g"
451
        elif self.NodeIdType == NodeIdType.ByteString:
452
            ntype = "b"
453 1
        string += "{}={}".format(ntype, self.Identifier)
454 1
        if self.ServerIndex:
455
            string = "srv=" + str(self.ServerIndex) + string
456 1
        if self.NamespaceUri:
457
            string += "nsu={}".format(self.NamespaceUri)
458 1
        return string
459
460 1
    def __str__(self):
461 1
        return "{}NodeId({})".format(self.NodeIdType.name, self.to_string())
462 1
    __repr__ = __str__
463
464 1
    def to_binary(self):
465 1
        if self.NodeIdType == NodeIdType.TwoByte:
466 1
            return struct.pack("<BB", self.NodeIdType.value, self.Identifier)
467 1
        elif self.NodeIdType == NodeIdType.FourByte:
468 1
            return struct.pack("<BBH", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
469 1
        elif self.NodeIdType == NodeIdType.Numeric:
470 1
            return struct.pack("<BHI", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
471 1
        elif self.NodeIdType == NodeIdType.String:
472 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
473
                pack_string(self.Identifier)
474 1
        elif self.NodeIdType == NodeIdType.ByteString:
475 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
476
                pack_bytes(self.Identifier)
477
        else:
478 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
479
                self.Identifier.to_binary()
480
        #FIXME: Missing NNamespaceURI and ServerIndex
481
482 1
    @staticmethod
483
    def from_binary(data):
484 1
        nid = NodeId()
485 1
        encoding = ord(data.read(1))
486 1
        nid.NodeIdType = NodeIdType(encoding & 0b00111111)
487
488 1
        if nid.NodeIdType == NodeIdType.TwoByte:
489 1
            nid.Identifier = ord(data.read(1))
490 1
        elif nid.NodeIdType == NodeIdType.FourByte:
491 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3))
492 1
        elif nid.NodeIdType == NodeIdType.Numeric:
493 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6))
494 1
        elif nid.NodeIdType == NodeIdType.String:
495 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
496 1
            nid.Identifier = unpack_string(data)
497 1
        elif nid.NodeIdType == NodeIdType.ByteString:
498 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
499 1
            nid.Identifier = unpack_bytes(data)
500 1
        elif nid.NodeIdType == NodeIdType.Guid:
501 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
502 1
            nid.Identifier = Guid.from_binary(data)
503
        else:
504
            raise UAError("Unknown NodeId encoding: " + str(nid.NodeIdType))
505
506 1
        if test_bit(encoding, 7):
507
            nid.NamespaceUri = unpack_string(data)
508 1
        if test_bit(encoding, 6):
509
            nid.ServerIndex = uatype_UInt32.unpack(data.read(4))[0]
510
511 1
        return nid
512
513
514 1
class TwoByteNodeId(NodeId):
515
516 1
    def __init__(self, identifier):
517 1
        NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte)
518
519
520 1
class FourByteNodeId(NodeId):
521
522 1
    def __init__(self, identifier, namespace=0):
523 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte)
524
525
526 1
class NumericNodeId(NodeId):
527
528 1
    def __init__(self, identifier, namespace=0):
529 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric)
530
531
532 1
class ByteStringNodeId(NodeId):
533
534 1
    def __init__(self, identifier, namespace=0):
535 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString)
536
537
538 1
class GuidNodeId(NodeId):
539
540 1
    def __init__(self, identifier, namespace=0):
541 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Guid)
542
543
544 1
class StringNodeId(NodeId):
545
546 1
    def __init__(self, identifier, namespace=0):
547 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.String)
548
549
550 1
ExpandedNodeId = NodeId
551
552
553 1
class QualifiedName(FrozenClass):
554
555
    '''
556
    A string qualified with a namespace index.
557
    '''
558
559 1
    def __init__(self, name="", namespaceidx=0):
560 1
        if not isinstance(namespaceidx, int):
561
            raise UAError("namespaceidx must be an int")
562 1
        self.NamespaceIndex = namespaceidx
563 1
        self.Name = name
564 1
        self._freeze = True
565
566 1
    def to_string(self):
567 1
        return "{}:{}".format(self.NamespaceIndex, self.Name)
568
569 1
    @staticmethod
570
    def from_string(string):
571 1
        if ":" in string:
572 1
            idx, name = string.split(":", 1)
573
        else:
574 1
            idx = 0
575 1
            name = string
576 1
        return QualifiedName(name, int(idx))
577
578 1
    def to_binary(self):
579 1
        packet = []
580 1
        packet.append(uatype_UInt16.pack(self.NamespaceIndex))
581 1
        packet.append(pack_string(self.Name))
582 1
        return b''.join(packet)
583
584 1
    @staticmethod
585
    def from_binary(data):
586 1
        obj = QualifiedName()
587 1
        obj.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
588 1
        obj.Name = unpack_string(data)
589 1
        return obj
590
591 1
    def __eq__(self, bname):
592 1
        return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex
593
594 1
    def __str__(self):
595
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
596
597 1
    __repr__ = __str__
598
599
600 1
class LocalizedText(FrozenClass):
601
602
    '''
603
    A string qualified with a namespace index.
604
    '''
605
606 1
    def __init__(self, text=""):
607 1
        self.Encoding = 0
608 1
        self.Text = text
609 1
        if isinstance(self.Text, unicode):
610 1
            self.Text = self.Text.encode('utf-8')
611 1
        if self.Text:
612 1
            self.Encoding |= (1 << 1)
613 1
        self.Locale = b''
614 1
        self._freeze = True
615
616 1
    def to_binary(self):
617 1
        packet = []
618 1
        if self.Locale:
619
            self.Encoding |= (1 << 0)
620 1
        if self.Text:
621 1
            self.Encoding |= (1 << 1)
622 1
        packet.append(uatype_UInt8.pack(self.Encoding))
623 1
        if self.Locale:
624
            packet.append(pack_bytes(self.Locale))
625 1
        if self.Text:
626 1
            packet.append(pack_bytes(self.Text))
627 1
        return b''.join(packet)
628
629 1
    @staticmethod
630
    def from_binary(data):
631 1
        obj = LocalizedText()
632 1
        obj.Encoding = ord(data.read(1))
633 1
        if obj.Encoding & (1 << 0):
634
            obj.Locale = unpack_bytes(data)
635 1
        if obj.Encoding & (1 << 1):
636 1
            obj.Text = unpack_bytes(data)
637 1
        return obj
638
639 1
    def to_string(self):
640
        # FIXME: use local
641
        return self.Text.decode()
642
643 1
    def __str__(self):
644
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
645
            'Locale:' + str(self.Locale) + ', ' + \
646
            'Text:' + str(self.Text) + ')'
647 1
    __repr__ = __str__
648
649 1
    def __eq__(self, other):
650 1
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
651 1
            return True
652 1
        return False
653
654
655 1
class ExtensionObject(FrozenClass):
656
657
    '''
658
659
    Any UA object packed as an ExtensionObject
660
661
662
    :ivar TypeId:
663
    :vartype TypeId: NodeId
664
    :ivar Body:
665
    :vartype Body: bytes
666
667
    '''
668
669 1
    def __init__(self):
670 1
        self.TypeId = NodeId()
671 1
        self.Encoding = 0
672 1
        self.Body = b''
673 1
        self._freeze = True
674
675 1
    def to_binary(self):
676 1
        packet = []
677 1
        if self.Body:
678 1
            self.Encoding |= (1 << 0)
679 1
        packet.append(self.TypeId.to_binary())
680 1
        packet.append(pack_uatype('UInt8', self.Encoding))
681 1
        if self.Body:
682 1
            packet.append(pack_uatype('ByteString', self.Body))
683 1
        return b''.join(packet)
684
685 1
    @staticmethod
686
    def from_binary(data):
687
        obj = ExtensionObject()
688
        obj.TypeId = NodeId.from_binary(data)
689
        obj.Encoding = unpack_uatype('UInt8', data)
690
        if obj.Encoding & (1 << 0):
691
            obj.Body = unpack_uatype('ByteString', data)
692
        return obj
693
694 1
    @staticmethod
695
    def from_object(obj):
696
        ext = ExtensionObject()
697
        oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__))
698
        ext.TypeId = FourByteNodeId(oid)
699
        ext.Body = obj.to_binary()
700
        return ext
701
702 1
    def __str__(self):
703
        return 'ExtensionObject(' + 'TypeId:' + str(self.TypeId) + ', ' + \
704
            'Encoding:' + str(self.Encoding) + ', ' + str(len(self.Body)) + ' bytes)'
705
706 1
    __repr__ = __str__
707
708
709 1
class VariantType(Enum):
710
711
    '''
712
    The possible types of a variant.
713
714
    :ivar Null:
715
    :ivar Boolean:
716
    :ivar SByte:
717
    :ivar Byte:
718
    :ivar Int16:
719
    :ivar UInt16:
720
    :ivar Int32:
721
    :ivar UInt32:
722
    :ivar Int64:
723
    :ivar UInt64:
724
    :ivar Float:
725
    :ivar Double:
726
    :ivar String:
727
    :ivar DateTime:
728
    :ivar Guid:
729
    :ivar ByteString:
730
    :ivar XmlElement:
731
    :ivar NodeId:
732
    :ivar ExpandedNodeId:
733
    :ivar StatusCode:
734
    :ivar QualifiedName:
735
    :ivar LocalizedText:
736
    :ivar ExtensionObject:
737
    :ivar DataValue:
738
    :ivar Variant:
739
    :ivar DiagnosticInfo:
740
741
742
743
    '''
744 1
    Null = 0
745 1
    Boolean = 1
746 1
    SByte = 2
747 1
    Byte = 3
748 1
    Int16 = 4
749 1
    UInt16 = 5
750 1
    Int32 = 6
751 1
    UInt32 = 7
752 1
    Int64 = 8
753 1
    UInt64 = 9
754 1
    Float = 10
755 1
    Double = 11
756 1
    String = 12
757 1
    DateTime = 13
758 1
    Guid = 14
759 1
    ByteString = 15
760 1
    XmlElement = 16
761 1
    NodeId = 17
762 1
    ExpandedNodeId = 18
763 1
    StatusCode = 19
764 1
    QualifiedName = 20
765 1
    LocalizedText = 21
766 1
    ExtensionObject = 22
767 1
    DataValue = 23
768 1
    Variant = 24
769 1
    DiagnosticInfo = 25
770
771
772 1
class Variant(FrozenClass):
773
774
    """
775
    Create an OPC-UA Variant object.
776
    if no argument a Null Variant is created.
777
    if not variant type is given, attemps to guess type from python type
778
    if a variant is given as value, the new objects becomes a copy of the argument
779
780
    :ivar Value:
781
    :vartype Value: Any supported type
782
    :ivar VariantType:
783
    :vartype VariantType: VariantType
784
    """
785
786 1
    def __init__(self, value=None, varianttype=None, encoding=0, dimensions=None):
787 1
        self.Encoding = encoding
788 1
        self.Value = value
789 1
        self.VariantType = varianttype
790 1
        self.Dimensions = dimensions
791 1
        self._freeze = True
792 1
        if isinstance(value, Variant):
793 1
            self.Value = value.Value
794 1
            self.VariantType = value.VariantType
795 1
        if self.VariantType is None:
796 1
            self.VariantType = self._guess_type(self.Value)
797 1
        if self.Dimensions is None and type(self.Value) in (list, tuple):
798 1
            dims = get_shape(self.Value)
799 1
            if len(dims) > 1:
800 1
                self.Dimensions = dims
801
802 1
    def __eq__(self, other):
803 1
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
804 1
            return True
805 1
        return False
806
807 1
    def _guess_type(self, val):
808 1
        while isinstance(val, (list, tuple)):
809 1
            if len(val) == 0:
810
                raise UAError("could not guess UA variable type")
811 1
            val = val[0]
812 1
        if val is None:
813 1
            return VariantType.Null
814 1
        elif isinstance(val, bool):
815 1
            return VariantType.Boolean
816 1
        elif isinstance(val, float):
817 1
            return VariantType.Double
818 1
        elif isinstance(val, int):
819 1
            return VariantType.Int64
820 1
        elif type(val) in (str, unicode):
821 1
            return VariantType.String
822 1
        elif isinstance(val, bytes):
823 1
            return VariantType.ByteString
824 1
        elif isinstance(val, datetime):
825 1
            return VariantType.DateTime
826
        else:
827 1
            if isinstance(val, object):
828 1
                try:
829 1
                    return getattr(VariantType, val.__class__.__name__)
830 1
                except AttributeError:
831 1
                    return VariantType.ExtensionObject
832
            else:
833
                raise UAError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
834
835 1
    def __str__(self):
836 1
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
837 1
    __repr__ = __str__
838
839 1
    def to_binary(self):
840 1
        b = []
841 1
        mask = self.Encoding & 0b00111111
842 1
        self.Encoding = (self.VariantType.value | mask)
843 1
        if type(self.Value) in (list, tuple):
844 1
            if self.Dimensions is not None:
845 1
                self.Encoding = set_bit(self.Encoding, 6)
846 1
            self.Encoding = set_bit(self.Encoding, 7)
847 1
            b.append(uatype_UInt8.pack(self.Encoding))
848 1
            b.append(pack_uatype_array(self.VariantType.name, flatten(self.Value)))
849 1
            if self.Dimensions is not None:
850 1
                b.append(pack_uatype_array("Int32", self.Dimensions))
851
        else:
852 1
            b.append(uatype_UInt8.pack(self.Encoding))
853 1
            b.append(pack_uatype(self.VariantType.name, self.Value))
854
855 1
        return b"".join(b)
856
857 1
    @staticmethod
858
    def from_binary(data):
859 1
        dimensions = None
860 1
        encoding = ord(data.read(1))
861 1
        vtype = VariantType(encoding & 0b00111111)
862 1
        if vtype == VariantType.Null:
863 1
            return Variant(None, vtype, encoding)
864 1
        if test_bit(encoding, 7):
865 1
            value = unpack_uatype_array(vtype.name, data)
866
        else:
867 1
            value = unpack_uatype(vtype.name, data)
868 1
        if test_bit(encoding, 6):
869 1
            dimensions = unpack_uatype_array("Int32", data)
870 1
            value = reshape(value, dimensions)
871
872 1
        return Variant(value, vtype, encoding, dimensions)
873
874
875 1
def reshape(flat, dims):
876 1
    subdims = dims[1:]
877 1
    subsize = 1
878 1
    for i in subdims:
879 1
        if i == 0:
880 1
            i = 1
881 1
        subsize *= i
882 1
    while dims[0] * subsize > len(flat):
883 1
        flat.append([])
884 1
    if not subdims or subdims == [0]:
885 1
        return flat
886 1
    return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)]
887
888
889 1
def _split_list(l, n):
890
    n = max(1, n)
891
    return [l[i:i + n] for i in range(0, len(l), n)]
892
893
894 1
def flatten_and_get_shape(mylist):
895
    dims = []
896
    dims.append(len(mylist))
897
    while isinstance(mylist[0], (list, tuple)):
898
        dims.append(len(mylist[0]))
899
        mylist = [item for sublist in mylist for item in sublist]
900
        if len(mylist) == 0:
901
            break
902
    return mylist, dims
903
904
905 1
def flatten(mylist):
906 1
    if len(mylist) == 0:
907
        return mylist
908 1
    while isinstance(mylist[0], (list, tuple)):
909 1
        mylist = [item for sublist in mylist for item in sublist]
910 1
        if len(mylist) == 0:
911 1
            break
912 1
    return mylist
913
914
915 1
def get_shape(mylist):
916 1
    dims = []
917 1
    while isinstance(mylist, (list, tuple)):
918 1
        dims.append(len(mylist))
919 1
        if len(mylist) == 0:
920 1
            break
921 1
        mylist = mylist[0]
922 1
    return dims
923
924
925 1
class XmlElement(FrozenClass):
926
    '''
927
    An XML element encoded as an UTF-8 string.
928
    '''
929 1
    def __init__(self, binary=None):
930
        if binary is not None:
931
            self._binary_init(binary)
932
            self._freeze = True
933
            return
934
        self.Value = []
935
        self._freeze = True
936
937 1
    def to_binary(self):
938
        return pack_string(self.Value)
939
940 1
    @staticmethod
941
    def from_binary(data):
942
        return XmlElement(data)
943
944 1
    def _binary_init(self, data):
945
        self.Value = unpack_string(data)
946
947 1
    def __str__(self):
948
        return 'XmlElement(Value:' + str(self.Value) + ')'
949
950 1
    __repr__ = __str__
951
952
953
954
955 1
class DataValue(FrozenClass):
956
957
    '''
958
    A value with an associated timestamp, and quality.
959
    Automatically generated from xml , copied and modified here to fix errors in xml spec
960
961
    :ivar Value:
962
    :vartype Value: Variant
963
    :ivar StatusCode:
964
    :vartype StatusCode: StatusCode
965
    :ivar SourceTimestamp:
966
    :vartype SourceTimestamp: datetime
967
    :ivar SourcePicoSeconds:
968
    :vartype SourcePicoSeconds: int
969
    :ivar ServerTimestamp:
970
    :vartype ServerTimestamp: datetime
971
    :ivar ServerPicoseconds:
972
    :vartype ServerPicoseconds: int
973
974
    '''
975
976 1
    def __init__(self, variant=None, status=None):
977 1
        self.Encoding = 0
978 1
        if not isinstance(variant, Variant):
979 1
            variant = Variant(variant)
980 1
        self.Value = variant
981 1
        if status is None:
982 1
            self.StatusCode = StatusCode()
983
        else:
984 1
            self.StatusCode = status
985 1
        self.SourceTimestamp = None  # DateTime()
986 1
        self.SourcePicoseconds = None
987 1
        self.ServerTimestamp = None  # DateTime()
988 1
        self.ServerPicoseconds = None
989 1
        self._freeze = True
990
991 1
    def to_binary(self):
992 1
        packet = []
993 1
        if self.Value:
994 1
            self.Encoding |= (1 << 0)
995 1
        if self.StatusCode:
996 1
            self.Encoding |= (1 << 1)
997 1
        if self.SourceTimestamp:
998 1
            self.Encoding |= (1 << 2)
999 1
        if self.ServerTimestamp:
1000 1
            self.Encoding |= (1 << 3)
1001 1
        if self.SourcePicoseconds:
1002
            self.Encoding |= (1 << 4)
1003 1
        if self.ServerPicoseconds:
1004
            self.Encoding |= (1 << 5)
1005 1
        packet.append(uatype_UInt8.pack(self.Encoding))
1006 1
        if self.Value:
1007 1
            packet.append(self.Value.to_binary())
1008 1
        if self.StatusCode:
1009 1
            packet.append(self.StatusCode.to_binary())
1010 1
        if self.SourceTimestamp:
1011 1
            packet.append(pack_datetime(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
1012 1
        if self.ServerTimestamp:
1013 1
            packet.append(pack_datetime(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
1014 1
        if self.SourcePicoseconds:
1015
            packet.append(uatype_UInt16.pack(self.SourcePicoseconds))
1016 1
        if self.ServerPicoseconds:
1017
            packet.append(uatype_UInt16.pack(self.ServerPicoseconds))
1018 1
        return b''.join(packet)
1019
1020 1
    @staticmethod
1021
    def from_binary(data):
1022 1
        encoding = ord(data.read(1))
1023 1
        if encoding & (1 << 0):
1024 1
            value = Variant.from_binary(data)
1025
        else:
1026
            value = None
1027 1
        if encoding & (1 << 1):
1028 1
            status = StatusCode.from_binary(data)
1029
        else:
1030
            status = None
1031 1
        obj = DataValue(value, status)
1032 1
        obj.Encoding = encoding
1033 1
        if obj.Encoding & (1 << 2):
1034 1
            obj.SourceTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1035 1
        if obj.Encoding & (1 << 3):
1036 1
            obj.ServerTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
1037 1
        if obj.Encoding & (1 << 4):
1038
            obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1039 1
        if obj.Encoding & (1 << 5):
1040
            obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0]
1041 1
        return obj
1042
1043 1
    def __str__(self):
1044
        s = 'DataValue(Value:{}'.format(self.Value)
1045
        if self.StatusCode is not None:
1046
            s += ', StatusCode:{}'.format(self.StatusCode)
1047
        if self.SourceTimestamp is not None:
1048
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
1049
        if self.ServerTimestamp is not None:
1050
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
1051
        if self.SourcePicoseconds is not None:
1052
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
1053
        if self.ServerPicoseconds is not None:
1054
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
1055
        s += ')'
1056
        return s
1057
1058 1
    __repr__ = __str__
1059
1060
1061 1
__nodeid_counter = 2000
1062
1063
1064 1
def generate_nodeid(idx):
1065
    global __nodeid_counter
1066 1
    __nodeid_counter += 1
1067
    return NodeId(__nodeid_counter, idx)
1068