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

NodeId   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Test Coverage

Coverage 92.78%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 197
ccs 90
cts 97
cp 0.9278
rs 4.8387
c 1
b 1
f 0
wmc 58

13 Methods

Rating   Name   Duplication   Size   Complexity  
D to_string() 0 23 10
A __key() 0 5 2
C __init__() 0 23 7
A __eq__() 0 2 1
F _from_string() 0 38 11
A is_null() 0 4 2
A __hash__() 0 2 1
A __ne__() 0 2 1
A __str__() 0 2 1
A from_string() 0 6 2
A has_null_identifier() 0 6 4
F from_binary() 0 30 9
B to_binary() 0 19 7

How to fix   Complexity   

Complex Class

Complex classes like NodeId often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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
        elif self.NodeIdType == NodeIdType.Guid:
392 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
393
                   uabin.Primitives.Guid.pack(self.Identifier)
394
        else:
395
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
396 1
                self.Identifier.to_binary()
397 1
        # FIXME: Missing NNamespaceURI and ServerIndex
398 1
399 1
    @staticmethod
400 1
    def from_binary(data):
401 1
        nid = NodeId()
402 1
        encoding = ord(data.read(1))
403
        nid.NodeIdType = NodeIdType(encoding & 0b00111111)
404
405 1
        if nid.NodeIdType == NodeIdType.TwoByte:
406
            nid.Identifier = ord(data.read(1))
407
        elif nid.NodeIdType == NodeIdType.FourByte:
408
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3))
409
        elif nid.NodeIdType == NodeIdType.Numeric:
410
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6))
411
        elif nid.NodeIdType == NodeIdType.String:
412
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
413
            nid.Identifier = uabin.Primitives.String.unpack(data)
414
        elif nid.NodeIdType == NodeIdType.ByteString:
415
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
416
            nid.Identifier = uabin.Primitives.Bytes.unpack(data)
417
        elif nid.NodeIdType == NodeIdType.Guid:
418
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
419
            nid.Identifier = uabin.Primitives.Guid.unpack(data)
420
        else:
421
            raise UaError("Unknown NodeId encoding: " + str(nid.NodeIdType))
422
423
        if uabin.test_bit(encoding, 7):
424
            nid.NamespaceUri = uabin.Primitives.String.unpack(data)
425
        if uabin.test_bit(encoding, 6):
426 1
            nid.ServerIndex = uabin.Primitives.UInt32.unpack(data)
427 1
428 1
        return nid
429 1
430 1
431 1
class TwoByteNodeId(NodeId):
432 1
433 1
    def __init__(self, identifier):
434 1
        NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte)
435 1
436 1
437 1
class FourByteNodeId(NodeId):
438 1
439 1
    def __init__(self, identifier, namespace=0):
440 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte)
441 1
442 1
443 1
class NumericNodeId(NodeId):
444
445
    def __init__(self, identifier, namespace=0):
446
        NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric)
447
448
449 1
class ByteStringNodeId(NodeId):
450 1
451 1
    def __init__(self, identifier, namespace=0):
452
        NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString)
453 1
454
455 1
class GuidNodeId(NodeId):
456 1
457
    def __init__(self, identifier, namespace=0):
458 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Guid)
459 1
460
461 1
class StringNodeId(NodeId):
462 1
463
    def __init__(self, identifier, namespace=0):
464 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.String)
465 1
466 1
467 1
ExpandedNodeId = NodeId
468
469 1
470 1
class QualifiedName(FrozenClass):
471 1
472 1
    '''
473 1
    A string qualified with a namespace index.
474 1
    '''
475
476 1
    def __init__(self, name=None, namespaceidx=0):
477
        if not isinstance(namespaceidx, int):
478 1
            raise UaError("namespaceidx must be an int")
479 1
        self.NamespaceIndex = namespaceidx
480 1
        self.Name = name
481 1
        self._freeze = True
482
483 1
    def to_string(self):
484
        return "{}:{}".format(self.NamespaceIndex, self.Name)
485 1
486 1
    @staticmethod
487 1
    def from_string(string):
