Completed
Push — master ( 994531...1fc97e )
by Olivier
09:55
created

Node.get_current_path()   A

Complexity

Conditions 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
dl 0
loc 16
ccs 9
cts 9
cp 1
crap 3
rs 9.4285
c 1
b 0
f 1
1
"""
2
High level node object, to access node attribute
3
and browse address space
4
"""
5
6 1
from opcua import ua
7
from opcua.common import events
8 1
import opcua.common 
9
10
class Node(object):
11 1
12
    """
13
    High level node object, to access node attribute,
14
    browse and populate address space.
15
    Node objects are usefull as-is but they do not expose the entire
16
    OPC-UA protocol. Feel free to look at the code of this class and call
17
    directly UA services methods to optimize your code
18
    """
19
20
    def __init__(self, server, nodeid):
21 1
        self.server = server
22 1
        self.nodeid = None
23 1
        if isinstance(nodeid, Node):
24 1
            self.nodeid = nodeid.nodeid
25 1
        elif isinstance(nodeid, ua.NodeId):
26 1
            self.nodeid = nodeid
27 1
        elif type(nodeid) in (str, bytes):
28 1
            self.nodeid = ua.NodeId.from_string(nodeid)
29 1
        elif isinstance(nodeid, int):
30
            self.nodeid = ua.NodeId(nodeid, 0)
31
        else:
32
            raise ua.UaError("argument to node must be a NodeId object or a string defining a nodeid found {} of type {}".format(nodeid, type(nodeid)))
33 1
34 1
    def __eq__(self, other):
35 1
        if isinstance(other, Node) and self.nodeid == other.nodeid:
36 1
            return True
37
        return False
38 1
39
    def __ne__(self, other):
40
        return not self.__eq__(other)
41 1
42
    def __str__(self):
43 1
        return "Node({})".format(self.nodeid)
44
    __repr__ = __str__
45 1
46 1
    def __hash__(self):
47
        return self.nodeid.__hash__()
48 1
49
    def get_browse_name(self):
50
        """
51
        Get browse name of a node. A browse name is a QualifiedName object
52
        composed of a string(name) and a namespace index.
53 1
        """
54 1
        result = self.get_attribute(ua.AttributeIds.BrowseName)
55
        return result.Value.Value
56 1
57
    def get_display_name(self):
58
        """
59
        get description attribute of node
60 1
        """
61 1
        result = self.get_attribute(ua.AttributeIds.DisplayName)
62
        return result.Value.Value
63 1
64
    def get_data_type(self):
65
        """
66
        get data type of node as NodeId
67 1
        """
68 1
        result = self.get_attribute(ua.AttributeIds.DataType)
69
        return result.Value.Value
70 1
71
    def get_data_type_as_variant_type(self):
72
        """
73
        get data type of node as VariantType
74
        This only works if node is a variable, otherwise type
75
        may not be convertible to VariantType
76
        """
77 1
        result = self.get_attribute(ua.AttributeIds.DataType)
78
        return ua.DataType_to_VariantType(result.Value.Value)
79
80
    def get_access_level(self):
81
        """
82
        Get the access level attribute of the node as a set of AccessLevel enum values.
83
        """
84 1
        result = self.get_attribute(ua.AttributeIds.AccessLevel)
85
        return ua.AccessLevel.parse_bitfield(result.Value.Value)
86
87
    def get_user_access_level(self):
88
        """
89 1
        Get the user access level attribute of the node as a set of AccessLevel enum values.
90 1
        """
91
        result = self.get_attribute(ua.AttributeIds.UserAccessLevel)
92 1
        return ua.AccessLevel.parse_bitfield(result.Value.Value)
93
94
    def get_event_notifier(self):
95
        """
96
        Get the event notifier attribute of the node as a set of EventNotifier enum values.
97
        """
98 1
        result = self.get_attribute(ua.AttributeIds.EventNotifier)
99
        return ua.EventNotifier.parse_bitfield(result.Value.Value)
100 1
101
    def set_event_notifier(self, values):
102
        """
103
        Set the event notifier attribute.
104
105 1
        :param values: an iterable of EventNotifier enum values.
106 1
        """
107
        event_notifier_bitfield = ua.EventNotifier.to_bitfield(values)
108 1
        self.set_attribute(ua.AttributeIds.EventNotifier, ua.DataValue(ua.Variant(event_notifier_bitfield, ua.VariantType.Byte)))
109
110
    def get_node_class(self):
