Completed
Pull Request — master (#340)
by Olivier
05:59
created

Variant   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 111
Duplicated Lines 32.43 %

Test Coverage

Coverage 68.89%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 36
loc 111
ccs 31
cts 45
cp 0.6889
rs 8.8
wmc 36

7 Methods

Rating   Name   Duplication   Size   Complexity  
A to_binary() 16 16 4
A __ne__() 0 2 1
C __init__() 0 19 8
F _guess_type() 0 31 14
A __str__() 0 2 1
A from_binary() 17 17 4
A __eq__() 0 4 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    :ivar value:
167 1
    :vartype value: int
168 1
    :ivar name:
169 1
    :vartype name: string
170 1
    :ivar doc:
171
    :vartype doc: string
172
    """
173
174 1
    def __init__(self, value=0):
175 1
        if isinstance(value, str):
176
            self.name = value
177 1
            self.value = getattr(status_codes.StatusCodes, value)
178 1
        else:
179 1
            self.value = value
180 1
            self.name, self.doc = status_codes.get_name_and_doc(value)
181 1
        self._freeze = True
182
183
    def to_binary(self):
184
        return uabin.Primitives.UInt32.pack(self.value)
185 1
186 1
    @staticmethod
187 1
    def from_binary(data):
188
        val = uabin.Primitives.UInt32.unpack(data)
189 1
        sc = StatusCode(val)
190 1
        return sc
191 1
192 1
    def check(self):
193 1
        """
194 1
        Raises an exception if the status code is anything else than 0 (good).
195
196 1
        Use the is_good() method if you do not want an exception.
197 1
        """
198
        if not self.is_good():
199 1
            raise UaStatusCodeError(self.value)
200 1
201 1
    def is_good(self):
202 1
        """
203
        return True if status is Good.
204
        """
205 1
        mask = 3 << 30
206 1
        if mask & self.value:
207 1
            return False
208
        else:
209
            return True
210 1
211 1
    def __str__(self):
212 1
        return 'StatusCode({})'.format(self.name)
213
    __repr__ = __str__
214
215 1
    def __eq__(self, other):
216 1
        return self.value == other.value
217 1
218 1
    def __ne__(self, other):
219 1
        return not self.__eq__(other)
220 1
221 1
222
class NodeIdType(Enum):
223 1
    TwoByte = 0
224
    FourByte = 1
225
    Numeric = 2
226 1
    String = 3
227 1
    Guid = 4
228 1
    ByteString = 5
229 1
230 1
231
class NodeId(FrozenClass):
232
    """
233 1
    NodeId Object
234 1
235 1
    Args:
236 1
        identifier: The identifier might be an int, a string, bytes or a Guid
237 1
        namespaceidx(int): The index of the namespace
238
        nodeidtype(NodeIdType): The type of the nodeid if it cannor be guess or you want something special like twobyte nodeid or fourbytenodeid
239
240 1
241
    :ivar Identifier:
242
    :vartype Identifier: NodeId
243 1
    :ivar NamespaceIndex:
244
    :vartype NamespaceIndex: Int
245
    :ivar NamespaceUri:
246 1
    :vartype NamespaceUri: String
247 1
    :ivar ServerIndex:
248 1
    :vartype ServerIndex: Int
249
    """
250
    
251 1
    def __init__(self, identifier=None, namespaceidx=0, nodeidtype=None):
252 1
253 1
        self.Identifier = identifier
254
        self.NamespaceIndex = namespaceidx
255
        self.NodeIdType = nodeidtype
256 1
        self.NamespaceUri = ""
257 1
        self.ServerIndex = 0
258 1
        self._freeze = True
259
        if not isinstance(self.NamespaceIndex, int):
260
            raise UaError("NamespaceIndex must be an int")
261 1
        if self.Identifier is None:
262
            self.Identifier = 0
263
            self.NodeIdType = NodeIdType.TwoByte
264
            return
265
        if self.NodeIdType is None:
266
            if isinstance(self.Identifier, int):
267 1
                self.NodeIdType = NodeIdType.Numeric
268
            elif isinstance(self.Identifier, str):
269 1
                self.NodeIdType = NodeIdType.String
270 1
            elif isinstance(self.Identifier, bytes):
271
                self.NodeIdType = NodeIdType.ByteString
272 1
            else:
273
                raise UaError("NodeId: Could not guess type of NodeId, set NodeIdType")
274 1
275
    def __key(self):
276
        if self.NodeIdType in (NodeIdType.TwoByte, NodeIdType.FourByte, NodeIdType.Numeric):  # twobyte, fourbyte and numeric may represent the same node
277
            return self.NamespaceIndex, self.Identifier
278
        else:
279
            return self.NodeIdType, self.NamespaceIndex, self.Identifier
280
281 1
    def __eq__(self, node):
282
        return isinstance(node, NodeId) and self.__key() == node.__key()
283
284 1
    def __ne__(self, other):
285
        return not self.__eq__(other)
286
287
    def __hash__(self):
288
        return hash(self.__key())
289
290 1
    def __lt__(self, other):
291 1
        if not isinstance(other, NodeId):
292 1
            raise AttributeError("Can only compare to NodeId")
293 1
        return self.__hash__() < other.__hash__()
294 1
295
    def is_null(self):
296 1
        if self.NamespaceIndex != 0:
297 1
            return False
298 1
        return self.has_null_identifier()
299
300
    def has_null_identifier(self):
301 1
        if not self.Identifier:
302
            return True
303
        if self.NodeIdType == NodeIdType.Guid and re.match(b'0.', self.Identifier):
304 1
            return True
305 1
        return False
306 1
307 1
    @staticmethod
308 1
    def from_string(string):
309
        try:
310
            return NodeId._from_string(string)
311 1
        except ValueError as ex:
312
            raise UaStringParsingError("Error parsing string {}".format(string), ex)
313
314
    @staticmethod
315 1
    def _from_string(string):
316 1
        l = string.split(";")
317 1
        identifier = None
318 1
        namespace = 0
319 1
        ntype = None
320
        srv = None
321
        nsu = None
322 1
        for el in l:
323
            if not el:
324 1
                continue
325 1
            k, v = el.split("=", 1)
326 1
            k = k.strip()
327
            v = v.strip()
328 1
            if k == "ns":
329 1
                namespace = int(v)
330
            elif k == "i":
331 1
                ntype = NodeIdType.Numeric
332
                identifier = int(v)
333
            elif k == "s":
334 1
                ntype = NodeIdType.String
335
                identifier = v
336 1
            elif k == "g":
337 1
                ntype = NodeIdType.Guid
338 1
                identifier = v
339
            elif k == "b":
340 1
                ntype = NodeIdType.ByteString
341 1
                identifier = v
342
            elif k == "srv":
343
                srv = v
344 1
            elif k == "nsu":
345
                nsu = v
346
        if identifier is None:
347
            raise UaStringParsingError("Could not find identifier in string: " + string)
348
        nodeid = NodeId(identifier, namespace, ntype)
349
        nodeid.NamespaceUri = nsu
350
        nodeid.ServerIndex = srv
351
        return nodeid
352
353
    def to_string(self):
354
        string = ""
355 1
        if self.NamespaceIndex != 0:
356 1
            string += "ns={};".format(self.NamespaceIndex)
357 1
        ntype = None
358 1
        if self.NodeIdType == NodeIdType.Numeric:
359
            ntype = "i"
360 1
        elif self.NodeIdType == NodeIdType.String:
361 1
            ntype = "s"
362
        elif self.NodeIdType == NodeIdType.TwoByte:
363 1
            ntype = "i"
364
        elif self.NodeIdType == NodeIdType.FourByte:
365 1
            ntype = "i"
366 1
        elif self.NodeIdType == NodeIdType.Guid:
367 1
            ntype = "g"
368
        elif self.NodeIdType == NodeIdType.ByteString:
369 1
            ntype = "b"
370
        string += "{}={}".format(ntype, self.Identifier)
371
        if self.ServerIndex:
372
            string = "srv=" + str(self.ServerIndex) + string
373
        if self.NamespaceUri:
374 1
            string += "nsu={}".format(self.NamespaceUri)
375 1
        return string
376
377 1
    def __str__(self):
378
        return "{}NodeId({})".format(self.NodeIdType.name, self.to_string())
379
    __repr__ = __str__
380
381 1
    def to_binary(self):
382 1
        if self.NodeIdType == NodeIdType.TwoByte:
383 1
            return struct.pack("<BB", self.NodeIdType.value, self.Identifier)
384
        elif self.NodeIdType == NodeIdType.FourByte:
385 1
            return struct.pack("<BBH", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
386
        elif self.NodeIdType == NodeIdType.Numeric:
387 1
            return struct.pack("<BHI", self.NodeIdType.value, self.NamespaceIndex, self.Identifier)
388
        elif self.NodeIdType == NodeIdType.String:
389 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
390
                uabin.Primitives.String.pack(self.Identifier)
391
        elif self.NodeIdType == NodeIdType.ByteString:
392 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
393
                uabin.Primitives.Bytes.pack(self.Identifier)
394
        elif self.NodeIdType == NodeIdType.Guid:
395
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
396 1
                   uabin.Primitives.Guid.pack(self.Identifier)
397 1
        else:
398 1
            return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \
399 1
                self.Identifier.to_binary()
400 1
        # FIXME: Missing NNamespaceURI and ServerIndex
401 1
402 1
    @staticmethod
403
    def from_binary(data):
404
        nid = NodeId()
405 1
        encoding = ord(data.read(1))
406
        nid.NodeIdType = NodeIdType(encoding & 0b00111111)
407
408
        if nid.NodeIdType == NodeIdType.TwoByte:
409
            nid.Identifier = ord(data.read(1))
410
        elif nid.NodeIdType == NodeIdType.FourByte:
411
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3))
412
        elif nid.NodeIdType == NodeIdType.Numeric:
413
            nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6))
414
        elif nid.NodeIdType == NodeIdType.String:
415
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
416
            nid.Identifier = uabin.Primitives.String.unpack(data)
417
        elif nid.NodeIdType == NodeIdType.ByteString:
418
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
419
            nid.Identifier = uabin.Primitives.Bytes.unpack(data)
420
        elif nid.NodeIdType == NodeIdType.Guid:
421
            nid.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
422
            nid.Identifier = uabin.Primitives.Guid.unpack(data)
423
        else:
424
            raise UaError("Unknown NodeId encoding: " + str(nid.NodeIdType))
425
426 1
        if uabin.test_bit(encoding, 7):
427 1
            nid.NamespaceUri = uabin.Primitives.String.unpack(data)
428 1
        if uabin.test_bit(encoding, 6):
429 1
            nid.ServerIndex = uabin.Primitives.UInt32.unpack(data)
430 1
431 1
        return nid
432 1
433 1
434 1
class TwoByteNodeId(NodeId):
435 1
436 1
    def __init__(self, identifier):
437 1
        NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte)
438 1
439 1
440 1
class FourByteNodeId(NodeId):
441 1
442 1
    def __init__(self, identifier, namespace=0):
443 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte)
444
445
446
class NumericNodeId(NodeId):
447
448
    def __init__(self, identifier, namespace=0):
449 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric)
450 1
451 1
452
class ByteStringNodeId(NodeId):
453 1
454
    def __init__(self, identifier, namespace=0):
455 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString)
456 1
457
458 1
class GuidNodeId(NodeId):
459 1
460
    def __init__(self, identifier, namespace=0):
461 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.Guid)
462 1
463
464 1
class StringNodeId(NodeId):
465 1
466 1
    def __init__(self, identifier, namespace=0):
467 1
        NodeId.__init__(self, identifier, namespace, NodeIdType.String)
468
469 1
470 1
ExpandedNodeId = NodeId
471 1
472 1
473 1
class QualifiedName(FrozenClass):
474 1
    """
475
    A string qualified with a namespace index.
476 1
    """
477
478 1
    def __init__(self, name=None, namespaceidx=0):
479 1
        if not isinstance(namespaceidx, int):
480 1
            raise UaError("namespaceidx must be an int")
481 1
        self.NamespaceIndex = namespaceidx
482
        self.Name = name
483 1
        self._freeze = True
484
485 1
    def to_string(self):
486 1
        return "{}:{}".format(self.NamespaceIndex, self.Name)
487 1
488 1
    @staticmethod
489 1
    def from_string(string):
490 1
        if ":" in string:
491 1
            try:
492 1
                idx, name = string.split(":", 1)
493 1
                idx = int(idx)
494 1
            except (TypeError, ValueError) as ex:
495 1
                raise UaStringParsingError("Error parsing string {}".format(string), ex)
496 1
        else:
497 1
            idx = 0
498 1
            name = string
499 1
        return QualifiedName(name, idx)
500 1
501 1
    def to_binary(self):
502 1
        packet = []
503 1
        packet.append(uabin.Primitives.UInt16.pack(self.NamespaceIndex))
504 1
        packet.append(uabin.Primitives.String.pack(self.Name))
505 1
        return b''.join(packet)
506
507
    @staticmethod
508 1
    def from_binary(data):
509
        obj = QualifiedName()
510
        obj.NamespaceIndex = uabin.Primitives.UInt16.unpack(data)
511 1
        obj.Name = uabin.Primitives.String.unpack(data)
512 1
        return obj
513
514
    def __eq__(self, bname):
515 1
        return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex
516 1
517 1
    def __ne__(self, other):
518 1
        return not self.__eq__(other)
519 1
520 1
    def __lt__(self, other):
521
        if not isinstance(other, QualifiedName):
522 1
            raise TypeError("Cannot compare QualifiedName and {}".format(other))
523 1
        if self.NamespaceIndex == other.NamespaceIndex:
524 1
            return self.Name < other.Name
525 1
        else:
526 1
            return self.NamespaceIndex < other.NamespaceIndex
527 1
528 1
    def __str__(self):
529 1
        return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name)
530 1
531 1
    __repr__ = __str__
532 1
533 1
534 1
class LocalizedText(FrozenClass):
535
    """
536
    A string qualified with a namespace index.
537
    """
538
539 1
    ua_types = {
540 1
        "Text": "ByteString",
541
        "Locale": "ByteString"
542 1
    }
543
544 1
    def __init__(self, text=None):
545
        self.Encoding = 0
546 1
        self.Text = text
547 1
        if isinstance(self.Text, unicode):
548 1
            self.Text = self.Text.encode('utf-8')
549
        if self.Text:
550 1
            self.Encoding |= (1 << 1)
551 1
        self.Locale = None
552 1
        self._freeze = True
553 1
554 1
    def to_binary(self):
555 1
        packet = []
556 1
        if self.Locale:
557 1
            self.Encoding |= (1 << 0)
558 1
        if self.Text:
559
            self.Encoding |= (1 << 1)
560 1
        packet.append(uabin.Primitives.UInt8.pack(self.Encoding))
561 1
        if self.Locale:
562
            packet.append(uabin.Primitives.Bytes.pack(self.Locale))
563
        if self.Text:
564 1
            packet.append(uabin.Primitives.Bytes.pack(self.Text))
565
        return b''.join(packet)
566
567
    @staticmethod
568 1
    def from_binary(data):
569
        obj = LocalizedText()
570 1
        obj.Encoding = ord(data.read(1))
571 1
        if obj.Encoding & (1 << 0):
572 1
            obj.Locale = uabin.Primitives.Bytes.unpack(data)
573
        if obj.Encoding & (1 << 1):
574 1
            obj.Text = uabin.Primitives.Bytes.unpack(data)
575 1
        return obj
576 1
577 1
    def to_string(self):
578 1
        # FIXME: use local
579 1
        if self.Text is None:
580 1
            return ""
581 1
        return self.Text.decode('utf-8')
582 1
583 1
    def __str__(self):
584 1
        return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \
585 1
            'Locale:' + str(self.Locale) + ', ' + \
586 1
            'Text:' + str(self.Text) + ')'
587 1
    __repr__ = __str__
588 1
589
    def __eq__(self, other):
590
        if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text:
591
            return True
592 1
        return False
593
594 1
    def __ne__(self, other):
595
        return not self.__eq__(other)
596
597 1
598
class ExtensionObject(FrozenClass):
599
    """
600 1
    Any UA object packed as an ExtensionObject
601
602 1
    :ivar TypeId:
603 1
    :vartype TypeId: NodeId
604
    :ivar Body:
605
    :vartype Body: bytes
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
    The possible types of a variant.
651
652 1
    :ivar Null:
653 1
    :ivar Boolean:
654
    :ivar SByte:
655 1
    :ivar Byte:
656
    :ivar Int16:
657 1
    :ivar UInt16:
658 1
    :ivar Int32:
659 1
    :ivar UInt32:
660 1
    :ivar Int64:
661 1
    :ivar UInt64:
662 1
    :ivar Float:
663
    :ivar Double:
664 1
    :ivar String:
665 1
    :ivar DateTime:
666 1
    :ivar Guid:
667
    :ivar ByteString:
668 1
    :ivar XmlElement:
669 1
    :ivar NodeId:
670 1
    :ivar ExpandedNodeId:
671 1
    :ivar StatusCode:
672 1
    :ivar QualifiedName:
673
    :ivar LocalizedText:
674 1
    :ivar ExtensionObject:
675
    :ivar DataValue:
676 1
    :ivar Variant:
677 1
    :ivar DiagnosticInfo:
678 1
    """
679 1
680
    Null = 0
681 1
    Boolean = 1
682 1
    SByte = 2
683
    Byte = 3
684 1
    Int16 = 4
685
    UInt16 = 5
686
    Int32 = 6
687 1
    UInt32 = 7
688
    Int64 = 8
689
    UInt64 = 9
690 1
    Float = 10
691
    Double = 11
692
    String = 12
693 1
    DateTime = 13
694
    Guid = 14
695
    ByteString = 15
696
    XmlElement = 16
697
    NodeId = 17
698
    ExpandedNodeId = 18
699 1
    StatusCode = 19
700 1
    QualifiedName = 20
701 1
    LocalizedText = 21
702 1
    ExtensionObject = 22
703 1
    DataValue = 23
704 1
    Variant = 24
705 1
    DiagnosticInfo = 25
706 1
707 1
708
class VariantTypeCustom(object):
709 1
    """
710 1
    Looks like sometime we get variant with other values than those
711 1
    defined in VariantType.
712
    FIXME: We should not need this class, as far as I iunderstand the spec
713 1
    variants can only be of VariantType
714 1
    """
715 1
716 1
    def __init__(self, val):
717
        self.name = "Custom"
718 1
        self.value = val
719 1
        if self.value > 0b00111111:
720 1
            raise UaError("Cannot create VariantType. VariantType must be {} > x > {}, received {}".format(0b111111, 25, val))
721
722 1
    def __str__(self):
723
        return "VariantType.Custom:{}".format(self.value)
724 1
    __repr__ = __str__
725 1
726 1
    def __eq__(self, other):
727
        return self.value == other.value
728 1
729 1
730 1
class Variant(FrozenClass):
731
    """
732 1
    Create an OPC-UA Variant object.
733
    if no argument a Null Variant is created.
734
    if not variant type is given, attemps to guess type from python type
735
    if a variant is given as value, the new objects becomes a copy of the argument
736 1
737
    :ivar Value:
738
    :vartype Value: Any supported type
739
    :ivar VariantType:
740 1
    :vartype VariantType: VariantType
741
    """
742 1
743 1
    def __init__(self, value=None, varianttype=None, dimensions=None):
744 1
        self.Value = value
745 1
        self.VariantType = varianttype
746
        self.Dimensions = dimensions
747 1
        self._freeze = True
748 1
        if isinstance(value, Variant):
749
            self.Value = value.Value
750
            self.VariantType = value.VariantType
751 1
        if self.VariantType is None:
752
            self.VariantType = self._guess_type(self.Value)
753
        if self.Value is None and self.VariantType not in (
754
                VariantType.Null,
755
                VariantType.String,
756
                VariantType.DateTime):
757
            raise UaError("Variant of type {} cannot have value None".format(self.VariantType))
758
        if self.Dimensions is None and type(self.Value) in (list, tuple):
759
            dims = get_shape(self.Value)
760
            if len(dims) > 1:
761
                self.Dimensions = dims
762
763
    def __eq__(self, other):
764
        if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value:
765 1
            return True
766 1
        return False
767 1
768 1
    def __ne__(self, other):
769 1
        return not self.__eq__(other)
770
771 1
    def _guess_type(self, val):
772 1
        if isinstance(val, (list, tuple)):
773 1
            error_val = val
774 1
        while isinstance(val, (list, tuple)):
775 1
            if len(val) == 0:
776 1
                raise UaError("could not guess UA type of variable {}".format(error_val))
777 1
            val = val[0]
778 1
        if val is None:
779 1
            return VariantType.Null
780
        elif isinstance(val, bool):
781 1
            return VariantType.Boolean
782
        elif isinstance(val, float):
783
            return VariantType.Double
784
        elif isinstance(val, int):
785
            return VariantType.Int64
786
        elif type(val) in (str, unicode):
787
            return VariantType.String
788
        elif isinstance(val, bytes):
789
            return VariantType.ByteString
790 1
        elif isinstance(val, datetime):
791
            return VariantType.DateTime
792
        elif isinstance(val, uuid.UUID):
793
            return VariantType.Guid
794
        else:
795
            if isinstance(val, object):
796
                try:
797
                    return getattr(VariantType, val.__class__.__name__)
798 1
                except AttributeError:
799
                    return VariantType.ExtensionObject
800
            else:
801
                raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val)))
802 1
803
    def __str__(self):
804
        return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType)
805 1 View Code Duplication
    __repr__ = __str__
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
806
807
    def to_binary(self):
808
        b = []
809
        encoding = self.VariantType.value & 0b111111
810
        if type(self.Value) in (list, tuple):
811
            if self.Dimensions is not None:
812
                encoding = uabin.set_bit(encoding, 6)
813
            encoding = uabin.set_bit(encoding, 7)
814
            b.append(uabin.Primitives.UInt8.pack(encoding))
815
            b.append(uabin.pack_uatype_array(self.VariantType, flatten(self.Value)))
816
            if self.Dimensions is not None:
817
                b.append(uabin.pack_uatype_array(VariantType.Int32, self.Dimensions))
818
        else:
819
            b.append(uabin.Primitives.UInt8.pack(encoding))
820
            b.append(uabin.pack_uatype(self.VariantType, self.Value))
821
822
        return b"".join(b)
823
824
    @staticmethod
825
    def from_binary(data):
826
        dimensions = None
827
        encoding = ord(data.read(1))
828
        int_type = encoding & 0b00111111
829
        vtype = datatype_to_varianttype(int_type)
830
        if vtype == VariantType.Null:
831
            return Variant(None, vtype, encoding)
832
        if uabin.test_bit(encoding, 7):
833
            value = uabin.unpack_uatype_array(vtype, data)
834
        else:
835
            value = uabin.unpack_uatype(vtype, data)
836
        if uabin.test_bit(encoding, 6):
837
            dimensions = uabin.unpack_uatype_array(VariantType.Int32, data)
838
            value = reshape(value, dimensions)
839
840 1
        return Variant(value, vtype, dimensions)
841 1
842 1
843 1
def reshape(flat, dims):
844 1
    subdims = dims[1:]
845 1
    subsize = 1
846 1
    for i in subdims:
847 1
        if i == 0:
848 1
            i = 1
849 1
        subsize *= i
850 1
    while dims[0] * subsize > len(flat):
851 1
        flat.append([])
852 1
    if not subdims or subdims == [0]:
853 1
        return flat
854 1
    return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)]
855 1
856 1
857 1
def _split_list(l, n):
858 1
    n = max(1, n)
859 1
    return [l[i:i + n] for i in range(0, len(l), n)]
860 1
861 1
862 1
def flatten_and_get_shape(mylist):
863 1
    dims = []
864 1
    dims.append(len(mylist))
865 1
    while isinstance(mylist[0], (list, tuple)):
866
        dims.append(len(mylist[0]))
867
        mylist = [item for sublist in mylist for item in sublist]
868 1
        if len(mylist) == 0:
869 1
            break
870 1
    return mylist, dims
871 1
872 1
873 1
def flatten(mylist):
874
    if len(mylist) == 0:
875 1
        return mylist
876
    while isinstance(mylist[0], (list, tuple)):
877 1
        mylist = [item for sublist in mylist for item in sublist]
878
        if len(mylist) == 0:
879 1
            break
880 1
    return mylist
881
882
883 1
def get_shape(mylist):
884
    dims = []
885
    while isinstance(mylist, (list, tuple)):
886
        dims.append(len(mylist))
887
        if len(mylist) == 0:
888
            break
889
        mylist = mylist[0]
890
    return dims
891
892
893
class XmlElement(FrozenClass):
894
    """
895
    An XML element encoded as an UTF-8 string.
896
    """
897 1
898 1
    def __init__(self, binary=None):
899 1
        if binary is not None:
900 1
            self._binary_init(binary)
901 1
            self._freeze = True
902 1
            return
903 1
        self.Value = []
904 1
        self._freeze = True
905 1
906 1
    def to_binary(self):
907 1
        return uabin.Primitives.String.pack(self.Value)
908 1
909 1
    @staticmethod
910 1
    def from_binary(data):
911
        return XmlElement(data)
912 1
913 1
    def _binary_init(self, data):
914 1
        self.Value = uabin.Primitives.String.unpack(data)
915 1
916
    def __str__(self):
917 1
        return 'XmlElement(Value:' + str(self.Value) + ')'
918 1
919
    __repr__ = __str__
920 1
921 1
922 1
class DataValue(FrozenClass):
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
    def __init__(self, variant=None, status=None):
942 1
        self.Encoding = 0
943 1
        if not isinstance(variant, Variant):
944 1
            variant = Variant(variant)
945 1
        self.Value = variant
946 1
        if status is None:
947
            self.StatusCode = StatusCode()
948
        else:
949
            self.StatusCode = status
950 1
        self.SourceTimestamp = None  # DateTime()
951 1
        self.SourcePicoseconds = None
952 1
        self.ServerTimestamp = None  # DateTime()
953
        self.ServerPicoseconds = None
954 1
        self._freeze = True
955 1
956 1
    def to_binary(self):
957 1
        packet = []
958 1
        if self.Value:
959 1
            self.Encoding |= (1 << 0)
960 1
        if self.StatusCode:
961 1
            self.Encoding |= (1 << 1)
962 1
        if self.SourceTimestamp:
963 1
            self.Encoding |= (1 << 2)
964 1
        if self.ServerTimestamp:
965
            self.Encoding |= (1 << 3)
966 1
        if self.SourcePicoseconds:
967 1
            self.Encoding |= (1 << 4)
968
        if self.ServerPicoseconds:
969 1
            self.Encoding |= (1 << 5)
970
        packet.append(uabin.Primitives.UInt8.pack(self.Encoding))
971 1
        if self.Value:
972
            packet.append(self.Value.to_binary())
973 1
        if self.StatusCode:
974 1
            packet.append(self.StatusCode.to_binary())
975 1
        if self.SourceTimestamp:
976 1
            packet.append(uabin.Primitives.DateTime.pack(self.SourceTimestamp))  # self.SourceTimestamp.to_binary())
977 1
        if self.ServerTimestamp:
978
            packet.append(uabin.Primitives.DateTime.pack(self.ServerTimestamp))  # self.ServerTimestamp.to_binary())
979 1
        if self.SourcePicoseconds:
980 1
            packet.append(uabin.Primitives.UInt16.pack(self.SourcePicoseconds))
981 1
        if self.ServerPicoseconds:
982 1
            packet.append(uabin.Primitives.UInt16.pack(self.ServerPicoseconds))
983 1
        return b''.join(packet)
984
985 1
    @staticmethod
986 1
    def from_binary(data):
987 1
        encoding = ord(data.read(1))
988 1
        if encoding & (1 << 0):
989
            value = Variant.from_binary(data)
990 1
        else:
991
            value = None
992
        if encoding & (1 << 1):
993 1
            status = StatusCode.from_binary(data)
994 1
        else:
995 1
            status = None
996 1
        obj = DataValue(value, status)
997 1
        obj.Encoding = encoding
998 1
        if obj.Encoding & (1 << 2):
999 1
            obj.SourceTimestamp = uabin.Primitives.DateTime.unpack(data)  # DateTime.from_binary(data)
1000 1
        if obj.Encoding & (1 << 3):
1001 1
            obj.ServerTimestamp = uabin.Primitives.DateTime.unpack(data)  # DateTime.from_binary(data)
1002 1
        if obj.Encoding & (1 << 4):
1003 1
            obj.SourcePicoseconds = uabin.Primitives.UInt16.unpack(data)
1004 1
        if obj.Encoding & (1 << 5):
1005
            obj.ServerPicoseconds = uabin.Primitives.UInt16.unpack(data)
1006
        return obj
1007 1
1008
    def __str__(self):
1009
        s = 'DataValue(Value:{}'.format(self.Value)
1010
        if self.StatusCode is not None:
1011
            s += ', StatusCode:{}'.format(self.StatusCode)
1012 1
        if self.SourceTimestamp is not None:
1013
            s += ', SourceTimestamp:{}'.format(self.SourceTimestamp)
1014
        if self.ServerTimestamp is not None:
1015
            s += ', ServerTimestamp:{}'.format(self.ServerTimestamp)
1016
        if self.SourcePicoseconds is not None:
1017
            s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds)
1018
        if self.ServerPicoseconds is not None:
1019
            s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds)
1020
        s += ')'
1021
        return s
1022
1023 1
    __repr__ = __str__
1024 1
1025 1
1026 1
def datatype_to_varianttype(int_type):
1027 1
    """
1028 1
    Takes a NodeId or int and return a VariantType
1029 1
    This is only supported if int_type < 63 due to VariantType encoding
1030 1
    At low level we do not have access to address space thus decoding is limited
1031
    a better version of this method can be find in ua_utils.py
1032
    """
1033 1
    if isinstance(int_type, NodeId):
1034 1
        int_type = int_type.Identifier
1035 1
1036 1
    if int_type <= 25:
1037 1
        return VariantType(int_type)
1038 1
    else:
1039
        return VariantTypeCustom(int_type)
1040