Test Failed
Pull Request — master (#490)
by Olivier
02:56
created

Variant.__ne__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 2
Ratio 100 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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