Completed
Push — master ( 5a9df5...39e3a6 )
by Olivier
223:12 queued 212:11
created

opcua.ua.DataValue.__init__()   A

Complexity

Conditions 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

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