Completed
Push — master ( 5ff98e...08e4db )
by Olivier
68:12 queued 62:14
created

opcua.ua.QualifiedName.from_string()   A

Complexity

Conditions 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2
Metric Value
cc 2
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
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
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
        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
    mask = 1 << offset
238
    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
476 1
    @staticmethod
477
    def from_binary(data):
478 1
        nid = NodeId()
479 1
        encoding = ord(data.read(1))
480 1
        nid.NodeIdType = NodeIdType(encoding & 0b00111111)
481
482 1
        if nid.NodeIdType == NodeIdType.TwoByte:
483 1
            nid.Identifier = ord(data.read(1))
484 1
        elif nid.NodeIdType == NodeIdType.FourByte:
485 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3))
486 1
        elif nid.NodeIdType == NodeIdType.Numeric:
487 1
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6))
488 1
        elif nid.NodeIdType == NodeIdType.String:
489 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
490 1
            nid.Identifier = unpack_string(data)
491 1
        elif nid.NodeIdType == NodeIdType.ByteString:
492 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
493 1
            nid.Identifier = unpack_bytes(data)
494 1
        elif nid.NodeIdType == NodeIdType.Guid:
495 1
            nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
496 1
            nid.Identifier = Guid.from_binary(data)
497
        else:
498
            raise UAError("Unknown NodeId encoding: " + str(nid.NodeIdType))
499
500 1
        if test_bit(encoding, 6):
501
            nid.NamespaceUri = unpack_string(data)
502 1
        if test_bit(encoding, 7):
503
            nid.ServerIndex = uatype_UInt32.unpack(data.read(4))[0]
504
505 1
        return nid
506
507
508 1
class TwoByteNodeId(NodeId):
509
510 1
    def __init__(self, identifier):
511 1
        NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte)
512
513
514 1
class FourByteNodeId(NodeId):
515
516 1
    def __init__(self, identifier, namespace=0):
517 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte)
518
519
520 1
class NumericNodeId(NodeId):
521
522 1
    def __init__(self, identifier, namespace=0):
523 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric)
524
525
526 1
class ByteStringNodeId(NodeId):
527
528 1
    def __init__(self, identifier, namespace=0):
529 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString)
530
531
532 1
class GuidNodeId(NodeId):
533
534 1
    def __init__(self, identifier, namespace=0):
535 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Guid)
536
537
538 1
class StringNodeId(NodeId):
539
540 1
    def __init__(self, identifier, namespace=0):
541 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.String)
542
543
544 1
ExpandedNodeId = NodeId
545
546
547 1
class QualifiedName(FrozenClass):
548
549
    '''
550
    A string qualified with a namespace index.
551
    '''
552
553 1
    def __init__(self, name="", namespaceidx=0):
554 1
        if not isinstance(namespaceidx, int):
555
            raise UAError("namespaceidx must be an int")
556 1
        self.NamespaceIndex = namespaceidx
557 1
        self.Name = name
558 1
        self._freeze = True
559
560 1
    def to_string(self):
561 1
        return "{}:{}".format(self.NamespaceIndex, self.Name)
562
563 1
    @staticmethod
564
    def from_string(string):
565 1
        if ":" in string:
566 1
            idx, name = string.split(":", 1)
567
        else:
568 1
            idx = 0
569 1
            name = string
570 1
        return QualifiedName(name, int(idx))
571
572 1
    def to_binary(self):
573 1
        packet = []
574 1
        packet.append(uatype_UInt16.pack(self.NamespaceIndex))
575 1
        packet.append(pack_string(self.Name))
576 1
        return b''.join(packet)
577
578 1
    @staticmethod
579
    def from_binary(data):
580 1
        obj = QualifiedName()
581 1
        obj.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0]
582 1
        obj.Name = unpack_string(data)
583 1
        return obj
584
585 1
    def __eq__(self, bname):
586 1
        return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex
587
588 1
    def __str__(self):
589
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
590
591 1
    __repr__ = __str__
592
593
594 1
class LocalizedText(FrozenClass):
595
596
    '''
597
    A string qualified with a namespace index.
598
    '''
599
600 1
    def __init__(self, text=""):
601 1
        self.Encoding = 0
602 1
        self.Text = text
603 1
        if isinstance(self.Text, unicode):
604 1
            self.Text = self.Text.encode('utf-8')
605 1
        if self.Text:
606 1
            self.Encoding |= (1 << 1)
607 1
        self.Locale = b''
608 1
        self._freeze = True
609
610 1
    def to_binary(self):
611 1
        packet = []
612 1
        if self.Locale:
613
            self.Encoding |= (1 << 0)
614 1
        if self.Text:
615 1
            self.Encoding |= (1 << 1)
616 1
        packet.append(uatype_UInt8.pack(self.Encoding))
617 1
        if self.Locale:
618
            packet.append(pack_bytes(self.Locale))
619 1
        if self.Text:
620 1
            packet.append(pack_bytes(self.Text))
621 1
        return b''.join(packet)
622
623 1
    @staticmethod
624
    def from_binary(data):
625 1
        obj = LocalizedText()
626 1
        obj.Encoding = ord(data.read(1))
