Passed
Pull Request — master (#144)
by
unknown
03:06
created

NodeManagementService._delete_reference()   B

Complexity

Conditions 6

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nop 3
dl 0
loc 13
rs 8.6666
c 0
b 0
f 0
1
import asyncio
2
import pickle
3
import shelve
4
import logging
5
import collections
6
from datetime import datetime
7
from concurrent.futures import ThreadPoolExecutor
8
from functools import partial
9
10
from asyncua import ua
11
from .users import User, UserRole
12
13
_logger = logging.getLogger(__name__)
14
15
16
class AttributeValue(object):
17
18
    def __init__(self, value):
19
        self.value = value
20
        self.value_callback = None
21
        self.datachange_callbacks = {}
22
23
    def __str__(self):
24
        return f"AttributeValue({self.value})"
25
26
    __repr__ = __str__
27
28
29
class NodeData:
30
31
    def __init__(self, nodeid):
32
        self.nodeid = nodeid
33
        self.attributes = {}
34
        self.references = []
35
        self.call = None
36
37
    def __str__(self):
38
        return f"NodeData(id:{self.nodeid}, attrs:{self.attributes}, refs:{self.references})"
39
40
    __repr__ = __str__
41
42
43
class AttributeService:
44
45
    def __init__(self, aspace: "AddressSpace"):
46
        self.logger = logging.getLogger(__name__)
47
        self._aspace: "AddressSpace" = aspace
48
49
    async def read(self, params):
50
        #self.logger.debug("read %s", params)
51
        res = []
52
        for readvalue in params.NodesToRead:
53
            res.append(await self._aspace.read_attribute_value(readvalue.NodeId, readvalue.AttributeId))
54
        return res
55
56
    async def write(self, params, user=User(role=UserRole.Admin)):
57
        # self.logger.debug("write %s as user %s", params, user)
58
        res = []
59
        for writevalue in params.NodesToWrite:
60
            if user.role != UserRole.Admin:
61
                if writevalue.AttributeId != ua.AttributeIds.Value:
62
                    res.append(ua.StatusCode(ua.StatusCodes.BadUserAccessDenied))
63
                    continue
64
                al = await self._aspace.read_attribute_value(writevalue.NodeId, ua.AttributeIds.AccessLevel)
65
                ual = await self._aspace.read_attribute_value(writevalue.NodeId, ua.AttributeIds.UserAccessLevel)
66
                if not al.StatusCode.is_good() or not ua.ua_binary.test_bit(
67
                        al.Value.Value, ua.AccessLevel.CurrentWrite) or not \
68
                        ua.ua_binary.test_bit(ual.Value.Value, ua.AccessLevel.CurrentWrite):
69
                    res.append(ua.StatusCode(ua.StatusCodes.BadUserAccessDenied))
70
                    continue
71
            res.append(
72
                await self._aspace.write_attribute_value(writevalue.NodeId, writevalue.AttributeId, writevalue.Value))
73
        return res
74
75
76
class ViewService(object):
77
78
    def __init__(self, aspace: "AddressSpace"):
79
        self.logger = logging.getLogger(__name__)
80
        self._aspace: "AddressSpace" = aspace
81
82
    def browse(self, params):
83
        # self.logger.debug("browse %s", params)
84
        res = []
85
        for desc in params.NodesToBrowse:
86
            res.append(self._browse(desc))
87
        return res
88
89
    def _browse(self, desc):
90
        res = ua.BrowseResult()
91
        if desc.NodeId not in self._aspace:
92
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
93
            return res
94
        node = self._aspace[desc.NodeId]
95
        for ref in node.references:
96
            if not self._is_suitable_ref(desc, ref):
97
                continue
98
            res.References.append(ref)
99
        return res
100
101
    def _is_suitable_ref(self, desc, ref):
102
        if not self._suitable_direction(desc.BrowseDirection, ref.IsForward):
103
            # self.logger.debug("%s is not suitable due to direction", ref)
104
            return False
105
        if not self._suitable_reftype(desc.ReferenceTypeId, ref.ReferenceTypeId, desc.IncludeSubtypes):
106
            # self.logger.debug("%s is not suitable due to type", ref)
107
            return False
108
        if desc.NodeClassMask and ((desc.NodeClassMask & ref.NodeClass) == 0):
109
            # self.logger.debug("%s is not suitable due to class", ref)
110
            return False
111
        # self.logger.debug("%s is a suitable ref for desc %s", ref, desc)
112
        return True
113
114
    def _suitable_reftype(self, ref1, ref2, subtypes):
115
        """
116
        """
117
        if ref1 == ua.NodeId(ua.ObjectIds.Null):
118
            # If ReferenceTypeId is not specified in the BrowseDescription,
119
            # all References are returned and includeSubtypes is ignored.
120
            return True
121
        if not subtypes and ref2.Identifier == ua.ObjectIds.HasSubtype:
122
            return False
123
        if ref1.Identifier == ref2.Identifier:
124
            return True
125
        oktypes = self._get_sub_ref(ref1)
126
        if not subtypes and ua.NodeId(ua.ObjectIds.HasSubtype) in oktypes:
127
            oktypes.remove(ua.NodeId(ua.ObjectIds.HasSubtype))
128
        return ref2 in oktypes
129
130
    def _get_sub_ref(self, ref):
131
        res = []
132
        nodedata = self._aspace[ref]
133
        if nodedata is not None:
134
            for ref in nodedata.references:
135
                if ref.ReferenceTypeId.Identifier == ua.ObjectIds.HasSubtype and ref.IsForward:
136
                    res.append(ref.NodeId)
137
                    res += self._get_sub_ref(ref.NodeId)
138
        return res
139
140
    def _suitable_direction(self, direction, isforward):
141
        if direction == ua.BrowseDirection.Both:
142
            return True
143
        if direction == ua.BrowseDirection.Forward and isforward:
144
            return True
145
        if direction == ua.BrowseDirection.Inverse and not isforward:
146
            return True
147
        return False
148
149
    def translate_browsepaths_to_nodeids(self, browsepaths):
150
        # self.logger.debug("translate browsepath: %s", browsepaths)
151
        results = []
152
        for path in browsepaths:
153
            results.append(self._translate_browsepath_to_nodeid(path))
154
        return results
155
156
    def _translate_browsepath_to_nodeid(self, path):
157
        # self.logger.debug("looking at path: %s", path)
158
        res = ua.BrowsePathResult()
159
        if not path.RelativePath.Elements[-1].TargetName:
160
            # OPC UA Part 4: Services, 5.8.4 TranslateBrowsePathsToNodeIds
161
            # it's unclear if this the check should also handle empty strings
162
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadBrowseNameInvalid)
163
            return res
