Completed
Push — master ( 0e5e79...d552f1 )
by Olivier
05:52
created

QualifiedName.__ne__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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