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

opcua.common.Node.add_variable()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
cc 1
dl 0
loc 3
rs 10
ccs 3
cts 3
cp 1
crap 1
1
"""
2
High level node object, to access node attribute
3
and browse address space
4
"""
5
6 1
from datetime import timedelta
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 Node code 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, returnbounds=True):
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
        """
303 1
        details = ua.ReadRawModifiedDetails()
304 1
        details.IsReadModified = False
305 1
        if starttime:
306 1
            details.StartTime = starttime
307
        else:
308 1
            details.StartTime = ua.DateTimeMinValue
309 1
        if endtime:
310 1
            details.EndTime = endtime
311
        else:
312
            details.EndTime = ua.DateTimeMinValue
313 1
        details.NumValuesPerNode = numvalues
314 1
        details.ReturnBounds = returnbounds
315 1
        result = self.history_read(details)
316
        # FIXME: read continuation point and call again
317 1
        return result.HistoryData.DataValues
318
319 1
    def history_read(self, details):
320
        """
321
        Read raw history of a node, low-level function
322
        result code from server is checked and an exception is raised in case of error
323
        """
324 1
        valueid = ua.HistoryReadValueId()
325 1
        valueid.NodeId = self.nodeid
326 1
        valueid.IndexRange = ''
327
328 1
        params = ua.HistoryReadParameters()
329 1
        params.HistoryReadDetails = details
330 1
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
331 1
        params.ReleaseContinuationPoints = False
332 1
        params.NodesToRead.append(valueid)
333 1
        result = self.server.history_read(params)[0]
334 1
        return result
335
336
    # Hack for convenience methods
337
    # local import is ugly but necessary for python2 support
338
    # feel fri to propose something better but I want to split all those
339
    # create methods fro Node
340
341 1
    def add_folder(*args, **kwargs):
342 1
        from opcua.common import manage_nodes
343 1
        return manage_nodes.create_folder(*args, **kwargs)
344
345 1
    def add_object(*args, **kwargs):
346 1
        from opcua.common import manage_nodes
347 1
        return manage_nodes.create_object(*args, **kwargs)
348
349 1
    def add_variable(*args, **kwargs):
350 1
        from opcua.common import manage_nodes
351 1
        return manage_nodes.create_variable(*args, **kwargs)
352
353 1
    def add_property(*args, **kwargs):
354 1
        from opcua.common import manage_nodes
355 1
        return manage_nodes.create_property(*args, **kwargs)
356
357 1
    def add_method(*args, **kwargs):
358 1
        from opcua.common import manage_nodes
359 1
        return manage_nodes.create_method(*args, **kwargs)
360
361 1
    def call_method(*args, **kwargs):
362 1
        from opcua.common import methods
363
        return methods.call_method(*args, **kwargs)
364