488 1
        if ":" in string:
489 1
            try:
490 1
                idx, name = string.split(":", 1)
491 1
                idx = int(idx)
492 1
            except (TypeError, ValueError) as ex:
493 1
                raise UaStringParsingError("Error parsing string {}".format(string), ex)
494 1
        else:
495 1
            idx = 0
496 1
            name = string
497 1
        return QualifiedName(name, idx)
498 1
499 1
    def to_binary(self):
500 1
        packet = []
501 1
        packet.append(uabin.Primitives.UInt16.pack(self.NamespaceIndex))
502 1
        packet.append(uabin.Primitives.String.pack(self.Name))
503 1
        return b''.join(packet)
504 1
505 1
    @staticmethod
506
    def from_binary(data):
507
        obj = QualifiedName()
508 1
        obj.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
509
        obj.Name = uabin.Primitives.String.unpack(data)
510
        return obj
511 1
512 1
    def __eq__(self, bname):
513
        return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex
514
515 1
    def __ne__(self, other):
516 1
        return not self.__eq__(other)
517 1
518 1
    def __lt__(self, other):
519 1
        if not isinstance(other, QualifiedName):
520 1
            raise TypeError("Cannot compare QualifiedName and {}".format(other))
521
        if self.NamespaceIndex == other.NamespaceIndex:
522 1
            return self.Name < other.Name
523 1
        else:
524 1
            return self.NamespaceIndex < other.NamespaceIndex
525 1
526 1
    def __str__(self):
527 1
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
528 1
529 1
    __repr__ = __str__
530 1
531 1
532 1
class LocalizedText(FrozenClass):
533 1
534 1
    '''
535
    A string qualified with a namespace index.
536
    '''
537
538
    ua_types = {
539 1
        "Text": "ByteString",
540 1
        "Locale": "ByteString"
541
    }
542 1
543
    def __init__(self, text=None):
544 1
        self.Encoding = 0
545
        self.Text = text
546 1
        if isinstance(self.Text, unicode):
547 1
            self.Text = self.Text.encode('utf-8')
548 1
        if self.Text:
549
            self.Encoding |= (1 << 1)
550 1
        self.Locale = None
551 1
        self._freeze = True
552 1
553 1
    def to_binary(self):
554 1
        packet = []
555 1
        if self.Locale:
556 1
            self.Encoding |= (1 << 0)
557 1
        if self.Text:
558 1
            self.Encoding |= (1 << 1)
559
        packet.append(uabin.Primitives.UInt8.pack(self.Encoding))
560 1
        if self.Locale:
561 1
            packet.append(uabin.Primitives.Bytes.pack(self.Locale))
562
        if self.Text:
563
            packet.append(uabin.Primitives.Bytes.pack(self.Text))
564 1
        return b''.join(packet)
565
566
    @staticmethod
567
    def from_binary(data):
568 1
        obj = LocalizedText()
569
        obj.Encoding = ord(data.read(1))
570 1
        if obj.Encoding & (1 << 0):
571 1
            obj.Locale = uabin.Primitives.Bytes.unpack(data)
572 1
        if obj.Encoding & (1 << 1):
573
            obj.Text = uabin.Primitives.Bytes.unpack(data)
574 1
        return obj
575 1
576 1
    def to_string(self):
577 1
        # FIXME: use local
578 1
        if self.Text is None:
579 1
            return ""
580 1
        return self.Text.decode('utf-8')
581 1
582 1
    def __str__(self):
583 1
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
584 1
            'Locale:' + str(self.Locale) + ', ' + \
585 1
            'Text:' + str(self.Text) + ')'
586 1
    __repr__ = __str__
587 1
588 1
    def __eq__(self, other):
589
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
590
            return True
591
        return False
592 1
593
    def __ne__(self, other):
594 1
        return not self.__eq__(other)
595
596
597 1
class ExtensionObject(FrozenClass):
598
599
    '''
600 1
601
    Any UA object packed as an ExtensionObject
602 1
603 1
604
    :ivar TypeId:
605
    :vartype TypeId: NodeId
606 1
    :ivar Body:
607
    :vartype Body: bytes
608 1
609 1
    '''