164
        if path.StartingNode not in self._aspace:
165
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
166
            return res
167
        current = path.StartingNode
168
        for el in path.RelativePath.Elements:
169
            nodeid = self._find_element_in_node(el, current)
170
            if not nodeid:
171
                res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNoMatch)
172
                return res
173
            current = nodeid
174
        target = ua.BrowsePathTarget()
175
        target.TargetId = current
176
        target.RemainingPathIndex = 4294967295
177
        res.Targets = [target]
178
        return res
179
180
    def _find_element_in_node(self, el, nodeid):
181
        nodedata = self._aspace[nodeid]
182
        for ref in nodedata.references:
183
            if ref.BrowseName != el.TargetName:
184
                continue
185
            if ref.IsForward == el.IsInverse:
186
                continue
187
            if not el.IncludeSubtypes and ref.ReferenceTypeId != el.ReferenceTypeId:
188
                continue
189
            elif el.IncludeSubtypes and ref.ReferenceTypeId != el.ReferenceTypeId:
190
                if ref.ReferenceTypeId not in self._get_sub_ref(el.ReferenceTypeId):
191
                    continue
192
            return ref.NodeId
193
        self.logger.info("element %s was not found in node %s", el, nodeid)
194
        return None
195
196
197
class NodeManagementService:
198
199
    def __init__(self, aspace: "AddressSpace"):
200
        self.logger = logging.getLogger(__name__)
201
        self._aspace: "AddressSpace" = aspace
