Completed
Push — master ( 3f750a...cf2066 )
by Olivier
02:32
created

reshape()   B

Complexity

Conditions 7

Size

Total Lines 12

Duplication

Lines 4
Ratio 33.33 %

Code Coverage

Tests 10
CRAP Score 7

Importance

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