Completed
Pull Request — master (#140)
by Olivier
02:33
created

opcua.common.Node   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 354
Duplicated Lines 0 %

Test Coverage

Coverage 90.66%
Metric Value
dl 0
loc 354
ccs 165
cts 182
cp 0.9066
rs 8.5454
wmc 49

34 Methods

Rating   Name   Duplication   Size   Complexity  
A __eq__() 0 4 3
A __init__() 0 11 4
A get_description() 0 6 1
A __hash__() 0 2 1
A get_data_value() 0 7 1
A get_browse_name() 0 7 1
A __ne__() 0 2 1
A get_data_type() 0 6 1
A get_value() 0 7 1
A get_display_name() 0 6 1
A get_node_class() 0 6 1
A get_attributes() 0 14 2
A get_properties() 0 6 1
A get_attribute() 0 13 1
B get_children() 0 28 2
A get_array_dimensions() 0 6 1
A set_value_rank() 0 6 1
A set_read_only() 0 6 1
A __str__() 0 2 1
B get_child() 0 30 4
A get_value_rank() 0 6 1
A set_attribute() 0 14 1
A set_writable() 0 11 2
A get_children_descriptions() 0 17 1
A set_value() 0 18 3
A set_array_dimensions() 0 7 1
A history_read() 0 16 1
A read_raw_history() 0 21 3
A call_method() 0 3 1
A add_object() 0 3 1
A add_variable() 0 3 1
A add_folder() 0 3 1
A add_method() 0 3 1
A add_property() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like opcua.common.Node often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
High level node object, to access node attribute
3
and browse address space
4
"""
5
6 1
from datetime import datetime
7
8 1
from opcua import ua
9
10
11 1
class Node(object):
12
13
    """
14
    High level node object, to access node attribute,
15
    browse and populate address space.
16
    Node objects are usefull as-is but they do not expose the entire
17
    OPC-UA protocol. Feel free to look at the code of this class and call
18
    directly UA services methods to optimize your code
19
    """
20
21 1
    def __init__(self, server, nodeid):
22 1
        self.server = server
23 1
        self.nodeid = None
24 1
        if isinstance(nodeid, ua.NodeId):
25 1
            self.nodeid = nodeid
26 1
        elif type(nodeid) in (str, bytes):
27 1
            self.nodeid = ua.NodeId.from_string(nodeid)
28
        elif isinstance(nodeid, int):
29
            self.nodeid = ua.NodeId(nodeid, 0)
30
        else:
31
            raise ua.UaError("argument to node must be a NodeId object or a string defining a nodeid found {} of type {}".format(nodeid, type(nodeid)))
32
33 1
    def __eq__(self, other):
34 1
        if isinstance(other, Node) and self.nodeid == other.nodeid:
35 1
            return True
36 1
        return False
37
38 1
    def __ne__(self, other):
39
        return not self.__eq__(other)
40
41 1
    def __str__(self):
42
        return "Node({})".format(self.nodeid)
43 1
    __repr__ = __str__
44
45 1
    def __hash__(self):
46 1
        return self.nodeid.__hash__()
47
48 1
    def get_browse_name(self):
49
        """
50
        Get browse name of a node. A browse name is a QualifiedName object
51
        composed of a string(name) and a namespace index.
52
        """
53 1
        result = self.get_attribute(ua.AttributeIds.BrowseName)
54 1
        return result.Value.Value
55
56 1
    def get_display_name(self):
57
        """
58
        get description attribute of node
59
        """
60 1
        result = self.get_attribute(ua.AttributeIds.DisplayName)
61 1
        return result.Value.Value
62
63 1
    def get_data_type(self):
64
        """
65
        get data type of node
66
        """
67 1
        result = self.get_attribute(ua.AttributeIds.DataType)
68 1
        return result.Value.Value
69
70 1
    def get_node_class(self):
71
        """
72
        get node class attribute of node
73
        """
74 1
        result = self.get_attribute(ua.AttributeIds.NodeClass)
75 1
        return result.Value.Value
76
77 1
    def get_description(self):
78
        """
79
        get description attribute class of node
80
        """
81 1
        result = self.get_attribute(ua.AttributeIds.Description)
82 1
        return result.Value.Value
83
84 1
    def get_value(self):
85
        """
86
        Get value of a node as a python type. Only variables ( and properties) have values.
87
        An exception will be generated for other node types.
88
        """
89 1
        result = self.get_data_value()
90 1
        return result.Value.Value
91
92 1
    def get_data_value(self):
93
        """
94
        Get value of a node as a DataValue object. Only variables (and properties) have values.
95
        An exception will be generated for other node types.
96
        DataValue contain a variable value as a variant as well as server and source timestamps
97
        """
98 1
        return self.get_attribute(ua.AttributeIds.Value)
99
100 1
    def set_array_dimensions(self, value):
101
        """
102
        Set attribute ArrayDimensions of node
103
        make sure it has the correct data type
104
        """
105 1
        v = ua.Variant(value, ua.VariantType.UInt32)
106 1
        self.set_attribute(ua.AttributeIds.ArrayDimensions, ua.DataValue(v))
107
108 1
    def get_array_dimensions(self):
109
        """
110
        Read and return ArrayDimensions attribute of node
111
        """
112 1
        res = self.get_attribute(ua.AttributeIds.ArrayDimensions)
113 1
        return res.Value.Value
114
115 1
    def set_value_rank(self, value):
116
        """
117
        Set attribute ArrayDimensions of node
118
        """
119 1
        v = ua.Variant(value, ua.VariantType.Int32)
120 1
        self.set_attribute(ua.AttributeIds.ValueRank, ua.DataValue(v))
121
122 1
    def get_value_rank(self):
123
        """
124
        Read and return ArrayDimensions attribute of node
125
        """
126 1
        res = self.get_attribute(ua.AttributeIds.ValueRank)
127 1
        return res.Value.Value
128
129 1
    def set_value(self, value, varianttype=None):
130
        """
131
        Set value of a node. Only variables(properties) have values.
132
        An exception will be generated for other node types.
133
        value argument is either:
134
        * a python built-in type, converted to opc-ua
135
        optionnaly using the variantype argument.
136
        * a ua.Variant, varianttype is then ignored
137
        * a ua.DataValue, you then have full control over data send to server
138
        """
139 1
        datavalue = None
140 1
        if isinstance(value, ua.DataValue):
141 1
            datavalue = value
142 1
        elif isinstance(value, ua.Variant):
143 1
            datavalue = ua.DataValue(value)
144
        else:
145 1
            datavalue = ua.DataValue(ua.Variant(value, varianttype))
146 1
        self.set_attribute(ua.AttributeIds.Value, datavalue)
147
148 1
    set_data_value = set_value
149
150 1
    def set_writable(self, writable=True):
151
        """
152
        Set node as writable by clients.
153
        A node is always writable on server side.
154
        """
155 1
        if writable:
156 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentWrite, ua.VariantType.Byte)))
157 1
            self.set_attribute(ua.AttributeIds.UserAccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentWrite, ua.VariantType.Byte)))
158
        else:
159 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentRead, ua.VariantType.Byte)))
160 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentRead, ua.VariantType.Byte)))
161
162 1
    def set_read_only(self):
163
        """
164
        Set a node as read-only for clients.
165
        A node is always writable on server side.
166
        """
167
        return self.set_writable(False)
168
169 1
    def set_attribute(self, attributeid, datavalue):
170
        """
171
        Set an attribute of a node
172
        attributeid is a member of ua.AttributeIds
173
        datavalue is a ua.DataValue object
174
        """
175 1
        attr = ua.WriteValue()
176 1
        attr.NodeId = self.nodeid
177 1
        attr.AttributeId = attributeid
178 1
        attr.Value = datavalue
179 1
        params = ua.WriteParameters()
180 1
        params.NodesToWrite = [attr]
181 1
        result = self.server.write(params)
182 1
        result[0].check()
183
184 1
    def get_attribute(self, attr):
185
        """
186
        Read one attribute of a node
187
        result code from server is checked and an exception is raised in case of error
188
        """
189 1
        rv = ua.ReadValueId()
190 1
        rv.NodeId = self.nodeid
191 1
        rv.AttributeId = attr
192 1
        params = ua.ReadParameters()
193 1
        params.NodesToRead.append(rv)
194 1
        result = self.server.read(params)
195 1
        result[0].StatusCode.check()
196 1
        return result[0]
197
198 1
    def get_attributes(self, attrs):
199
        """
200
        Read several attributes of a node
201
        list of DataValue is returned
202
        """
203
        params = ua.ReadParameters()
204
        for attr in attrs:
205
            rv = ua.ReadValueId()
206
            rv.NodeId = self.nodeid
207
            rv.AttributeId = attr
208
            params.NodesToRead.append(rv)
209
210
        results = self.server.read(params)
211
        return results
212
213 1
    def get_children(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified):
214
        """
215
        Get all children of a node. By default hierarchical references and all node classes are returned.
216
        Other reference types may be given:
217
        References = 31
218
        NonHierarchicalReferences = 32
219
        HierarchicalReferences = 33
220
        HasChild = 34
221
        Organizes = 35
222
        HasEventSource = 36
223
        HasModellingRule = 37
224
        HasEncoding = 38
225
        HasDescription = 39
226
        HasTypeDefinition = 40
227
        GeneratesEvent = 41
228
        Aggregates = 44
229
        HasSubtype = 45
230
        HasProperty = 46
231
        HasComponent = 47
232
        HasNotifier = 48
233
        HasOrderedComponent = 49
234
        """
235 1
        references = self.get_children_descriptions(refs, nodeclassmask)
236 1
        nodes = []
237 1
        for desc in references:
238 1
            node = Node(self.server, desc.NodeId)
239 1
            nodes.append(node)
240 1
        return nodes
241
242 1
    def get_properties(self):
243
        """
244
        return properties of node.
245
        properties are child nodes with a reference of type HasProperty and a NodeClass of Variable
246
        """
247
        return self.get_children(refs=ua.ObjectIds.HasProperty, nodeclassmask=ua.NodeClass.Variable)
248
249 1
    def get_children_descriptions(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
250
        """
251
        return all attributes of child nodes as UA BrowseResult structs
252
        """
253 1
        desc = ua.BrowseDescription()
254 1
        desc.BrowseDirection = ua.BrowseDirection.Forward
255 1
        desc.ReferenceTypeId = ua.TwoByteNodeId(refs)
256 1
        desc.IncludeSubtypes = includesubtypes
257 1
        desc.NodeClassMask = nodeclassmask
258 1
        desc.ResultMask = ua.BrowseResultMask.All
259
260 1
        desc.NodeId = self.nodeid
261 1
        params = ua.BrowseParameters()
262 1
        params.View.Timestamp = ua.win_epoch_to_datetime(0)
263 1
        params.NodesToBrowse.append(desc)
264 1
        results = self.server.browse(params)
265 1
        return results[0].References
266
267 1
    def get_child(self, path):
268
        """
269
        get a child specified by its path from this node.
270
        A path might be:
271
        * a string representing a qualified name.
272
        * a qualified name
273
        * a list of string
274
        * a list of qualified names
275
        """
276 1
        if type(path) not in (list, tuple):
277 1
            path = [path]
278 1
        rpath = ua.RelativePath()
279 1
        for item in path:
280 1
            el = ua.RelativePathElement()
281 1
            el.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HierarchicalReferences)
282 1
            el.IsInverse = False
283 1
            el.IncludeSubtypes = True
284 1
            if isinstance(item, ua.QualifiedName):
285
                el.TargetName = item
286
            else:
287 1
                el.TargetName = ua.QualifiedName.from_string(item)
288 1
            rpath.Elements.append(el)
289 1
        bpath = ua.BrowsePath()
290 1
        bpath.StartingNode = self.nodeid
291 1
        bpath.RelativePath = rpath
292 1
        result = self.server.translate_browsepaths_to_nodeids([bpath])
293 1
        result = result[0]
294 1
        result.StatusCode.check()
295
        # FIXME: seems this method may return several nodes
296 1
        return Node(self.server, result.Targets[0].TargetId)
297
298 1
    def read_raw_history(self, starttime=None, endtime=None, numvalues=0):
299
        """
300
        Read raw history of a node
301
        result code from server is checked and an exception is raised in case of error
302
        If numvalues is > 0 and number of events in period is > numvalues
303
        then result will be truncated
304
        """
305 1
        details = ua.ReadRawModifiedDetails()
306 1
        details.IsReadModified = False
307 1
        if starttime:
308 1
            details.StartTime = starttime
309
        else:
310 1
            details.StartTime = ua.DateTimeMinValue
311 1
        if endtime:
312 1
            details.EndTime = endtime
313
        else:
314
            details.EndTime = ua.DateTimeMinValue
315 1
        details.NumValuesPerNode = numvalues
316 1
        details.ReturnBounds = True
317 1
        result = self.history_read(details)
318 1
        return result.HistoryData.DataValues
319
320 1
    def history_read(self, details):
321
        """
322
        Read raw history of a node, low-level function
323
        result code from server is checked and an exception is raised in case of error
324
        """
325 1
        valueid = ua.HistoryReadValueId()
326 1
        valueid.NodeId = self.nodeid
327 1
        valueid.IndexRange = ''
328
329 1
        params = ua.HistoryReadParameters()
330 1
        params.HistoryReadDetails = details
331 1
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
332 1
        params.ReleaseContinuationPoints = False
333 1
        params.NodesToRead.append(valueid)
334 1
        result = self.server.history_read(params)[0]
335 1
        return result
336
337
    # Hack for convenience methods
338
    # local import is ugly but necessary for python2 support
339
    # feel fri to propose something better but I want to split all those
340
    # create methods from Node
341
342 1
    def add_folder(*args, **kwargs):
343 1
        from opcua.common import manage_nodes
344 1
        return manage_nodes.create_folder(*args, **kwargs)
345
346 1
    def add_object(*args, **kwargs):
347 1
        from opcua.common import manage_nodes
348 1
        return manage_nodes.create_object(*args, **kwargs)
349
350 1
    def add_variable(*args, **kwargs):
351 1
        from opcua.common import manage_nodes
352 1
        return manage_nodes.create_variable(*args, **kwargs)
353
354 1
    def add_property(*args, **kwargs):
355 1
        from opcua.common import manage_nodes
356 1
        return manage_nodes.create_property(*args, **kwargs)
357
358 1
    def add_method(*args, **kwargs):
359 1
        from opcua.common import manage_nodes
360 1
        return manage_nodes.create_method(*args, **kwargs)
361
362 1
    def call_method(*args, **kwargs):
363 1
        from opcua.common import methods
364
        return methods.call_method(*args, **kwargs)
365