202
203
    async def add_nodes(self, addnodeitems, user=User(role=UserRole.Admin)):
204
        results = []
205
        for item in addnodeitems:
206
            results.append(await self._add_node(item, user))
207
        return results
208
209
    async def try_add_nodes(self, addnodeitems, user=User(role=UserRole.Admin), check=True):
210
        for item in addnodeitems:
211
            ret = await self._add_node(item, user, check=check)
212
            if not ret.StatusCode.is_good():
213
                yield item
214
215
    async def _add_node(self, item, user, check=True):
216
        #self.logger.debug("Adding node %s %s", item.RequestedNewNodeId, item.BrowseName)
217
        result = ua.AddNodesResult()
218
219
        if not user.role == UserRole.Admin:
220
            result.StatusCode = ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
221
            return result
222
223
        if item.RequestedNewNodeId.has_null_identifier():
224
            # If Identifier of requested NodeId is null we generate a new NodeId using
225
            # the namespace of the nodeid, this is an extention of the spec to allow
226
            # to requests the server to generate a new nodeid in a specified namespace
227
            # self.logger.debug("RequestedNewNodeId has null identifier, generating Identifier")
228
            item.RequestedNewNodeId = self._aspace.generate_nodeid(item.RequestedNewNodeId.NamespaceIndex)
229
        else:
230
            if item.RequestedNewNodeId in self._aspace:
231
                self.logger.warning("AddNodesItem: Requested NodeId %s already exists", item.RequestedNewNodeId)
232
                result.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdExists)
233
                return result
234
235
        if item.ParentNodeId.is_null():
236
            # self.logger.info("add_node: while adding node %s, requested parent node is null %s %s",
237
            # item.RequestedNewNodeId, item.ParentNodeId, item.ParentNodeId.is_null())
238
            if check:
239
                result.StatusCode = ua.StatusCode(ua.StatusCodes.BadParentNodeIdInvalid)
240
                return result
241
242
        parentdata = self._aspace.get(item.ParentNodeId)
243
        if parentdata is None and not item.ParentNodeId.is_null():
244
            self.logger.info("add_node: while adding node %s, requested parent node %s does not exists",
245
                             item.RequestedNewNodeId, item.ParentNodeId)
246
            result.StatusCode = ua.StatusCode(ua.StatusCodes.BadParentNodeIdInvalid)
247
            return result
248
249
        nodedata = NodeData(item.RequestedNewNodeId)
250
251
        self._add_node_attributes(nodedata, item, add_timestamps=check)
252
253
        # now add our node to db
254
        self._aspace[nodedata.nodeid] = nodedata
255
256
        if parentdata is not None:
257
            self._add_ref_from_parent(nodedata, item, parentdata)
258
            await self._add_ref_to_parent(nodedata, item, parentdata)
259
260
        # add type definition
261
        if item.TypeDefinition != ua.NodeId():
262
            await self._add_type_definition(nodedata, item)
263
264
        result.StatusCode = ua.StatusCode()
265
        result.AddedNodeId = nodedata.nodeid
266
267
        return result
268
269
    def _add_node_attributes(self, nodedata, item, add_timestamps):
270
        # add common attrs
271
        nodedata.attributes[ua.AttributeIds.NodeId] = AttributeValue(
272
            ua.DataValue(ua.Variant(nodedata.nodeid, ua.VariantType.NodeId))
273
        )
274
        nodedata.attributes[ua.AttributeIds.BrowseName] = AttributeValue(
275
            ua.DataValue(ua.Variant(item.BrowseName, ua.VariantType.QualifiedName))
276
        )
277
        nodedata.attributes[ua.AttributeIds.NodeClass] = AttributeValue(
278
            ua.DataValue(ua.Variant(item.NodeClass, ua.VariantType.Int32))
279
        )
280
        # add requested attrs
281
        self._add_nodeattributes(item.NodeAttributes, nodedata, add_timestamps)
282
283
    def _add_unique_reference(self, nodedata, desc):
284
        for r in nodedata.references:
285
            if r.ReferenceTypeId == desc.ReferenceTypeId and r.NodeId == desc.NodeId:
