Completed
Push — master ( 1f3680...dee454 )
by Olivier
04:42
created

NodeId.__init__()   D

Complexity

Conditions 8

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.048

Importance

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