1
|
|
|
""" |
2
|
|
|
implement ua datatypes |
3
|
|
|
""" |
4
|
1 |
|
import logging |
5
|
1 |
|
from enum import Enum |
6
|
1 |
|
from datetime import datetime, timedelta, tzinfo, MAXYEAR |
7
|
1 |
|
from calendar import timegm |
8
|
1 |
|
import sys |
9
|
1 |
|
import os |
10
|
1 |
|
import uuid |
11
|
1 |
|
import struct |
12
|
1 |
|
if sys.version_info.major > 2: |
13
|
1 |
|
unicode = str |
14
|
|
|
|
15
|
1 |
|
from opcua.ua import status_codes |
16
|
1 |
|
from opcua.common.uaerrors import UaError |
17
|
1 |
|
from opcua.common.uaerrors import UaStatusCodeError |
18
|
1 |
|
from opcua.common.uaerrors import UaStringParsingError |
19
|
|
|
from opcua.ua.object_ids import ObjectIds |
20
|
|
|
|
21
|
1 |
|
logger = logging.getLogger('opcua.uaprotocol') |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
# types that will packed and unpacked directly using struct (string, bytes and datetime are handles as special cases |
25
|
1 |
|
UaTypes = ("Boolean", "SByte", "Byte", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Float", "Double") |
26
|
|
|
|
27
|
|
|
|
28
|
1 |
|
EPOCH_AS_FILETIME = 116444736000000000 # January 1, 1970 as MS file time |
29
|
1 |
|
HUNDREDS_OF_NANOSECONDS = 10000000 |
30
|
1 |
|
FILETIME_EPOCH_AS_DATETIME = datetime(1601, 1, 1) |
31
|
|
|
|
32
|
|
|
|
33
|
1 |
|
class UTC(tzinfo): |
34
|
|
|
|
35
|
|
|
"""UTC""" |
36
|
|
|
|
37
|
1 |
|
def utcoffset(self, dt): |
38
|
|
|
return timedelta(0) |
39
|
|
|
|
40
|
1 |
|
def tzname(self, dt): |
41
|
|
|
return "UTC" |
42
|
|
|
|
43
|
1 |
|
def dst(self, dt): |
44
|
1 |
|
return timedelta(0) |
45
|
|
|
|
46
|
|
|
|
47
|
|
|
# method copied from David Buxton <[email protected]> sample code |
48
|
1 |
|
def datetime_to_win_epoch(dt): |
49
|
1 |
|
if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None): |
50
|
1 |
|
dt = dt.replace(tzinfo=UTC()) |
51
|
1 |
|
ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS) |
52
|
1 |
|
return ft + (dt.microsecond * 10) |
53
|
|
|
|
54
|
|
|
|
55
|
1 |
|
def win_epoch_to_datetime(epch): |
56
|
1 |
|
try: |
57
|
1 |
|
return FILETIME_EPOCH_AS_DATETIME + timedelta(microseconds=epch // 10) |
58
|
|
|
except OverflowError: |
59
|
|
|
# FILETIMEs after 31 Dec 9999 can't be converted to datetime |
60
|
|
|
logger.warning("datetime overflow: {}".format(epch)) |
61
|
|
|
return datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999) |
62
|
|
|
|
63
|
|
|
|
64
|
1 |
|
def build_array_format_py2(prefix, length, fmtchar): |
65
|
|
|
return prefix + str(length) + fmtchar |
66
|
|
|
|
67
|
|
|
|
68
|
1 |
|
def build_array_format_py3(prefix, length, fmtchar): |
69
|
1 |
|
return prefix + str(length) + chr(fmtchar) |
70
|
|
|
|
71
|
|
|
|
72
|
1 |
|
if sys.version_info.major < 3: |
73
|
|
|
build_array_format = build_array_format_py2 |
74
|
|
|
else: |
75
|
1 |
|
build_array_format = build_array_format_py3 |
76
|
|
|
|
77
|
|
|
|
78
|
1 |
|
def pack_uatype_array_primitive(st, value, length): |
79
|
1 |
|
if length == 1: |
80
|
1 |
|
return b'\x01\x00\x00\x00' + st.pack(value[0]) |
81
|
|
|
else: |
82
|
1 |
|
return struct.pack(build_array_format("<i", length, st.format[1]), length, *value) |
83
|
|
|
|
84
|
|
|
|
85
|
1 |
|
def pack_uatype_array(uatype, value): |
86
|
1 |
|
if value is None: |
87
|
|
|
return b'\xff\xff\xff\xff' |
88
|
1 |
|
length = len(value) |
89
|
1 |
|
if length == 0: |
90
|
1 |
|
return b'\x00\x00\x00\x00' |
91
|
1 |
|
if uatype in uatype2struct: |
92
|
1 |
|
return pack_uatype_array_primitive(uatype2struct[uatype], value, length) |
93
|
1 |
|
b = [] |
94
|
1 |
|
b.append(uatype_Int32.pack(length)) |
95
|
1 |
|
for val in value: |
96
|
1 |
|
b.append(pack_uatype(uatype, val)) |
97
|
1 |
|
return b"".join(b) |
98
|
|
|
|
99
|
|
|
|
100
|
1 |
|
def pack_uatype(uatype, value): |
101
|
1 |
|
if uatype in uatype2struct: |
102
|
1 |
|
return uatype2struct[uatype].pack(value) |
103
|
1 |
|
elif uatype == "Null": |
104
|
1 |
|
return b'' |
105
|
1 |
|
elif uatype == "String": |
106
|
1 |
|
return pack_string(value) |
107
|
1 |
|
elif uatype in ("CharArray", "ByteString", "Custom"): |
108
|
1 |
|
return pack_bytes(value) |
109
|
1 |
|
elif uatype == "DateTime": |
110
|
1 |
|
return pack_datetime(value) |
111
|
1 |
|
elif uatype == "ExtensionObject": |
112
|
|
|
# dependency loop: classes in uaprotocol_auto use Variant defined in this file, |
113
|
|
|
# but Variant can contain any object from uaprotocol_auto as ExtensionObject. |
114
|
|
|
# Using local import to avoid import loop |
115
|
1 |
|
from opcua.ua.uaprotocol_auto import extensionobject_to_binary |
116
|
1 |
|
return extensionobject_to_binary(value) |
117
|
|
|
else: |
118
|
1 |
|
return value.to_binary() |
119
|
|
|
|
120
|
1 |
|
uatype_Int8 = struct.Struct("<b") |
121
|
1 |
|
uatype_SByte = uatype_Int8 |
122
|
1 |
|
uatype_Int16 = struct.Struct("<h") |
123
|
1 |
|
uatype_Int32 = struct.Struct("<i") |
124
|
1 |
|
uatype_Int64 = struct.Struct("<q") |
125
|
1 |
|
uatype_UInt8 = struct.Struct("<B") |
126
|
1 |
|
uatype_Char = uatype_UInt8 |
127
|
1 |
|
uatype_Byte = uatype_UInt8 |
128
|
1 |
|
uatype_UInt16 = struct.Struct("<H") |
129
|
1 |
|
uatype_UInt32 = struct.Struct("<I") |
130
|
1 |
|
uatype_UInt64 = struct.Struct("<Q") |
131
|
1 |
|
uatype_Boolean = struct.Struct("<?") |
132
|
1 |
|
uatype_Double = struct.Struct("<d") |
133
|
1 |
|
uatype_Float = struct.Struct("<f") |
134
|
|
|
|
135
|
1 |
|
uatype2struct = { |
136
|
|
|
"Int8": uatype_Int8, |
137
|
|
|
"SByte": uatype_SByte, |
138
|
|
|
"Int16": uatype_Int16, |
139
|
|
|
"Int32": uatype_Int32, |
140
|
|
|
"Int64": uatype_Int64, |
141
|
|
|
"UInt8": uatype_UInt8, |
142
|
|
|
"Char": uatype_Char, |
143
|
|
|
"Byte": uatype_Byte, |
144
|
|
|
"UInt16": uatype_UInt16, |
145
|
|
|
"UInt32": uatype_UInt32, |
146
|
|
|
"UInt64": uatype_UInt64, |
147
|
|
|
"Boolean": uatype_Boolean, |
148
|
|
|
"Double": uatype_Double, |
149
|
|
|
"Float": uatype_Float, |
150
|
|
|
} |
151
|
|
|
|
152
|
|
|
|
153
|
1 |
|
def unpack_uatype(uatype, data): |
154
|
1 |
|
if uatype in uatype2struct: |
155
|
1 |
|
st = uatype2struct[uatype] |
156
|
1 |
|
return st.unpack(data.read(st.size))[0] |
157
|
1 |
|
elif uatype == "String": |
158
|
1 |
|
return unpack_string(data) |
159
|
1 |
|
elif uatype in ("CharArray", "ByteString", "Custom"): |
160
|
1 |
|
return unpack_bytes(data) |
161
|
1 |
|
elif uatype == "DateTime": |
162
|
1 |
|
return unpack_datetime(data) |
163
|
1 |
|
elif uatype == "ExtensionObject": |
164
|
|
|
# dependency loop: classes in uaprotocol_auto use Variant defined in this file, |
165
|
|
|
# but Variant can contain any object from uaprotocol_auto as ExtensionObject. |
166
|
|
|
# Using local import to avoid import loop |
167
|
1 |
|
from opcua.ua.uaprotocol_auto import extensionobject_from_binary |
168
|
1 |
|
return extensionobject_from_binary(data) |
169
|
|
|
else: |
170
|
1 |
|
glbs = globals() |
171
|
1 |
|
if uatype in glbs: |
172
|
1 |
|
klass = glbs[uatype] |
173
|
1 |
|
if hasattr(klass, 'from_binary'): |
174
|
1 |
|
return klass.from_binary(data) |
175
|
|
|
raise UaError("can not unpack unknown uatype %s" % uatype) |
176
|
|
|
|
177
|
|
|
|
178
|
1 |
|
def unpack_uatype_array(uatype, data): |
179
|
1 |
|
length = uatype_Int32.unpack(data.read(4))[0] |
180
|
1 |
|
if length == -1: |
181
|
|
|
return None |
182
|
1 |
|
elif length == 0: |
183
|
1 |
|
return [] |
184
|
1 |
|
elif uatype in uatype2struct: |
185
|
1 |
|
st = uatype2struct[uatype] |
186
|
1 |
|
if length == 1: |
187
|
1 |
|
return list(st.unpack(data.read(st.size))) |
188
|
|
|
else: |
189
|
1 |
|
arrst = struct.Struct(build_array_format("<", length, st.format[1])) |
190
|
1 |
|
return list(arrst.unpack(data.read(arrst.size))) |
191
|
|
|
else: |
192
|
1 |
|
result = [] |
193
|
1 |
|
for _ in range(0, length): |
194
|
1 |
|
result.append(unpack_uatype(uatype, data)) |
195
|
1 |
|
return result |
196
|
|
|
|
197
|
|
|
|
198
|
1 |
|
def pack_datetime(value): |
199
|
1 |
|
epch = datetime_to_win_epoch(value) |
200
|
1 |
|
return uatype_Int64.pack(epch) |
201
|
|
|
|
202
|
|
|
|
203
|
1 |
|
def unpack_datetime(data): |
204
|
1 |
|
epch = uatype_Int64.unpack(data.read(8))[0] |
205
|
1 |
|
return win_epoch_to_datetime(epch) |
206
|
|
|
|
207
|
|
|
|
208
|
1 |
|
def pack_string(string): |
209
|
1 |
|
if isinstance(string, unicode): |
210
|
1 |
|
string = string.encode('utf-8') |
211
|
1 |
|
length = len(string) |
212
|
1 |
|
if length == 0: |
213
|
1 |
|
return b'\xff\xff\xff\xff' |
214
|
1 |
|
return uatype_Int32.pack(length) + string |
215
|
|
|
|
216
|
1 |
|
pack_bytes = pack_string |
217
|
|
|
|
218
|
|
|
|
219
|
1 |
|
def unpack_bytes(data): |
220
|
1 |
|
length = uatype_Int32.unpack(data.read(4))[0] |
221
|
1 |
|
if length == -1: |
222
|
1 |
|
return b'' |
223
|
1 |
|
return data.read(length) |
224
|
|
|
|
225
|
|
|
|
226
|
1 |
|
def py3_unpack_string(data): |
227
|
1 |
|
b = unpack_bytes(data) |
228
|
1 |
|
return b.decode("utf-8") |
229
|
|
|
|
230
|
|
|
|
231
|
1 |
|
if sys.version_info.major < 3: |
232
|
|
|
unpack_string = unpack_bytes |
233
|
|
|
else: |
234
|
1 |
|
unpack_string = py3_unpack_string |
235
|
|
|
|
236
|
|
|
|
237
|
1 |
|
def test_bit(data, offset): |
238
|
1 |
|
mask = 1 << offset |
239
|
1 |
|
return data & mask |
240
|
|
|
|
241
|
|
|
|
242
|
1 |
|
def set_bit(data, offset): |
243
|
1 |
|
mask = 1 << offset |
244
|
1 |
|
return data | mask |
245
|
|
|
|
246
|
|
|
|
247
|
1 |
|
class _FrozenClass(object): |
248
|
|
|
|
249
|
|
|
""" |
250
|
|
|
make it impossible to add members to a class. |
251
|
|
|
This is a hack since I found out that most bugs are due to misspelling a variable in protocol |
252
|
|
|
""" |
253
|
1 |
|
_freeze = False |
254
|
|
|
|
255
|
1 |
|
def __setattr__(self, key, value): |
256
|
1 |
|
if self._freeze and not hasattr(self, key): |
257
|
|
|
raise TypeError("Error adding member '{}' to class '{}', class is frozen, members are {}".format(key, self.__class__.__name__, self.__dict__.keys())) |
258
|
1 |
|
object.__setattr__(self, key, value) |
259
|
|
|
|
260
|
1 |
|
if "PYOPCUA_NO_TYPO_CHECK" in os.environ: |
261
|
|
|
# typo check is cpu consuming, but it will make debug easy. |
262
|
|
|
# if typo check is not need (in production), please set env PYOPCUA_NO_TYPO_CHECK. |
263
|
|
|
# this will make all uatype class inherit from object intead of _FrozenClass |
264
|
|
|
# and skip the typo check. |
265
|
|
|
FrozenClass = object |
266
|
|
|
else: |
267
|
1 |
|
FrozenClass = _FrozenClass |
268
|
|
|
|
269
|
|
|
|
270
|
1 |
|
class Guid(FrozenClass): |
271
|
|
|
|
272
|
1 |
|
def __init__(self): |
273
|
1 |
|
self.uuid = uuid.uuid4() |
274
|
1 |
|
self._freeze = True |
275
|
|
|
|
276
|
1 |
|
def to_binary(self): |
277
|
1 |
|
return self.uuid.bytes |
278
|
|
|
|
279
|
1 |
|
def __hash__(self): |
280
|
|
|
return hash(self.uuid.bytes) |
281
|
|
|
|
282
|
1 |
|
@staticmethod |
283
|
|
|
def from_binary(data): |
284
|
1 |
|
g = Guid() |
285
|
1 |
|
g.uuid = uuid.UUID(bytes=data.read(16)) |
286
|
1 |
|
return g |
287
|
|
|
|
288
|
1 |
|
def __eq__(self, other): |
289
|
1 |
|
return isinstance(other, Guid) and self.uuid == other.uuid |
290
|
|
|
|
291
|
|
|
|
292
|
1 |
|
class StatusCode(FrozenClass): |
293
|
|
|
|
294
|
|
|
""" |
295
|
|
|
:ivar value: |
296
|
|
|
:vartype value: int |
297
|
|
|
:ivar name: |
298
|
|
|
:vartype name: string |
299
|
|
|
:ivar doc: |
300
|
|
|
:vartype doc: string |
301
|
|
|
""" |
302
|
|
|
|
303
|
1 |
|
def __init__(self, value=0): |
304
|
1 |
|
self.value = value |
305
|
1 |
|
self.name, self.doc = status_codes.get_name_and_doc(value) |
306
|
1 |
|
self._freeze = True |
307
|
|
|
|
308
|
1 |
|
def to_binary(self): |
309
|
1 |
|
return uatype_UInt32.pack(self.value) |
310
|
|
|
|
311
|
1 |
|
@staticmethod |
312
|
|
|
def from_binary(data): |
313
|
1 |
|
val = uatype_UInt32.unpack(data.read(4))[0] |
314
|
1 |
|
sc = StatusCode(val) |
315
|
1 |
|
return sc |
316
|
|
|
|
317
|
1 |
|
def check(self): |
318
|
|
|
""" |
319
|
|
|
raise en exception if status code is anything else than 0 |
320
|
|
|
use is is_good() method if not exception is desired |
321
|
|
|
""" |
322
|
1 |
|
if self.value != 0: |
323
|
1 |
|
raise UaStatusCodeError("{}({})".format(self.doc, self.name)) |
324
|
|
|
|
325
|
1 |
|
def is_good(self): |
326
|
|
|
""" |
327
|
|
|
return True if status is Good. |
328
|
|
|
""" |
329
|
1 |
|
if self.value == 0: |
330
|
1 |
|
return True |
331
|
1 |
|
return False |
332
|
|
|
|
333
|
1 |
|
def __str__(self): |
334
|
|
|
return 'StatusCode({})'.format(self.name) |
335
|
1 |
|
__repr__ = __str__ |
336
|
|
|
|
337
|
1 |
|
def __eq__(self, other): |
338
|
|
|
return self.value == other.value |
339
|
|
|
|
340
|
1 |
|
def __ne__(self, other): |
341
|
|
|
return not self.__eq__(other) |
342
|
|
|
|
343
|
|
|
|
344
|
1 |
|
class NodeIdType(Enum): |
345
|
1 |
|
TwoByte = 0 |
346
|
1 |
|
FourByte = 1 |
347
|
1 |
|
Numeric = 2 |
348
|
1 |
|
String = 3 |
349
|
1 |
|
Guid = 4 |
350
|
1 |
|
ByteString = 5 |
351
|
|
|
|
352
|
|
|
|
353
|
1 |
|
class NodeId(FrozenClass): |
354
|
|
|
|
355
|
|
|
""" |
356
|
|
|
NodeId Object |
357
|
|
|
|
358
|
|
|
Args: |
359
|
|
|
identifier: The identifier might be an int, a string, bytes or a Guid |
360
|
|
|
namespaceidx(int): The index of the namespace |
361
|
|
|
nodeidtype(NodeIdType): The type of the nodeid if it cannor be guess or you want something special like twobyte nodeid or fourbytenodeid |
362
|
|
|
|
363
|
|
|
|
364
|
|
|
:ivar Identifier: |
365
|
|
|
:vartype Identifier: NodeId |
366
|
|
|
:ivar NamespaceIndex: |
367
|
|
|
:vartype NamespaceIndex: Int |
368
|
|
|
:ivar NamespaceUri: |
369
|
|
|
:vartype NamespaceUri: String |
370
|
|
|
:ivar ServerIndex: |
371
|
|
|
:vartype ServerIndex: Int |
372
|
|
|
""" |
373
|
|
|
|
374
|
1 |
|
def __init__(self, identifier=None, namespaceidx=0, nodeidtype=None): |
375
|
1 |
|
self.Identifier = identifier |
376
|
1 |
|
self.NamespaceIndex = namespaceidx |
377
|
1 |
|
self.NodeIdType = nodeidtype |
378
|
1 |
|
self.NamespaceUri = "" |
379
|
1 |
|
self.ServerIndex = 0 |
380
|
1 |
|
self._freeze = True |
381
|
1 |
|
if not isinstance(self.NamespaceIndex, int): |
382
|
1 |
|
raise UaError("NamespaceIndex must be an int") |
383
|
1 |
|
if self.Identifier is None: |
384
|
1 |
|
self.Identifier = 0 |
385
|
1 |
|
self.NodeIdType = NodeIdType.TwoByte |
386
|
1 |
|
return |
387
|
1 |
|
if self.NodeIdType is None: |
388
|
1 |
|
if isinstance(self.Identifier, int): |
389
|
1 |
|
self.NodeIdType = NodeIdType.Numeric |
390
|
1 |
|
elif isinstance(self.Identifier, str): |
391
|
1 |
|
self.NodeIdType = NodeIdType.String |
392
|
|
|
elif isinstance(self.Identifier, bytes): |
393
|
|
|
self.NodeIdType = NodeIdType.ByteString |
394
|
|
|
else: |
395
|
|
|
raise UaError("NodeId: Could not guess type of NodeId, set NodeIdType") |
396
|
|
|
|
397
|
1 |
|
def __key(self): |
398
|
1 |
|
if self.NodeIdType in (NodeIdType.TwoByte, NodeIdType.FourByte, NodeIdType.Numeric): # twobyte, fourbyte and numeric may represent the same node |
399
|
1 |
|
return self.NamespaceIndex, self.Identifier |
400
|
|
|
else: |
401
|
1 |
|
return self.NodeIdType, self.NamespaceIndex, self.Identifier |
402
|
|
|
|
403
|
1 |
|
def __eq__(self, node): |
404
|
1 |
|
return isinstance(node, NodeId) and self.__key() == node.__key() |
405
|
|
|
|
406
|
1 |
|
def __ne__(self, other): |
407
|
1 |
|
return not self.__eq__(other) |
408
|
|
|
|
409
|
1 |
|
def __hash__(self): |
410
|
1 |
|
return hash(self.__key()) |
411
|
|
|
|
412
|
1 |
|
@staticmethod |
413
|
|
|
def from_string(string): |
414
|
1 |
|
try: |
415
|
1 |
|
return NodeId._from_string(string) |
416
|
1 |
|
except ValueError as ex: |
417
|
1 |
|
raise UaStringParsingError("Error parsing string {}".format(string), ex) |
418
|
|
|
|
419
|
1 |
|
@staticmethod |
420
|
|
|
def _from_string(string): |
421
|
1 |
|
l = string.split(";") |
422
|
1 |
|
identifier = None |
423
|
1 |
|
namespace = 0 |
424
|
1 |
|
ntype = None |
425
|
1 |
|
srv = None |
426
|
1 |
|
nsu = None |
427
|
1 |
|
for el in l: |
428
|
1 |
|
if not el: |
429
|
1 |
|
continue |
430
|
1 |
|
k, v = el.split("=", 1) |
431
|
1 |
|
k = k.strip() |
432
|
1 |
|
v = v.strip() |
433
|
1 |
|
if k == "ns": |
434
|
1 |
|
namespace = int(v) |
435
|
1 |
|
elif k == "i": |
436
|
1 |
|
ntype = NodeIdType.Numeric |
437
|
1 |
|
identifier = int(v) |
438
|
1 |
|
elif k == "s": |
439
|
1 |
|
ntype = NodeIdType.String |
440
|
1 |
|
identifier = v |
441
|
1 |
|
elif k == "g": |
442
|
|
|
ntype = NodeIdType.Guid |
443
|
|
|
identifier = v |
444
|
1 |
|
elif k == "b": |
445
|
|
|
ntype = NodeIdType.ByteString |
446
|
|
|
identifier = v |
447
|
1 |
|
elif k == "srv": |
448
|
1 |
|
srv = v |
449
|
|
|
elif k == "nsu": |
450
|
|
|
nsu = v |
451
|
1 |
|
if identifier is None: |
452
|
1 |
|
raise UaStringParsingError("Could not find identifier in string: " + string) |
453
|
1 |
|
nodeid = NodeId(identifier, namespace, ntype) |
454
|
1 |
|
nodeid.NamespaceUri = nsu |
455
|
1 |
|
nodeid.ServerIndex = srv |
456
|
1 |
|
return nodeid |
457
|
|
|
|
458
|
1 |
|
def to_string(self): |
459
|
1 |
|
string = "" |
460
|
1 |
|
if self.NamespaceIndex != 0: |
461
|
1 |
|
string += "ns={};".format(self.NamespaceIndex) |
462
|
1 |
|
ntype = None |
463
|
1 |
|
if self.NodeIdType == NodeIdType.Numeric: |
464
|
|
|
ntype = "i" |
465
|
1 |
|
elif self.NodeIdType == NodeIdType.String: |
466
|
1 |
|
ntype = "s" |
467
|
1 |
|
elif self.NodeIdType == NodeIdType.TwoByte: |
468
|
1 |
|
ntype = "i" |
469
|
1 |
|
elif self.NodeIdType == NodeIdType.FourByte: |
470
|
1 |
|
ntype = "i" |
471
|
|
|
elif self.NodeIdType == NodeIdType.Guid: |
472
|
|
|
ntype = "g" |
473
|
|
|
elif self.NodeIdType == NodeIdType.ByteString: |
474
|
|
|
ntype = "b" |
475
|
1 |
|
string += "{}={}".format(ntype, self.Identifier) |
476
|
1 |
|
if self.ServerIndex: |
477
|
|
|
string = "srv=" + str(self.ServerIndex) + string |
478
|
1 |
|
if self.NamespaceUri: |
479
|
|
|
string += "nsu={}".format(self.NamespaceUri) |
480
|
1 |
|
return string |
481
|
|
|
|
482
|
1 |
|
def __str__(self): |
483
|
1 |
|
return "{}NodeId({})".format(self.NodeIdType.name, self.to_string()) |
484
|
1 |
|
__repr__ = __str__ |
485
|
|
|
|
486
|
1 |
|
def to_binary(self): |
487
|
1 |
|
if self.NodeIdType == NodeIdType.TwoByte: |
488
|
1 |
|
return struct.pack("<BB", self.NodeIdType.value, self.Identifier) |
489
|
1 |
|
elif self.NodeIdType == NodeIdType.FourByte: |
490
|
1 |
|
return struct.pack("<BBH", self.NodeIdType.value, self.NamespaceIndex, self.Identifier) |
491
|
1 |
|
elif self.NodeIdType == NodeIdType.Numeric: |
492
|
1 |
|
return struct.pack("<BHI", self.NodeIdType.value, self.NamespaceIndex, self.Identifier) |
493
|
1 |
|
elif self.NodeIdType == NodeIdType.String: |
494
|
1 |
|
return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \ |
495
|
|
|
pack_string(self.Identifier) |
496
|
1 |
|
elif self.NodeIdType == NodeIdType.ByteString: |
497
|
1 |
|
return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \ |
498
|
|
|
pack_bytes(self.Identifier) |
499
|
|
|
else: |
500
|
1 |
|
return struct.pack("<BH", self.NodeIdType.value, self.NamespaceIndex) + \ |
501
|
|
|
self.Identifier.to_binary() |
502
|
|
|
#FIXME: Missing NNamespaceURI and ServerIndex |
503
|
|
|
|
504
|
1 |
|
@staticmethod |
505
|
|
|
def from_binary(data): |
506
|
1 |
|
nid = NodeId() |
507
|
1 |
|
encoding = ord(data.read(1)) |
508
|
1 |
|
nid.NodeIdType = NodeIdType(encoding & 0b00111111) |
509
|
|
|
|
510
|
1 |
|
if nid.NodeIdType == NodeIdType.TwoByte: |
511
|
1 |
|
nid.Identifier = ord(data.read(1)) |
512
|
1 |
|
elif nid.NodeIdType == NodeIdType.FourByte: |
513
|
1 |
|
nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3)) |
514
|
1 |
|
elif nid.NodeIdType == NodeIdType.Numeric: |
515
|
1 |
|
nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6)) |
516
|
1 |
|
elif nid.NodeIdType == NodeIdType.String: |
517
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
518
|
1 |
|
nid.Identifier = unpack_string(data) |
519
|
1 |
|
elif nid.NodeIdType == NodeIdType.ByteString: |
520
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
521
|
1 |
|
nid.Identifier = unpack_bytes(data) |
522
|
1 |
|
elif nid.NodeIdType == NodeIdType.Guid: |
523
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
524
|
1 |
|
nid.Identifier = Guid.from_binary(data) |
525
|
|
|
else: |
526
|
|
|
raise UaError("Unknown NodeId encoding: " + str(nid.NodeIdType)) |
527
|
|
|
|
528
|
1 |
|
if test_bit(encoding, 7): |
529
|
|
|
nid.NamespaceUri = unpack_string(data) |
530
|
1 |
|
if test_bit(encoding, 6): |
531
|
|
|
nid.ServerIndex = uatype_UInt32.unpack(data.read(4))[0] |
532
|
|
|
|
533
|
1 |
|
return nid |
534
|
|
|
|
535
|
|
|
|
536
|
1 |
|
class TwoByteNodeId(NodeId): |
537
|
|
|
|
538
|
1 |
|
def __init__(self, identifier): |
539
|
1 |
|
NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte) |
540
|
|
|
|
541
|
|
|
|
542
|
1 |
|
class FourByteNodeId(NodeId): |
543
|
|
|
|
544
|
1 |
|
def __init__(self, identifier, namespace=0): |
545
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte) |
546
|
|
|
|
547
|
|
|
|
548
|
1 |
|
class NumericNodeId(NodeId): |
549
|
|
|
|
550
|
1 |
|
def __init__(self, identifier, namespace=0): |
551
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric) |
552
|
|
|
|
553
|
|
|
|
554
|
1 |
|
class ByteStringNodeId(NodeId): |
555
|
|
|
|
556
|
1 |
|
def __init__(self, identifier, namespace=0): |
557
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString) |
558
|
|
|
|
559
|
|
|
|
560
|
1 |
|
class GuidNodeId(NodeId): |
561
|
|
|
|
562
|
1 |
|
def __init__(self, identifier, namespace=0): |
563
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.Guid) |
564
|
|
|
|
565
|
|
|
|
566
|
1 |
|
class StringNodeId(NodeId): |
567
|
|
|
|
568
|
1 |
|
def __init__(self, identifier, namespace=0): |
569
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.String) |
570
|
|
|
|
571
|
|
|
|
572
|
1 |
|
ExpandedNodeId = NodeId |
573
|
|
|
|
574
|
|
|
|
575
|
1 |
|
class QualifiedName(FrozenClass): |
576
|
|
|
|
577
|
|
|
''' |
578
|
|
|
A string qualified with a namespace index. |
579
|
|
|
''' |
580
|
|
|
|
581
|
1 |
|
def __init__(self, name="", namespaceidx=0): |
582
|
1 |
|
if not isinstance(namespaceidx, int): |
583
|
|
|
raise UaError("namespaceidx must be an int") |
584
|
1 |
|
self.NamespaceIndex = namespaceidx |
585
|
1 |
|
self.Name = name |
586
|
1 |
|
self._freeze = True |
587
|
|
|
|
588
|
1 |
|
def to_string(self): |
589
|
1 |
|
return "{}:{}".format(self.NamespaceIndex, self.Name) |
590
|
|
|
|
591
|
1 |
|
@staticmethod |
592
|
|
|
def from_string(string): |
593
|
1 |
|
if ":" in string: |
594
|
1 |
|
try: |
595
|
1 |
|
idx, name = string.split(":", 1) |
596
|
1 |
|
idx = int(idx) |
597
|
1 |
|
except (TypeError, ValueError) as ex: |
598
|
1 |
|
raise UaStringParsingError("Error parsing string {}".format(string), ex) |
599
|
|
|
else: |
600
|
1 |
|
idx = 0 |
601
|
1 |
|
name = string |
602
|
1 |
|
return QualifiedName(name, idx) |
603
|
|
|
|
604
|
1 |
|
def to_binary(self): |
605
|
1 |
|
packet = [] |
606
|
1 |
|
packet.append(uatype_UInt16.pack(self.NamespaceIndex)) |
607
|
1 |
|
packet.append(pack_string(self.Name)) |
608
|
1 |
|
return b''.join(packet) |
609
|
|
|
|
610
|
1 |
|
@staticmethod |
611
|
|
|
def from_binary(data): |
612
|
1 |
|
obj = QualifiedName() |
613
|
1 |
|
obj.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
614
|
1 |
|
obj.Name = unpack_string(data) |
615
|
1 |
|
return obj |
616
|
|
|
|
617
|
1 |
|
def __eq__(self, bname): |
618
|
1 |
|
return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex |
619
|
|
|
|
620
|
1 |
|
def __ne__(self, other): |
621
|
|
|
return not self.__eq__(other) |
622
|
|
|
|
623
|
1 |
|
def __str__(self): |
624
|
|
|
return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name) |
625
|
|
|
|
626
|
1 |
|
__repr__ = __str__ |
627
|
|
|
|
628
|
|
|
|
629
|
1 |
|
class LocalizedText(FrozenClass): |
630
|
|
|
|
631
|
|
|
''' |
632
|
|
|
A string qualified with a namespace index. |
633
|
|
|
''' |
634
|
|
|
|
635
|
1 |
|
def __init__(self, text=""): |
636
|
1 |
|
self.Encoding = 0 |
637
|
1 |
|
self.Text = text |
638
|
1 |
|
if isinstance(self.Text, unicode): |
639
|
1 |
|
self.Text = self.Text.encode('utf-8') |
640
|
1 |
|
if self.Text: |
641
|
1 |
|
self.Encoding |= (1 << 1) |
642
|
1 |
|
self.Locale = b'' |
643
|
1 |
|
self._freeze = True |
644
|
|
|
|
645
|
1 |
|
def to_binary(self): |
646
|
1 |
|
packet = [] |
647
|
1 |
|
if self.Locale: |
648
|
|
|
self.Encoding |= (1 << 0) |
649
|
1 |
|
if self.Text: |
650
|
1 |
|
self.Encoding |= (1 << 1) |
651
|
1 |
|
packet.append(uatype_UInt8.pack(self.Encoding)) |
652
|
1 |
|
if self.Locale: |
653
|
|
|
packet.append(pack_bytes(self.Locale)) |
654
|
1 |
|
if self.Text: |
655
|
1 |
|
packet.append(pack_bytes(self.Text)) |
656
|
1 |
|
return b''.join(packet) |
657
|
|
|
|
658
|
1 |
|
@staticmethod |
659
|
|
|
def from_binary(data): |
660
|
1 |
|
obj = LocalizedText() |
661
|
1 |
|
obj.Encoding = ord(data.read(1)) |
662
|
1 |
|
if obj.Encoding & (1 << 0): |
663
|
|
|
obj.Locale = unpack_bytes(data) |
664
|
1 |
|
if obj.Encoding & (1 << 1): |
665
|
1 |
|
obj.Text = unpack_bytes(data) |
666
|
1 |
|
return obj |
667
|
|
|
|
668
|
1 |
|
def to_string(self): |
669
|
|
|
# FIXME: use local |
670
|
|
|
return self.Text.decode() |
671
|
|
|
|
672
|
1 |
|
def __str__(self): |
673
|
|
|
return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \ |
674
|
|
|
'Locale:' + str(self.Locale) + ', ' + \ |
675
|
|
|
'Text:' + str(self.Text) + ')' |
676
|
1 |
|
__repr__ = __str__ |
677
|
|
|
|
678
|
1 |
|
def __eq__(self, other): |
679
|
1 |
|
if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text: |
680
|
1 |
|
return True |
681
|
1 |
|
return False |
682
|
|
|
|
683
|
1 |
|
def __ne__(self, other): |
684
|
1 |
|
return not self.__eq__(other) |
685
|
|
|
|
686
|
|
|
|
687
|
1 |
|
class ExtensionObject(FrozenClass): |
688
|
|
|
|
689
|
|
|
''' |
690
|
|
|
|
691
|
|
|
Any UA object packed as an ExtensionObject |
692
|
|
|
|
693
|
|
|
|
694
|
|
|
:ivar TypeId: |
695
|
|
|
:vartype TypeId: NodeId |
696
|
|
|
:ivar Body: |
697
|
|
|
:vartype Body: bytes |
698
|
|
|
|
699
|
|
|
''' |
700
|
|
|
|
701
|
1 |
|
def __init__(self): |
702
|
1 |
|
self.TypeId = NodeId() |
703
|
1 |
|
self.Encoding = 0 |
704
|
1 |
|
self.Body = b'' |
705
|
1 |
|
self._freeze = True |
706
|
|
|
|
707
|
1 |
|
def to_binary(self): |
708
|
1 |
|
packet = [] |
709
|
1 |
|
if self.Body: |
710
|
1 |
|
self.Encoding |= (1 << 0) |
711
|
1 |
|
packet.append(self.TypeId.to_binary()) |
712
|
1 |
|
packet.append(pack_uatype('UInt8', self.Encoding)) |
713
|
1 |
|
if self.Body: |
714
|
1 |
|
packet.append(pack_uatype('ByteString', self.Body)) |
715
|
1 |
|
return b''.join(packet) |
716
|
|
|
|
717
|
1 |
|
@staticmethod |
718
|
|
|
def from_binary(data): |
719
|
|
|
obj = ExtensionObject() |
720
|
|
|
obj.TypeId = NodeId.from_binary(data) |
721
|
|
|
obj.Encoding = unpack_uatype('UInt8', data) |
722
|
|
|
if obj.Encoding & (1 << 0): |
723
|
|
|
obj.Body = unpack_uatype('ByteString', data) |
724
|
|
|
return obj |
725
|
|
|
|
726
|
1 |
|
@staticmethod |
727
|
|
|
def from_object(obj): |
728
|
|
|
ext = ExtensionObject() |
729
|
|
|
oid = getattr(ObjectIds, "{}_Encoding_DefaultBinary".format(obj.__class__.__name__)) |
730
|
|
|
ext.TypeId = FourByteNodeId(oid) |
731
|
|
|
ext.Body = obj.to_binary() |
732
|
|
|
return ext |
733
|
|
|
|
734
|
1 |
|
def __str__(self): |
735
|
|
|
return 'ExtensionObject(' + 'TypeId:' + str(self.TypeId) + ', ' + \ |
736
|
|
|
'Encoding:' + str(self.Encoding) + ', ' + str(len(self.Body)) + ' bytes)' |
737
|
|
|
|
738
|
1 |
|
__repr__ = __str__ |
739
|
|
|
|
740
|
|
|
|
741
|
1 |
|
class VariantType(Enum): |
742
|
|
|
|
743
|
|
|
''' |
744
|
|
|
The possible types of a variant. |
745
|
|
|
|
746
|
|
|
:ivar Null: |
747
|
|
|
:ivar Boolean: |
748
|
|
|
:ivar SByte: |
749
|
|
|
:ivar Byte: |
750
|
|
|
:ivar Int16: |
751
|
|
|
:ivar UInt16: |
752
|
|
|
:ivar Int32: |
753
|
|
|
:ivar UInt32: |
754
|
|
|
:ivar Int64: |
755
|
|
|
:ivar UInt64: |
756
|
|
|
:ivar Float: |
757
|
|
|
:ivar Double: |
758
|
|
|
:ivar String: |
759
|
|
|
:ivar DateTime: |
760
|
|
|
:ivar Guid: |
761
|
|
|
:ivar ByteString: |
762
|
|
|
:ivar XmlElement: |
763
|
|
|
:ivar NodeId: |
764
|
|
|
:ivar ExpandedNodeId: |
765
|
|
|
:ivar StatusCode: |
766
|
|
|
:ivar QualifiedName: |
767
|
|
|
:ivar LocalizedText: |
768
|
|
|
:ivar ExtensionObject: |
769
|
|
|
:ivar DataValue: |
770
|
|
|
:ivar Variant: |
771
|
|
|
:ivar DiagnosticInfo: |
772
|
|
|
|
773
|
|
|
|
774
|
|
|
|
775
|
|
|
''' |
776
|
1 |
|
Null = 0 |
777
|
1 |
|
Boolean = 1 |
778
|
1 |
|
SByte = 2 |
779
|
1 |
|
Byte = 3 |
780
|
1 |
|
Int16 = 4 |
781
|
1 |
|
UInt16 = 5 |
782
|
1 |
|
Int32 = 6 |
783
|
1 |
|
UInt32 = 7 |
784
|
1 |
|
Int64 = 8 |
785
|
1 |
|
UInt64 = 9 |
786
|
1 |
|
Float = 10 |
787
|
1 |
|
Double = 11 |
788
|
1 |
|
String = 12 |
789
|
1 |
|
DateTime = 13 |
790
|
1 |
|
Guid = 14 |
791
|
1 |
|
ByteString = 15 |
792
|
1 |
|
XmlElement = 16 |
793
|
1 |
|
NodeId = 17 |
794
|
1 |
|
ExpandedNodeId = 18 |
795
|
1 |
|
StatusCode = 19 |
796
|
1 |
|
QualifiedName = 20 |
797
|
1 |
|
LocalizedText = 21 |
798
|
1 |
|
ExtensionObject = 22 |
799
|
1 |
|
DataValue = 23 |
800
|
1 |
|
Variant = 24 |
801
|
1 |
|
DiagnosticInfo = 25 |
802
|
|
|
|
803
|
|
|
|
804
|
1 |
|
class VariantTypeCustom(object): |
805
|
1 |
|
def __init__(self, val): |
806
|
1 |
|
self.name = "Custom" |
807
|
1 |
|
self.value = val |
808
|
1 |
|
if self.value > 0b00111111: |
809
|
1 |
|
raise UaError("Cannot create VariantType. VariantType must be %s > x > %s", 0b111111, 25) |
810
|
|
|
|
811
|
1 |
|
def __str__(self): |
812
|
|
|
return "VariantType.Custom:{}".format(self.value) |
813
|
1 |
|
__repr__ = __str__ |
814
|
|
|
|
815
|
1 |
|
def __eq__(self, other): |
816
|
1 |
|
return self.value == other.value |
817
|
|
|
|
818
|
|
|
|
819
|
1 |
|
class Variant(FrozenClass): |
820
|
|
|
|
821
|
|
|
""" |
822
|
|
|
Create an OPC-UA Variant object. |
823
|
|
|
if no argument a Null Variant is created. |
824
|
|
|
if not variant type is given, attemps to guess type from python type |
825
|
|
|
if a variant is given as value, the new objects becomes a copy of the argument |
826
|
|
|
|
827
|
|
|
:ivar Value: |
828
|
|
|
:vartype Value: Any supported type |
829
|
|
|
:ivar VariantType: |
830
|
|
|
:vartype VariantType: VariantType |
831
|
|
|
""" |
832
|
|
|
|
833
|
1 |
|
def __init__(self, value=None, varianttype=None, dimensions=None): |
834
|
1 |
|
self.Value = value |
835
|
1 |
|
self.VariantType = varianttype |
836
|
1 |
|
self.Dimensions = dimensions |
837
|
1 |
|
self._freeze = True |
838
|
1 |
|
if isinstance(value, Variant): |
839
|
1 |
|
self.Value = value.Value |
840
|
1 |
|
self.VariantType = value.VariantType |
841
|
1 |
|
if self.VariantType is None: |
842
|
1 |
|
self.VariantType = self._guess_type(self.Value) |
843
|
1 |
|
if self.Dimensions is None and type(self.Value) in (list, tuple): |
844
|
1 |
|
dims = get_shape(self.Value) |
845
|
1 |
|
if len(dims) > 1: |
846
|
1 |
|
self.Dimensions = dims |
847
|
|
|
|
848
|
1 |
|
def __eq__(self, other): |
849
|
1 |
|
if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value: |
850
|
1 |
|
return True |
851
|
1 |
|
return False |
852
|
|
|
|
853
|
1 |
|
def __ne__(self, other): |
854
|
1 |
|
return not self.__eq__(other) |
855
|
|
|
|
856
|
1 |
|
def _guess_type(self, val): |
857
|
1 |
|
while isinstance(val, (list, tuple)): |
858
|
1 |
|
if len(val) == 0: |
859
|
|
|
raise UaError("could not guess UA variable type") |
860
|
1 |
|
val = val[0] |
861
|
1 |
|
if val is None: |
862
|
1 |
|
return VariantType.Null |
863
|
1 |
|
elif isinstance(val, bool): |
864
|
1 |
|
return VariantType.Boolean |
865
|
1 |
|
elif isinstance(val, float): |
866
|
1 |
|
return VariantType.Double |
867
|
1 |
|
elif isinstance(val, int): |
868
|
1 |
|
return VariantType.Int64 |
869
|
1 |
|
elif type(val) in (str, unicode): |
870
|
1 |
|
return VariantType.String |
871
|
1 |
|
elif isinstance(val, bytes): |
872
|
1 |
|
return VariantType.ByteString |
873
|
1 |
|
elif isinstance(val, datetime): |
874
|
1 |
|
return VariantType.DateTime |
875
|
|
|
else: |
876
|
1 |
|
if isinstance(val, object): |
877
|
1 |
|
try: |
878
|
1 |
|
return getattr(VariantType, val.__class__.__name__) |
879
|
1 |
|
except AttributeError: |
880
|
1 |
|
return VariantType.ExtensionObject |
881
|
|
|
else: |
882
|
|
|
raise UaError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val))) |
883
|
|
|
|
884
|
1 |
|
def __str__(self): |
885
|
1 |
|
return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType) |
886
|
1 |
|
__repr__ = __str__ |
887
|
|
|
|
888
|
1 |
|
def to_binary(self): |
889
|
1 |
|
b = [] |
890
|
1 |
|
encoding = self.VariantType.value & 0b111111 |
891
|
1 |
|
if type(self.Value) in (list, tuple): |
892
|
1 |
|
if self.Dimensions is not None: |
893
|
1 |
|
encoding = set_bit(encoding, 6) |
894
|
1 |
|
encoding = set_bit(encoding, 7) |
895
|
1 |
|
b.append(uatype_UInt8.pack(encoding)) |
896
|
1 |
|
b.append(pack_uatype_array(self.VariantType.name, flatten(self.Value))) |
897
|
1 |
|
if self.Dimensions is not None: |
898
|
1 |
|
b.append(pack_uatype_array("Int32", self.Dimensions)) |
899
|
|
|
else: |
900
|
1 |
|
b.append(uatype_UInt8.pack(encoding)) |
901
|
1 |
|
b.append(pack_uatype(self.VariantType.name, self.Value)) |
902
|
|
|
|
903
|
1 |
|
return b"".join(b) |
904
|
|
|
|
905
|
1 |
|
@staticmethod |
906
|
|
|
def from_binary(data): |
907
|
1 |
|
dimensions = None |
908
|
1 |
|
encoding = ord(data.read(1)) |
909
|
1 |
|
int_type = encoding & 0b00111111 |
910
|
1 |
|
if int_type > 25: |
911
|
1 |
|
vtype = VariantTypeCustom(int_type) |
912
|
|
|
else: |
913
|
1 |
|
vtype = VariantType(int_type) |
914
|
1 |
|
if vtype == VariantType.Null: |
915
|
1 |
|
return Variant(None, vtype, encoding) |
916
|
1 |
|
if test_bit(encoding, 7): |
917
|
1 |
|
value = unpack_uatype_array(vtype.name, data) |
918
|
|
|
else: |
919
|
1 |
|
value = unpack_uatype(vtype.name, data) |
920
|
1 |
|
if test_bit(encoding, 6): |
921
|
1 |
|
dimensions = unpack_uatype_array("Int32", data) |
922
|
1 |
|
value = reshape(value, dimensions) |
923
|
|
|
|
924
|
1 |
|
return Variant(value, vtype, dimensions) |
925
|
|
|
|
926
|
|
|
|
927
|
1 |
|
def reshape(flat, dims): |
928
|
1 |
|
subdims = dims[1:] |
929
|
1 |
|
subsize = 1 |
930
|
1 |
|
for i in subdims: |
931
|
1 |
|
if i == 0: |
932
|
1 |
|
i = 1 |
933
|
1 |
|
subsize *= i |
934
|
1 |
|
while dims[0] * subsize > len(flat): |
935
|
1 |
|
flat.append([]) |
936
|
1 |
|
if not subdims or subdims == [0]: |
937
|
1 |
|
return flat |
938
|
1 |
|
return [reshape(flat[i: i + subsize], subdims) for i in range(0, len(flat), subsize)] |
939
|
|
|
|
940
|
|
|
|
941
|
1 |
|
def _split_list(l, n): |
942
|
|
|
n = max(1, n) |
943
|
|
|
return [l[i:i + n] for i in range(0, len(l), n)] |
944
|
|
|
|
945
|
|
|
|
946
|
1 |
|
def flatten_and_get_shape(mylist): |
947
|
|
|
dims = [] |
948
|
|
|
dims.append(len(mylist)) |
949
|
|
|
while isinstance(mylist[0], (list, tuple)): |
950
|
|
|
dims.append(len(mylist[0])) |
951
|
|
|
mylist = [item for sublist in mylist for item in sublist] |
952
|
|
|
if len(mylist) == 0: |
953
|
|
|
break |
954
|
|
|
return mylist, dims |
955
|
|
|
|
956
|
|
|
|
957
|
1 |
|
def flatten(mylist): |
958
|
1 |
|
if len(mylist) == 0: |
959
|
1 |
|
return mylist |
960
|
1 |
|
while isinstance(mylist[0], (list, tuple)): |
961
|
1 |
|
mylist = [item for sublist in mylist for item in sublist] |
962
|
1 |
|
if len(mylist) == 0: |
963
|
1 |
|
break |
964
|
1 |
|
return mylist |
965
|
|
|
|
966
|
|
|
|
967
|
1 |
|
def get_shape(mylist): |
968
|
1 |
|
dims = [] |
969
|
1 |
|
while isinstance(mylist, (list, tuple)): |
970
|
1 |
|
dims.append(len(mylist)) |
971
|
1 |
|
if len(mylist) == 0: |
972
|
1 |
|
break |
973
|
1 |
|
mylist = mylist[0] |
974
|
1 |
|
return dims |
975
|
|
|
|
976
|
|
|
|
977
|
1 |
|
class XmlElement(FrozenClass): |
978
|
|
|
''' |
979
|
|
|
An XML element encoded as an UTF-8 string. |
980
|
|
|
''' |
981
|
1 |
|
def __init__(self, binary=None): |
982
|
|
|
if binary is not None: |
983
|
|
|
self._binary_init(binary) |
984
|
|
|
self._freeze = True |
985
|
|
|
return |
986
|
|
|
self.Value = [] |
987
|
|
|
self._freeze = True |
988
|
|
|
|
989
|
1 |
|
def to_binary(self): |
990
|
|
|
return pack_string(self.Value) |
991
|
|
|
|
992
|
1 |
|
@staticmethod |
993
|
|
|
def from_binary(data): |
994
|
|
|
return XmlElement(data) |
995
|
|
|
|
996
|
1 |
|
def _binary_init(self, data): |
997
|
|
|
self.Value = unpack_string(data) |
998
|
|
|
|
999
|
1 |
|
def __str__(self): |
1000
|
|
|
return 'XmlElement(Value:' + str(self.Value) + ')' |
1001
|
|
|
|
1002
|
1 |
|
__repr__ = __str__ |
1003
|
|
|
|
1004
|
|
|
|
1005
|
|
|
|
1006
|
|
|
|
1007
|
1 |
|
class DataValue(FrozenClass): |
1008
|
|
|
|
1009
|
|
|
''' |
1010
|
|
|
A value with an associated timestamp, and quality. |
1011
|
|
|
Automatically generated from xml , copied and modified here to fix errors in xml spec |
1012
|
|
|
|
1013
|
|
|
:ivar Value: |
1014
|
|
|
:vartype Value: Variant |
1015
|
|
|
:ivar StatusCode: |
1016
|
|
|
:vartype StatusCode: StatusCode |
1017
|
|
|
:ivar SourceTimestamp: |
1018
|
|
|
:vartype SourceTimestamp: datetime |
1019
|
|
|
:ivar SourcePicoSeconds: |
1020
|
|
|
:vartype SourcePicoSeconds: int |
1021
|
|
|
:ivar ServerTimestamp: |
1022
|
|
|
:vartype ServerTimestamp: datetime |
1023
|
|
|
:ivar ServerPicoseconds: |
1024
|
|
|
:vartype ServerPicoseconds: int |
1025
|
|
|
|
1026
|
|
|
''' |
1027
|
|
|
|
1028
|
1 |
|
def __init__(self, variant=None, status=None): |
1029
|
1 |
|
self.Encoding = 0 |
1030
|
1 |
|
if not isinstance(variant, Variant): |
1031
|
1 |
|
variant = Variant(variant) |
1032
|
1 |
|
self.Value = variant |
1033
|
1 |
|
if status is None: |
1034
|
1 |
|
self.StatusCode = StatusCode() |
1035
|
|
|
else: |
1036
|
1 |
|
self.StatusCode = status |
1037
|
1 |
|
self.SourceTimestamp = None # DateTime() |
1038
|
1 |
|
self.SourcePicoseconds = None |
1039
|
1 |
|
self.ServerTimestamp = None # DateTime() |
1040
|
1 |
|
self.ServerPicoseconds = None |
1041
|
1 |
|
self._freeze = True |
1042
|
|
|
|
1043
|
1 |
|
def to_binary(self): |
1044
|
1 |
|
packet = [] |
1045
|
1 |
|
if self.Value: |
1046
|
1 |
|
self.Encoding |= (1 << 0) |
1047
|
1 |
|
if self.StatusCode: |
1048
|
1 |
|
self.Encoding |= (1 << 1) |
1049
|
1 |
|
if self.SourceTimestamp: |
1050
|
1 |
|
self.Encoding |= (1 << 2) |
1051
|
1 |
|
if self.ServerTimestamp: |
1052
|
1 |
|
self.Encoding |= (1 << 3) |
1053
|
1 |
|
if self.SourcePicoseconds: |
1054
|
|
|
self.Encoding |= (1 << 4) |
1055
|
1 |
|
if self.ServerPicoseconds: |
1056
|
|
|
self.Encoding |= (1 << 5) |
1057
|
1 |
|
packet.append(uatype_UInt8.pack(self.Encoding)) |
1058
|
1 |
|
if self.Value: |
1059
|
1 |
|
packet.append(self.Value.to_binary()) |
1060
|
1 |
|
if self.StatusCode: |
1061
|
1 |
|
packet.append(self.StatusCode.to_binary()) |
1062
|
1 |
|
if self.SourceTimestamp: |
1063
|
1 |
|
packet.append(pack_datetime(self.SourceTimestamp)) # self.SourceTimestamp.to_binary()) |
1064
|
1 |
|
if self.ServerTimestamp: |
1065
|
1 |
|
packet.append(pack_datetime(self.ServerTimestamp)) # self.ServerTimestamp.to_binary()) |
1066
|
1 |
|
if self.SourcePicoseconds: |
1067
|
|
|
packet.append(uatype_UInt16.pack(self.SourcePicoseconds)) |
1068
|
1 |
|
if self.ServerPicoseconds: |
1069
|
|
|
packet.append(uatype_UInt16.pack(self.ServerPicoseconds)) |
1070
|
1 |
|
return b''.join(packet) |
1071
|
|
|
|
1072
|
1 |
|
@staticmethod |
1073
|
|
|
def from_binary(data): |
1074
|
1 |
|
encoding = ord(data.read(1)) |
1075
|
1 |
|
if encoding & (1 << 0): |
1076
|
1 |
|
value = Variant.from_binary(data) |
1077
|
|
|
else: |
1078
|
|
|
value = None |
1079
|
1 |
|
if encoding & (1 << 1): |
1080
|
1 |
|
status = StatusCode.from_binary(data) |
1081
|
|
|
else: |
1082
|
|
|
status = None |
1083
|
1 |
|
obj = DataValue(value, status) |
1084
|
1 |
|
obj.Encoding = encoding |
1085
|
1 |
|
if obj.Encoding & (1 << 2): |
1086
|
1 |
|
obj.SourceTimestamp = unpack_datetime(data) # DateTime.from_binary(data) |
1087
|
1 |
|
if obj.Encoding & (1 << 3): |
1088
|
1 |
|
obj.ServerTimestamp = unpack_datetime(data) # DateTime.from_binary(data) |
1089
|
1 |
|
if obj.Encoding & (1 << 4): |
1090
|
|
|
obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0] |
1091
|
1 |
|
if obj.Encoding & (1 << 5): |
1092
|
|
|
obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0] |
1093
|
1 |
|
return obj |
1094
|
|
|
|
1095
|
1 |
|
def __str__(self): |
1096
|
|
|
s = 'DataValue(Value:{}'.format(self.Value) |
1097
|
|
|
if self.StatusCode is not None: |
1098
|
|
|
s += ', StatusCode:{}'.format(self.StatusCode) |
1099
|
|
|
if self.SourceTimestamp is not None: |
1100
|
|
|
s += ', SourceTimestamp:{}'.format(self.SourceTimestamp) |
1101
|
|
|
if self.ServerTimestamp is not None: |
1102
|
|
|
s += ', ServerTimestamp:{}'.format(self.ServerTimestamp) |
1103
|
|
|
if self.SourcePicoseconds is not None: |
1104
|
|
|
s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds) |
1105
|
|
|
if self.ServerPicoseconds is not None: |
1106
|
|
|
s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds) |
1107
|
|
|
s += ')' |
1108
|
|
|
return s |
1109
|
|
|
|
1110
|
1 |
|
__repr__ = __str__ |
1111
|
|
|
|
1112
|
|
|
|
1113
|
1 |
|
# TODO: This should be autogeneratd form XML description of EventTypes |
1114
|
|
|
class BaseEvent(FrozenClass): |
1115
|
|
|
|
1116
|
1 |
|
''' |
1117
|
|
|
BaseEvent implements BaseEventType from which inherit all other events and it is used per default. |
1118
|
1 |
|
|
1119
|
1 |
|
''' |
1120
|
|
|
|
1121
|
|
|
def __init__(self, sourcenode=NodeId(), message=None, severity=1): |
1122
|
|
|
self.EventId = bytes() |
1123
|
|
|
self.EventType = NodeId(ObjectIds.BaseEventType) |
1124
|
|
|
self.SourceNode = sourcenode |
1125
|
|
|
self.SourceName = None |
1126
|
|
|
self.Time = None |
1127
|
|
|
self.RecieveTime = None |
1128
|
|
|
self.LocalTime = None |
1129
|
|
|
self.Message = LocalizedText(message) |
1130
|
|
|
self.Severity = Variant(severity, VariantType.UInt16) |
1131
|
|
|
# FIXME: Should be frozen but for now is not because of asigning parameters |
1132
|
|
|
#self._freeze = True |
1133
|
|
|
|
1134
|
|
|
def __str__(self): |
1135
|
|
|
s = 'BaseEventType(EventId:{}'.format(self.EventId) |
1136
|
|
|
s += ', EventType:{}'.format(self.EventType) |
1137
|
|
|
s += ', SourceNode:{}'.format(self.SourceNode) |
1138
|
|
|
s += ', SourceName:{}'.format(self.SourceName) |
1139
|
|
|
s += ', Time:{}'.format(self.Time) |
1140
|
|
|
s += ', RecieveTime:{}'.format(self.RecieveTime) |
1141
|
|
|
s += ', LocalTime:{}'.format(self.LocalTime) |
1142
|
|
|
s += ', Message:{}'.format(self.Message) |
1143
|
|
|
s += ', Severity:{}'.format(self.Severity) |
1144
|
|
|
s += ')' |
1145
|
|
|
return s |
1146
|
|
|
__repr__ = __str__ |
1147
|
|
|
|
1148
|
|
|
|
1149
|
|
|
__nodeid_counter = 2000 |
1150
|
|
|
|
1151
|
|
|
|
1152
|
|
|
def generate_nodeid(idx): |
1153
|
|
|
global __nodeid_counter |
1154
|
|
|
__nodeid_counter += 1 |
1155
|
|
|
return NodeId(__nodeid_counter, idx) |
1156
|
|
|
|