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

opcua.common.Node.__str__()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
cc 1
dl 0
loc 2
ccs 2
cts 2
cp 1
crap 1
rs 10
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 1
        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_value(self, value, varianttype=None):
101
        """
102
        Set value of a node. Only variables(properties) have values.
103
        An exception will be generated for other node types.
104
        value argument is either:
105
        * a python built-in type, converted to opc-ua
106
        optionnaly using the variantype argument.
107
        * a ua.Variant, varianttype is then ignored
108
        * a ua.DataValue, you then have full control over data send to server
109
        """
110 1
        datavalue = None
111 1
        if isinstance(value, ua.DataValue):
112 1
            datavalue = value
113 1
        elif isinstance(value, ua.Variant):
114 1
            datavalue = ua.DataValue(value)
115
        else:
116 1
            datavalue = ua.DataValue(ua.Variant(value, varianttype))
117 1
        self.set_attribute(ua.AttributeIds.Value, datavalue)
118
119 1
    set_data_value = set_value
120
121 1
    def set_writable(self, writable=True):
122
        """
123
        Set node as writable by clients.
124
        A node is always writable on server side.
125
        """
126 1
        if writable:
127 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentWrite, ua.VariantType.Byte)))
128 1
            self.set_attribute(ua.AttributeIds.UserAccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentWrite, ua.VariantType.Byte)))
129
        else:
130 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentRead, ua.VariantType.Byte)))
131 1
            self.set_attribute(ua.AttributeIds.AccessLevel, ua.DataValue(ua.Variant(ua.AccessLevelMask.CurrentRead, ua.VariantType.Byte)))
132
133 1
    def set_read_only(self):
134
        """
135
        Set a node as read-only for clients.
136
        A node is always writable on server side.
137
        """
138
        return self.set_writable(False)
139
140 1
    def set_attribute(self, attributeid, datavalue):
141
        """
142
        Set an attribute of a node
143
        """
144 1
        attr = ua.WriteValue()
145 1
        attr.NodeId = self.nodeid
146 1
        attr.AttributeId = attributeid
147 1
        attr.Value = datavalue
148 1
        params = ua.WriteParameters()
149 1
        params.NodesToWrite = [attr]
150 1
        result = self.server.write(params)
151 1
        result[0].check()
152
153 1
    def get_attribute(self, attr):
154
        """
155
        Read one attribute of a node
156
        result code from server is checked and an exception is raised in case of error
157
        """
158 1
        rv = ua.ReadValueId()
159 1
        rv.NodeId = self.nodeid
160 1
        rv.AttributeId = attr
161 1
        params = ua.ReadParameters()
162 1
        params.NodesToRead.append(rv)
163 1
        result = self.server.read(params)
164 1
        result[0].StatusCode.check()
165 1
        return result[0]
166
167 1
    def get_attributes(self, attrs):
168
        """
169
        Read several attributes of a node
170
        list of DataValue is returned
171
        """
172
        params = ua.ReadParameters()
173
        for attr in attrs:
174
            rv = ua.ReadValueId()
175
            rv.NodeId = self.nodeid
176
            rv.AttributeId = attr
177
            params.NodesToRead.append(rv)
178
179
        results = self.server.read(params)
180
        return results
181
182 1
    def get_children(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified):
183
        """
184
        Get all children of a node. By default hierarchical references and all node classes are returned.
185
        Other reference types may be given:
186
        References = 31
187
        NonHierarchicalReferences = 32
188
        HierarchicalReferences = 33
189
        HasChild = 34
190
        Organizes = 35
191
        HasEventSource = 36
192
        HasModellingRule = 37
193
        HasEncoding = 38
194
        HasDescription = 39
195
        HasTypeDefinition = 40
196
        GeneratesEvent = 41
197
        Aggregates = 44
198
        HasSubtype = 45
199
        HasProperty = 46
200
        HasComponent = 47
201
        HasNotifier = 48
202
        HasOrderedComponent = 49
203
        """
204 1
        references = self.get_children_descriptions(refs, nodeclassmask)
205 1
        nodes = []
206 1
        for desc in references:
207 1
            node = Node(self.server, desc.NodeId)
208 1
            nodes.append(node)
209 1
        return nodes
210
211 1
    def get_properties(self):
212
        """
213
        return properties of node.
214
        properties are child nodes with a reference of type HasProperty and a NodeClass of Variable
215
        """
216
        return self.get_children(refs=ua.ObjectIds.HasProperty, nodeclassmask=ua.NodeClass.Variable)
217
218 1
    def get_children_descriptions(self, refs=ua.ObjectIds.HierarchicalReferences, nodeclassmask=ua.NodeClass.Unspecified, includesubtypes=True):
