Completed
Pull Request — master (#338)
by
unknown
03:33
created

Guid   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 14
cts 15
cp 0.9333
rs 10
c 0
b 0
f 0
wmc 5

1 Method

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