111
        """
112 1
        get node class attribute of node
113 1
        """
114
        result = self.get_attribute(ua.AttributeIds.NodeClass)
115 1
        return result.Value.Value
116
117
    def get_description(self):
118
        """
119 1
        get description attribute class of node
120 1
        """
121
        result = self.get_attribute(ua.AttributeIds.Description)
122 1
        return result.Value.Value
123
124
    def get_value(self):
125
        """
126 1
        Get value of a node as a python type. Only variables ( and properties) have values.
127 1
        An exception will be generated for other node types.
128
        """
129 1
        result = self.get_data_value()
130
        return result.Value.Value
131
132
    def get_data_value(self):
133
        """
134
        Get value of a node as a DataValue object. Only variables (and properties) have values.
135
        An exception will be generated for other node types.
136
        DataValue contain a variable value as a variant as well as server and source timestamps
137
        """
138
        return self.get_attribute(ua.AttributeIds.Value)
139 1
140 1
    def set_array_dimensions(self, value):
141 1
        """
142 1
        Set attribute ArrayDimensions of node
143 1
        make sure it has the correct data type
144
        """
145 1
        v = ua.Variant(value, ua.VariantType.UInt32)
146 1
        self.set_attribute(ua.AttributeIds.ArrayDimensions, ua.DataValue(v))
147
148 1
    def get_array_dimensions(self):
149
        """
150 1
        Read and return ArrayDimensions attribute of node
151
        """
152
        res = self.get_attribute(ua.AttributeIds.ArrayDimensions)
153
        return res.Value.Value
154
155 1
    def set_value_rank(self, value):
156 1
        """
157 1
        Set attribute ArrayDimensions of node
158
        """
159 1
        v = ua.Variant(value, ua.VariantType.Int32)
160 1
        self.set_attribute(ua.AttributeIds.ValueRank, ua.DataValue(v))
161
162 1
    def get_value_rank(self):
163 1
        """
164 1
        Read and return ArrayDimensions attribute of node
165 1
        """
166
        res = self.get_attribute(ua.AttributeIds.ValueRank)
167 1
        return res.Value.Value
168 1
169 1
    def set_value(self, value, varianttype=None):
170 1
        """
171
        Set value of a node. Only variables(properties) have values.
172 1
        An exception will be generated for other node types.
173
        value argument is either:
174
        * a python built-in type, converted to opc-ua
175
        optionnaly using the variantype argument.
176
        * a ua.Variant, varianttype is then ignored
177
        * a ua.DataValue, you then have full control over data send to server
178
        """
179 1
        datavalue = None
180
        if isinstance(value, ua.DataValue):
181
            datavalue = value
182
        elif isinstance(value, ua.Variant):
183
            datavalue = ua.DataValue(value)
184
        else:
185 1
            datavalue = ua.DataValue(ua.Variant(value, varianttype))
186 1
        self.set_attribute(ua.AttributeIds.Value, datavalue)
187 1
188 1
    set_data_value = set_value
189 1
190 1
    def set_writable(self, writable=True):
191 1
        """
192 1
        Set node as writable by clients.
193
        A node is always writable on server side.
194 1
        """
195
        if writable:
196
            self.set_attr_bit(ua.AttributeIds.AccessLevel, ua.AccessLevel.CurrentWrite)
197
            self.set_attr_bit(ua.AttributeIds.UserAccessLevel, ua.AccessLevel.CurrentWrite)
198
        else:
199 1
            self.unset_attr_bit(ua.AttributeIds.AccessLevel, ua.AccessLevel.CurrentWrite)
200 1
            self.unset_attr_bit(ua.AttributeIds.UserAccessLevel, ua.AccessLevel.CurrentWrite)
201 1
202 1
    def set_attr_bit(self, attr, bit):
203 1
        val = self.get_attribute(attr)
204 1
        val.Value.Value = ua.set_bit(val.Value.Value, bit)
205 1
        self.set_attribute(attr, val)
206 1
207
    def unset_attr_bit(self, attr, bit):
208 1
        val = self.get_attribute(attr)
209
        val.Value.Value = ua.unset_bit(val.Value.Value, bit)
210
        self.set_attribute(attr, val)
211
212
    def set_read_only(self):
213
        """
214
        Set a node as read-only for clients.
215
        A node is always writable on server side.
216
        """
217
        return self.set_writable(False)
218
219
    def set_attribute(self, attributeid, datavalue):