286
                if r.IsForward != desc.IsForward:
287
                    self.logger.error("Cannot add conflicting reference %s ", str(desc))
288
                    return ua.StatusCode(ua.StatusCodes.BadReferenceNotAllowed)
289
                break  # ref already exists
290
        else:
291
            nodedata.references.append(desc)
292
        return ua.StatusCode()
293
294
    def _add_ref_from_parent(self, nodedata, item, parentdata):
295
        desc = ua.ReferenceDescription()
296
        desc.ReferenceTypeId = item.ReferenceTypeId
297
        desc.NodeId = nodedata.nodeid
298
        desc.NodeClass = item.NodeClass
299
        desc.BrowseName = item.BrowseName
300
        desc.DisplayName = item.NodeAttributes.DisplayName
301
        desc.TypeDefinition = item.TypeDefinition
302
        desc.IsForward = True
303
        self._add_unique_reference(parentdata, desc)
304
305
    async def _add_ref_to_parent(self, nodedata, item, parentdata):
306
        addref = ua.AddReferencesItem()
307
        addref.ReferenceTypeId = item.ReferenceTypeId
308
        addref.SourceNodeId = nodedata.nodeid
309
        addref.TargetNodeId = item.ParentNodeId
310
        addref.TargetNodeClass = parentdata.attributes[ua.AttributeIds.NodeClass].value.Value.Value
311
        addref.IsForward = False
312
        await self._add_reference_no_check(nodedata, addref)
313
314
    async def _add_type_definition(self, nodedata, item):
315
        addref = ua.AddReferencesItem()
316
        addref.SourceNodeId = nodedata.nodeid
317
        addref.IsForward = True
318
        addref.ReferenceTypeId = ua.NodeId(ua.ObjectIds.HasTypeDefinition)
319
        addref.TargetNodeId = item.TypeDefinition
320
        addref.TargetNodeClass = ua.NodeClass.DataType
321
        await self._add_reference_no_check(nodedata, addref)
322
323
    def delete_nodes(self, deletenodeitems, user=User(role=UserRole.Admin)):
324
        results = []
325
        for item in deletenodeitems.NodesToDelete:
326
            results.append(self._delete_node(item, user))
327
        return results
328
329
    def _delete_node(self, item, user):
330
        if user.role != UserRole.Admin:
331
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
332
333
        if item.NodeId not in self._aspace:
334
            self.logger.warning("DeleteNodesItem: NodeId %s does not exists", item.NodeId)
335
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
336
337
        if item.DeleteTargetReferences:
338
            for elem in self._aspace.keys():
339
                for rdesc in self._aspace[elem].references:
340
                    if rdesc.NodeId == item.NodeId:
341
                        self._aspace[elem].references.remove(rdesc)
342
343
        self._delete_node_callbacks(self._aspace[item.NodeId])
344
345
        del (self._aspace[item.NodeId])
346
347
        return ua.StatusCode()
348
349
    def _delete_node_callbacks(self, nodedata):
350
        if ua.AttributeIds.Value in nodedata.attributes:
351
            for handle, callback in list(nodedata.attributes[ua.AttributeIds.Value].datachange_callbacks.items()):
352
                try:
353
                    callback(handle, None, ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown))
354
                    self._aspace.delete_datachange_callback(handle)
355
                except Exception as ex:
356
                    self.logger.exception("Error calling delete node callback callback %s, %s, %s", nodedata,
357
                                          ua.AttributeIds.Value, ex)
358
359
    async def add_references(self, refs, user=User(role=UserRole.Admin)):
360
        result = []
361
        for ref in refs:
362
            result.append(await self._add_reference(ref, user))
363
        return result
364
365
    async def try_add_references(self, refs, user=User(role=UserRole.Admin)):
366
        for ref in refs:
367
            ret = await self._add_reference(ref, user)
368
            if not ret.is_good():
369
                yield ref
370
371
    async def _add_reference(self, addref, user):
372
        sourcedata = self._aspace.get(addref.SourceNodeId)
373
        if sourcedata is None:
374
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
375
        if addref.TargetNodeId not in self._aspace:
