Completed
Push — master ( 84aa05...20fced )
by Olivier
02:36
created

opcua.common.Node.get_node_class()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

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