Completed
Pull Request — master (#217)
by Olivier
04:18
created

Node.set_event_notifier()   A

Complexity

Conditions 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 9
ccs 3
cts 3
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
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
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 VariantType
67 1
        """
68 1
        result = self.get_attribute(ua.AttributeIds.DataType)
69
        return ua.DataType_to_VariantType(result.Value.Value)
70 1
71
    def get_access_level(self):
72
        """
73
        get access level of node as a list of AccessLevel Enum
74
        """
75
        result = self.get_attribute(ua.AttributeIds.AccessLevel)
76
        return ua.int_to_AccessLevel(result.Value.Value)
77 1
78
    def get_user_access_level(self):
79
        """
80
        get user access level of node as a list of AccessLevel Enum
81
        """
82
        result = self.get_attribute(ua.AttributeIds.UserAccessLevel)
83
        return ua.int_to_AccessLevel(result.Value.Value)
84 1
85
    def set_event_notifier(self, enum_list):
86
        """
87
        set event notifier attribute,
88
        arg is a list of EventNotifier Enum
89 1
        """
90 1
        res = 1
91
        for en in enum_list:
92 1
            ua.set_bit(res, en.value)
93
        self.set_attribute(ua.AttributeIds.EventNotifier, ua.DataValue(ua.Variant(res, ua.VariantType.Byte)))
94
95
    def get_node_class(self):
96
        """
97
        get node class attribute of node
98 1
        """
99
        result = self.get_attribute(ua.AttributeIds.NodeClass)
100 1
        return result.Value.Value
101
102
    def get_description(self):
103
        """
104
        get description attribute class of node
105 1
        """
106 1
        result = self.get_attribute(ua.AttributeIds.Description)
107
        return result.Value.Value
108 1
109
    def get_value(self):
110
        """
111
        Get value of a node as a python type. Only variables ( and properties) have values.
112 1
        An exception will be generated for other node types.
113 1
        """
114
        result = self.get_data_value()
115 1
        return result.Value.Value
116
117
    def get_data_value(self):
118
        """
119 1
        Get value of a node as a DataValue object. Only variables (and properties) have values.
120 1
        An exception will be generated for other node types.
121
        DataValue contain a variable value as a variant as well as server and source timestamps
122 1
        """
123
        return self.get_attribute(ua.AttributeIds.Value)
124
125
    def set_array_dimensions(self, value):
126 1
        """
127 1
        Set attribute ArrayDimensions of node
128
        make sure it has the correct data type
129 1
        """
130
        v = ua.Variant(value, ua.VariantType.UInt32)
131
        self.set_attribute(ua.AttributeIds.ArrayDimensions, ua.DataValue(v))
132
133
    def get_array_dimensions(self):
134
        """
135
        Read and return ArrayDimensions attribute of node
136
        """
137
        res = self.get_attribute(ua.AttributeIds.ArrayDimensions)
138
        return res.Value.Value
139 1
140 1
    def set_value_rank(self, value):
141 1
        """
142 1
        Set attribute ArrayDimensions of node
143 1
        """
144
        v = ua.Variant(value, ua.VariantType.Int32)
145 1
        self.set_attribute(ua.AttributeIds.ValueRank, ua.DataValue(v))
146 1
147
    def get_value_rank(self):
148 1
        """
149
        Read and return ArrayDimensions attribute of node
150 1
        """
151
        res = self.get_attribute(ua.AttributeIds.ValueRank)
152
        return res.Value.Value
153
154
    def set_value(self, value, varianttype=None):
155 1
        """
156 1
        Set value of a node. Only variables(properties) have values.
157 1
        An exception will be generated for other node types.
158
        value argument is either:
159 1
        * a python built-in type, converted to opc-ua
160 1
        optionnaly using the variantype argument.
161
        * a ua.Variant, varianttype is then ignored
162 1
        * a ua.DataValue, you then have full control over data send to server
163 1
        """
164 1
        datavalue = None
165 1
        if isinstance(value, ua.DataValue):
166
            datavalue = value
167 1
        elif isinstance(value, ua.Variant):
168 1
            datavalue = ua.DataValue(value)
169 1
        else:
170 1
            datavalue = ua.DataValue(ua.Variant(value, varianttype))
171
        self.set_attribute(ua.AttributeIds.Value, datavalue)
172 1
173
    set_data_value = set_value
174
175
    def set_writable(self, writable=True):
176
        """
177
        Set node as writable by clients.
178
        A node is always writable on server side.
179 1
        """
180
        if writable:
181
            self.set_attr_bit(ua.AttributeIds.AccessLevel, ua.AccessLevel.CurrentWrite)
182
            self.set_attr_bit(ua.AttributeIds.UserAccessLevel, ua.AccessLevel.CurrentWrite)
183
        else:
184
            self.unset_attr_bit(ua.AttributeIds.AccessLevel, ua.AccessLevel.CurrentWrite)
185 1
            self.unset_attr_bit(ua.AttributeIds.UserAccessLevel, ua.AccessLevel.CurrentWrite)
186 1
187 1
    def set_attr_bit(self, attr, bit):
188 1
        val = self.get_attribute(attr)
189 1
        val.Value.Value = ua.set_bit(val.Value.Value, bit)
190 1
        self.set_attribute(attr, val)
191 1
192 1
    def unset_attr_bit(self, attr, bit):
193
        val = self.get_attribute(attr)
194 1
        val.Value.Value = ua.unset_bit(val.Value.Value, bit)
195
        self.set_attribute(attr, val)
196
197
    def set_read_only(self):
198
        """
199 1
        Set a node as read-only for clients.
200 1
        A node is always writable on server side.
201 1
        """
202 1
        return self.set_writable(False)
203 1
204 1
    def set_attribute(self, attributeid, datavalue):
205 1
        """
206 1
        Set an attribute of a node
207
        attributeid is a member of ua.AttributeIds
208 1
        datavalue is a ua.DataValue object
209
        """
210
        attr = ua.WriteValue()
211
        attr.NodeId = self.nodeid
212
        attr.AttributeId = attributeid
213
        attr.Value = datavalue
214
        params = ua.WriteParameters()
215
        params.NodesToWrite = [attr]
216
        result = self.server.write(params)
217
        result[0].check()
218
219
    def get_attribute(self, attr):
220
        """
221
        Read one attribute of a node
222
        result code from server is checked and an exception is raised in case of error
223 1
        """
224
        rv = ua.ReadValueId()
225
        rv.NodeId = self.nodeid
226
        rv.AttributeId = attr
227
        params = ua.ReadParameters()
228
        params.NodesToRead.append(rv)
229
        result = self.server.read(params)
230
        result[0].StatusCode.check()
231
        return result[0]
232
233
    def get_attributes(self, attrs):
234
        """
235
        Read several attributes of a node
236
        list of DataValue is returned
237
        """
238
        params = ua.ReadParameters()
239
        for attr in attrs:
240
            rv = ua.ReadValueId()
241
            rv.NodeId = self.nodeid
242
            rv.AttributeId = attr
243
            params.NodesToRead.append(rv)
244
245 1
        results = self.server.read(params)
246
        return results
247 1
248
    def get_children(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified):
249
        """
250
        Get all children of a node. By default hierarchical references and all node classes are returned.
251
        Other reference types may be given:
252 1
        References = 31
253
        NonHierarchicalReferences = 32
254 1
        HierarchicalReferences = 33
255
        HasChild = 34
256
        Organizes = 35
257 1
        HasEventSource = 36
258
        HasModellingRule = 37
259
        HasEncoding = 38
260
        HasDescription = 39
261
        HasTypeDefinition = 40
262
        GeneratesEvent = 41
263
        Aggregates = 44
264
        HasSubtype = 45
265
        HasProperty = 46
266 1
        HasComponent = 47
267 1
        HasNotifier = 48
268 1
        HasOrderedComponent = 49
269 1
        """
270 1
        return self.get_referenced_nodes(refs, ua.BrowseDirection.Forward, nodeclassmask)
271 1
272
    def get_properties(self):
273 1
        """
274 1
        return properties of node.
275 1
        properties are child nodes with a reference of type HasProperty and a NodeClass of Variable
276 1
        """
277 1
        return self.get_children(refs=ua.ObjectIds.HasProperty, nodeclassmask=ua.NodeClass.Variable)
278 1
279
    def get_children_descriptions(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
280 1
        return self.get_references(refs, ua.BrowseDirection.Forward, nodeclassmask, includesubtypes)
281
282
    def get_references(self, refs=ua.ObjectIds.References, direction=ua.BrowseDirection.Both, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
283
        """
284
        returns references of the node based on specific filter defined with:
285
286 1
        refs = ObjectId of the Reference
287 1
        direction = Browse direction for references
288 1
        nodeclassmask = filter nodes based on specific class
289 1
        includesubtypes = If true subtypes of the reference (ref) are also included
290 1
        """
291 1
        desc = ua.BrowseDescription()
292
        desc.BrowseDirection = direction
293 1
        desc.ReferenceTypeId = ua.TwoByteNodeId(refs)
294
        desc.IncludeSubtypes = includesubtypes
295
        desc.NodeClassMask = nodeclassmask
296
        desc.ResultMask = ua.BrowseResultMask.All
297 1
298 1
        desc.NodeId = self.nodeid
299 1
        params = ua.BrowseParameters()
300 1
        params.View.Timestamp = ua.win_epoch_to_datetime(0)
301
        params.NodesToBrowse.append(desc)
302 1
        results = self.server.browse(params)
303
        return results[0].References
304
305
    def get_referenced_nodes(self, refs=ua.ObjectIds.References, direction=ua.BrowseDirection.Both, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
306 1
        """
307
        returns referenced nodes based on specific filter
308 1
        Paramters are the same as for get_references
309
310 1
        """
311
        references = self.get_references(refs, direction, nodeclassmask, includesubtypes)
312
        nodes = []
313
        for desc in references:
314
            node = Node(self.server, desc.NodeId)
315
            nodes.append(node)
316
        return nodes
317
318
    def get_type_definition(self):
319 1
        """
320 1
        returns type definition of the node.
321 1
        """
322 1
        references = self.get_references(refs=ua.ObjectIds.HasTypeDefinition, direction=ua.BrowseDirection.Forward)
323 1
        if len(references) == 0:
324 1
            return ua.ObjectIds.BaseObjectType
325 1
        return references[0].NodeId.Identifier
326 1
327 1
    def get_parent(self):
328
        """
329 1
        returns parent of the node.
330
        """
331 1
        refs = self.get_references(refs=ua.ObjectIds.HierarchicalReferences, direction=ua.BrowseDirection.Inverse)
332 1
333 1
        return Node(self.server, refs[0].NodeId)
334 1
335 1
    def get_child(self, path):
336 1
        """
337 1
        get a child specified by its path from this node.
338 1
        A path might be:
339
        * a string representing a qualified name.
340
        * a qualified name
341 1
        * a list of string
342 1
        * a list of qualified names
343 1
        """
344
        if type(path) not in (list, tuple):
345 1
            path = [path]
346
        rpath = self._make_relative_path(path)
347
        bpath = ua.BrowsePath()
348
        bpath.StartingNode = self.nodeid
349
        bpath.RelativePath = rpath
350
        result = self.server.translate_browsepaths_to_nodeids([bpath])
351
        result = result[0]
352 1
        result.StatusCode.check()
353 1
        # FIXME: seems this method may return several nodes
354 1
        return Node(self.server, result.Targets[0].TargetId)
355 1
356
    def _make_relative_path(self, path):
357 1
        rpath = ua.RelativePath()
358 1
        for item in path:
359 1
            el = ua.RelativePathElement()
360
            el.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HierarchicalReferences)
361 1
            el.IsInverse = False
362 1
            el.IncludeSubtypes = True
363 1
            if isinstance(item, ua.QualifiedName):
364 1
                el.TargetName = item
365 1
            else:
366
                el.TargetName = ua.QualifiedName.from_string(item)
367 1
            rpath.Elements.append(el)
368
        return rpath
369
370
    def read_raw_history(self, starttime=None, endtime=None, numvalues=0):
371
        """
372 1
        Read raw history of a node
373 1
        result code from server is checked and an exception is raised in case of error
374 1
        If numvalues is > 0 and number of events in period is > numvalues
375
        then result will be truncated
376 1
        """
377 1
        details = ua.ReadRawModifiedDetails()
378 1
        details.IsReadModified = False
379 1
        if starttime:
380 1
            details.StartTime = starttime
381 1
        else:
382 1
            details.StartTime = ua.DateTimeMinValue
383
        if endtime:
384 1
            details.EndTime = endtime
385
        else:
386
            details.EndTime = ua.DateTimeMinValue
387
        details.NumValuesPerNode = numvalues
388
        details.ReturnBounds = True
389
        result = self.history_read(details)
390
        return result.HistoryData.DataValues
391
392 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...
393
        """
394
        Read raw history of a node, low-level function
395
        result code from server is checked and an exception is raised in case of error
396 1
        """
397 1
        valueid = ua.HistoryReadValueId()
398 1
        valueid.NodeId = self.nodeid
399
        valueid.IndexRange = ''
400 1
401 1
        params = ua.HistoryReadParameters()
402 1
        params.HistoryReadDetails = details
403
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
404 1
        params.ReleaseContinuationPoints = False
405 1
        params.NodesToRead.append(valueid)
406
        result = self.server.history_read(params)[0]
407 1
        return result
408
409 1
    def read_event_history(self, starttime=None, endtime=None, numvalues=0, evtypes=ua.ObjectIds.BaseEventType):
410 1
        """
411
        Read event history of a source node 
412 1
        result code from server is checked and an exception is raised in case of error
413
        If numvalues is > 0 and number of events in period is > numvalues
414
        then result will be truncated
415
        """
416
417 1
        details = ua.ReadEventDetails()
418 1
        if starttime:
419 1
            details.StartTime = starttime
420
        else:
421 1
            details.StartTime = ua.DateTimeMinValue
422 1
        if endtime:
423 1
            details.EndTime = endtime
424 1
        else:
425 1
            details.EndTime = ua.DateTimeMinValue
426 1
        details.NumValuesPerNode = numvalues
427 1
428
        if not isinstance(evtypes, (list, tuple)):
429
            evtypes = [evtypes]
430
431
        evtypes = [Node(self.server, evtype) for evtype in evtypes]
432
433
        evfilter = events.get_filter_from_event_type(evtypes)
434 1
        details.Filter = evfilter
435 1
436 1
        result = self.history_read_events(details)
437
        event_res = []
438 1
        for res in result.HistoryData.Events:
439 1
            event_res.append(events.Event.from_event_fields(evfilter.SelectClauses, res.EventFields))
440 1
        return event_res
441
442 1 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...
443 1
        """
444 1
        Read event history of a node, low-level function
445
        result code from server is checked and an exception is raised in case of error
446 1
        """
447 1
        valueid = ua.HistoryReadValueId()
448 1
        valueid.NodeId = self.nodeid
449
        valueid.IndexRange = ''
450 1
451 1
        params = ua.HistoryReadParameters()
452 1
        params.HistoryReadDetails = details
453
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
454 1
        params.ReleaseContinuationPoints = False
455 1
        params.NodesToRead.append(valueid)
456 1
        result = self.server.history_read(params)[0]
457
        return result
458 1
459 1
    # Hack for convenience methods
460 1
    # local import is ugly but necessary for python2 support
461
    # feel fri to propose something better but I want to split all those
462
    # create methods from Node
463
464
    def add_folder(*args, **kwargs):
465
        from opcua.common import manage_nodes
466
        return manage_nodes.create_folder(*args, **kwargs)
467
468
    def add_object(*args, **kwargs):
469
        from opcua.common import manage_nodes
470
        return manage_nodes.create_object(*args, **kwargs)
471
472
    def add_variable(*args, **kwargs):
473
        from opcua.common import manage_nodes
474
        return manage_nodes.create_variable(*args, **kwargs)
475
476
    def add_property(*args, **kwargs):
477
        from opcua.common import manage_nodes
478
        return manage_nodes.create_property(*args, **kwargs)
479
480
    def add_method(*args, **kwargs):
481
        from opcua.common import manage_nodes
482
        return manage_nodes.create_method(*args, **kwargs)
483
484
    def add_subtype(*args, **kwargs):
485
        from opcua.common import manage_nodes
486
        return manage_nodes.create_subtype(*args, **kwargs)
487
488
    def call_method(*args, **kwargs):
489
        from opcua.common import methods
490
        return methods.call_method(*args, **kwargs)
491