Completed
Pull Request — master (#490)
by Olivier
05:51
created

NodeId   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 156
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 156
ccs 102
cts 119
cp 0.8571
rs 8.3999
wmc 46

13 Methods

Rating   Name   Duplication   Size   Complexity  
D to_string() 0 23 10
D __init__() 0 25 8
A __eq__() 0 2 1
F _from_string() 0 38 11
A is_null() 0 4 2
A __hash__() 0 2 1
A __lt__() 0 4 2
A __ne__() 0 2 1
A __str__() 0 2 1
A from_string() 0 6 2
A _key() 0 5 2
A to_binary() 0 3 1
A has_null_identifier() 0 6 4

How to fix   Complexity   

Complex Class

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

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

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