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.
Files changed (50) hide show
  1. opensmi/server/__init__.py +45 -0
  2. opensmi/server/_server.py +454 -0
  3. opensmi/server/access_control.py +257 -0
  4. opensmi/server/base_callable.py +137 -0
  5. opensmi/server/base_feasibility_check.py +18 -0
  6. opensmi/server/base_machine.py +90 -0
  7. opensmi/server/base_machinery_item.py +447 -0
  8. opensmi/server/base_method.py +57 -0
  9. opensmi/server/base_precondition_check.py +20 -0
  10. opensmi/server/base_skill.py +299 -0
  11. opensmi/server/base_startup_skill.py +111 -0
  12. opensmi/server/common.py +93 -0
  13. opensmi/server/config.py +124 -0
  14. opensmi/server/interfaces.py +280 -0
  15. opensmi/server/lock.py +347 -0
  16. opensmi/server/mixins/__init__.py +22 -0
  17. opensmi/server/mixins/lockable_mixin.py +37 -0
  18. opensmi/server/mixins/notification_mixins.py +78 -0
  19. opensmi/server/mixins/parent_mixin.py +79 -0
  20. opensmi/server/mixins/requirements_mixin.py +77 -0
  21. opensmi/server/mixins/skill_logic_mixins.py +470 -0
  22. opensmi/server/mixins/spatial_object_mixin.py +88 -0
  23. opensmi/server/mixins/ua_object_container_mixins.py +131 -0
  24. opensmi/server/mixins/ua_variable_container_mixins.py +294 -0
  25. opensmi/server/nodesets/Opc.Ua.Di.NodeSet2.xml +5719 -0
  26. opensmi/server/nodesets/Opc.Ua.Machinery.NodeSet2.xml +1713 -0
  27. opensmi/server/nodesets/Opc.Ua.RSL.NodeSet2.xml +601 -0
  28. opensmi/server/nodesets/Opc.Ua.SmartFactory.MachineSet.NodeSet2.xml +2886 -0
  29. opensmi/server/nodesets/Opc.Ua.SmartFactory.SkillSet.NodeSet2.xml +856 -0
  30. opensmi/server/nodesets/__init__.py +26 -0
  31. opensmi/server/nodesets/di.py +74 -0
  32. opensmi/server/nodesets/machinery.py +36 -0
  33. opensmi/server/nodesets/rsl.py +31 -0
  34. opensmi/server/nodesets/smart_factory_machine_set.py +52 -0
  35. opensmi/server/nodesets/smart_factory_skill_set.py +32 -0
  36. opensmi/server/notification.py +112 -0
  37. opensmi/server/protocols.py +165 -0
  38. opensmi/server/resource.py +104 -0
  39. opensmi/server/spatial_object.py +328 -0
  40. opensmi/server/ua_fsm.py +261 -0
  41. opensmi/server/ua_object.py +212 -0
  42. opensmi/server/ua_object_containers.py +181 -0
  43. opensmi/server/ua_variable.py +450 -0
  44. opensmi/server/ua_variable_containers.py +331 -0
  45. opensmi/server/user.py +154 -0
  46. opensmi_server-0.1.dist-info/METADATA +239 -0
  47. opensmi_server-0.1.dist-info/RECORD +50 -0
  48. opensmi_server-0.1.dist-info/WHEEL +5 -0
  49. opensmi_server-0.1.dist-info/licenses/LICENSES/MIT.txt +18 -0
  50. opensmi_server-0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,470 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """State machine logic for both finite & continuous skills."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import contextlib
11
+ from abc import abstractmethod
12
+ from asyncio import Task
13
+ from collections.abc import AsyncGenerator, Awaitable, Callable
14
+ from typing import Literal
15
+
16
+ from asyncua import ua
17
+ from asyncua.common.methods import uamethod
18
+ from asyncua.ua import NodeId, StatusCode
19
+ from asyncua.ua.status_codes import StatusCodes as UaStatusCodes
20
+ from opensmi.core import SkillState
21
+ from opensmi.core.errors import OpenSmiRuntimeError
22
+ from opensmi.core.lifecycle_mixin import lifecycle
23
+ from transitions import MachineError
24
+ from typing_extensions import override
25
+
26
+ from opensmi.server.base_callable import BaseCallable
27
+ from opensmi.server.interfaces import AbstractSkill, AbstractUaLogger
28
+ from opensmi.server.nodesets import SmartFactoryMachineSetNodeIds
29
+ from opensmi.server.protocols import SessionProtocol, UserAuthorization
30
+ from opensmi.server.ua_fsm import UaFiniteStateMachine
31
+ from opensmi.server.ua_object import UaObjectDefinition
32
+ from opensmi.server.ua_variable import UaVariable
33
+ from opensmi.server.ua_variable_containers import FinalResultData
34
+ from opensmi.server.user import INTERNAL_USER
35
+
36
+ TRIGGER = Literal[
37
+ "halt",
38
+ "halting_done",
39
+ "reset",
40
+ "resetting_done",
41
+ "start",
42
+ "starting_done",
43
+ "suspend",
44
+ "suspending_done",
45
+ "done_internal",
46
+ ]
47
+ """ All state machine transition triggers for the skill state machine. """
48
+
49
+
50
+ class _SkillLogicMixin(AbstractSkill, AbstractUaLogger):
51
+ """Base class for all python-native skills (with state machine logic)."""
52
+
53
+ def __init__(self, **kwargs) -> None: # TODO(CaHa): proper mixin without __init__
54
+ """*Cooperative* constructor."""
55
+ super().__init__(**kwargs)
56
+
57
+ self.__tasks: dict[str, Task] = {}
58
+ """Keeps track of tasks related to skill execution and their name.
59
+ These tasks will get canceled and emptied before handle_halting() is called."""
60
+
61
+ self._resume_event: asyncio.Event = asyncio.Event()
62
+ self._resume_event.set() # not suspended by default
63
+ self._paused_event: asyncio.Event = asyncio.Event()
64
+
65
+ self._machine: UaFiniteStateMachine = UaFiniteStateMachine(
66
+ name=f"{self.name}_StateMachine",
67
+ states=SkillState, # type: ignore
68
+ initial=SkillState.HALTED,
69
+ exclude_states=[] if self.is_finite else [SkillState.COMPLETED, SkillState.COMPLETING],
70
+ write_func=self._write_current_state,
71
+ )
72
+ """Skill Finite State Machine."""
73
+ self._add_transitions()
74
+
75
+ @lifecycle(after=BaseCallable.lifecycle_callable)
76
+ async def lifecycle_skill_state_machine(self) -> AsyncGenerator[None]:
77
+ """Initialize the skill state machine."""
78
+ # ensure initialization comes first
79
+ await self._machine.init(self.ua_state_machine)
80
+ # self.server.ua_get_node_id(SmartFactoryMachineSetNodeIds.SkillStateMachineType),
81
+ yield
82
+ # no shutdown
83
+
84
+ def _add_transitions(self) -> None:
85
+ self._machine.add_transition(
86
+ trigger="reset",
87
+ source=[SkillState.HALTED, SkillState.STARTING, SkillState.SUSPENDED, SkillState.COMPLETED],
88
+ dest=SkillState.RESETTING,
89
+ conditions=[self._condition_access_allowed, self._condition_reset_allowed],
90
+ after=self._after_resetting,
91
+ )
92
+ self._machine.add_transition(trigger="resetting_done", source=SkillState.RESETTING, dest=SkillState.READY)
93
+
94
+ self._machine.add_transition(
95
+ trigger="halt",
96
+ source=[
97
+ SkillState.RESETTING,
98
+ SkillState.READY,
99
+ SkillState.STARTING,
100
+ SkillState.RUNNING,
101
+ SkillState.COMPLETED,
102
+ SkillState.SUSPENDED,
103
+ SkillState.SUSPENDING,
104
+ ],
105
+ dest=SkillState.HALTING,
106
+ conditions=[self._condition_access_allowed],
107
+ after=self._after_halting,
108
+ )
109
+ self._machine.add_transition(trigger="halting_done", source=SkillState.HALTING, dest=SkillState.HALTED)
110
+
111
+ self._machine.add_transition(
112
+ trigger="start",
113
+ source=[SkillState.READY, SkillState.SUSPENDED],
114
+ dest=SkillState.STARTING,
115
+ conditions=[
116
+ self._condition_access_allowed,
117
+ self._condition_startup_completed,
118
+ self._condition_dependencies_ready,
119
+ self._condition_start_allowed,
120
+ ],
121
+ after=self._after_starting,
122
+ )
123
+ self._machine.add_transition(
124
+ trigger="starting_done", source=SkillState.STARTING, dest=SkillState.RUNNING, after=self._after_running
125
+ )
126
+
127
+ self._machine.add_transition(
128
+ trigger="suspend",
129
+ source=SkillState.RUNNING,
130
+ dest=SkillState.SUSPENDING,
131
+ conditions=[
132
+ self._condition_access_allowed,
133
+ self._condition_is_suspendable,
134
+ self._condition_suspend_allowed,
135
+ ],
136
+ after=self._after_suspending,
137
+ )
138
+ self._machine.add_transition(trigger="suspending_done", source=SkillState.SUSPENDING, dest=SkillState.SUSPENDED)
139
+
140
+ async def _after_resetting(self, *args, **kwargs) -> None:
141
+ """Is called by the finite state machine after the `SkillState.RESETTING` state is entered."""
142
+ await self._wrap_handle_method(handle_method=self._handle_resetting, success_trigger="resetting_done")
143
+
144
+ async def _after_halting(self, *args, **kwargs) -> None:
145
+ """Is called by the finite state machine after the `SkillState.HALTING` state is entered."""
146
+ # prevent infinite loop
147
+ await self._wrap_handle_method(
148
+ handle_method=self._handle_halting,
149
+ success_trigger="halting_done",
150
+ fail_trigger="halting_done",
151
+ cancel_others=True,
152
+ )
153
+
154
+ async def _after_starting(self, *args, **kwargs) -> None:
155
+ """Is called by the finite state machine after the `SkillState.STARTING` state is entered."""
156
+ # covers both a fresh start (Ready) and a resume (from Suspended)
157
+ self._resume_event.set()
158
+
159
+ await self._wrap_handle_method(handle_method=self._handle_starting, success_trigger="starting_done")
160
+
161
+ @abstractmethod
162
+ async def _after_running(self, *args, **kwargs) -> None:
163
+ raise NotImplementedError
164
+
165
+ async def _after_suspending(self, *args, **kwargs):
166
+ """Is called by the finite state machine after the `SkillState.SUSPENDING` state is entered."""
167
+ self._resume_event.clear()
168
+
169
+ async def _suspend_and_wait_for_pause() -> None:
170
+ await self._handle_suspending()
171
+ await self._paused_event.wait()
172
+
173
+ await self._wrap_handle_method(handle_method=_suspend_and_wait_for_pause, success_trigger="suspending_done")
174
+
175
+ async def _wrap_handle_method(
176
+ self,
177
+ *,
178
+ handle_method: Callable[[], Awaitable],
179
+ success_trigger: TRIGGER | None,
180
+ fail_trigger: TRIGGER = "halt",
181
+ cancel_others: bool = False,
182
+ ):
183
+ self.logger.debug(
184
+ "_wrap_handle_method called",
185
+ handle_method_name=handle_method.__name__,
186
+ success_trigger=success_trigger,
187
+ fail_trigger=fail_trigger,
188
+ cancel_others=cancel_others,
189
+ )
190
+
191
+ if cancel_others:
192
+ for task in self.__tasks.values():
193
+ if not task.cancelled() and not task.done():
194
+ self.logger.debug("Canceling task...", task_name=task.get_name())
195
+ task.cancel()
196
+ self.__tasks.clear()
197
+ # else:
198
+ # with contextlib.suppress(ValueError):
199
+ # await asyncio.wait(self.tasks) # tasks might be empty and raise a ValueError
200
+ # self.tasks.clear()
201
+
202
+ async def _wrapped() -> None:
203
+ try:
204
+ await handle_method()
205
+ if success_trigger is not None:
206
+ await self._machine.trigger(success_trigger, INTERNAL_USER) # type: ignore
207
+ except OpenSmiRuntimeError as err:
208
+ await self.ua_log_error(err.msg, code=err.error_code)
209
+ await asyncio.shield(self._machine.trigger(fail_trigger, INTERNAL_USER)) # type: ignore
210
+ except asyncio.CancelledError:
211
+ self.logger.debug(
212
+ "Task was cancelled",
213
+ handle_method_name=handle_method.__name__,
214
+ )
215
+ with contextlib.suppress(MachineError): # we might fail due to already halting
216
+ await asyncio.shield(self._machine.trigger(fail_trigger, INTERNAL_USER)) # type: ignore
217
+ except Exception as ex:
218
+ self.logger.exception(
219
+ "Caught unhandled unknown exception",
220
+ handle_method_name=handle_method.__name__,
221
+ )
222
+ await self.ua_log_error(f"Caught unhandled unknown exception: {ex}")
223
+ await asyncio.shield(self._machine.trigger(fail_trigger, INTERNAL_USER)) # type: ignore
224
+
225
+ def _remove_task(finished_task: Task):
226
+ with contextlib.suppress(KeyError):
227
+ del self.__tasks[finished_task.get_name()]
228
+ self.logger.debug("Removed finished task", task_name=finished_task.get_name())
229
+
230
+ task_name = f"Task_{self.name}_{handle_method.__name__}"
231
+ with contextlib.suppress(KeyError):
232
+ existing_task = self.__tasks[task_name]
233
+ if not existing_task.done() and not existing_task.cancelled():
234
+ self.logger.debug("Task already exists, skipping task creation!", task_name=task_name)
235
+ return
236
+
237
+ task = asyncio.create_task(_wrapped(), name=task_name)
238
+ self.__tasks[task_name] = task
239
+ task.add_done_callback(_remove_task) # remove task when done
240
+
241
+ ######################################
242
+ # skill logic callbacks from the state machine
243
+
244
+ async def _handle_resetting(self) -> None:
245
+ """Handle user-specific logic during `SkillState.RESETTING` state.
246
+
247
+ After this function is done, the skill will automatically advance to the `SkillState.READY` state.
248
+ """
249
+
250
+ async def _handle_starting(self) -> None:
251
+ """Handle user-specific logic during the `SkillState.STARTING` state.
252
+
253
+ After this function is done, the skill will automatically advance to the `SkillState.RUNNING` state.
254
+ """
255
+
256
+ @abstractmethod
257
+ async def _handle_running(self) -> None:
258
+ """Handle user-specific logic during the `SkillState.RUNNING` state.
259
+
260
+ After this function is done, the skill will automatically advance to the `SkillState.COMPLETED` state
261
+ if it is finite. Behavior of continuous skills can be configured. By default, they go to
262
+ `SkillState.HALTING` state, but if desired can stay in `SkillState.RUNNING`.
263
+
264
+ **Note**: This continues to be executed during `SkillState.SUSPENDING` and `SkillState.SUSPENDED` states.
265
+ If your skill supports suspending, you have to check in what state the skill is!
266
+ """
267
+ raise NotImplementedError
268
+
269
+ async def _handle_halting(self) -> None:
270
+ """Handle user-specific logic during the `SkillState.HALTING` state.
271
+
272
+ After this function is done, the skill will automatically advance to the `SkillState.HALTED` state.
273
+ """
274
+
275
+ async def _handle_suspending(self) -> None:
276
+ """Handle user-specific logic during the `SkillState.SUSPENDING` state.
277
+
278
+ After this function is returns, the skill will automatically advance to the `SkillState.SUSPENDED` state.
279
+ """
280
+
281
+ async def _suspend_point(self) -> None:
282
+ """Blocks if current_state is `SkillState.SUSPENDING` and allow advance to `SkillState.SUSPENDED`.
283
+
284
+ Call from `_handle_running` at any point where it's safe to pause.
285
+ """
286
+ if self._resume_event.is_set():
287
+ return
288
+
289
+ self._paused_event.set()
290
+ try:
291
+ self.logger.debug("Paused at checkpoint, awaiting resume...")
292
+ await self._resume_event.wait()
293
+ self.logger.debug("Resumed from checkpoint")
294
+ finally:
295
+ self._paused_event.clear()
296
+
297
+ ######################################
298
+ # OPC-UA Callbacks
299
+
300
+ @uamethod
301
+ @override
302
+ async def _ua_start(self, _parent: NodeId, session: SessionProtocol) -> StatusCode:
303
+ self.logger.debug("Start method called", username=session.user.name)
304
+ return await self._machine.try_trigger(session.user, "start")
305
+
306
+ @uamethod
307
+ @override
308
+ async def _ua_suspend(self, _parent: NodeId, session: SessionProtocol) -> StatusCode:
309
+ self.logger.debug("Suspend method called", username=session.user.name)
310
+ return await self._machine.try_trigger(session.user, "suspend")
311
+
312
+ @uamethod
313
+ @override
314
+ async def _ua_reset(self, _parent: NodeId, session: SessionProtocol) -> StatusCode:
315
+ self.logger.debug("Reset method called", username=session.user.name)
316
+ return await self._machine.try_trigger(session.user, "reset")
317
+
318
+ @uamethod
319
+ @override
320
+ async def _ua_halt(self, _parent: NodeId, session: SessionProtocol) -> StatusCode:
321
+ self.logger.debug("Halt method called", username=session.user.name)
322
+ return await self._machine.try_trigger(session.user, "halt")
323
+
324
+ ######################################
325
+ # Internal skill interface (for composite skills)
326
+
327
+ @override
328
+ async def start(self) -> None:
329
+ await self._machine.trigger("start", INTERNAL_USER) # type: ignore
330
+
331
+ @override
332
+ async def suspend(self) -> None:
333
+ await self._machine.trigger("suspend", INTERNAL_USER) # type: ignore
334
+
335
+ @override
336
+ async def reset(self) -> None:
337
+ await self._machine.trigger("reset", INTERNAL_USER) # type: ignore
338
+
339
+ @override
340
+ async def halt(self) -> None:
341
+ await self._machine.trigger("halt", INTERNAL_USER) # type: ignore
342
+
343
+ async def _condition_start_allowed(self, _user: UserAuthorization) -> bool:
344
+ """Implement additional custom conditions checked before starting the skill.
345
+
346
+ :return: Always ``True``, else an exception is raised.
347
+ :raises UaStatusCodeError: If the skill is not allowed to start.
348
+ """
349
+ return True
350
+
351
+ async def _condition_reset_allowed(self, _user: UserAuthorization) -> bool:
352
+ """Implement additional custom conditions checked before resetting the skill.
353
+
354
+ :return: Always ``True``, else an exception is raised.
355
+ :raises UaStatusCodeError: If the skill is not allowed to reset.
356
+ """
357
+ return True
358
+
359
+ async def _condition_suspend_allowed(self, _user: UserAuthorization) -> bool:
360
+ """Implement additional custom conditions checked before suspending the skill.
361
+
362
+ :return: Always ``True``, else an exception is raised.
363
+ :raises UaStatusCodeError: If the skill is not allowed to suspend.
364
+ """
365
+ return True
366
+
367
+
368
+ class BaseSkillFinalResultData(FinalResultData):
369
+ """Base final result data for finite skills."""
370
+
371
+ SuccessfulExecutionsCount: UaVariable[int]
372
+
373
+
374
+ class ContinuousSkillLogicMixin(_SkillLogicMixin):
375
+ """Mixin for providing continuous skill logic."""
376
+
377
+ @override
378
+ async def _get_definition(self) -> UaObjectDefinition:
379
+ return UaObjectDefinition(
380
+ object_type=SmartFactoryMachineSetNodeIds.ContinuousSkillType,
381
+ instantiate_optional=True, # TODO(CaHa): instantiate only what is actually needed
382
+ )
383
+
384
+ @override
385
+ async def _after_running(self, *args, **kwargs):
386
+ """Is called by the finite state machine after `SkillState.RUNNING` is entered."""
387
+ with contextlib.suppress(AttributeError):
388
+ old_value = await self.final_result_data.SuccessfulExecutionsCount.read() # pyright: ignore[reportAttributeAccessIssue]
389
+ new_value = old_value + 1 if old_value is not None else 1
390
+ await self.final_result_data.SuccessfulExecutionsCount.write(new_value) # pyright: ignore[reportAttributeAccessIssue]
391
+
392
+ await self._wrap_handle_method(handle_method=self._handle_running, success_trigger=None)
393
+
394
+ @property
395
+ @override
396
+ def is_finite(self) -> bool:
397
+ return False
398
+
399
+ @override
400
+ async def condition_as_dependency_ready(self, _user: UserAuthorization) -> bool:
401
+ if self.current_state not in [SkillState.READY, SkillState.RUNNING]:
402
+ msg = (
403
+ f"Denied, required continuous skill '{self.path}' is neither ready nor "
404
+ f"running (state={self.current_state})!"
405
+ )
406
+ await self.ua_log_error(msg)
407
+ raise ua.UaStatusCodeError(UaStatusCodes.BadStateNotActive)
408
+
409
+ return True
410
+
411
+
412
+ class FiniteSkillLogicMixin(_SkillLogicMixin):
413
+ """Mixin for providing finite skill logic."""
414
+
415
+ @override
416
+ async def _get_definition(self) -> UaObjectDefinition:
417
+ return UaObjectDefinition(
418
+ object_type=SmartFactoryMachineSetNodeIds.FiniteSkillType,
419
+ instantiate_optional=True, # TODO(CaHa): instantiate only what is actually needed
420
+ )
421
+
422
+ @override
423
+ def _add_transitions(self) -> None:
424
+ super()._add_transitions()
425
+
426
+ # the only difference between finite and continuous skills is that finite skills have the completed state.
427
+ # hence, we only need to add missing transitions
428
+ self._machine.add_transition(
429
+ trigger="done_internal", source=SkillState.RUNNING, dest=SkillState.COMPLETING, after=self._after_completing
430
+ )
431
+ self._machine.add_transition(trigger="done_internal", source=SkillState.COMPLETING, dest=SkillState.COMPLETED)
432
+
433
+ @override
434
+ async def _after_running(self, *args, **kwargs):
435
+ """Is called by the finite state machine after the `SkillState.RUNNING` state is entered."""
436
+ await self._wrap_handle_method(handle_method=self._handle_running, success_trigger="done_internal")
437
+
438
+ async def _after_completing(self, *args, **kwargs):
439
+ """Is called by the finite state machine after the `SkillState.COMPLETED` state is entered."""
440
+ # Update successful executions count if it exists
441
+ with contextlib.suppress(AttributeError):
442
+ old_value: int = await self.final_result_data.SuccessfulExecutionsCount.read() # pyright: ignore[reportAttributeAccessIssue]
443
+ new_value = old_value + 1 if old_value is not None else 1
444
+ await self.final_result_data.SuccessfulExecutionsCount.write(new_value) # pyright: ignore[reportAttributeAccessIssue]
445
+ self.logger.debug("Updated successful executions count", new_value=new_value)
446
+
447
+ await self._wrap_handle_method(handle_method=self._handle_completing, success_trigger="done_internal")
448
+
449
+ async def _handle_completing(self) -> None:
450
+ """Handle user-specific logic during the `SkillState.COMPLETING` state.
451
+
452
+ After this function is done, the skill will automatically advance to the `SkillState.COMPLETED` state.
453
+ """
454
+
455
+ @property
456
+ @override
457
+ def is_finite(self) -> bool:
458
+ return True
459
+
460
+ @override
461
+ async def condition_as_dependency_ready(self, _user: UserAuthorization) -> bool:
462
+ if self.current_state not in [SkillState.READY, SkillState.COMPLETED]:
463
+ msg = (
464
+ f"Denied, required finite skill '{self.path}' is neither ready nor completed!"
465
+ f" (state={self.current_state})!"
466
+ )
467
+ await self.ua_log_error(msg)
468
+ raise ua.UaStatusCodeError(UaStatusCodes.BadStateNotActive)
469
+
470
+ return True
@@ -0,0 +1,88 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Mixins related to OPC UA spatial objects."""
6
+
7
+ from collections.abc import AsyncGenerator
8
+ from typing import TYPE_CHECKING
9
+
10
+ from asyncua import ua
11
+ from opensmi.core.errors import OpenSmiRuntimeError
12
+ from opensmi.core.lifecycle_mixin import lifecycle
13
+
14
+ from opensmi.server.mixins.ua_variable_container_mixins import MonitoringMixin
15
+ from opensmi.server.nodesets import RSLNodeIds
16
+ from opensmi.server.spatial_object import Orientation, Position, SpatialObject, SpatialObjectList, WorldFrame
17
+ from opensmi.server.ua_object import UaObject
18
+
19
+ if TYPE_CHECKING:
20
+ from opensmi.server.base_machine import BaseMachine
21
+
22
+
23
+ class SpatialObjectMixin:
24
+ """Mixin for `UaObject` that have a OPC UA spatial object."""
25
+
26
+ __spatial_object: SpatialObject | None = None
27
+
28
+ async def _init_spatial_object(self, spatial_object: SpatialObject) -> None:
29
+ assert spatial_object is not None, "No spatial object given!"
30
+
31
+ if not spatial_object.is_initialized:
32
+ spatial_object.parent = self # pyright: ignore[reportAttributeAccessIssue]
33
+ await spatial_object.ua_create_node(self.monitoring.ua_node) # pyright: ignore[reportAttributeAccessIssue]
34
+ await spatial_object.init()
35
+
36
+ root_parent = getattr(self, "root_parent", None)
37
+ assert isinstance(root_parent, BaseMachine)
38
+ spatial_object_list = getattr(root_parent, "spatial_object_list", None)
39
+ if not isinstance(spatial_object_list, SpatialObjectList):
40
+ msg = f"Spatial object list of {root_parent.name} was not initialized!"
41
+ raise OpenSmiRuntimeError(msg)
42
+ await spatial_object_list.add_spatial_object(spatial_object)
43
+ self.__spatial_object = spatial_object
44
+
45
+ @property
46
+ def spatial_object(self) -> SpatialObject:
47
+ """The spatial object that belongs to this object. Read-only property."""
48
+ assert self.__spatial_object is not None, "Spatial object was not initialized!"
49
+ return self.__spatial_object
50
+
51
+
52
+ class SpatialObjectListMixin:
53
+ """Mixin for `UaObject` that have a OPC UA spatial object list."""
54
+
55
+ __spatial_object_list: SpatialObjectList | None = None
56
+
57
+ @lifecycle(after=MonitoringMixin.lifecycle_monitoring, requires=MonitoringMixin.lifecycle_monitoring)
58
+ async def lifecycle_spatial_object_list(self) -> AsyncGenerator[None]:
59
+ """Initialize the `SpatialObjectList`."""
60
+ assert isinstance(self, UaObject)
61
+ self.__spatial_object_list = SpatialObjectList(
62
+ world_frame=WorldFrame(
63
+ position=Position(0, 0, 0),
64
+ orientation=Orientation(0, 0, 0),
65
+ ),
66
+ parent=self, # pyright: ignore[reportArgumentType]
67
+ )
68
+ await self.__spatial_object_list.ua_create_node(self.monitoring.ua_node) # pyright: ignore[reportAttributeAccessIssue]
69
+ await self.__spatial_object_list.init()
70
+
71
+ ns = self.server.ua_get_namespace_index(RSLNodeIds.URI)
72
+ ua_rsl_location = await self.server.ua_server.get_objects_node().get_child( # pyright: ignore[reportAttributeAccessIssue]
73
+ f"{ns}:RelativeSpatialLocations"
74
+ )
75
+ await ua_rsl_location.add_reference(
76
+ target=self.__spatial_object_list.ua_node, reftype=ua.object_ids.ObjectIds.Organizes
77
+ )
78
+
79
+ yield
80
+ # no shutdown
81
+
82
+ @property
83
+ def spatial_object_list(self) -> SpatialObjectList:
84
+ """The spatial object list that belongs to this object. Read-only property."""
85
+ if self.__spatial_object_list is None:
86
+ msg = "Spatial object list was not initialized!"
87
+ raise OpenSmiRuntimeError(msg)
88
+ return self.__spatial_object_list
@@ -0,0 +1,131 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Mixins for various `UaObjectContainer` containing `UaObject`."""
6
+
7
+ from abc import abstractmethod
8
+ from collections.abc import AsyncGenerator
9
+ from typing import Any, Generic, TypeVar, cast, get_type_hints
10
+
11
+ import structlog
12
+ from opensmi.core.lifecycle_mixin import lifecycle
13
+ from opensmi.core.meta import resolve_generic_arguments
14
+
15
+ from opensmi.server.base_machinery_item import BaseMachineryItem
16
+ from opensmi.server.ua_object_containers import Components, MethodSet, Resources, SkillSet
17
+
18
+ _LOGGER = structlog.get_logger(__name__)
19
+
20
+
21
+ def _validate_types(*, cls: type, target: type, obj: Any) -> None:
22
+ """Validate ``obj`` attributes against the resolved type annotations."""
23
+ types: tuple[type, ...] | None = resolve_generic_arguments(cls, target)
24
+ assert types is not None
25
+ assert len(types) == 1, f"Expected 1 type, got {len(types)}"
26
+
27
+ try:
28
+ annotations = get_type_hints(types[0])
29
+ for name, annotation in annotations.items():
30
+ if name.startswith("_"): # skip private attributes
31
+ continue
32
+
33
+ attr = getattr(obj, name, None)
34
+ assert isinstance(attr, annotation), f"{name} is not of type {annotation}!"
35
+ except NameError as err:
36
+ _LOGGER.warning("Can not validate types", reason=err, cls=cls, target=target, obj=obj)
37
+
38
+
39
+ class ResourcesMixin:
40
+ """Mixin for `BaseMachineryItem` with `Resources`."""
41
+
42
+ __resources: Resources | None = None
43
+
44
+ @abstractmethod
45
+ async def _init_resources(self) -> None:
46
+ pass
47
+
48
+ @lifecycle
49
+ async def lifecycle_resources(self) -> AsyncGenerator[None]:
50
+ """Initialize the resources `UaObjectContainer`."""
51
+ self.resources.parent = self # pyright: ignore[reportAttributeAccessIssue]
52
+ await self.resources.ua_create_node(self.ua_node) # pyright: ignore[reportAttributeAccessIssue]
53
+ await self.resources.init()
54
+
55
+ await self._init_resources()
56
+
57
+ yield
58
+ # no shutdown
59
+
60
+ @property
61
+ def resources(self) -> Resources:
62
+ """Return the `Resources` container."""
63
+ if self.__resources is None:
64
+ self.__resources = Resources()
65
+ return self.__resources
66
+
67
+
68
+ #################################################################################################################
69
+
70
+ SkillSetType = TypeVar("SkillSetType", bound="SkillSet")
71
+
72
+
73
+ class SkillSetMixin(Generic[SkillSetType]):
74
+ """Mixin for `BaseMachineryItem` with typed `SkillSet`. Automatically validates provided type hints."""
75
+
76
+ _skill_set: SkillSet # without type hints
77
+
78
+ @lifecycle(after=BaseMachineryItem.lifecycle_machinery_item)
79
+ async def _lifecycle_validate_skill_set_types(self) -> AsyncGenerator[None]:
80
+ _validate_types(cls=type(self), target=SkillSetMixin, obj=self.skill_set)
81
+ yield
82
+ # no shutdown
83
+
84
+ @property
85
+ def skill_set(self) -> SkillSetType:
86
+ """Return typed skill set `UaObjectContainer`. Read-only property."""
87
+ return cast(SkillSetType, self._skill_set)
88
+
89
+
90
+ #################################################################################################################
91
+
92
+ MethodSetType = TypeVar("MethodSetType", bound="MethodSet")
93
+
94
+
95
+ class MethodSetMixin(Generic[MethodSetType]):
96
+ """Mixin for `BaseMachineryItem` with typed `MethodSet`. Automatically validates provided type hints."""
97
+
98
+ _method_set: MethodSet # without type hints
99
+
100
+ @lifecycle(after=BaseMachineryItem.lifecycle_machinery_item)
101
+ async def _lifecycle_validate_method_set_types(self) -> AsyncGenerator[None]:
102
+ _validate_types(cls=type(self), target=MethodSetMixin, obj=self.method_set)
103
+ yield
104
+ # no shutdown
105
+
106
+ @property
107
+ def method_set(self) -> MethodSetType:
108
+ """Return typed method set `UaObjectContainer`. Read-only property."""
109
+ return cast(MethodSetType, self._method_set)
110
+
111
+
112
+ #################################################################################################################
113
+
114
+ ComponentsType = TypeVar("ComponentsType", bound="Components")
115
+
116
+
117
+ class ComponentsMixin(Generic[ComponentsType]):
118
+ """Mixin for `BaseMachineryItem` with typed `Components`. Automatically validates provided type hints."""
119
+
120
+ _components: Components # without type hints
121
+
122
+ @lifecycle(after=BaseMachineryItem.lifecycle_machinery_item)
123
+ async def _lifecycle_validate_components_types(self) -> AsyncGenerator[None]:
124
+ _validate_types(cls=type(self), target=ComponentsMixin, obj=self.components)
125
+ yield
126
+ # no shutdown
127
+
128
+ @property
129
+ def components(self) -> ComponentsType:
130
+ """Return typed components `UaObjectContainer`. Read-only property."""
131
+ return cast(ComponentsType, self._components)