376
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
377
        if user.role != UserRole.Admin:
378
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
379
        return await self._add_reference_no_check(sourcedata, addref)
380
381
    async def _add_reference_no_check(self, sourcedata, addref):
382
        rdesc = ua.ReferenceDescription()
383
        rdesc.ReferenceTypeId = addref.ReferenceTypeId
384
        rdesc.IsForward = addref.IsForward
385
        rdesc.NodeId = addref.TargetNodeId
386
        if addref.TargetNodeClass == ua.NodeClass.Unspecified:
387
            rdesc.NodeClass = (await self._aspace.read_attribute_value(
388
                addref.TargetNodeId, ua.AttributeIds.NodeClass)).Value.Value
389
        else:
390
            rdesc.NodeClass = addref.TargetNodeClass
391
        bname = (await self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.BrowseName)).Value.Value
392
        if bname:
393
            rdesc.BrowseName = bname
394
        dname = (await self._aspace.read_attribute_value(addref.TargetNodeId, ua.AttributeIds.DisplayName)).Value.Value
395
        if dname:
396
            rdesc.DisplayUser = dname
397
        return self._add_unique_reference(sourcedata, rdesc)
398
399
    def delete_references(self, refs, user=User(role=UserRole.Admin)):
400
        result = []
401
        for ref in refs:
402
            result.append(self._delete_reference(ref, user))
403
        return result
404
405
    def _delete_unique_reference(self, item, invert=False):
406
        if invert:
407
            source, target, forward = item.TargetNodeId, item.SourceNodeId, not item.IsForward
408
        else:
409
            source, target, forward = item.SourceNodeId, item.TargetNodeId, item.IsForward
410
        for rdesc in self._aspace[source].references:
411
            if rdesc.NodeId == target and rdesc.ReferenceTypeId == item.ReferenceTypeId:
412
                if rdesc.IsForward == forward:
413
                    self._aspace[source].references.remove(rdesc)
414
                    return ua.StatusCode()
415
        return ua.StatusCode(ua.StatusCodes.BadNotFound)
416
417
    def _delete_reference(self, item, user):
418
        if item.SourceNodeId not in self._aspace:
419
            return ua.StatusCode(ua.StatusCodes.BadSourceNodeIdInvalid)
420
        if item.TargetNodeId not in self._aspace:
421
            return ua.StatusCode(ua.StatusCodes.BadTargetNodeIdInvalid)
422
        if item.ReferenceTypeId not in self._aspace:
423
            return ua.StatusCode(ua.StatusCodes.BadReferenceTypeIdInvalid)
424
        if user.role != UserRole.Admin:
425
            return ua.StatusCode(ua.StatusCodes.BadUserAccessDenied)
426
427
        if item.DeleteBidirectional:
428
            self._delete_unique_reference(item, True)
429
        return self._delete_unique_reference(item)
430
431
    def _add_node_attr(self, item, nodedata, name, vtype=None, add_timestamps=False):
432
        if item.SpecifiedAttributes & getattr(ua.NodeAttributesMask, name):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable getattr does not seem to be defined.
Loading history...
433
            dv = ua.DataValue(ua.Variant(getattr(item, name), vtype))
434
            if add_timestamps:
435
                # dv.ServerTimestamp = datetime.utcnow()  # Disabled until someone explains us it should be there
436
                dv.SourceTimestamp = datetime.utcnow()
437
            nodedata.attributes[getattr(ua.AttributeIds, name)] = AttributeValue(dv)
438
439
    def _add_nodeattributes(self, item, nodedata, add_timestamps):
440
        self._add_node_attr(item, nodedata, "AccessLevel", ua.VariantType.Byte)
441
        self._add_node_attr(item, nodedata, "ArrayDimensions", ua.VariantType.UInt32)
442
        self._add_node_attr(item, nodedata, "BrowseName", ua.VariantType.QualifiedName)
443
        self._add_node_attr(item, nodedata, "ContainsNoLoops", ua.VariantType.Boolean)
444
        self._add_node_attr(item, nodedata, "DataType", ua.VariantType.NodeId)