627 1
        if obj.Encoding & (1 << 0):
628
            obj.Locale = unpack_bytes(data)
629 1
        if obj.Encoding & (1 << 1):
630 1
            obj.Text = unpack_bytes(data)
631 1
        return obj
632
633 1
    def to_string(self):
634
        # FIXME: use local
635
        return self.Text.decode()
636
637 1
    def __str__(self):
638
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
639
            'Locale:' + str(self.Locale) + ', ' + \
640
            'Text:' + str(self.Text) + ')'
641 1
    __repr__ = __str__
642
643 1
    def __eq__(self, other):
644 1
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
645 1
            return True
646 1
        return False
647
648
649 1
class VariantType(Enum):
650
651
    '''
652
    The possible types of a variant.
653
654
    :ivar Null:
655
    :ivar Boolean:
656
    :ivar SByte:
657
    :ivar Byte:
658
    :ivar Int16:
659
    :ivar UInt16:
660
    :ivar Int32:
661
    :ivar UInt32:
662
    :ivar Int64:
663
    :ivar UInt64:
664
    :ivar Float:
665
    :ivar Double:
666
    :ivar String:
667
    :ivar DateTime:
668
    :ivar Guid:
669
    :ivar ByteString:
670
    :ivar XmlElement:
671
    :ivar NodeId:
672
    :ivar ExpandedNodeId:
673
    :ivar StatusCode:
674
    :ivar QualifiedName:
675
    :ivar LocalizedText:
676
    :ivar ExtensionObject:
677
    :ivar DataValue:
678
    :ivar Variant:
679
    :ivar DiagnosticInfo:
680
681
682
683
    '''
684 1
    Null = 0
685 1
    Boolean = 1
686 1
    SByte = 2
687 1
    Byte = 3
688 1
    Int16 = 4
689 1
    UInt16 = 5
690 1
    Int32 = 6
691 1
    UInt32 = 7
692 1
    Int64 = 8
693 1
    UInt64 = 9
694 1
    Float = 10
695 1
    Double = 11
696 1
    String = 12
697 1
    DateTime = 13
698 1
    Guid = 14
699 1
    ByteString = 15
700 1
    XmlElement = 16
701 1
    NodeId = 17
702 1
    ExpandedNodeId = 18
703 1
    StatusCode = 19
704 1
    QualifiedName = 20
705 1
    LocalizedText = 21
706 1
    ExtensionObject = 22
707 1
    DataValue = 23
708 1
    Variant = 24
709 1
    DiagnosticInfo = 25
710
711
712 1
class Variant(FrozenClass):
713
714
    """
715
    Create an OPC-UA Variant object.
716
    if no argument a Null Variant is created.
717
    if not variant type is given, attemps to guess type from python type
718
    if a variant is given as value, the new objects becomes a copy of the argument
719
720
    :ivar Value:
721
    :vartype Value: Any supported type
722
    :ivar VariantType:
723
    :vartype VariantType: VariantType
724
    """
725
726 1
    def __init__(self, value=None, varianttype=None, encoding=0):
727 1
        self.Encoding = encoding
728 1
        self.Value = value
729 1
        self.VariantType = varianttype
730 1
        if isinstance(value, Variant):
731 1
            self.Value = value.Value
732 1
            self.VariantType = value.VariantType
733 1
        if self.VariantType is None:
734 1
            if type(self.Value) in (list, tuple):
735 1
                if len(self.Value) == 0:
736
                    raise UAError("could not guess UA variable type")
737 1
                self.VariantType = self._guess_type(self.Value[0])
738
            else:
739 1
                self.VariantType = self._guess_type(self.Value)
740 1
        self._freeze = True
741
742 1
    def __eq__(self, other):
743 1
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
744 1
            return True
745 1
        return False
746
747 1
    def _guess_type(self, val):
748 1
        if val is None:
749 1
            return VariantType.Null
750 1
        elif isinstance(val, bool):
751 1
            return VariantType.Boolean
752 1
        elif isinstance(val, float):
753 1
            return VariantType.Double
754 1
        elif isinstance(val, int):
755 1
            return VariantType.Int64
756 1
        elif type(val) in (str, unicode):
757 1
            return VariantType.String
758 1
        elif isinstance(val, bytes):
759 1
            return VariantType.ByteString
760 1
        elif isinstance(val, datetime):
761 1
            return VariantType.DateTime
762
        else:
763 1
            if isinstance(val, object):
764 1
                try:
765 1
                    return getattr(VariantType, val.__class__.__name__)
766 1
                except AttributeError:
767 1
                    return VariantType.ExtensionObject
768
            else:
769
                raise UAError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
770
771 1
    def __str__(self):
772 1
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
773 1
    __repr__ = __str__
774
775 1
    def to_binary(self):
776 1
        b = []
777 1
        mask = self.Encoding & 0b01111111
778 1
        self.Encoding = (self.VariantType.value | mask)
779 1
        if type(self.Value) in (list, tuple):
780 1
            self.Encoding |= (1 << 7)
781 1
            b.append(uatype_UInt8.pack(self.Encoding))