220
        """
221
        Set an attribute of a node
222
        attributeid is a member of ua.AttributeIds
223 1
        datavalue is a ua.DataValue object
224
        """
225
        attr = ua.WriteValue()
226
        attr.NodeId = self.nodeid
227
        attr.AttributeId = attributeid
228
        attr.Value = datavalue
229
        params = ua.WriteParameters()
230
        params.NodesToWrite = [attr]
231
        result = self.server.write(params)
232
        result[0].check()
233
234
    def get_attribute(self, attr):
235
        """
236
        Read one attribute of a node
237
        result code from server is checked and an exception is raised in case of error
238
        """
239
        rv = ua.ReadValueId()
240
        rv.NodeId = self.nodeid
241
        rv.AttributeId = attr
242
        params = ua.ReadParameters()
243
        params.NodesToRead.append(rv)
244
        result = self.server.read(params)
245 1
        result[0].StatusCode.check()
246
        return result[0]
247 1
248
    def get_attributes(self, attrs):
249
        """
250
        Read several attributes of a node
251
        list of DataValue is returned
252 1
        """
253
        params = ua.ReadParameters()
254 1
        for attr in attrs:
255
            rv = ua.ReadValueId()
256
            rv.NodeId = self.nodeid
257 1
            rv.AttributeId = attr
258
            params.NodesToRead.append(rv)
259
260
        results = self.server.read(params)
261
        return results
262
263
    def get_children(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified):
264
        """
265
        Get all children of a node. By default hierarchical references and all node classes are returned.
266 1
        Other reference types may be given:
267 1
        References = 31
268 1
        NonHierarchicalReferences = 32
269 1
        HierarchicalReferences = 33
270 1
        HasChild = 34
271 1
        Organizes = 35
272
        HasEventSource = 36
273 1
        HasModellingRule = 37
274 1
        HasEncoding = 38
275 1
        HasDescription = 39
276 1
        HasTypeDefinition = 40
277 1
        GeneratesEvent = 41
278 1
        Aggregates = 44
279
        HasSubtype = 45
280 1
        HasProperty = 46
281
        HasComponent = 47
282
        HasNotifier = 48
283
        HasOrderedComponent = 49
284
        """
285
        return self.get_referenced_nodes(refs, ua.BrowseDirection.Forward, nodeclassmask)
286 1
287 1
    def get_properties(self):
288 1
        """
289 1
        return properties of node.
290 1
        properties are child nodes with a reference of type HasProperty and a NodeClass of Variable
291 1
        """
292
        return self.get_children(refs=ua.ObjectIds.HasProperty, nodeclassmask=ua.NodeClass.Variable)
293 1
294
    def get_variables(self):
295
        """
296
        return variables of node.
297 1
        properties are child nodes with a reference of type HasComponent and a NodeClass of Variable
298 1
        """
299 1
        return self.get_children(refs=ua.ObjectIds.HasComponent, nodeclassmask=ua.NodeClass.Variable)
300 1
301
    def get_methods(self):
302 1
        """
303
        return methods of node.
304
        properties are child nodes with a reference of type HasComponent and a NodeClass of Method
305
        """
306 1
        return self.get_children(refs=ua.ObjectIds.HasComponent, nodeclassmask=ua.NodeClass.Method)
