Completed
Pull Request — master (#490)
by Olivier
08:10
created

NodeId.has_null_identifier()   A

Complexity

Conditions 4

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

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