610
611
    def __init__(self):
612 1
        self.TypeId = NodeId()
613
        self.Encoding = 0
614 1
        self.Body = b''
615 1
        self._freeze = True
616
617
    def to_binary(self):
618 1
        packet = []
619
        if self.Body:
620 1
            self.Encoding |= (1 << 0)
621 1
        packet.append(self.TypeId.to_binary())
622
        packet.append(uabin.Primitives.UInt8.pack(self.Encoding))
623
        if self.Body:
624 1
            packet.append(uabin.Primitives.ByteString.pack(self.Body))
625
        return b''.join(packet)
626 1
627 1
    @staticmethod
628
    def from_binary(data):
629
        obj = ExtensionObject()
630 1
        obj.TypeId = NodeId.from_binary(data)
631
        obj.Encoding = uabin.Primitives.UInt8.unpack(data)
632 1
        if obj.Encoding & (1 << 0):
633 1
            obj.Body = uabin.Primitives.ByteString.unpack(data)
634
        return obj
635
636 1
    @staticmethod
637
    def from_object(obj):
638
        ext = ExtensionObject()
639 1
        oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__))
640
        ext.TypeId = FourByteNodeId(oid)
641
        ext.Body = obj.to_binary()
642
        return ext
643
644
    def __str__(self):
645 1
        return 'ExtensionObject(' + 'TypeId:' + str(self.TypeId) + ', ' + \
646 1
            'Encoding:' + str(self.Encoding) + ', ' + str(len(self.Body)) + ' bytes)'
647
648 1
    __repr__ = __str__
649 1
650 1
651
class VariantType(Enum):
652 1
653 1
    '''
654
    The possible types of a variant.
655 1
656
    :ivar Null:
657 1
    :ivar Boolean:
658 1
    :ivar SByte:
659 1
    :ivar Byte:
660 1
    :ivar Int16:
661 1
    :ivar UInt16:
662 1
    :ivar Int32:
663
    :ivar UInt32:
664 1
    :ivar Int64:
665 1
    :ivar UInt64:
666 1
    :ivar Float:
667
    :ivar Double:
668 1
    :ivar String:
669 1
    :ivar DateTime:
670 1
    :ivar Guid:
671 1
    :ivar ByteString:
672 1
    :ivar XmlElement:
673
    :ivar NodeId:
674 1
    :ivar ExpandedNodeId:
675
    :ivar StatusCode:
676 1
    :ivar QualifiedName:
677 1
    :ivar LocalizedText:
678 1
    :ivar ExtensionObject:
679 1
    :ivar DataValue:
680
    :ivar Variant:
681 1
    :ivar DiagnosticInfo:
682 1
683
684 1
685
    '''
686
    Null = 0
687 1
    Boolean = 1
688
    SByte = 2
689
    Byte = 3
690 1
    Int16 = 4
691
    UInt16 = 5
692
    Int32 = 6
693 1
    UInt32 = 7
694
    Int64 = 8
695
    UInt64 = 9
696
    Float = 10
697
    Double = 11
698
    String = 12
699 1
    DateTime = 13
700 1
    Guid = 14
701 1
    ByteString = 15
702 1
    XmlElement = 16
703 1
    NodeId = 17
704 1
    ExpandedNodeId = 18
705 1
    StatusCode = 19
706 1
    QualifiedName = 20
707 1
    LocalizedText = 21
708
    ExtensionObject = 22
709 1
    DataValue = 23
710 1
    Variant = 24
711 1
    DiagnosticInfo = 25
712
713 1
714 1
class VariantTypeCustom(object):
715 1
    """
716 1
    Looks like sometime we get variant with other values than those
717
    defined in VariantType.
718 1
    FIXME: We should not need this class, as far as I iunderstand the spec
719 1
    variants can only be of VariantType
720 1
    """
721
722 1
    def __init__(self, val):
723
        self.name = "Custom"
724 1
        self.value = val
725 1
        if self.value > 0b00111111:
