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

Variant.to_binary()   B

Complexity

Conditions 5

Size

Total Lines 17

Duplication

Lines 17
Ratio 100 %

Code Coverage

Tests 15
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
dl 17
loc 17
ccs 15
cts 15
cp 1
crap 5
rs 8.5454
c 0
b 0
f 0

2 Methods

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