1
|
|
|
""" |
2
|
|
|
implement ua datatypes |
3
|
|
|
""" |
4
|
1 |
|
import logging |
5
|
1 |
|
from enum import Enum |
6
|
1 |
|
from datetime import datetime, timedelta, tzinfo |
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
|
|
|
|
17
|
|
|
|
18
|
1 |
|
logger = logging.getLogger('opcua.uaprotocol') |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
# types that will packed and unpacked directly using struct (string, bytes and datetime are handles as special cases |
22
|
1 |
|
UaTypes = ("Boolean", "SByte", "Byte", "Int8", "UInt8", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Float", "Double") |
23
|
|
|
|
24
|
|
|
|
25
|
1 |
|
EPOCH_AS_FILETIME = 116444736000000000 # January 1, 1970 as MS file time |
26
|
1 |
|
HUNDREDS_OF_NANOSECONDS = 10000000 |
27
|
1 |
|
FILETIME_EPOCH_AS_DATETIME = datetime(1601, 1, 1) |
28
|
|
|
|
29
|
|
|
|
30
|
1 |
|
class UAError(RuntimeError): |
31
|
1 |
|
pass |
32
|
|
|
|
33
|
|
|
|
34
|
1 |
|
class UTC(tzinfo): |
35
|
|
|
|
36
|
|
|
"""UTC""" |
37
|
|
|
|
38
|
1 |
|
def utcoffset(self, dt): |
39
|
|
|
return timedelta(0) |
40
|
|
|
|
41
|
1 |
|
def tzname(self, dt): |
42
|
|
|
return "UTC" |
43
|
|
|
|
44
|
1 |
|
def dst(self, dt): |
45
|
1 |
|
return timedelta(0) |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
# method copied from David Buxton <[email protected]> sample code |
49
|
1 |
|
def datetime_to_win_epoch(dt): |
50
|
1 |
|
if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None): |
51
|
1 |
|
dt = dt.replace(tzinfo=UTC()) |
52
|
1 |
|
ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS) |
53
|
1 |
|
return ft + (dt.microsecond * 10) |
54
|
|
|
|
55
|
|
|
|
56
|
1 |
|
def win_epoch_to_datetime(epch): |
57
|
1 |
|
return FILETIME_EPOCH_AS_DATETIME + timedelta(microseconds=epch // 10) |
58
|
|
|
|
59
|
|
|
|
60
|
1 |
|
def build_array_format_py2(prefix, length, fmtchar): |
61
|
|
|
return prefix + str(length) + fmtchar |
62
|
|
|
|
63
|
|
|
|
64
|
1 |
|
def build_array_format_py3(prefix, length, fmtchar): |
65
|
1 |
|
return prefix + str(length) + chr(fmtchar) |
66
|
|
|
|
67
|
|
|
|
68
|
1 |
|
if sys.version_info.major < 3: |
69
|
|
|
build_array_format = build_array_format_py2 |
70
|
|
|
else: |
71
|
1 |
|
build_array_format = build_array_format_py3 |
72
|
|
|
|
73
|
|
|
|
74
|
1 |
|
def pack_uatype_array_primitive(st, value, length): |
75
|
1 |
|
if length == 1: |
76
|
1 |
|
return b'\x01\x00\x00\x00' + st.pack(value[0]) |
77
|
|
|
else: |
78
|
1 |
|
return struct.pack(build_array_format("<i", length, st.format[1]), length, *value) |
79
|
|
|
|
80
|
|
|
|
81
|
1 |
|
def pack_uatype_array(uatype, value): |
82
|
1 |
|
if value is None: |
83
|
|
|
return b'\xff\xff\xff\xff' |
84
|
1 |
|
length = len(value) |
85
|
1 |
|
if length == 0: |
86
|
|
|
return b'\x00\x00\x00\x00' |
87
|
1 |
|
if uatype in uatype2struct: |
88
|
1 |
|
return pack_uatype_array_primitive(uatype2struct[uatype], value, length) |
89
|
1 |
|
b = [] |
90
|
1 |
|
b.append(uatype_Int32.pack(length)) |
91
|
1 |
|
for val in value: |
92
|
1 |
|
b.append(pack_uatype(uatype, val)) |
93
|
1 |
|
return b"".join(b) |
94
|
|
|
|
95
|
|
|
|
96
|
1 |
|
def pack_uatype(uatype, value): |
97
|
1 |
|
if uatype in uatype2struct: |
98
|
1 |
|
return uatype2struct[uatype].pack(value) |
99
|
1 |
|
elif uatype == "Null": |
100
|
1 |
|
return b'' |
101
|
1 |
|
elif uatype == "String": |
102
|
1 |
|
return pack_string(value) |
103
|
1 |
|
elif uatype in ("CharArray", "ByteString"): |
104
|
1 |
|
return pack_bytes(value) |
105
|
1 |
|
elif uatype == "DateTime": |
106
|
1 |
|
return pack_datetime(value) |
107
|
1 |
|
elif uatype == "ExtensionObject": |
108
|
|
|
# dependency loop: classes in uaprotocol_auto use Variant defined in this file, |
109
|
|
|
# but Variant can contain any object from uaprotocol_auto as ExtensionObject. |
110
|
|
|
# Using local import to avoid import loop |
111
|
1 |
|
from opcua.ua.uaprotocol_auto import extensionobject_to_binary |
112
|
1 |
|
return extensionobject_to_binary(value) |
113
|
|
|
else: |
114
|
1 |
|
return value.to_binary() |
115
|
|
|
|
116
|
1 |
|
uatype_Int8 = struct.Struct("<b") |
117
|
1 |
|
uatype_SByte = uatype_Int8 |
118
|
1 |
|
uatype_Int16 = struct.Struct("<h") |
119
|
1 |
|
uatype_Int32 = struct.Struct("<i") |
120
|
1 |
|
uatype_Int64 = struct.Struct("<q") |
121
|
1 |
|
uatype_UInt8 = struct.Struct("<B") |
122
|
1 |
|
uatype_Char = uatype_UInt8 |
123
|
1 |
|
uatype_Byte = uatype_UInt8 |
124
|
1 |
|
uatype_UInt16 = struct.Struct("<H") |
125
|
1 |
|
uatype_UInt32 = struct.Struct("<I") |
126
|
1 |
|
uatype_UInt64 = struct.Struct("<Q") |
127
|
1 |
|
uatype_Boolean = struct.Struct("<?") |
128
|
1 |
|
uatype_Double = struct.Struct("<d") |
129
|
1 |
|
uatype_Float = struct.Struct("<f") |
130
|
|
|
|
131
|
1 |
|
uatype2struct = { |
132
|
|
|
"Int8": uatype_Int8, |
133
|
|
|
"SByte": uatype_SByte, |
134
|
|
|
"Int16": uatype_Int16, |
135
|
|
|
"Int32": uatype_Int32, |
136
|
|
|
"Int64": uatype_Int64, |
137
|
|
|
"UInt8": uatype_UInt8, |
138
|
|
|
"Char": uatype_Char, |
139
|
|
|
"Byte": uatype_Byte, |
140
|
|
|
"UInt16": uatype_UInt16, |
141
|
|
|
"UInt32": uatype_UInt32, |
142
|
|
|
"UInt64": uatype_UInt64, |
143
|
|
|
"Boolean": uatype_Boolean, |
144
|
|
|
"Double": uatype_Double, |
145
|
|
|
"Float": uatype_Float, |
146
|
|
|
} |
147
|
|
|
|
148
|
|
|
|
149
|
1 |
|
def unpack_uatype(uatype, data): |
150
|
1 |
|
if uatype in uatype2struct: |
151
|
1 |
|
st = uatype2struct[uatype] |
152
|
1 |
|
return st.unpack(data.read(st.size))[0] |
153
|
1 |
|
elif uatype == "String": |
154
|
1 |
|
return unpack_string(data) |
155
|
1 |
|
elif uatype in ("CharArray", "ByteString"): |
156
|
1 |
|
return unpack_bytes(data) |
157
|
1 |
|
elif uatype == "DateTime": |
158
|
1 |
|
return unpack_datetime(data) |
159
|
1 |
|
elif uatype == "ExtensionObject": |
160
|
|
|
# dependency loop: classes in uaprotocol_auto use Variant defined in this file, |
161
|
|
|
# but Variant can contain any object from uaprotocol_auto as ExtensionObject. |
162
|
|
|
# Using local import to avoid import loop |
163
|
1 |
|
from opcua.ua.uaprotocol_auto import extensionobject_from_binary |
164
|
1 |
|
return extensionobject_from_binary(data) |
165
|
|
|
else: |
166
|
1 |
|
glbs = globals() |
167
|
1 |
|
if uatype in glbs: |
168
|
1 |
|
klass = glbs[uatype] |
169
|
1 |
|
if hasattr(klass, 'from_binary'): |
170
|
1 |
|
return klass.from_binary(data) |
171
|
|
|
raise UAError("can not unpack unknown uatype %s" % uatype) |
172
|
|
|
|
173
|
|
|
|
174
|
1 |
|
def unpack_uatype_array(uatype, data): |
175
|
1 |
|
length = uatype_Int32.unpack(data.read(4))[0] |
176
|
1 |
|
if length == -1: |
177
|
|
|
return None |
178
|
1 |
|
elif length == 0: |
179
|
1 |
|
return [] |
180
|
1 |
|
elif uatype in uatype2struct: |
181
|
1 |
|
st = uatype2struct[uatype] |
182
|
1 |
|
if length == 1: |
183
|
1 |
|
return list(st.unpack(data.read(st.size))) |
184
|
|
|
else: |
185
|
1 |
|
arrst = struct.Struct(build_array_format("<", length, st.format[1])) |
186
|
1 |
|
return list(arrst.unpack(data.read(arrst.size))) |
187
|
|
|
else: |
188
|
1 |
|
result = [] |
189
|
1 |
|
for _ in range(0, length): |
190
|
1 |
|
result.append(unpack_uatype(uatype, data)) |
191
|
1 |
|
return result |
192
|
|
|
|
193
|
|
|
|
194
|
1 |
|
def pack_datetime(value): |
195
|
1 |
|
epch = datetime_to_win_epoch(value) |
196
|
1 |
|
return uatype_Int64.pack(epch) |
197
|
|
|
|
198
|
|
|
|
199
|
1 |
|
def unpack_datetime(data): |
200
|
1 |
|
epch = uatype_Int64.unpack(data.read(8))[0] |
201
|
1 |
|
return win_epoch_to_datetime(epch) |
202
|
|
|
|
203
|
|
|
|
204
|
1 |
|
def pack_string(string): |
205
|
1 |
|
if type(string) is unicode: |
206
|
1 |
|
string = string.encode('utf-8') |
207
|
1 |
|
length = len(string) |
208
|
1 |
|
if length == 0: |
209
|
1 |
|
return b'\xff\xff\xff\xff' |
210
|
1 |
|
return uatype_Int32.pack(length) + string |
211
|
|
|
|
212
|
1 |
|
pack_bytes = pack_string |
213
|
|
|
|
214
|
|
|
|
215
|
1 |
|
def unpack_bytes(data): |
216
|
1 |
|
length = uatype_Int32.unpack(data.read(4))[0] |
217
|
1 |
|
if length == -1: |
218
|
1 |
|
return b'' |
219
|
1 |
|
return data.read(length) |
220
|
|
|
|
221
|
|
|
|
222
|
1 |
|
def py3_unpack_string(data): |
223
|
1 |
|
b = unpack_bytes(data) |
224
|
1 |
|
return b.decode("utf-8") |
225
|
|
|
|
226
|
|
|
|
227
|
1 |
|
if sys.version_info.major < 3: |
228
|
|
|
unpack_string = unpack_bytes |
229
|
|
|
else: |
230
|
1 |
|
unpack_string = py3_unpack_string |
231
|
|
|
|
232
|
|
|
|
233
|
1 |
|
def test_bit(data, offset): |
234
|
1 |
|
mask = 1 << offset |
235
|
1 |
|
return data & mask |
236
|
|
|
|
237
|
|
|
|
238
|
1 |
|
def set_bit(data, offset): |
239
|
|
|
mask = 1 << offset |
240
|
|
|
return data | mask |
241
|
|
|
|
242
|
|
|
|
243
|
1 |
|
class _FrozenClass(object): |
244
|
|
|
|
245
|
|
|
""" |
246
|
|
|
make it impossible to add members to a class. |
247
|
|
|
This is a hack since I found out that most bugs are due to misspelling a variable in protocol |
248
|
|
|
""" |
249
|
1 |
|
_freeze = False |
250
|
|
|
|
251
|
1 |
|
def __setattr__(self, key, value): |
252
|
1 |
|
if self._freeze and not hasattr(self, key): |
253
|
|
|
raise TypeError("Error adding member '{}' to class '{}', class is frozen, members are {}".format(key, self.__class__.__name__, self.__dict__.keys())) |
254
|
1 |
|
object.__setattr__(self, key, value) |
255
|
|
|
|
256
|
1 |
|
if "PYOPCUA_NO_TYPO_CHECK" in os.environ: |
257
|
|
|
# typo check is cpu consuming, but it will make debug easy. |
258
|
|
|
# if typo check is not need (in production), please set env PYOPCUA_NO_TYPO_CHECK. |
259
|
|
|
# this will make all uatype class inherit from object intead of _FrozenClass |
260
|
|
|
# and skip the typo check. |
261
|
|
|
FrozenClass = object |
262
|
|
|
else: |
263
|
1 |
|
FrozenClass = _FrozenClass |
264
|
|
|
|
265
|
|
|
|
266
|
1 |
|
class Guid(FrozenClass): |
267
|
|
|
|
268
|
1 |
|
def __init__(self): |
269
|
1 |
|
self.uuid = uuid.uuid4() |
270
|
1 |
|
self._freeze = True |
271
|
|
|
|
272
|
1 |
|
def to_binary(self): |
273
|
1 |
|
return self.uuid.bytes |
274
|
|
|
|
275
|
1 |
|
@staticmethod |
276
|
|
|
def from_binary(data): |
277
|
1 |
|
g = Guid() |
278
|
1 |
|
g.uuid = uuid.UUID(bytes=data.read(16)) |
279
|
1 |
|
return g |
280
|
|
|
|
281
|
1 |
|
def __eq__(self, other): |
282
|
1 |
|
return isinstance(other, Guid) and self.uuid == other.uuid |
283
|
|
|
|
284
|
|
|
|
285
|
1 |
|
class StatusCode(FrozenClass): |
286
|
|
|
|
287
|
|
|
""" |
288
|
|
|
:ivar value: |
289
|
|
|
:vartype value: int |
290
|
|
|
:ivar name: |
291
|
|
|
:vartype name: string |
292
|
|
|
:ivar doc: |
293
|
|
|
:vartype doc: string |
294
|
|
|
""" |
295
|
|
|
|
296
|
1 |
|
def __init__(self, value=0): |
297
|
1 |
|
self.value = value |
298
|
1 |
|
self.name, self.doc = status_codes.get_name_and_doc(value) |
299
|
1 |
|
self._freeze = True |
300
|
|
|
|
301
|
1 |
|
def to_binary(self): |
302
|
1 |
|
return uatype_UInt32.pack(self.value) |
303
|
|
|
|
304
|
1 |
|
@staticmethod |
305
|
|
|
def from_binary(data): |
306
|
1 |
|
val = uatype_UInt32.unpack(data.read(4))[0] |
307
|
1 |
|
sc = StatusCode(val) |
308
|
1 |
|
return sc |
309
|
|
|
|
310
|
1 |
|
def check(self): |
311
|
|
|
""" |
312
|
|
|
raise en exception if status code is anything else than 0 |
313
|
|
|
use is is_good() method if not exception is desired |
314
|
|
|
""" |
315
|
1 |
|
if self.value != 0: |
316
|
1 |
|
raise UAError("{}({})".format(self.doc, self.name)) |
317
|
|
|
|
318
|
1 |
|
def is_good(self): |
319
|
|
|
""" |
320
|
|
|
return True if status is Good. |
321
|
|
|
""" |
322
|
1 |
|
if self.value == 0: |
323
|
1 |
|
return True |
324
|
1 |
|
return False |
325
|
|
|
|
326
|
1 |
|
def __str__(self): |
327
|
|
|
return 'StatusCode({})'.format(self.name) |
328
|
1 |
|
__repr__ = __str__ |
329
|
|
|
|
330
|
|
|
|
331
|
1 |
|
class NodeIdType(object): |
332
|
1 |
|
TwoByte = 0 |
333
|
1 |
|
FourByte = 1 |
334
|
1 |
|
Numeric = 2 |
335
|
1 |
|
String = 3 |
336
|
1 |
|
Guid = 4 |
337
|
1 |
|
ByteString = 5 |
338
|
|
|
|
339
|
|
|
|
340
|
1 |
|
class NodeId(FrozenClass): |
341
|
|
|
|
342
|
|
|
""" |
343
|
|
|
NodeId Object |
344
|
|
|
|
345
|
|
|
Args: |
346
|
|
|
identifier: The identifier might be an int, a string, bytes or a Guid |
347
|
|
|
namespaceidx(int): The index of the namespace |
348
|
|
|
nodeidtype(NodeIdType): The type of the nodeid if it cannor be guess or you want something special like twobyte nodeid or fourbytenodeid |
349
|
|
|
|
350
|
|
|
|
351
|
|
|
:ivar Identifier: |
352
|
|
|
:vartype Identifier: NodeId |
353
|
|
|
:ivar NamespaceIndex: |
354
|
|
|
:vartype NamespaceIndex: Int |
355
|
|
|
:ivar NamespaceUri: |
356
|
|
|
:vartype NamespaceUri: String |
357
|
|
|
:ivar ServerIndex: |
358
|
|
|
:vartype ServerIndex: Int |
359
|
|
|
""" |
360
|
|
|
|
361
|
1 |
|
def __init__(self, identifier=None, namespaceidx=0, nodeidtype=None): |
362
|
1 |
|
self.Identifier = identifier |
363
|
1 |
|
self.NamespaceIndex = namespaceidx |
364
|
1 |
|
self.NodeIdType = nodeidtype |
365
|
1 |
|
self.NamespaceUri = "" |
366
|
1 |
|
self.ServerIndex = 0 |
367
|
1 |
|
self._freeze = True |
368
|
1 |
|
if self.Identifier is None: |
369
|
1 |
|
self.Identifier = 0 |
370
|
1 |
|
self.NodeIdType = NodeIdType.TwoByte |
371
|
1 |
|
return |
372
|
1 |
|
if self.NodeIdType is None: |
373
|
1 |
|
if isinstance(self.Identifier, int): |
374
|
1 |
|
self.NodeIdType = NodeIdType.Numeric |
375
|
1 |
|
elif isinstance(self.Identifier, str): |
376
|
1 |
|
self.NodeIdType = NodeIdType.String |
377
|
|
|
elif isinstance(self.Identifier, bytes): |
378
|
|
|
self.NodeIdType = NodeIdType.ByteString |
379
|
|
|
else: |
380
|
|
|
raise UAError("NodeId: Could not guess type of NodeId, set NodeIdType") |
381
|
|
|
|
382
|
1 |
|
def __key(self): |
383
|
1 |
|
if self.NodeIdType in (NodeIdType.TwoByte, NodeIdType.FourByte, NodeIdType.Numeric): # twobyte, fourbyte and numeric may represent the same node |
384
|
1 |
|
return self.NamespaceIndex, self.Identifier |
385
|
|
|
else: |
386
|
1 |
|
return self.NodeIdType, self.NamespaceIndex, self.Identifier |
387
|
|
|
|
388
|
1 |
|
def __eq__(self, node): |
389
|
1 |
|
return isinstance(node, NodeId) and self.__key() == node.__key() |
390
|
|
|
|
391
|
1 |
|
def __hash__(self): |
392
|
1 |
|
return hash(self.__key()) |
393
|
|
|
|
394
|
1 |
|
@staticmethod |
395
|
|
|
def from_string(string): |
396
|
1 |
|
l = string.split(";") |
397
|
1 |
|
identifier = None |
398
|
1 |
|
namespace = 0 |
399
|
1 |
|
ntype = None |
400
|
1 |
|
srv = None |
401
|
1 |
|
nsu = None |
402
|
1 |
|
for el in l: |
403
|
1 |
|
if not el: |
404
|
1 |
|
continue |
405
|
1 |
|
k, v = el.split("=") |
406
|
1 |
|
k = k.strip() |
407
|
1 |
|
v = v.strip() |
408
|
1 |
|
if k == "ns": |
409
|
1 |
|
namespace = int(v) |
410
|
1 |
|
elif k == "i": |
411
|
1 |
|
ntype = NodeIdType.Numeric |
412
|
1 |
|
identifier = int(v) |
413
|
1 |
|
elif k == "s": |
414
|
1 |
|
ntype = NodeIdType.String |
415
|
1 |
|
identifier = v |
416
|
1 |
|
elif k == "g": |
417
|
|
|
ntype = NodeIdType.Guid |
418
|
|
|
identifier = v |
419
|
1 |
|
elif k == "b": |
420
|
|
|
ntype = NodeIdType.ByteString |
421
|
|
|
identifier = v |
422
|
1 |
|
elif k == "srv": |
423
|
1 |
|
srv = v |
424
|
|
|
elif k == "nsu": |
425
|
|
|
nsu = v |
426
|
1 |
|
if identifier is None: |
427
|
|
|
raise UAError("Could not parse nodeid string: " + string) |
428
|
1 |
|
nodeid = NodeId(identifier, namespace, ntype) |
429
|
1 |
|
nodeid.NamespaceUri = nsu |
430
|
1 |
|
nodeid.ServerIndex = srv |
431
|
1 |
|
return nodeid |
432
|
|
|
|
433
|
1 |
|
def to_string(self): |
434
|
1 |
|
string = "" |
435
|
1 |
|
if self.NamespaceIndex != 0: |
436
|
1 |
|
string += "ns={};".format(self.NamespaceIndex) |
437
|
1 |
|
ntype = None |
438
|
1 |
|
if self.NodeIdType == NodeIdType.Numeric: |
439
|
|
|
ntype = "i" |
440
|
1 |
|
elif self.NodeIdType == NodeIdType.String: |
441
|
1 |
|
ntype = "s" |
442
|
1 |
|
elif self.NodeIdType == NodeIdType.TwoByte: |
443
|
1 |
|
ntype = "i" |
444
|
1 |
|
elif self.NodeIdType == NodeIdType.FourByte: |
445
|
1 |
|
ntype = "i" |
446
|
|
|
elif self.NodeIdType == NodeIdType.Guid: |
447
|
|
|
ntype = "g" |
448
|
|
|
elif self.NodeIdType == NodeIdType.ByteString: |
449
|
|
|
ntype = "b" |
450
|
1 |
|
string += "{}={}".format(ntype, self.Identifier) |
451
|
1 |
|
if self.ServerIndex: |
452
|
|
|
string = "srv=" + str(self.ServerIndex) + string |
453
|
1 |
|
if self.NamespaceUri: |
454
|
|
|
string += "nsu={}".format(self.NamespaceUri) |
455
|
1 |
|
return string |
456
|
|
|
|
457
|
1 |
|
def __str__(self): |
458
|
1 |
|
return "NodeId({})".format(self.to_string()) |
459
|
1 |
|
__repr__ = __str__ |
460
|
|
|
|
461
|
1 |
|
def to_binary(self): |
462
|
1 |
|
if self.NodeIdType == NodeIdType.TwoByte: |
463
|
1 |
|
return struct.pack("<BB", self.NodeIdType, self.Identifier) |
464
|
1 |
|
elif self.NodeIdType == NodeIdType.FourByte: |
465
|
1 |
|
return struct.pack("<BBH", self.NodeIdType, self.NamespaceIndex, self.Identifier) |
466
|
1 |
|
elif self.NodeIdType == NodeIdType.Numeric: |
467
|
1 |
|
return struct.pack("<BHI", self.NodeIdType, self.NamespaceIndex, self.Identifier) |
468
|
1 |
|
elif self.NodeIdType == NodeIdType.String: |
469
|
1 |
|
return struct.pack("<BH", self.NodeIdType, self.NamespaceIndex) + \ |
470
|
|
|
pack_string(self.Identifier) |
471
|
1 |
|
elif self.NodeIdType == NodeIdType.ByteString: |
472
|
1 |
|
return struct.pack("<BH", self.NodeIdType, self.NamespaceIndex) + \ |
473
|
|
|
pack_bytes(self.Identifier) |
474
|
|
|
else: |
475
|
1 |
|
return struct.pack("<BH", self.NodeIdType, self.NamespaceIndex) + \ |
476
|
|
|
self.Identifier.to_binary() |
477
|
|
|
|
478
|
1 |
|
@staticmethod |
479
|
|
|
def from_binary(data): |
480
|
1 |
|
nid = NodeId() |
481
|
1 |
|
encoding = ord(data.read(1)) |
482
|
1 |
|
nid.NodeIdType = encoding & 0b00111111 |
483
|
|
|
|
484
|
1 |
|
if nid.NodeIdType == NodeIdType.TwoByte: |
485
|
1 |
|
nid.Identifier = ord(data.read(1)) |
486
|
1 |
|
elif nid.NodeIdType == NodeIdType.FourByte: |
487
|
1 |
|
nid.NamespaceIndex, nid.Identifier = struct.unpack("<BH", data.read(3)) |
488
|
1 |
|
elif nid.NodeIdType == NodeIdType.Numeric: |
489
|
1 |
|
nid.NamespaceIndex, nid.Identifier = struct.unpack("<HI", data.read(6)) |
490
|
1 |
|
elif nid.NodeIdType == NodeIdType.String: |
491
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
492
|
1 |
|
nid.Identifier = unpack_string(data) |
493
|
1 |
|
elif nid.NodeIdType == NodeIdType.ByteString: |
494
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
495
|
1 |
|
nid.Identifier = unpack_bytes(data) |
496
|
1 |
|
elif nid.NodeIdType == NodeIdType.Guid: |
497
|
1 |
|
nid.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
498
|
1 |
|
nid.Identifier = Guid.from_binary(data) |
499
|
|
|
else: |
500
|
|
|
raise UAError("Unknown NodeId encoding: " + str(nid.NodeIdType)) |
501
|
|
|
|
502
|
1 |
|
if test_bit(encoding, 6): |
503
|
|
|
nid.NamespaceUri = unpack_string(data) |
504
|
1 |
|
if test_bit(encoding, 7): |
505
|
|
|
nid.ServerIndex = uatype_UInt32.unpack(data.read(4))[0] |
506
|
|
|
|
507
|
1 |
|
return nid |
508
|
|
|
|
509
|
|
|
|
510
|
1 |
|
class TwoByteNodeId(NodeId): |
511
|
|
|
|
512
|
1 |
|
def __init__(self, identifier): |
513
|
1 |
|
NodeId.__init__(self, identifier, 0, NodeIdType.TwoByte) |
514
|
|
|
|
515
|
|
|
|
516
|
1 |
|
class FourByteNodeId(NodeId): |
517
|
|
|
|
518
|
1 |
|
def __init__(self, identifier, namespace=0): |
519
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.FourByte) |
520
|
|
|
|
521
|
|
|
|
522
|
1 |
|
class NumericNodeId(NodeId): |
523
|
|
|
|
524
|
1 |
|
def __init__(self, identifier, namespace=0): |
525
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.Numeric) |
526
|
|
|
|
527
|
|
|
|
528
|
1 |
|
class ByteStringNodeId(NodeId): |
529
|
|
|
|
530
|
1 |
|
def __init__(self, identifier, namespace=0): |
531
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.ByteString) |
532
|
|
|
|
533
|
|
|
|
534
|
1 |
|
class GuidNodeId(NodeId): |
535
|
|
|
|
536
|
1 |
|
def __init__(self, identifier, namespace=0): |
537
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.Guid) |
538
|
|
|
|
539
|
|
|
|
540
|
1 |
|
class StringNodeId(NodeId): |
541
|
|
|
|
542
|
1 |
|
def __init__(self, identifier, namespace=0): |
543
|
1 |
|
NodeId.__init__(self, identifier, namespace, NodeIdType.String) |
544
|
|
|
|
545
|
|
|
|
546
|
1 |
|
ExpandedNodeId = NodeId |
547
|
|
|
|
548
|
|
|
|
549
|
1 |
|
class QualifiedName(FrozenClass): |
550
|
|
|
|
551
|
|
|
''' |
552
|
|
|
A string qualified with a namespace index. |
553
|
|
|
''' |
554
|
|
|
|
555
|
1 |
|
def __init__(self, name="", namespaceidx=0): |
556
|
1 |
|
self.NamespaceIndex = namespaceidx |
557
|
1 |
|
self.Name = name |
558
|
1 |
|
self._freeze = True |
559
|
|
|
|
560
|
1 |
|
def to_string(self): |
561
|
1 |
|
return "{}:{}".format(self.NamespaceIndex, self.Name) |
562
|
|
|
|
563
|
1 |
|
@staticmethod |
564
|
|
|
def from_string(string): |
565
|
1 |
|
if ":" in string: |
566
|
1 |
|
idx, name = string.split(":", 1) |
567
|
|
|
else: |
568
|
1 |
|
idx = 0 |
569
|
1 |
|
name = string |
570
|
1 |
|
return QualifiedName(name, int(idx)) |
571
|
|
|
|
572
|
1 |
|
def to_binary(self): |
573
|
1 |
|
packet = [] |
574
|
1 |
|
packet.append(uatype_UInt16.pack(self.NamespaceIndex)) |
575
|
1 |
|
packet.append(pack_string(self.Name)) |
576
|
1 |
|
return b''.join(packet) |
577
|
|
|
|
578
|
1 |
|
@staticmethod |
579
|
|
|
def from_binary(data): |
580
|
1 |
|
obj = QualifiedName() |
581
|
1 |
|
obj.NamespaceIndex = uatype_UInt16.unpack(data.read(2))[0] |
582
|
1 |
|
obj.Name = unpack_string(data) |
583
|
1 |
|
return obj |
584
|
|
|
|
585
|
1 |
|
def __eq__(self, bname): |
586
|
1 |
|
return isinstance(bname, QualifiedName) and self.Name == bname.Name and self.NamespaceIndex == bname.NamespaceIndex |
587
|
|
|
|
588
|
1 |
|
def __str__(self): |
589
|
|
|
return 'QualifiedName({}:{})'.format(self.NamespaceIndex, self.Name) |
590
|
|
|
|
591
|
1 |
|
__repr__ = __str__ |
592
|
|
|
|
593
|
|
|
|
594
|
1 |
|
class LocalizedText(FrozenClass): |
595
|
|
|
|
596
|
|
|
''' |
597
|
|
|
A string qualified with a namespace index. |
598
|
|
|
''' |
599
|
|
|
|
600
|
1 |
|
def __init__(self, text=""): |
601
|
1 |
|
self.Encoding = 0 |
602
|
1 |
|
self.Text = text |
603
|
1 |
|
if type(self.Text) is unicode: |
604
|
1 |
|
self.Text = self.Text.encode('utf-8') |
605
|
1 |
|
if self.Text: |
606
|
1 |
|
self.Encoding |= (1 << 1) |
607
|
1 |
|
self.Locale = b'' |
608
|
1 |
|
self._freeze = True |
609
|
|
|
|
610
|
1 |
|
def to_binary(self): |
611
|
1 |
|
packet = [] |
612
|
1 |
|
if self.Locale: |
613
|
|
|
self.Encoding |= (1 << 0) |
614
|
1 |
|
if self.Text: |
615
|
1 |
|
self.Encoding |= (1 << 1) |
616
|
1 |
|
packet.append(uatype_UInt8.pack(self.Encoding)) |
617
|
1 |
|
if self.Locale: |
618
|
|
|
packet.append(pack_bytes(self.Locale)) |
619
|
1 |
|
if self.Text: |
620
|
1 |
|
packet.append(pack_bytes(self.Text)) |
621
|
1 |
|
return b''.join(packet) |
622
|
|
|
|
623
|
1 |
|
@staticmethod |
624
|
|
|
def from_binary(data): |
625
|
1 |
|
obj = LocalizedText() |
626
|
1 |
|
obj.Encoding = ord(data.read(1)) |
627
|
1 |
|
if obj.Encoding & (1 << 0): |
628
|
|
|
obj.Locale = unpack_bytes(data) |
629
|
1 |
|
if obj.Encoding & (1 << 1): |
630
|
1 |
|
obj.Text = unpack_bytes(data) |
631
|
1 |
|
return obj |
632
|
|
|
|
633
|
1 |
|
def to_string(self): |
634
|
|
|
# FIXME: use local |
635
|
|
|
return self.Text.decode() |
636
|
|
|
|
637
|
1 |
|
def __str__(self): |
638
|
|
|
return 'LocalizedText(' + 'Encoding:' + str(self.Encoding) + ', ' + \ |
639
|
|
|
'Locale:' + str(self.Locale) + ', ' + \ |
640
|
|
|
'Text:' + str(self.Text) + ')' |
641
|
1 |
|
__repr__ = __str__ |
642
|
|
|
|
643
|
1 |
|
def __eq__(self, other): |
644
|
1 |
|
if isinstance(other, LocalizedText) and self.Locale == other.Locale and self.Text == other.Text: |
645
|
1 |
|
return True |
646
|
1 |
|
return False |
647
|
|
|
|
648
|
|
|
|
649
|
1 |
|
class VariantType(Enum): |
650
|
|
|
|
651
|
|
|
''' |
652
|
|
|
The possible types of a variant. |
653
|
|
|
|
654
|
|
|
:ivar Null: |
655
|
|
|
:ivar Boolean: |
656
|
|
|
:ivar SByte: |
657
|
|
|
:ivar Byte: |
658
|
|
|
:ivar Int16: |
659
|
|
|
:ivar UInt16: |
660
|
|
|
:ivar Int32: |
661
|
|
|
:ivar UInt32: |
662
|
|
|
:ivar Int64: |
663
|
|
|
:ivar UInt64: |
664
|
|
|
:ivar Float: |
665
|
|
|
:ivar Double: |
666
|
|
|
:ivar String: |
667
|
|
|
:ivar DateTime: |
668
|
|
|
:ivar Guid: |
669
|
|
|
:ivar ByteString: |
670
|
|
|
:ivar XmlElement: |
671
|
|
|
:ivar NodeId: |
672
|
|
|
:ivar ExpandedNodeId: |
673
|
|
|
:ivar StatusCode: |
674
|
|
|
:ivar QualifiedName: |
675
|
|
|
:ivar LocalizedText: |
676
|
|
|
:ivar ExtensionObject: |
677
|
|
|
:ivar DataValue: |
678
|
|
|
:ivar Variant: |
679
|
|
|
:ivar DiagnosticInfo: |
680
|
|
|
|
681
|
|
|
|
682
|
|
|
|
683
|
|
|
''' |
684
|
1 |
|
Null = 0 |
685
|
1 |
|
Boolean = 1 |
686
|
1 |
|
SByte = 2 |
687
|
1 |
|
Byte = 3 |
688
|
1 |
|
Int16 = 4 |
689
|
1 |
|
UInt16 = 5 |
690
|
1 |
|
Int32 = 6 |
691
|
1 |
|
UInt32 = 7 |
692
|
1 |
|
Int64 = 8 |
693
|
1 |
|
UInt64 = 9 |
694
|
1 |
|
Float = 10 |
695
|
1 |
|
Double = 11 |
696
|
1 |
|
String = 12 |
697
|
1 |
|
DateTime = 13 |
698
|
1 |
|
Guid = 14 |
699
|
1 |
|
ByteString = 15 |
700
|
1 |
|
XmlElement = 16 |
701
|
1 |
|
NodeId = 17 |
702
|
1 |
|
ExpandedNodeId = 18 |
703
|
1 |
|
StatusCode = 19 |
704
|
1 |
|
QualifiedName = 20 |
705
|
1 |
|
LocalizedText = 21 |
706
|
1 |
|
ExtensionObject = 22 |
707
|
1 |
|
DataValue = 23 |
708
|
1 |
|
Variant = 24 |
709
|
1 |
|
DiagnosticInfo = 25 |
710
|
|
|
|
711
|
|
|
|
712
|
1 |
|
class Variant(FrozenClass): |
713
|
|
|
|
714
|
|
|
""" |
715
|
|
|
Create an OPC-UA Variant object. |
716
|
|
|
if no argument a Null Variant is created. |
717
|
|
|
if not variant type is given, attemps to guess type from python type |
718
|
|
|
if a variant is given as value, the new objects becomes a copy of the argument |
719
|
|
|
|
720
|
|
|
:ivar Value: |
721
|
|
|
:vartype Value: Any supported type |
722
|
|
|
:ivar VariantType: |
723
|
|
|
:vartype VariantType: VariantType |
724
|
|
|
""" |
725
|
|
|
|
726
|
1 |
|
def __init__(self, value=None, varianttype=None, encoding=0): |
727
|
1 |
|
self.Encoding = encoding |
728
|
1 |
|
self.Value = value |
729
|
1 |
|
self.VariantType = varianttype |
730
|
1 |
|
if isinstance(value, Variant): |
731
|
1 |
|
self.Value = value.Value |
732
|
1 |
|
self.VariantType = value.VariantType |
733
|
1 |
|
if self.VariantType is None: |
734
|
1 |
|
if type(self.Value) in (list, tuple): |
735
|
1 |
|
if len(self.Value) == 0: |
736
|
|
|
raise UAError("could not guess UA variable type") |
737
|
1 |
|
self.VariantType = self._guess_type(self.Value[0]) |
738
|
|
|
else: |
739
|
1 |
|
self.VariantType = self._guess_type(self.Value) |
740
|
1 |
|
self._freeze = True |
741
|
|
|
|
742
|
1 |
|
def __eq__(self, other): |
743
|
1 |
|
if isinstance(other, Variant) and self.VariantType == other.VariantType and self.Value == other.Value: |
744
|
1 |
|
return True |
745
|
1 |
|
return False |
746
|
|
|
|
747
|
1 |
|
def _guess_type(self, val): |
748
|
1 |
|
if val is None: |
749
|
1 |
|
return VariantType.Null |
750
|
1 |
|
elif isinstance(val, bool): |
751
|
1 |
|
return VariantType.Boolean |
752
|
1 |
|
elif isinstance(val, float): |
753
|
1 |
|
return VariantType.Double |
754
|
1 |
|
elif isinstance(val, int): |
755
|
1 |
|
return VariantType.Int64 |
756
|
1 |
|
elif type(val) in (str, unicode): |
757
|
1 |
|
return VariantType.String |
758
|
1 |
|
elif isinstance(val, bytes): |
759
|
1 |
|
return VariantType.ByteString |
760
|
1 |
|
elif isinstance(val, datetime): |
761
|
1 |
|
return VariantType.DateTime |
762
|
|
|
else: |
763
|
1 |
|
if isinstance(val, object): |
764
|
1 |
|
try: |
765
|
1 |
|
return getattr(VariantType, val.__class__.__name__) |
766
|
1 |
|
except AttributeError: |
767
|
1 |
|
return VariantType.ExtensionObject |
768
|
|
|
else: |
769
|
|
|
raise UAError("Could not guess UA type of {} with type {}, specify UA type".format(val, type(val))) |
770
|
|
|
|
771
|
1 |
|
def __str__(self): |
772
|
1 |
|
return "Variant(val:{!s},type:{})".format(self.Value, self.VariantType) |
773
|
1 |
|
__repr__ = __str__ |
774
|
|
|
|
775
|
1 |
|
def to_binary(self): |
776
|
1 |
|
b = [] |
777
|
1 |
|
mask = self.Encoding & 0b01111111 |
778
|
1 |
|
self.Encoding = (self.VariantType.value | mask) |
779
|
1 |
|
if type(self.Value) in (list, tuple): |
780
|
1 |
|
self.Encoding |= (1 << 7) |
781
|
1 |
|
b.append(uatype_UInt8.pack(self.Encoding)) |
782
|
1 |
|
b.append(pack_uatype_array(self.VariantType.name, self.Value)) |
783
|
|
|
else: |
784
|
1 |
|
b.append(uatype_UInt8.pack(self.Encoding)) |
785
|
1 |
|
b.append(pack_uatype(self.VariantType.name, self.Value)) |
786
|
1 |
|
return b"".join(b) |
787
|
|
|
|
788
|
1 |
|
@staticmethod |
789
|
|
|
def from_binary(data): |
790
|
1 |
|
encoding = ord(data.read(1)) |
791
|
1 |
|
vtype = VariantType(encoding & 0b01111111) |
792
|
1 |
|
if vtype == VariantType.Null: |
793
|
1 |
|
return Variant(None, vtype, encoding) |
794
|
1 |
|
if encoding & (1 << 7): |
795
|
1 |
|
value = unpack_uatype_array(vtype.name, data) |
796
|
|
|
else: |
797
|
1 |
|
value = unpack_uatype(vtype.name, data) |
798
|
1 |
|
return Variant(value, vtype, encoding) |
799
|
|
|
|
800
|
|
|
|
801
|
1 |
|
class DataValue(FrozenClass): |
802
|
|
|
|
803
|
|
|
''' |
804
|
|
|
A value with an associated timestamp, and quality. |
805
|
|
|
Automatically generated from xml , copied and modified here to fix errors in xml spec |
806
|
|
|
|
807
|
|
|
:ivar Value: |
808
|
|
|
:vartype Value: Variant |
809
|
|
|
:ivar StatusCode: |
810
|
|
|
:vartype StatusCode: StatusCode |
811
|
|
|
:ivar SourceTimestamp: |
812
|
|
|
:vartype SourceTimestamp: datetime |
813
|
|
|
:ivar SourcePicoSeconds: |
814
|
|
|
:vartype SourcePicoSeconds: int |
815
|
|
|
:ivar ServerTimestamp: |
816
|
|
|
:vartype ServerTimestamp: datetime |
817
|
|
|
:ivar ServerPicoseconds: |
818
|
|
|
:vartype ServerPicoseconds: int |
819
|
|
|
|
820
|
|
|
''' |
821
|
|
|
|
822
|
1 |
|
def __init__(self, variant=None, status=None): |
823
|
1 |
|
self.Encoding = 0 |
824
|
1 |
|
if not isinstance(variant, Variant): |
825
|
1 |
|
variant = Variant(variant) |
826
|
1 |
|
self.Value = variant |
827
|
1 |
|
if status is None: |
828
|
1 |
|
self.StatusCode = StatusCode() |
829
|
|
|
else: |
830
|
1 |
|
self.StatusCode = status |
831
|
1 |
|
self.SourceTimestamp = None # DateTime() |
832
|
1 |
|
self.SourcePicoseconds = None |
833
|
1 |
|
self.ServerTimestamp = None # DateTime() |
834
|
1 |
|
self.ServerPicoseconds = None |
835
|
1 |
|
self._freeze = True |
836
|
|
|
|
837
|
1 |
|
def to_binary(self): |
838
|
1 |
|
packet = [] |
839
|
1 |
|
if self.Value: |
840
|
1 |
|
self.Encoding |= (1 << 0) |
841
|
1 |
|
if self.StatusCode: |
842
|
1 |
|
self.Encoding |= (1 << 1) |
843
|
1 |
|
if self.SourceTimestamp: |
844
|
1 |
|
self.Encoding |= (1 << 2) |
845
|
1 |
|
if self.ServerTimestamp: |
846
|
1 |
|
self.Encoding |= (1 << 3) |
847
|
1 |
|
if self.SourcePicoseconds: |
848
|
|
|
self.Encoding |= (1 << 4) |
849
|
1 |
|
if self.ServerPicoseconds: |
850
|
|
|
self.Encoding |= (1 << 5) |
851
|
1 |
|
packet.append(uatype_UInt8.pack(self.Encoding)) |
852
|
1 |
|
if self.Value: |
853
|
1 |
|
packet.append(self.Value.to_binary()) |
854
|
1 |
|
if self.StatusCode: |
855
|
1 |
|
packet.append(self.StatusCode.to_binary()) |
856
|
1 |
|
if self.SourceTimestamp: |
857
|
1 |
|
packet.append(pack_datetime(self.SourceTimestamp)) # self.SourceTimestamp.to_binary()) |
858
|
1 |
|
if self.ServerTimestamp: |
859
|
1 |
|
packet.append(pack_datetime(self.ServerTimestamp)) # self.ServerTimestamp.to_binary()) |
860
|
1 |
|
if self.SourcePicoseconds: |
861
|
|
|
packet.append(uatype_UInt16.pack(self.SourcePicoseconds)) |
862
|
1 |
|
if self.ServerPicoseconds: |
863
|
|
|
packet.append(uatype_UInt16.pack(self.ServerPicoseconds)) |
864
|
1 |
|
return b''.join(packet) |
865
|
|
|
|
866
|
1 |
|
@staticmethod |
867
|
|
|
def from_binary(data): |
868
|
1 |
|
encoding = ord(data.read(1)) |
869
|
1 |
|
if encoding & (1 << 0): |
870
|
1 |
|
value = Variant.from_binary(data) |
871
|
|
|
else: |
872
|
|
|
value = None |
873
|
1 |
|
if encoding & (1 << 1): |
874
|
1 |
|
status = StatusCode.from_binary(data) |
875
|
|
|
else: |
876
|
|
|
status = None |
877
|
1 |
|
obj = DataValue(value, status) |
878
|
1 |
|
obj.Encoding = encoding |
879
|
1 |
|
if obj.Encoding & (1 << 2): |
880
|
1 |
|
obj.SourceTimestamp = unpack_datetime(data) # DateTime.from_binary(data) |
881
|
1 |
|
if obj.Encoding & (1 << 3): |
882
|
1 |
|
obj.ServerTimestamp = unpack_datetime(data) # DateTime.from_binary(data) |
883
|
1 |
|
if obj.Encoding & (1 << 4): |
884
|
|
|
obj.SourcePicoseconds = uatype_UInt16.unpack(data.read(2))[0] |
885
|
1 |
|
if obj.Encoding & (1 << 5): |
886
|
|
|
obj.ServerPicoseconds = uatype_UInt16.unpack(data.read(2))[0] |
887
|
1 |
|
return obj |
888
|
|
|
|
889
|
1 |
|
def __str__(self): |
890
|
|
|
s = 'DataValue(Value:{}'.format(self.Value) |
891
|
|
|
if self.StatusCode is not None: |
892
|
|
|
s += ', StatusCode:{}'.format(self.StatusCode) |
893
|
|
|
if self.SourceTimestamp is not None: |
894
|
|
|
s += ', SourceTimestamp:{}'.format(self.SourceTimestamp) |
895
|
|
|
if self.ServerTimestamp is not None: |
896
|
|
|
s += ', ServerTimestamp:{}'.format(self.ServerTimestamp) |
897
|
|
|
if self.SourcePicoseconds is not None: |
898
|
|
|
s += ', SourcePicoseconds:{}'.format(self.SourcePicoseconds) |
899
|
|
|
if self.ServerPicoseconds is not None: |
900
|
|
|
s += ', ServerPicoseconds:{}'.format(self.ServerPicoseconds) |
901
|
|
|
s += ')' |
902
|
|
|
return s |
903
|
|
|
|
904
|
1 |
|
__repr__ = __str__ |
905
|
|
|
|
906
|
|
|
|
907
|
1 |
|
__nodeid_counter = 2000 |
908
|
|
|
|
909
|
|
|
|
910
|
1 |
|
def generate_nodeid(idx): |
911
|
|
|
global __nodeid_counter |
912
|
1 |
|
__nodeid_counter += 1 |
913
|
|
|
return NodeId(__nodeid_counter, idx) |
914
|
|
|
|