726 1
            raise UaError("Cannot create VariantType. VariantType must be {} > x > {}, received {}".format(0b111111, 25, val))
727
728 1
    def __str__(self):
729 1
        return "VariantType.Custom:{}".format(self.value)
730 1
    __repr__ = __str__
731
732 1
    def __eq__(self, other):
733
        return self.value == other.value
734
735
736 1
class Variant(FrozenClass):
737
738
    """
739
    Create an OPC-UA Variant object.
740 1
    if no argument a Null Variant is created.
741
    if not variant type is given, attemps to guess type from python type
742 1
    if a variant is given as value, the new objects becomes a copy of the argument
743 1
744 1
    :ivar Value:
745 1
    :vartype Value: Any supported type
746
    :ivar VariantType:
747 1
    :vartype VariantType: VariantType
748 1
    """
749
750
    def __init__(self, value=None, varianttype=None, dimensions=None):
751 1
        self.Value = value
752
        self.VariantType = varianttype
753
        self.Dimensions = dimensions
754
        self._freeze = True
755
        if isinstance(value, Variant):
756
            self.Value = value.Value
757
            self.VariantType = value.VariantType
758
        if self.VariantType is None:
759
            self.VariantType = self._guess_type(self.Value)
760
        if self.Dimensions is None and type(self.Value) in (list, tuple):
761
            dims = get_shape(self.Value)
762
            if len(dims) > 1:
763
                self.Dimensions = dims
764
765 1
    def __eq__(self, other):
766 1
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
767 1
            return True
768 1
        return False
769 1
770
    def __ne__(self, other):
771 1
        return not self.__eq__(other)
772 1
773 1
    def _guess_type(self, val):
774 1
        if isinstance(val, (list, tuple)):
775 1
            error_val = val
776 1
        while isinstance(val, (list, tuple)):
777 1
            if len(val) == 0:
778 1
                raise UaError("could not guess UA type of variable {}".format(error_val))
779 1
            val = val[0]
780
        if val is None:
781 1
            return VariantType.Null
782
        elif isinstance(val, bool):
783
            return VariantType.Boolean
784
        elif isinstance(val, float):
785
            return VariantType.Double
786
        elif isinstance(val, int):
787
            return VariantType.Int64
788
        elif type(val) in (str, unicode):
789
            return VariantType.String
790 1
        elif isinstance(val, bytes):
791
            return VariantType.ByteString
792
        elif isinstance(val, datetime):
793
            return VariantType.DateTime
794
        elif isinstance(val, uuid.UUID):
795
            return VariantType.Guid
796
        else:
797
            if isinstance(val, object):
798 1
                try:
799
                    return getattr(VariantType, val.__class__.__name__)
800
                except AttributeError:
801
                    return VariantType.ExtensionObject
802 1
            else:
803
                raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
804
805 1 View Code Duplication
    def __str__(self):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
806
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
807
    __repr__ = __str__
808
809
    def to_binary(self):
810
        b = []
811
        encoding = self.VariantType.value & 0b111111
812
        if type(self.Value) in (list, tuple):
813
            if self.Dimensions is not None:
814
                encoding = uabin.set_bit(encoding, 6)
815
            encoding = uabin.set_bit(encoding, 7)
816
            b.append(uabin.Primitives.UInt8.pack(encoding))
817
            b.append(uabin.pack_uatype_array(self.VariantType, flatten(self.Value)))
818
            if self.Dimensions is not None:
819
                b.append(uabin.pack_uatype_array(VariantType.Int32, self.Dimensions))
820
        else:
821
            b.append(uabin.Primitives.UInt8.pack(encoding))
822
            b.append(uabin.pack_uatype(self.VariantType, self.Value))
823
824
        return b"".join(b)
825
826
    @staticmethod
827
    def from_binary(data):
828
        dimensions = None
829
        encoding = ord(data.read(1))
830
        int_type = encoding & 0b00111111
831
        vtype = DataType_to_VariantType(int_type)
832
        if vtype == VariantType.Null:
833
            return Variant(None, vtype, encoding)
834
        if uabin.test_bit(encoding, 7):