445
        self._add_node_attr(item, nodedata, "Description", ua.VariantType.LocalizedText)
446
        self._add_node_attr(item, nodedata, "DisplayName", ua.VariantType.LocalizedText)
447
        self._add_node_attr(item, nodedata, "EventNotifier", ua.VariantType.Byte)
448
        self._add_node_attr(item, nodedata, "Executable", ua.VariantType.Boolean)
449
        self._add_node_attr(item, nodedata, "Historizing", ua.VariantType.Boolean)
450
        self._add_node_attr(item, nodedata, "InverseName", ua.VariantType.LocalizedText)
451
        self._add_node_attr(item, nodedata, "IsAbstract", ua.VariantType.Boolean)
452
        self._add_node_attr(item, nodedata, "MinimumSamplingInterval", ua.VariantType.Double)
453
        self._add_node_attr(item, nodedata, "NodeClass", ua.VariantType.Int32)
454
        self._add_node_attr(item, nodedata, "NodeId", ua.VariantType.NodeId)
455
        self._add_node_attr(item, nodedata, "Symmetric", ua.VariantType.Boolean)
456
        self._add_node_attr(item, nodedata, "UserAccessLevel", ua.VariantType.Byte)
457
        self._add_node_attr(item, nodedata, "UserExecutable", ua.VariantType.Boolean)
458
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.Byte)
459
        self._add_node_attr(item, nodedata, "ValueRank", ua.VariantType.Int32)
460
        self._add_node_attr(item, nodedata, "WriteMask", ua.VariantType.UInt32)
461
        self._add_node_attr(item, nodedata, "UserWriteMask", ua.VariantType.UInt32)
462
        self._add_node_attr(item, nodedata, "Value", add_timestamps=add_timestamps)
463
464
465
class MethodService:
466
467
    def __init__(self, aspace: "AddressSpace"):
468
        self.logger = logging.getLogger(__name__)
469
        self._aspace: "AddressSpace" = aspace
470
        self._pool = ThreadPoolExecutor()
471
472
    def stop(self):
473
        self._pool.shutdown()
474
475
    async def call(self, methods):
476
        results = []
477
        for method in methods:
478
            res = await self._call(method)
479
            results.append(res)
480
        return results
481
482
    async def _call(self, method):
483
        self.logger.info("Calling: %s", method)
484
        res = ua.CallMethodResult()
485
        if method.ObjectId not in self._aspace or method.MethodId not in self._aspace:
486
            res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdInvalid)
487
        else:
488
            node = self._aspace[method.MethodId]
489
            if node.call is None:
490
                res.StatusCode = ua.StatusCode(ua.StatusCodes.BadNothingToDo)
491
            else:
492
                try:
493
                    result = await self._run_method(node.call, method.ObjectId, *method.InputArguments)
494
                except Exception:
495
                    self.logger.exception("Error executing method call %s, an exception was raised: ", method)
496
                    res.StatusCode = ua.StatusCode(ua.StatusCodes.BadUnexpectedError)
497
                else:
498
                    if isinstance(result, ua.CallMethodResult):
499
                        res = result
500
                    elif isinstance(result, ua.StatusCode):
501
                        res.StatusCode = result
502
                    else:
503
                        res.OutputArguments = result
504
                    while len(res.InputArgumentResults) < len(method.InputArguments):
505
                        res.InputArgumentResults.append(ua.StatusCode())
506
        return res
507
508
    async def _run_method(self, func, parent, *args):
509
        if asyncio.iscoroutinefunction(func):
510
            return await func(parent, *args)
511
        p = partial(func, parent, *args)
512
        res = await asyncio.get_event_loop().run_in_executor(self._pool, p)
513
        return res
514
515
516
class AddressSpace:
517
    """
518
    The address space object stores all the nodes of the OPC-UA server and helper methods.
519
    The methods are thread safe
520
    """
521
522
    def __init__(self):
523
        self.logger = logging.getLogger(__name__)
524
        self._nodes = {}
525
        self._datachange_callback_counter = 200
526
        self._handle_to_attribute_map = {}
527
        self._default_idx = 2
528
        self._nodeid_counter = {0: 20000, 1: 2000}
