OpenSMI-Server 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- opensmi/server/__init__.py +45 -0
- opensmi/server/_server.py +454 -0
- opensmi/server/access_control.py +257 -0
- opensmi/server/base_callable.py +137 -0
- opensmi/server/base_feasibility_check.py +18 -0
- opensmi/server/base_machine.py +90 -0
- opensmi/server/base_machinery_item.py +447 -0
- opensmi/server/base_method.py +57 -0
- opensmi/server/base_precondition_check.py +20 -0
- opensmi/server/base_skill.py +299 -0
- opensmi/server/base_startup_skill.py +111 -0
- opensmi/server/common.py +93 -0
- opensmi/server/config.py +124 -0
- opensmi/server/interfaces.py +280 -0
- opensmi/server/lock.py +347 -0
- opensmi/server/mixins/__init__.py +22 -0
- opensmi/server/mixins/lockable_mixin.py +37 -0
- opensmi/server/mixins/notification_mixins.py +78 -0
- opensmi/server/mixins/parent_mixin.py +79 -0
- opensmi/server/mixins/requirements_mixin.py +77 -0
- opensmi/server/mixins/skill_logic_mixins.py +470 -0
- opensmi/server/mixins/spatial_object_mixin.py +88 -0
- opensmi/server/mixins/ua_object_container_mixins.py +131 -0
- opensmi/server/mixins/ua_variable_container_mixins.py +294 -0
- opensmi/server/nodesets/Opc.Ua.Di.NodeSet2.xml +5719 -0
- opensmi/server/nodesets/Opc.Ua.Machinery.NodeSet2.xml +1713 -0
- opensmi/server/nodesets/Opc.Ua.RSL.NodeSet2.xml +601 -0
- opensmi/server/nodesets/Opc.Ua.SmartFactory.MachineSet.NodeSet2.xml +2886 -0
- opensmi/server/nodesets/Opc.Ua.SmartFactory.SkillSet.NodeSet2.xml +856 -0
- opensmi/server/nodesets/__init__.py +26 -0
- opensmi/server/nodesets/di.py +74 -0
- opensmi/server/nodesets/machinery.py +36 -0
- opensmi/server/nodesets/rsl.py +31 -0
- opensmi/server/nodesets/smart_factory_machine_set.py +52 -0
- opensmi/server/nodesets/smart_factory_skill_set.py +32 -0
- opensmi/server/notification.py +112 -0
- opensmi/server/protocols.py +165 -0
- opensmi/server/resource.py +104 -0
- opensmi/server/spatial_object.py +328 -0
- opensmi/server/ua_fsm.py +261 -0
- opensmi/server/ua_object.py +212 -0
- opensmi/server/ua_object_containers.py +181 -0
- opensmi/server/ua_variable.py +450 -0
- opensmi/server/ua_variable_containers.py +331 -0
- opensmi/server/user.py +154 -0
- opensmi_server-0.1.dist-info/METADATA +239 -0
- opensmi_server-0.1.dist-info/RECORD +50 -0
- opensmi_server-0.1.dist-info/WHEEL +5 -0
- opensmi_server-0.1.dist-info/licenses/LICENSES/MIT.txt +18 -0
- opensmi_server-0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 OpenSMI Contributors
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""Abstraction-layer for OPC UA variables our framework users interacts with."""
|
|
6
|
+
|
|
7
|
+
from collections.abc import AsyncGenerator, Iterator
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from enum import Enum, IntEnum
|
|
10
|
+
from typing import Generic
|
|
11
|
+
|
|
12
|
+
from asyncua import ua
|
|
13
|
+
from asyncua.common.node import Node
|
|
14
|
+
from opensmi.core import Unit
|
|
15
|
+
from opensmi.core.errors import NoValidValueReadError, OutOfRangeError
|
|
16
|
+
from opensmi.core.lifecycle_mixin import lifecycle
|
|
17
|
+
from opensmi.core.ua_node_util import (
|
|
18
|
+
NULL_NODE_ID,
|
|
19
|
+
get_node_id,
|
|
20
|
+
get_properties,
|
|
21
|
+
write_range,
|
|
22
|
+
write_unit,
|
|
23
|
+
write_value,
|
|
24
|
+
)
|
|
25
|
+
from typing_extensions import TypeVar, override
|
|
26
|
+
|
|
27
|
+
from opensmi.server.mixins.parent_mixin import ParentMixin
|
|
28
|
+
from opensmi.server.ua_object import UaObject, UaObjectDefinition
|
|
29
|
+
|
|
30
|
+
_VariableType = TypeVar("_VariableType")
|
|
31
|
+
"""Python-native variable type of the `UaVariable` (e.g. ``int``, ``string``, ...)."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _get_initial_value_and_type(
|
|
35
|
+
initial_value: _VariableType | None, variable_type: type[_VariableType] | None
|
|
36
|
+
) -> tuple[ua.Variant, type[_VariableType]]:
|
|
37
|
+
if variable_type is not None and issubclass(variable_type, UaObject):
|
|
38
|
+
initial_value_type = variable_type
|
|
39
|
+
node_id = NULL_NODE_ID
|
|
40
|
+
if isinstance(initial_value, UaObject):
|
|
41
|
+
node_id = initial_value.ua_node.nodeid
|
|
42
|
+
elif isinstance(initial_value, ua.Variant):
|
|
43
|
+
assert initial_value.VariantType == ua.VariantType.NodeId
|
|
44
|
+
node_id = initial_value.Value
|
|
45
|
+
|
|
46
|
+
return ua.Variant(Value=node_id, VariantType=ua.VariantType.NodeId), initial_value_type
|
|
47
|
+
|
|
48
|
+
if isinstance(initial_value, UaObject):
|
|
49
|
+
return ua.Variant(Value=initial_value.ua_node, VariantType=ua.VariantType.NodeId), UaObject # pyright: ignore[reportReturnType]
|
|
50
|
+
|
|
51
|
+
if isinstance(initial_value, ua.Variant):
|
|
52
|
+
match initial_value.VariantType: # only variant types that allow None are a problem
|
|
53
|
+
case ua.VariantType.String:
|
|
54
|
+
return initial_value, str # pyright: ignore[reportReturnType]
|
|
55
|
+
case _:
|
|
56
|
+
return initial_value, type(initial_value.Value)
|
|
57
|
+
|
|
58
|
+
if initial_value is not None:
|
|
59
|
+
return ua.Variant(Value=initial_value), type(initial_value)
|
|
60
|
+
|
|
61
|
+
msg = f"Please provided either a non-Null {initial_value=} or a compatible {variable_type=}!"
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _validate_enum_type(enum_type: type[Enum]) -> None:
|
|
66
|
+
"""Ensure given ``enum_type`` satisfies OPC UA's enumeration requirements."""
|
|
67
|
+
if not issubclass(enum_type, IntEnum):
|
|
68
|
+
msg = "Enums are only supported as IntEnums!"
|
|
69
|
+
raise TypeError(msg)
|
|
70
|
+
|
|
71
|
+
values = [member.value for member in enum_type]
|
|
72
|
+
expected = list(range(len(values)))
|
|
73
|
+
if values != expected:
|
|
74
|
+
msg = (
|
|
75
|
+
f"OPC UA compatible IntEnums must start at 0 and increase by 1 per member; "
|
|
76
|
+
f"{enum_type.__name__} has values {values}, expected {expected}."
|
|
77
|
+
)
|
|
78
|
+
raise ValueError(msg)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class UaVariable(UaObject, ParentMixin[UaObject], Generic[_VariableType]):
|
|
82
|
+
"""OPC UA Variable for use in `ParameterSet`, `Monitoring`, `FinalResultData`, etc.
|
|
83
|
+
|
|
84
|
+
Abstracts raw OPC UA/``asyncua`` away and provides a simple, high-level interface.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
_initial_value_type: type[_VariableType]
|
|
88
|
+
_initial_value: ua.Variant
|
|
89
|
+
_unit: ua.EUInformation | None
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
initial_value: _VariableType | None,
|
|
94
|
+
*,
|
|
95
|
+
unit: Unit | str | int | ua.EUInformation | None = None,
|
|
96
|
+
range: tuple[float | int, float | int] | ua.Range | None = None, # noqa: A002
|
|
97
|
+
minimum_access_level: int | None = None,
|
|
98
|
+
writable: bool = False,
|
|
99
|
+
historize: bool = False,
|
|
100
|
+
bypass_lock: bool = False,
|
|
101
|
+
variable_type: type[_VariableType] | None = None,
|
|
102
|
+
optional_ok: bool = False,
|
|
103
|
+
**kwargs,
|
|
104
|
+
) -> None:
|
|
105
|
+
"""*Cooperative* constructor for a new variable instance.
|
|
106
|
+
|
|
107
|
+
:param initial_value: The initial value of the variable. This should not be ``None`` for both correct type hints
|
|
108
|
+
and correctly guessed OPC UA data type of the corresponding OPC UA variable node.
|
|
109
|
+
:param unit: The engineering unit of the variable. Can either be an `Unit`, an integer
|
|
110
|
+
(= OPC UA `ua.EUInformation.UnitId`, e.g. 4410708), or a string (symbol = OPC UA display name, e.g. "cm").
|
|
111
|
+
If provided, the range ``range_`` parameter is mandatory!
|
|
112
|
+
:param range: Tuple containing the minimum and maximum values of the variable.
|
|
113
|
+
:param minimum_access_level: Minimum access level required to write to the variable (externally via OPC UA).
|
|
114
|
+
:param writable: Whether the variable is writable externally or not. Always writable internally.
|
|
115
|
+
:param historize: Whether to keep a history of past values of this variable.
|
|
116
|
+
:param bypass_lock: Whether the variable can be written to without ownership of corresponding lock.
|
|
117
|
+
:param variable_type: The Python type of the variable. Is only required if type cannot be determined from
|
|
118
|
+
``initial_value``, i.e. when ``None`` is provided.
|
|
119
|
+
"""
|
|
120
|
+
super().__init__(minimum_access_level=minimum_access_level, bypass_lock=bypass_lock, **kwargs) # pyright: ignore[reportArgumentType]
|
|
121
|
+
|
|
122
|
+
self._initial_value, self._initial_value_type = _get_initial_value_and_type(initial_value, variable_type)
|
|
123
|
+
assert self._initial_value.VariantType != ua.VariantType.Null
|
|
124
|
+
if issubclass(self._initial_value_type, Enum):
|
|
125
|
+
_validate_enum_type(self._initial_value_type)
|
|
126
|
+
|
|
127
|
+
if isinstance(unit, Unit):
|
|
128
|
+
self._unit = unit.ua_eu_information
|
|
129
|
+
elif isinstance(unit, str):
|
|
130
|
+
self._unit = Unit.from_symbol(unit).ua_eu_information
|
|
131
|
+
elif isinstance(unit, int):
|
|
132
|
+
self._unit = Unit.from_ua_unit_id(unit).ua_eu_information
|
|
133
|
+
elif isinstance(unit, ua.EUInformation):
|
|
134
|
+
self._unit = unit
|
|
135
|
+
else:
|
|
136
|
+
assert unit is None, f"Given {unit} is neither str, int, ua.EUInformation nor None!"
|
|
137
|
+
self._unit = unit
|
|
138
|
+
|
|
139
|
+
if isinstance(range, ua.Range):
|
|
140
|
+
range = (range.Low, range.High) # noqa: A001
|
|
141
|
+
self._range: tuple[float | int, float | int] | None = range
|
|
142
|
+
self._writable: bool = writable
|
|
143
|
+
self._historize: bool = historize
|
|
144
|
+
self._references: set[UaObject] = set()
|
|
145
|
+
self.optional_ok: bool = optional_ok
|
|
146
|
+
|
|
147
|
+
@lifecycle
|
|
148
|
+
async def _init(self) -> AsyncGenerator[None]:
|
|
149
|
+
try:
|
|
150
|
+
await self.write(self._initial_value)
|
|
151
|
+
except ua.uaerrors.UaError as err:
|
|
152
|
+
self.logger.warning("Could not write initial value", value=self._initial_value, reason=err)
|
|
153
|
+
|
|
154
|
+
if self._unit is not None:
|
|
155
|
+
await write_unit(self.ua_node, self._unit)
|
|
156
|
+
|
|
157
|
+
if self._range is not None:
|
|
158
|
+
await write_range(self.ua_node, self._range)
|
|
159
|
+
|
|
160
|
+
if self._writable: # ua nodes are not writable by default
|
|
161
|
+
await self.set_writable(self._writable)
|
|
162
|
+
|
|
163
|
+
# deliberately after writing initial value
|
|
164
|
+
if self._historize:
|
|
165
|
+
await self.set_historize(self._historize)
|
|
166
|
+
|
|
167
|
+
# Note: references added after we are initialized are created immediately
|
|
168
|
+
for ref in self._references:
|
|
169
|
+
await self._ua_add_reference(ref)
|
|
170
|
+
|
|
171
|
+
yield
|
|
172
|
+
# no shutdown
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def initial_value(self) -> _VariableType:
|
|
176
|
+
"""Initial value of the variable."""
|
|
177
|
+
if isinstance(self._initial_value, ua.Variant):
|
|
178
|
+
return self._extract_value(self._initial_value.Value)
|
|
179
|
+
return self._extract_value(self._initial_value)
|
|
180
|
+
|
|
181
|
+
@initial_value.setter
|
|
182
|
+
def initial_value(self, value: _VariableType | ua.Variant) -> None:
|
|
183
|
+
if isinstance(value, ua.Variant):
|
|
184
|
+
value = value.Value
|
|
185
|
+
|
|
186
|
+
if not isinstance(value, self._initial_value_type):
|
|
187
|
+
msg = f"Type of {value} ({type(value)}) is not the same as previous type: {self._initial_value_type}"
|
|
188
|
+
raise TypeError(msg)
|
|
189
|
+
|
|
190
|
+
previous = self._initial_value
|
|
191
|
+
value = ua.uatypes.get_default_value(self._initial_value.VariantType) if value is None else value
|
|
192
|
+
self._initial_value, _ = _get_initial_value_and_type(value, self._initial_value_type)
|
|
193
|
+
self.logger.debug("Updated initial value", initial_value=self._initial_value, previous_value=previous)
|
|
194
|
+
|
|
195
|
+
async def set_writable(self, writable: bool) -> None:
|
|
196
|
+
"""Set the variable to ``writable`` externally. Internally, a variable is always writable."""
|
|
197
|
+
await self.ua_node.set_writable(writable)
|
|
198
|
+
self._writable = writable
|
|
199
|
+
self.logger.debug("Set variable writable", writable=writable)
|
|
200
|
+
|
|
201
|
+
async def set_historize(self, historize: bool, *, period: timedelta = timedelta(days=7), count: int = 1000) -> None:
|
|
202
|
+
"""Set the variable to ``historize``.
|
|
203
|
+
|
|
204
|
+
:param historize: Whether the variable should be historized or not. The other parameters are ignored
|
|
205
|
+
when ``False``.
|
|
206
|
+
:param period: data older than this will be deleted from the history. By default, keep the last 7 days.
|
|
207
|
+
:param count: max. number of value changes to keep in the history. ``0`` = no count limit
|
|
208
|
+
"""
|
|
209
|
+
if historize:
|
|
210
|
+
await self.server.ua_server.historize_node_data_change(self.ua_node, period=period, count=count)
|
|
211
|
+
else:
|
|
212
|
+
await self.server.ua_server.dehistorize_node_data_change(self.ua_node)
|
|
213
|
+
self._historize = historize
|
|
214
|
+
self.logger.debug("Set variable historize", historize=historize)
|
|
215
|
+
|
|
216
|
+
@override
|
|
217
|
+
async def _get_definition(self) -> UaObjectDefinition:
|
|
218
|
+
raise NotImplementedError # We don't use this since we override own _ua_create_node
|
|
219
|
+
|
|
220
|
+
@override
|
|
221
|
+
async def _ua_create_node(
|
|
222
|
+
self, ua_location: Node, *, instantiate_optional: bool, exist_ok: bool, remove_existing: bool
|
|
223
|
+
) -> None:
|
|
224
|
+
node_id = get_node_id(ua_location, name=self.name)
|
|
225
|
+
browse_name = ua.QualifiedName(self.name, NamespaceIndex=1)
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
if issubclass(self._initial_value_type, IntEnum):
|
|
229
|
+
if self._unit is not None or self._range is not None:
|
|
230
|
+
msg = "Enums cannot be used with units or ranges!"
|
|
231
|
+
raise ValueError(msg)
|
|
232
|
+
|
|
233
|
+
ua_datatype_node = await self.server.get_enum(self._initial_value_type) # pyright: ignore[reportArgumentType]
|
|
234
|
+
self.ua_node = await ua_location.add_variable(
|
|
235
|
+
nodeid=node_id, bname=browse_name, val=self._initial_value, datatype=ua_datatype_node
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
elif self._unit is None:
|
|
239
|
+
if self._range is not None: # notify programmer of their error instead of silently ignoring it
|
|
240
|
+
msg = "Ranges can only be used in combination with a unit!"
|
|
241
|
+
raise ValueError(msg)
|
|
242
|
+
|
|
243
|
+
self.ua_node = await ua_location.add_variable(
|
|
244
|
+
nodeid=node_id, bname=browse_name, val=self._initial_value
|
|
245
|
+
)
|
|
246
|
+
return
|
|
247
|
+
else:
|
|
248
|
+
if self._range is None:
|
|
249
|
+
object_type = ua.object_ids.ObjectIds.AnalogUnitType
|
|
250
|
+
else:
|
|
251
|
+
object_type = ua.object_ids.ObjectIds.AnalogUnitRangeType
|
|
252
|
+
|
|
253
|
+
self.ua_node = await ua_location.add_object(
|
|
254
|
+
nodeid=node_id,
|
|
255
|
+
bname=browse_name,
|
|
256
|
+
objecttype=object_type,
|
|
257
|
+
instantiate_optional=False,
|
|
258
|
+
)
|
|
259
|
+
except ua.uaerrors.BadNodeIdExists:
|
|
260
|
+
if exist_ok:
|
|
261
|
+
self.logger.warning(
|
|
262
|
+
"Variable node already exists, skipping instantiation!",
|
|
263
|
+
node_id=node_id.to_string(),
|
|
264
|
+
)
|
|
265
|
+
self.ua_node = Node(ua_location.session, node_id)
|
|
266
|
+
data_value = await self.ua_node.read_data_value()
|
|
267
|
+
assert data_value.Value is not None
|
|
268
|
+
self._initial_value = data_value.Value
|
|
269
|
+
self._variant_type = await self.ua_node.read_data_type_as_variant_type()
|
|
270
|
+
properties = await get_properties(self.ua_node)
|
|
271
|
+
self._unit = properties.unit
|
|
272
|
+
if properties.range is not None:
|
|
273
|
+
self._range = (properties.range.Low, properties.range.High)
|
|
274
|
+
elif remove_existing:
|
|
275
|
+
msg = "remove_existing parameter is not implemented yet!"
|
|
276
|
+
raise NotImplementedError(msg) from None # TODO(CaHa)
|
|
277
|
+
else:
|
|
278
|
+
raise
|
|
279
|
+
|
|
280
|
+
async def add_reference(self, target: UaObject) -> None:
|
|
281
|
+
"""Add a reference to the given ``target`` `UaObject`, i.e. a `Resource`.
|
|
282
|
+
|
|
283
|
+
Defines valid values for `UaObject` variable types.
|
|
284
|
+
"""
|
|
285
|
+
if not issubclass(self._initial_value_type, UaObject):
|
|
286
|
+
msg = f"Variable type of {self.path} is not of type UaObject: {self._initial_value_type}!"
|
|
287
|
+
raise TypeError(msg)
|
|
288
|
+
assert isinstance(target, UaObject)
|
|
289
|
+
self._references.add(target)
|
|
290
|
+
if self.is_initialized and target.is_initialized:
|
|
291
|
+
# we can only add OPC UA references when both UaObjects have ua nodes
|
|
292
|
+
await self._ua_add_reference(target)
|
|
293
|
+
|
|
294
|
+
async def _ua_add_reference(self, target: UaObject) -> None:
|
|
295
|
+
await self.ua_node.add_reference(
|
|
296
|
+
target=target.ua_node,
|
|
297
|
+
reftype=ua.FourByteNodeId(ua.Int32(ua.object_ids.ObjectIds.Utilizes)),
|
|
298
|
+
)
|
|
299
|
+
self.logger.debug("Added utilizes reference", target=target.path)
|
|
300
|
+
|
|
301
|
+
async def remove_reference(self, target: UaObject) -> None:
|
|
302
|
+
"""Remove the existing reference to the given ``target`` `UaObject`."""
|
|
303
|
+
assert isinstance(target, UaObject)
|
|
304
|
+
self._references.remove(target)
|
|
305
|
+
await self.ua_node.delete_reference(
|
|
306
|
+
target=target.ua_node,
|
|
307
|
+
reftype=ua.FourByteNodeId(ua.Int32(ua.object_ids.ObjectIds.Utilizes)),
|
|
308
|
+
)
|
|
309
|
+
self.logger.debug("Removed utilizes reference", target=target.path)
|
|
310
|
+
|
|
311
|
+
def write_check(self, value: _VariableType | ua.Variant | None) -> None:
|
|
312
|
+
"""Check whether given ``value`` can be written to this variable.
|
|
313
|
+
|
|
314
|
+
:raises OutOfRangeError: if ``value`` is not within the range of the variable.
|
|
315
|
+
"""
|
|
316
|
+
self.logger.debug("write check", value=value)
|
|
317
|
+
|
|
318
|
+
if value is None and not self.optional_ok and self._initial_value_type is not str:
|
|
319
|
+
msg = f"None is not a valid value for {self.path}!"
|
|
320
|
+
raise OutOfRangeError(msg)
|
|
321
|
+
|
|
322
|
+
if isinstance(value, ua.Variant):
|
|
323
|
+
value = value.Value
|
|
324
|
+
|
|
325
|
+
if isinstance(value, UaObject) and value not in self._references:
|
|
326
|
+
msg = f"{value=} is not referenced as a valid value for {self.path}!"
|
|
327
|
+
raise OutOfRangeError(msg)
|
|
328
|
+
if isinstance(value, ua.NodeId):
|
|
329
|
+
if value.is_null() and self.optional_ok:
|
|
330
|
+
return
|
|
331
|
+
|
|
332
|
+
try:
|
|
333
|
+
obj = self.server.get_ua_object(value)
|
|
334
|
+
if obj not in self._references:
|
|
335
|
+
msg = f"{value=} is a valid {obj}, but not referenced as a valid value for {self.path}!"
|
|
336
|
+
raise OutOfRangeError(msg)
|
|
337
|
+
except KeyError:
|
|
338
|
+
msg = f"{value=} is not a valid UaObject!"
|
|
339
|
+
raise OutOfRangeError(msg) from None
|
|
340
|
+
|
|
341
|
+
if not self.check_range(value):
|
|
342
|
+
assert self._range is not None
|
|
343
|
+
msg = (
|
|
344
|
+
f"Value {value} is out of range for {self.path}! Must be between {self._range[0]} and {self._range[1]}!"
|
|
345
|
+
)
|
|
346
|
+
raise OutOfRangeError(msg)
|
|
347
|
+
|
|
348
|
+
if issubclass(self._initial_value_type, IntEnum):
|
|
349
|
+
try:
|
|
350
|
+
value = self._initial_value_type(value)
|
|
351
|
+
except ValueError as err:
|
|
352
|
+
msg = f"{self.path}: Given value {value} is outside of valid values for {self._initial_value_type}!"
|
|
353
|
+
raise OutOfRangeError(msg) from err
|
|
354
|
+
|
|
355
|
+
async def write(self, value: _VariableType | ua.Variant | None) -> None:
|
|
356
|
+
"""Write given ``value`` to this variable.
|
|
357
|
+
|
|
358
|
+
**Note**: ``None`` is only valid for a small set of variable types:
|
|
359
|
+
``str`` and `UaObject` based (internally OPC UA nodes)
|
|
360
|
+
|
|
361
|
+
:raises OutOfRangeError: if ``value`` is not within the range of the variable.
|
|
362
|
+
"""
|
|
363
|
+
# self.write_check(value) # is checked by access control
|
|
364
|
+
if isinstance(value, UaObject):
|
|
365
|
+
value = value.ua_node.nodeid # pyright: ignore[reportAssignmentType]
|
|
366
|
+
await write_value(node=self.ua_node, value=value, variant_type=self._initial_value.VariantType)
|
|
367
|
+
# self.logger.debug("Written to variable", value=new_value)
|
|
368
|
+
|
|
369
|
+
def _extract_value(self, value) -> _VariableType:
|
|
370
|
+
if issubclass(self._initial_value_type, IntEnum):
|
|
371
|
+
return self._initial_value_type(value)
|
|
372
|
+
if issubclass(self._initial_value_type, UaObject):
|
|
373
|
+
if isinstance(value, Node):
|
|
374
|
+
value = value.nodeid
|
|
375
|
+
assert isinstance(value, ua.NodeId), f"{value=} is not a valid NodeId!"
|
|
376
|
+
if value.is_null():
|
|
377
|
+
msg = f"No valid value provided for '{self.path}'!"
|
|
378
|
+
raise NoValidValueReadError(msg)
|
|
379
|
+
ua_object = self.server.get_ua_object(value)
|
|
380
|
+
assert isinstance(ua_object, self._initial_value_type), (
|
|
381
|
+
f"UaObject does not have type {self._initial_value_type}: {ua_object.__class__.__name__}!"
|
|
382
|
+
)
|
|
383
|
+
return ua_object # pyright: ignore[reportReturnType]
|
|
384
|
+
return value
|
|
385
|
+
|
|
386
|
+
async def read(self) -> _VariableType:
|
|
387
|
+
"""Read current value from variable.
|
|
388
|
+
|
|
389
|
+
:raises PyUaRuntimeError: If reading an `UaObject` based variable type would result in ``None`` due to
|
|
390
|
+
Null Node ID.
|
|
391
|
+
"""
|
|
392
|
+
value = await self.ua_node.read_value()
|
|
393
|
+
return self._extract_value(value)
|
|
394
|
+
|
|
395
|
+
async def read_optional(self) -> _VariableType | None:
|
|
396
|
+
"""Read current value from variable. Might be ``None``."""
|
|
397
|
+
try:
|
|
398
|
+
return await self.read()
|
|
399
|
+
except NoValidValueReadError:
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
async def reset(self) -> None:
|
|
403
|
+
"""Reset variable to initial value."""
|
|
404
|
+
await self.write(self._initial_value)
|
|
405
|
+
|
|
406
|
+
def check_range(self, value: _VariableType | ua.Variant | None) -> bool:
|
|
407
|
+
"""Check whether the given value is within the range.
|
|
408
|
+
|
|
409
|
+
:returns: ``True`` if the given value is within the range (or there is no range specified), ``False`` otherwise.
|
|
410
|
+
"""
|
|
411
|
+
if self._range is None:
|
|
412
|
+
return True
|
|
413
|
+
if isinstance(value, ua.Variant):
|
|
414
|
+
value = value.Value
|
|
415
|
+
assert isinstance(value, (float, int)), f"{self.path}: {value} is not a float or int!"
|
|
416
|
+
low, high = self._range
|
|
417
|
+
return low <= value <= high
|
|
418
|
+
|
|
419
|
+
def clone(self, *, name: str, writable: bool | None = None) -> "UaVariable[_VariableType]":
|
|
420
|
+
"""Clone the variable configuration. It must be initialized before using it.
|
|
421
|
+
|
|
422
|
+
:param name: The name of the variable.
|
|
423
|
+
:param writable: Override ``writable`` configuration in clone if not ``None``.
|
|
424
|
+
"""
|
|
425
|
+
if writable is None:
|
|
426
|
+
writable = self._writable
|
|
427
|
+
return UaVariable( # pyright: ignore[reportReturnType]
|
|
428
|
+
name=name,
|
|
429
|
+
minimum_access_level=self.minimum_access_level,
|
|
430
|
+
initial_value=self._initial_value,
|
|
431
|
+
unit=self._unit,
|
|
432
|
+
range=self._range,
|
|
433
|
+
writable=writable,
|
|
434
|
+
historize=self._historize,
|
|
435
|
+
bypass_lock=self.bypass_lock,
|
|
436
|
+
variable_type=self._initial_value_type,
|
|
437
|
+
optional_ok=self.optional_ok,
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
@override
|
|
441
|
+
def _repr_items(self) -> Iterator[tuple[str, object]]:
|
|
442
|
+
yield "initial_value", self._initial_value
|
|
443
|
+
yield "initial_value_type", self._initial_value_type
|
|
444
|
+
yield "unit", self._unit
|
|
445
|
+
yield "range", self._range
|
|
446
|
+
yield "writable", self._writable
|
|
447
|
+
yield "historize", self._historize
|
|
448
|
+
yield "variable_type", self._initial_value_type
|
|
449
|
+
yield "optional_ok", self.optional_ok
|
|
450
|
+
yield from super()._repr_items()
|