835
            value = uabin.unpack_uatype_array(vtype, data)
836
        else:
837
            value = uabin.unpack_uatype(vtype, data)
838
        if uabin.test_bit(encoding, 6):
839
            dimensions = uabin.unpack_uatype_array(VariantType.Int32, data)
840 1
            value = reshape(value, dimensions)
841 1
842 1
        return Variant(value, vtype, dimensions)
843 1
844 1
845 1
def reshape(flat, dims):
846 1
    subdims = dims[1:]
847 1
    subsize = 1
848 1
    for i in subdims:
849 1
        if i == 0:
850 1
            i = 1
851 1
        subsize *= i
852 1
    while dims[0] * subsize > len(flat):
853 1
        flat.append([])
854 1
    if not subdims or subdims == [0]:
855 1
        return flat
856 1
    return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)]
857 1
858 1
859 1
def _split_list(l, n):
860 1
    n = max(1, n)
861 1
    return [l[i:i + n] for i in range(0, len(l), n)]
862 1
863 1
864 1
def flatten_and_get_shape(mylist):
865 1
    dims = []
866
    dims.append(len(mylist))
867
    while isinstance(mylist[0], (list, tuple)):
868 1
        dims.append(len(mylist[0]))
869 1
        mylist = [item for sublist in mylist for item in sublist]
870 1
        if len(mylist) == 0:
871 1
            break
872 1
    return mylist, dims
873 1
874
875 1
def flatten(mylist):
876
    if len(mylist) == 0:
877 1
        return mylist
878
    while isinstance(mylist[0], (list, tuple)):
879 1
        mylist = [item for sublist in mylist for item in sublist]
880 1
        if len(mylist) == 0:
881
            break
882
    return mylist
883 1
884
885
def get_shape(mylist):
886
    dims = []
887
    while isinstance(mylist, (list, tuple)):
888
        dims.append(len(mylist))
889
        if len(mylist) == 0:
890
            break
891
        mylist = mylist[0]
892
    return dims
893
894
895
class XmlElement(FrozenClass):
896
    '''
897 1
    An XML element encoded as an UTF-8 string.
898 1
    '''
899 1
900 1
    def __init__(self, binary=None):
901 1
        if binary is not None:
902 1
            self._binary_init(binary)
903 1
            self._freeze = True
904 1
            return
905 1
        self.Value = []
906 1
        self._freeze = True
907 1
908 1
    def to_binary(self):
909 1
        return uabin.Primitives.String.pack(self.Value)
910 1
911
    @staticmethod
912 1
    def from_binary(data):
913 1
        return XmlElement(data)
914 1
915 1
    def _binary_init(self, data):
916
        self.Value = uabin.Primitives.String.unpack(data)
917 1
918 1
    def __str__(self):
919
        return 'XmlElement(Value:' + str(self.Value) + ')'
920 1
921 1
    __repr__ = __str__
922 1
923 1
924 1
class DataValue(FrozenClass):
925
926 1
    '''
927 1
    A value with an associated timestamp, and quality.
928 1
    Automatically generated from xml , copied and modified here to fix errors in xml spec
929 1
930 1
    :ivar Value:
931 1
    :vartype Value: Variant
932 1
    :ivar StatusCode:
933 1
    :vartype StatusCode: StatusCode
934 1
    :ivar SourceTimestamp:
935 1
    :vartype SourceTimestamp: datetime
936 1
    :ivar SourcePicoSeconds:
937 1
    :vartype SourcePicoSeconds: int
938 1
    :ivar ServerTimestamp:
939 1
    :vartype ServerTimestamp: datetime
940 1
    :ivar ServerPicoseconds:
941
    :vartype ServerPicoseconds: int
942 1
943 1
    '''
944 1
945 1
    def __init__(self, variant=None, status=None):
946 1
        self.Encoding = 0
947
        if not isinstance(variant, Variant):
948
            variant = Variant(variant)
949
        self.Value = variant
950 1
        if status is None:
951 1
            self.StatusCode = StatusCode()
952 1
        else:
953
            self.StatusCode = status
954 1
        self.SourceTimestamp = None  # DateTime()