529
530
    def __getitem__(self, nodeid):
531
        return self._nodes.__getitem__(nodeid)
532
533
    def get(self, nodeid):
534
        return self._nodes.get(nodeid, None)
535
536
    def __setitem__(self, nodeid, value):
537
        return self._nodes.__setitem__(nodeid, value)
538
539
    def __contains__(self, nodeid):
540
        return self._nodes.__contains__(nodeid)
541
542
    def __delitem__(self, nodeid):
543
        self._nodes.__delitem__(nodeid)
544
545
    def generate_nodeid(self, idx=None):
546
        if idx is None:
547
            idx = self._default_idx
548
        if idx in self._nodeid_counter:
549
            self._nodeid_counter[idx] += 1
550
        else:
551
            # get the biggest identifier number from the existed nodes in address space
552
            identifier_list = sorted([
553
                nodeid.Identifier for nodeid in self._nodes.keys()
554
                if nodeid.NamespaceIndex == idx and nodeid.NodeIdType in (
555
                    ua.NodeIdType.Numeric, ua.NodeIdType.TwoByte, ua.NodeIdType.FourByte
556
                )
557
            ])
558
            if identifier_list:
559
                self._nodeid_counter[idx] = identifier_list[-1]
560
            else:
561
                self._nodeid_counter[idx] = 1
562
        nodeid = ua.NodeId(self._nodeid_counter[idx], idx)
563
        while True:
564
            if nodeid in self._nodes:
565
                nodeid = self.generate_nodeid(idx)
566
            else:
567
                return nodeid
568
569
    def keys(self):
570
        return self._nodes.keys()
571
572
    def empty(self):
573
        """Delete all nodes in address space"""
574
        self._nodes = {}
575
576
    def dump(self, path):
577
        """
578
        Dump address space as binary to file; note that server must be stopped for this method to work
579
        DO NOT DUMP AN ADDRESS SPACE WHICH IS USING A SHELF (load_aspace_shelf), ONLY CACHED NODES WILL GET DUMPED!
580
        """
581
        # prepare nodes in address space for being serialized
582
        for nodeid, ndata in self._nodes.items():
583
            # if the node has a reference to a method call, remove it so the object can be serialized
584
            if ndata.call is not None:
585
                self._nodes[nodeid].call = None
586
587
        with open(path, 'wb') as f:
588
            pickle.dump(self._nodes, f, pickle.HIGHEST_PROTOCOL)
589
590
    def load(self, path):
591
        """
592
        Load address space from a binary file, overwriting everything in the current address space
593
        """
594
        with open(path, 'rb') as f:
595
            self._nodes = pickle.load(f)
596
597
    def make_aspace_shelf(self, path):
598
        """
599
        Make a shelf for containing the nodes from the standard address space; this is typically only done on first
600
        start of the server. Subsequent server starts will load the shelf, nodes are then moved to a cache
601
        by the LazyLoadingDict class when they are accessed. Saving data back to the shelf
602
        is currently NOT supported, it is only used for the default OPC UA standard address space
603
604
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
605
        """
606
        with shelve.open(path, 'n', protocol=pickle.HIGHEST_PROTOCOL) as s:
607
            for nodeid, ndata in self._nodes.items():
608
                s[nodeid.to_string()] = ndata
609
610
    def load_aspace_shelf(self, path):
611
        """
612
        Load the standard address space nodes from a python shelve via LazyLoadingDict as needed.
613
        The dump() method can no longer be used if the address space is being loaded from a shelf
614
615
        Note: Intended for slow devices, such as Raspberry Pi, to greatly improve start up time
616
        """
617
        raise NotImplementedError
618
619
        # ToDo: async friendly implementation - load all at once?
620
        class LazyLoadingDict(collections.MutableMapping):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable collections does not seem to be defined.
Loading history...
621
            """
622
            Special dict that only loads nodes as they are accessed. If a node is accessed it gets copied from the
623
            shelve to the cache dict. All user nodes are saved in the cache ONLY. Saving data back to the shelf
624
            is currently NOT supported
625
            """
626
627
            def __init__(self, source):