782 1
            b.append(pack_uatype_array(self.VariantType.name, self.Value))
783
        else:
784 1
            b.append(uatype_UInt8.pack(self.Encoding))
785 1
            b.append(pack_uatype(self.VariantType.name, self.Value))
786 1
        return b"".join(b)
787
788 1
    @staticmethod
789
    def from_binary(data):
790 1
        encoding = ord(data.read(1))
791 1
        vtype = VariantType(encoding & 0b01111111)
792 1
        if vtype == VariantType.Null:
793 1
            return Variant(None, vtype, encoding)
794 1
        if encoding & (1 << 7):
795 1
            value = unpack_uatype_array(vtype.name, data)
796
        else:
797 1
            value = unpack_uatype(vtype.name, data)
798 1
        return Variant(value, vtype, encoding)
799
800
801 1
class DataValue(FrozenClass):
802
803
    '''
804
    A value with an associated timestamp, and quality.
805
    Automatically generated from xml , copied and modified here to fix errors in xml spec
806
807
    :ivar Value:
808
    :vartype Value: Variant
809
    :ivar StatusCode:
810
    :vartype StatusCode: StatusCode
811
    :ivar SourceTimestamp:
812
    :vartype SourceTimestamp: datetime
813
    :ivar SourcePicoSeconds:
814
    :vartype SourcePicoSeconds: int
815
    :ivar ServerTimestamp:
816
    :vartype ServerTimestamp: datetime
817
    :ivar ServerPicoseconds:
818
    :vartype ServerPicoseconds: int
819
820
    '''
821
822 1
    def __init__(self, variant=None, status=None):
823 1
        self.Encoding = 0
824 1
        if not isinstance(variant, Variant):
825 1
            variant = Variant(variant)
826 1
        self.Value = variant
827 1
        if status is None:
828 1
            self.StatusCode = StatusCode()
829
        else:
830 1
            self.StatusCode = status
831 1
        self.SourceTimestamp = None  # DateTime()
832 1
        self.SourcePicoseconds = None
833 1
        self.ServerTimestamp = None  # DateTime()
834 1
        self.ServerPicoseconds = None
835 1
        self._freeze = True
836
837 1
    def to_binary(self):
838 1
        packet = []
839 1
        if self.Value:
840 1
            self.Encoding |= (1 << 0)
841 1
        if self.StatusCode:
842 1
            self.Encoding |= (1 << 1)
843 1
        if self.SourceTimestamp:
844 1
            self.Encoding |= (1 << 2)
845 1
        if self.ServerTimestamp:
846 1
            self.Encoding |= (1 << 3)
847 1
        if self.SourcePicoseconds:
848
            self.Encoding |= (1 << 4)
849 1
        if self.ServerPicoseconds:
850
            self.Encoding |= (1 << 5)
851 1
        packet.append(uatype_UInt8.pack(self.Encoding))
852 1
        if self.Value:
853 1
            packet.append(self.Value.to_binary())
854 1
        if self.StatusCode:
855 1
            packet.append(self.StatusCode.to_binary())
856 1
        if self.SourceTimestamp:
857 1
            packet.append(pack_datetime(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
858 1
        if self.ServerTimestamp:
859 1
            packet.append(pack_datetime(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
860 1
        if self.SourcePicoseconds:
861
            packet.append(uatype_UInt16.pack(self.SourcePicoseconds))
862 1
        if self.ServerPicoseconds:
863
            packet.append(uatype_UInt16.pack(self.ServerPicoseconds))
864 1
        return b''.join(packet)
865
866 1
    @staticmethod
867
    def from_binary(data):
868 1
        encoding = ord(data.read(1))
869 1
        if encoding & (1 << 0):
870 1
            value = Variant.from_binary(data)
871
        else:
872
            value = None
873 1
        if encoding & (1 << 1):
874 1
            status = StatusCode.from_binary(data)
875
        else:
876
            status = None
877 1
        obj = DataValue(value, status)
878 1
        obj.Encoding = encoding
879 1
        if obj.Encoding & (1 << 2):
880 1
            obj.SourceTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
881 1
        if obj.Encoding & (1 << 3):
882 1
            obj.ServerTimestamp = unpack_datetime(data)  # DateTime.from_binary(data)
883 1
        if obj.Encoding & (1 << 4):
884
            obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0]
885 1
        if obj.Encoding & (1 << 5):
886
            obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0]
887 1
        return obj
888
889 1
    def __str__(self):
890
        s = 'DataValue(Value:{}'.format(self.Value)
891
        if self.StatusCode is not None:
892
            s += ', StatusCode:{}'.format(self.StatusCode)
893
        if self.SourceTimestamp is not None:
894
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
895
        if self.ServerTimestamp is not None:
896
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
897
        if self.SourcePicoseconds is not None:
898
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
899
        if self.ServerPicoseconds is not None:
900
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
901
        s += ')'
902
        return s
903
904 1
    __repr__ = __str__
905
906
907 1
__nodeid_counter = 2000
908
909
910 1
def generate_nodeid(idx):
911
    global __nodeid_counter
912 1
    __nodeid_counter += 1
913
    return NodeId(__nodeid_counter, idx)
914