Completed
Push — master ( 7542cb...d1dda2 )
by Olivier
02:19
created

reshape()   D

Complexity

Conditions 7

Size

Total Lines 12

Duplication

Lines 1
Ratio 8.33 %

Code Coverage

Tests 8
CRAP Score 7.0671

Importance

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