307
308 1
    def get_children_descriptions(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
309
        return self.get_references(refs, ua.BrowseDirection.Forward, nodeclassmask, includesubtypes)
310 1
311
    def get_references(self, refs=ua.ObjectIds.References, direction=ua.BrowseDirection.Both, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
312
        """
313
        returns references of the node based on specific filter defined with:
314
315
        refs = ObjectId of the Reference
316
        direction = Browse direction for references
317
        nodeclassmask = filter nodes based on specific class
318
        includesubtypes = If true subtypes of the reference (ref) are also included
319 1
        """
320 1
        desc = ua.BrowseDescription()
321 1
        desc.BrowseDirection = direction
322 1
        desc.ReferenceTypeId = ua.TwoByteNodeId(refs)
323 1
        desc.IncludeSubtypes = includesubtypes
324 1
        desc.NodeClassMask = nodeclassmask
325 1
        desc.ResultMask = ua.BrowseResultMask.All
326 1
327 1
        desc.NodeId = self.nodeid
328
        params = ua.BrowseParameters()
329 1
        params.View.Timestamp = ua.win_epoch_to_datetime(0)
330
        params.NodesToBrowse.append(desc)
331 1
        results = self.server.browse(params)
332 1
        return results[0].References
333 1
334 1
    def get_referenced_nodes(self, refs=ua.ObjectIds.References, direction=ua.BrowseDirection.Both, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
335 1
        """
336 1
        returns referenced nodes based on specific filter
337 1
        Paramters are the same as for get_references
338 1
339
        """
340
        references = self.get_references(refs, direction, nodeclassmask, includesubtypes)
341 1
        nodes = []
342 1
        for desc in references:
343 1
            node = Node(self.server, desc.NodeId)
344
            nodes.append(node)
345 1
        return nodes
346
347
    def get_type_definition(self):
348
        """
349
        returns type definition of the node.
350
        """
351
        references = self.get_references(refs=ua.ObjectIds.HasTypeDefinition, direction=ua.BrowseDirection.Forward)
352 1
        if len(references) == 0:
353 1
            return None
354 1
        return references[0].NodeId
355 1
356
    def get_current_path(self):
357 1
        """
358 1
        Attempt to find current path of node and return it as a list of strings.
359 1
        There might several possible paths to a node, this function will return one
360
        Some nodes may be missing references, so this method may
361 1
        return an empty list
362 1
        """
363 1
        path = []
364 1
        node = self
365 1
        while True:
366
            refs = node.get_references(refs=ua.ObjectIds.HierarchicalReferences, direction=ua.BrowseDirection.Inverse)
367 1
            if len(refs) > 0:
368
                path.insert(0, refs[0].BrowseName.to_string())
369
                node = Node(self.server, refs[0].NodeId)
370
            else:
371
                return path
372 1
373 1
    def get_parent(self):
374 1
        """
375
        returns parent of the node.
376 1
        A Node may have several parents, the first found is returned.
377 1
        This method uses reverse references, a node might be missing such a link,
378 1
        thus we will not find its parent.
379 1
        """
380 1
        refs = self.get_references(refs=ua.ObjectIds.HierarchicalReferences, direction=ua.BrowseDirection.Inverse)
381 1
        if len(refs) > 0:
382 1
            return Node(self.server, refs[0].NodeId)
383
        else:
384 1
            return None
385
386
    def get_child(self, path):
387
        """
388
        get a child specified by its path from this node.
389
        A path might be:
390
        * a string representing a qualified name.
391
        * a qualified name
392
        * a list of string
393
        * a list of qualified names
394
        """
395
        if type(path) not in (list, tuple):
396 1
            path = [path]
397 1
        rpath = self._make_relative_path(path)
398 1
        bpath = ua.BrowsePath()
399
        bpath.StartingNode = self.nodeid
400 1
        bpath.RelativePath = rpath
401 1
        result = self.server.translate_browsepaths_to_nodeids([bpath])
402 1
        result = result[0]
403
        result.StatusCode.check()
404 1
        # FIXME: seems this method may return several nodes
405 1
        return Node(self.server, result.Targets[0].TargetId)
406
407 1
    def _make_relative_path(self, path):
408
        rpath = ua.RelativePath()
409 1
        for item in path:
410 1
            el = ua.RelativePathElement()
411
            el.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HierarchicalReferences)
412 1
            el.IsInverse = False
413
            el.IncludeSubtypes = True
414
            if isinstance(item, ua.QualifiedName):
415
                el.TargetName = item
416
            else:
417 1
                el.TargetName = ua.QualifiedName.from_string(item)
418 1
            rpath.Elements.append(el)
419 1
        return rpath
420
421 1
    def read_raw_history(self, starttime=None, endtime=None, numvalues=0):
422 1
        """
423 1
        Read raw history of a node
424 1
        result code from server is checked and an exception is raised in case of error
425 1
        If numvalues is > 0 and number of events in period is > numvalues
426 1
        then result will be truncated
427 1
        """
428
        details = ua.ReadRawModifiedDetails()
429
        details.IsReadModified = False
430
        if starttime:
431
            details.StartTime = starttime
432
        else:
433
            details.StartTime = ua.DateTimeMinValue
434 1
        if endtime:
435 1
            details.EndTime = endtime
436 1
        else:
437
            details.EndTime = ua.DateTimeMinValue
438 1
        details.NumValuesPerNode = numvalues
439 1
        details.ReturnBounds = True
440 1
        result = self.history_read(details)
441
        return result.HistoryData.DataValues
442 1
443 1 View Code Duplication
    def history_read(self, details):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
444 1
        """
445
        Read raw history of a node, low-level function
446 1
        result code from server is checked and an exception is raised in case of error
447 1
        """
448 1
        valueid = ua.HistoryReadValueId()
449
        valueid.NodeId = self.nodeid
450 1
        valueid.IndexRange = ''
451 1
452 1
        params = ua.HistoryReadParameters()
453
        params.HistoryReadDetails = details
454 1
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
455 1
        params.ReleaseContinuationPoints = False
456 1
        params.NodesToRead.append(valueid)
457
        result = self.server.history_read(params)[0]
458 1
        return result
459 1
460 1
    def read_event_history(self, starttime=None, endtime=None, numvalues=0, evtypes=ua.ObjectIds.BaseEventType):
461
        """
462
        Read event history of a source node
463
        result code from server is checked and an exception is raised in case of error
464
        If numvalues is > 0 and number of events in period is > numvalues
465
        then result will be truncated
466
        """
467
468
        details = ua.ReadEventDetails()
469
        if starttime:
470
            details.StartTime = starttime
471
        else:
472
            details.StartTime = ua.DateTimeMinValue
473
        if endtime:
474
            details.EndTime = endtime
475
        else:
476
            details.EndTime = ua.DateTimeMinValue
477
        details.NumValuesPerNode = numvalues
478
479
        if not isinstance(evtypes, (list, tuple)):
480
            evtypes = [evtypes]
481
482
        evtypes = [Node(self.server, evtype) for evtype in evtypes]
483
484
        evfilter = events.get_filter_from_event_type(evtypes)
485
        details.Filter = evfilter
486
487
        result = self.history_read_events(details)
488
        event_res = []
489
        for res in result.HistoryData.Events:
490
            event_res.append(events.Event.from_event_fields(evfilter.SelectClauses, res.EventFields))
491
        return event_res
492
493 View Code Duplication
    def history_read_events(self, details):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
494
        """
495
        Read event history of a node, low-level function
496
        result code from server is checked and an exception is raised in case of error
497
        """
498
        valueid = ua.HistoryReadValueId()
499
        valueid.NodeId = self.nodeid
500
        valueid.IndexRange = ''
501
502
        params = ua.HistoryReadParameters()
503
        params.HistoryReadDetails = details
504
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
505
        params.ReleaseContinuationPoints = False
506
        params.NodesToRead.append(valueid)
507
        result = self.server.history_read(params)[0]
508
        return result
509
510
    def delete(self, delete_references=True):
511
        """
512
        Delete node from address space
513
        """
514
        ditem = ua.DeleteNodesItem()
515
        ditem.NodeId = self.nodeid
516
        ditem.DeleteTargetReferences = delete_references
517
        params = ua.DeleteNodesParameters()
518
        params.NodesToDelete = [ditem]
519
        result = self.server.delete_nodes(params)
520
        result[0].check()
521
522
    def add_folder(self, nodeid, bname):
523
        return  opcua.common.manage_nodes.create_folder(self, nodeid, bname)
524
 
525
    def add_object(self, nodeid, bname, objecttype=None):
526
        return opcua.common.manage_nodes.create_object(self, nodeid, bname, objecttype)
527
 
528
    def add_variable(self, nodeid, bname, val, varianttype=None, datatype=None):
529
        return opcua.common.manage_nodes.create_variable(self, nodeid, bname, val, varianttype, datatype)
530
 
531
    def add_object_type(self, nodeid, bname):
532
        return opcua.common.manage_nodes.create_object_type(self, nodeid, bname)
533
 
534
    def add_variable_type(self, nodeid, bname, datatype):
535
        return opcua.common.manage_nodes.create_variable_type(self, nodeid, bname, datatype)
536
 
537
    def add_data_type(self, nodeid, bname, description=None):
538
        return opcua.common.manage_nodes.create_data_type(self, nodeid, bname, description=None)
539
 
540
    def add_property(self, nodeid, bname, val, varianttype=None, datatype=None):
541
        return opcua.common.manage_nodes.create_property(self, nodeid, bname, val, varianttype, datatype)
542
 
543
    def add_method(self, *args):
544
        return opcua.common.manage_nodes.create_method(self, *args)
545
 
546
    def add_reference_type(self, parent, nodeid, bname):
547
        return opcua.common.manage_nodes.create_reference_type(parent, nodeid, bname)
548
    
549
    def call_method(parent, methodid, *args):
550
        return opcua.common.methods.call_method(parent, methodid, *args)
551