219
        """
220
        return all attributes of child nodes as UA BrowseResult structs
221
        """
222 1
        desc = ua.BrowseDescription()
223 1
        desc.BrowseDirection = ua.BrowseDirection.Forward
224 1
        desc.ReferenceTypeId = ua.TwoByteNodeId(refs)
225 1
        desc.IncludeSubtypes = includesubtypes
226 1
        desc.NodeClassMask = nodeclassmask
227 1
        desc.ResultMask = ua.BrowseResultMask.All
228
229 1
        desc.NodeId = self.nodeid
230 1
        params = ua.BrowseParameters()
231 1
        params.View.Timestamp = ua.win_epoch_to_datetime(0)
232 1
        params.NodesToBrowse.append(desc)
233 1
        results = self.server.browse(params)
234 1
        return results[0].References
235
236 1
    def get_child(self, path):
237
        """
238
        get a child specified by its path from this node.
239
        A path might be:
240
        * a string representing a qualified name.
241
        * a qualified name
242
        * a list of string
243
        * a list of qualified names
244
        """
245 1
        if type(path) not in (list, tuple):
246 1
            path = [path]
247 1
        rpath = ua.RelativePath()
248 1
        for item in path:
249 1
            el = ua.RelativePathElement()
250 1
            el.ReferenceTypeId = ua.TwoByteNodeId(ua.ObjectIds.HierarchicalReferences)
251 1
            el.IsInverse = False
252 1
            el.IncludeSubtypes = True
253 1
            if isinstance(item, ua.QualifiedName):
254
                el.TargetName = item
255
            else:
256 1
                el.TargetName = ua.QualifiedName.from_string(item)
257 1
            rpath.Elements.append(el)
258 1
        bpath = ua.BrowsePath()
259 1
        bpath.StartingNode = self.nodeid
260 1
        bpath.RelativePath = rpath
261 1
        result = self.server.translate_browsepaths_to_nodeids([bpath])
262 1
        result = result[0]
263 1
        result.StatusCode.check()
264
        # FIXME: seems this method may return several nodes
265 1
        return Node(self.server, result.Targets[0].TargetId)
266
267 1
    def read_raw_history(self, starttime=None, endtime=None, numvalues=0, returnbounds=True):
268
        """
269
        Read raw history of a node
270
        result code from server is checked and an exception is raised in case of error
271
        """
272
        details = ua.ReadRawModifiedDetails()
273
        details.IsReadModified = False
274
        if starttime:
275
            details.StartTime = starttime
276
        if endtime:
277
            details.EndTime = endtime
278
        details.NumValuesPerNode = numvalues
279
        details.ReturnBounds = returnbounds
280
        return self.history_read(details)
281
282 1
    def history_read(self, details):
283
        """
284
        Read raw history of a node, low-level function
285
        result code from server is checked and an exception is raised in case of error
286
        """
287
        valueid = ua.HistoryReadValueId()
288
        valueid.NodeId = self.nodeid
289
        valueid.IndexRange = ''
290
291
        params = ua.HistoryReadParameters()
292
        params.HistoryReadDetails = details
293
        params.TimestampsToReturn = ua.TimestampsToReturn.Both
294
        params.ReleaseContinuationPoints = False
295
        params.NodesToRead.append(valueid)
296
        result = self.server.history_read(params)[0]
297
        return result.HistoryData
298
299
    # Hack for convenience methods
300
    # local import is ugly but necessary for python2 support
301
    # feel fri to propose something better but I want to split all those
302
    # create methods fro Node
303
304 1
    def add_folder(*args, **kwargs):
305 1
        from opcua.common import manage_nodes
306 1
        return manage_nodes.create_folder(*args, **kwargs)
307
308 1
    def add_object(*args, **kwargs):
309 1
        from opcua.common import manage_nodes
310 1
        return manage_nodes.create_object(*args, **kwargs)
311
312 1
    def add_variable(*args, **kwargs):
313 1
        from opcua.common import manage_nodes
314 1
        return manage_nodes.create_variable(*args, **kwargs)
315
316 1
    def add_property(*args, **kwargs):
317 1
        from opcua.common import manage_nodes
318 1
        return manage_nodes.create_property(*args, **kwargs)
319
320 1
    def add_method(*args, **kwargs):
321 1
        from opcua.common import manage_nodes
322 1
        return manage_nodes.create_method(*args, **kwargs)
323
324 1
    def call_method(*args, **kwargs):
325 1
        from opcua.common import methods
326
        return methods.call_method(*args, **kwargs)
327