955 1
        self.SourcePicoseconds = None
956 1
        self.ServerTimestamp = None  # DateTime()
957 1
        self.ServerPicoseconds = None
958 1
        self._freeze = True
959 1
960 1
    def to_binary(self):
961 1
        packet = []
962 1
        if self.Value:
963 1
            self.Encoding |= (1 << 0)
964 1
        if self.StatusCode:
965
            self.Encoding |= (1 << 1)
966 1
        if self.SourceTimestamp:
967 1
            self.Encoding |= (1 << 2)
968
        if self.ServerTimestamp:
969 1
            self.Encoding |= (1 << 3)
970
        if self.SourcePicoseconds:
971 1
            self.Encoding |= (1 << 4)
972
        if self.ServerPicoseconds:
973 1
            self.Encoding |= (1 << 5)
974 1
        packet.append(uabin.Primitives.UInt8.pack(self.Encoding))
975 1
        if self.Value:
976 1
            packet.append(self.Value.to_binary())
977 1
        if self.StatusCode:
978
            packet.append(self.StatusCode.to_binary())
979 1
        if self.SourceTimestamp:
980 1
            packet.append(uabin.Primitives.DateTime.pack(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
981 1
        if self.ServerTimestamp:
982 1
            packet.append(uabin.Primitives.DateTime.pack(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
983 1
        if self.SourcePicoseconds:
984
            packet.append(uabin.Primitives.UInt16.pack(self.SourcePicoseconds))
985 1
        if self.ServerPicoseconds:
986 1
            packet.append(uabin.Primitives.UInt16.pack(self.ServerPicoseconds))
987 1
        return b''.join(packet)
988 1
989
    @staticmethod
990 1
    def from_binary(data):
991
        encoding = ord(data.read(1))
992
        if encoding & (1 << 0):
993 1
            value = Variant.from_binary(data)
994 1
        else:
995 1
            value = None
996 1
        if encoding & (1 << 1):
997 1
            status = StatusCode.from_binary(data)
998 1
        else:
999 1
            status = None
1000 1
        obj = DataValue(value, status)
1001 1
        obj.Encoding = encoding
1002 1
        if obj.Encoding & (1 << 2):
1003 1
            obj.SourceTimestamp = uabin.Primitives.DateTime.unpack(data)  # DateTime.from_binary(data)
1004 1
        if obj.Encoding & (1 << 3):
1005
            obj.ServerTimestamp = uabin.Primitives.DateTime.unpack(data)  # DateTime.from_binary(data)
1006
        if obj.Encoding & (1 << 4):
1007 1
            obj.SourcePicoseconds = uabin.Primitives.UInt16.unpack(data)
1008
        if obj.Encoding & (1 << 5):
1009
            obj.ServerPicoseconds = uabin.Primitives.UInt16.unpack(data)
1010
        return obj
1011
1012 1
    def __str__(self):
1013
        s = 'DataValue(Value:{}'.format(self.Value)
1014
        if self.StatusCode is not None:
1015
            s += ', StatusCode:{}'.format(self.StatusCode)
1016
        if self.SourceTimestamp is not None:
1017
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
1018
        if self.ServerTimestamp is not None:
1019
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
1020
        if self.SourcePicoseconds is not None:
1021
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
1022
        if self.ServerPicoseconds is not None:
1023 1
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
1024 1
        s += ')'
1025 1
        return s
1026 1
1027 1
    __repr__ = __str__
1028 1
1029 1
1030 1
def DataType_to_VariantType(int_type):
1031
    """
1032
    Takes a NodeId or int and return a VariantType
1033 1
    This is only supported if int_type < 63 due to VariantType encoding
1034 1
    At low level we do not have access to address space thus decodig is limited
1035 1
    a better version of this method can be find in ua_utils.py
1036 1
    """
1037 1
    if isinstance(int_type, NodeId):
1038 1
        int_type = int_type.Identifier
1039 1
1040 1
    if int_type <= 25:
1041
        return VariantType(int_type)
1042
    else:
1043
        return VariantTypeCustom(int_type)
1044