628
                self.source = source  # python shelf
629
                self.cache = {}  # internal dict
630
631
            def __getitem__(self, key):
632
                # try to get the item (node) from the cache, if it isn't there get it from the shelf
633
                try:
634
                    return self.cache[key]
635
                except KeyError:
636
                    node = self.cache[key] = self.source[key.to_string()]
637
                    return node
638
639
            def __setitem__(self, key, value):
640
                # add a new item to the cache; if this item is in the shelf it is not updated
641
                self.cache[key] = value
642
643
            def __contains__(self, key):
644
                return key in self.cache or key.to_string() in self.source
645
646
            def __delitem__(self, key):
647
                # only deleting items from the cache is allowed
648
                del self.cache[key]
649
650
            def __iter__(self):
651
                # only the cache can be iterated over
652
                return iter(self.cache.keys())
653
654
            def __len__(self):
655
                # only returns the length of items in the cache, not unaccessed items in the shelf
656
                return len(self.cache)
657
658
        self._nodes = LazyLoadingDict(shelve.open(path, "r"))
659
660
    async def read_attribute_value(self, nodeid, attr):
661
        # self.logger.debug("get attr val: %s %s", nodeid, attr)
662
        if nodeid not in self._nodes:
663
            dv = ua.DataValue()
664
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
665
            return dv
666
        node = self._nodes[nodeid]
667
        if attr not in node.attributes:
668
            dv = ua.DataValue()
669
            dv.StatusCode = ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
670
            return dv
671
        attval = node.attributes[attr]
672
        if attval.value_callback:
673
            if asyncio.iscoroutinefunction(attval.value_callback):
674
                await attval.value_callback()
675
            else:
676
                return attval.value_callback()
677
        return attval.value
678
679
    async def write_attribute_value(self, nodeid, attr, value):
680
        # self.logger.debug("set attr val: %s %s %s", nodeid, attr, value)
681
        node = self._nodes.get(nodeid, None)
682
        if node is None:
683
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown)
684
        attval = node.attributes.get(attr, None)
685
        if attval is None:
686
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid)
687
688
        old = attval.value
689
        attval.value = value
690
        cbs = []
691
        if old.Value != value.Value:  # only send call callback when a value change has happend
692
            cbs = list(attval.datachange_callbacks.items())
693
694
        for k, v in cbs:
695
            try:
696
                await v(k, value)
697
            except Exception as ex:
698
                self.logger.exception("Error calling datachange callback %s, %s, %s", k, v, ex)
699
700
        return ua.StatusCode()
701
702
    def add_datachange_callback(self, nodeid, attr, callback):
703
        self.logger.debug("set attr callback: %s %s %s", nodeid, attr, callback)
704
        if nodeid not in self._nodes:
705
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown), 0
706
        node = self._nodes[nodeid]
707
        if attr not in node.attributes:
708
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid), 0
709
        attval = node.attributes[attr]
710
        self._datachange_callback_counter += 1
711
        handle = self._datachange_callback_counter
712
        attval.datachange_callbacks[handle] = callback
713
        self._handle_to_attribute_map[handle] = (nodeid, attr)
714
        return ua.StatusCode(), handle
715
716
    def delete_datachange_callback(self, handle):
717
        if handle in self._handle_to_attribute_map:
718
            nodeid, attr = self._handle_to_attribute_map.pop(handle)
719
            self._nodes[nodeid].attributes[attr].datachange_callbacks.pop(handle)
720
721
    def add_method_callback(self, methodid, callback):
722
        node = self._nodes[methodid]
723
        node.call = callback
724
725
    def add_value_callback_to_node(self, nodeid, attr, callback):
726
        if nodeid not in self._nodes:
727
            return ua.StatusCode(ua.StatusCodes.BadNodeIdUnknown), 0
728
        node = self._nodes[nodeid]
729
        if attr not in node.attributes:
730
            return ua.StatusCode(ua.StatusCodes.BadAttributeIdInvalid), 0
731
        attval = self._nodes[nodeid].attributes[attr]
732
        attval.value_callback = callback
733
        return ua.StatusCode()
734