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,447 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import contextlib
9
+ import time
10
+ from abc import abstractmethod
11
+ from collections.abc import AsyncGenerator, Iterable, Sequence
12
+
13
+ from asyncua import ua
14
+ from asyncua.common.node import Node
15
+ from asyncua.ua.status_codes import StatusCodes as UaStatusCodes
16
+ from asyncua.ua.uaerrors import BadNoMatch
17
+ from opensmi.core import MachineryItemState, MachineryOperationMode, SkillState, lifecycle
18
+ from opensmi.core.errors import OpenSmiRuntimeError
19
+ from opensmi.core.ua_node_util import write_value
20
+ from typing_extensions import TypeVar, override
21
+
22
+ from opensmi.server.common import (
23
+ halt_skills_parallel_and_wait,
24
+ reset_skills_parallel_and_wait,
25
+ )
26
+ from opensmi.server.interfaces import AbstractMethod, AbstractSkill, AbstractUaLogger
27
+ from opensmi.server.mixins.ua_variable_container_mixins import (
28
+ AttributesMixin,
29
+ IdentificationMixin,
30
+ MonitoringMixin,
31
+ ParameterSetMixin,
32
+ )
33
+ from opensmi.server.nodesets import MachineryNodeIds, SmartFactoryMachineSetNodeIds
34
+ from opensmi.server.protocols import UserAuthorization
35
+ from opensmi.server.ua_object import UaObject, UaObjectDefinition
36
+ from opensmi.server.ua_object_containers import Components, MethodSet, SkillSet
37
+ from opensmi.server.ua_variable_containers import MachineryComponentIdentification
38
+
39
+ _ComponentType = TypeVar("_ComponentType", bound="BaseMachineryItem")
40
+ _SkillType = TypeVar("_SkillType", bound="AbstractSkill")
41
+ _MethodType = TypeVar("_MethodType", bound="AbstractMethod")
42
+
43
+ INITIAL_STATE = MachineryItemState.OUT_OF_SERVICE
44
+ INITIAL_OPERATION_MODE = MachineryOperationMode.NONE
45
+
46
+
47
+ class BaseMachineryItem(UaObject, AbstractUaLogger):
48
+ """Base class for both machines (`BaseMachine`) and components (`BaseComponent`)."""
49
+
50
+ _ua_machinery_building_blocks: Node | None = None
51
+ _ua_state_machine: Node | None = None
52
+ """Optional 'MachineryItemState' (finite state machine) OPC UA node."""
53
+ _ua_operation_mode: Node | None = None
54
+ """Optional 'MachineryOperationMode' (finite state machine) OPC UA node."""
55
+
56
+ _ua_state_machine_current_state: Node | None = None
57
+ """Optional current_state OPC UA node of 'MachineryItemState'."""
58
+ _ua_operation_mode_current_state: Node | None = None
59
+ """Optional current_state OPC UA node of 'MachineryOperationMode'."""
60
+
61
+ def __init__(
62
+ self,
63
+ *,
64
+ name: str | None = None,
65
+ minimum_access_level: int | None = None,
66
+ **kwargs,
67
+ ) -> None:
68
+ """*Cooperative* constructor."""
69
+ super().__init__(name=name, minimum_access_level=minimum_access_level, **kwargs)
70
+ self._components: Components = Components()
71
+ self._skill_set: SkillSet = SkillSet()
72
+ self._method_set: MethodSet = MethodSet()
73
+
74
+ self._current_state: MachineryItemState = INITIAL_STATE
75
+ self._current_operation_mode: MachineryOperationMode = INITIAL_OPERATION_MODE
76
+
77
+ @property
78
+ def components(self) -> Components:
79
+ """(Untyped) subcomponents of this machinery item."""
80
+ return self._components
81
+
82
+ async def __init_components(self) -> None:
83
+ self._components.parent = self
84
+ await self._components.ua_create_node(self.ua_node, remove_existing=True)
85
+ await self._components.init()
86
+
87
+ async def add_component(self, component: _ComponentType) -> _ComponentType:
88
+ """Add given (sub-)component instance, initializes it and keep track of it."""
89
+ assert isinstance(component, BaseComponent), f"Given component '{component.__class__.__name__}' is invalid!"
90
+ assert not component.is_initialized, f"Given component '{component.__class__.__name__}' is already initialized!"
91
+
92
+ if not self._components.is_initialized:
93
+ await self.__init_components()
94
+
95
+ start_time = time.monotonic()
96
+
97
+ component.parent = self # pyright: ignore[reportAttributeAccessIssue]
98
+ await component.ua_create_node(self._components.ua_node)
99
+ await component.init()
100
+
101
+ self._components[component.name] = component
102
+ self.logger.info("Added sub-component", sub_component=component.name, elapsed=time.monotonic() - start_time)
103
+ return component
104
+
105
+ async def _init_status(self) -> None:
106
+ ns = self.server.ua_get_namespace_index(MachineryNodeIds)
107
+ try:
108
+ self._ua_machinery_building_blocks = await self.ua_node.get_child(f"{ns}:MachineryBuildingBlocks")
109
+
110
+ self._ua_state_machine = await self._ua_machinery_building_blocks.get_child(f"{ns}:MachineryItemState")
111
+ self._ua_operation_mode = await self._ua_machinery_building_blocks.get_child(f"{ns}:MachineryOperationMode")
112
+
113
+ self._ua_state_machine_current_state = await self._ua_state_machine.get_child("CurrentState")
114
+ self._ua_operation_mode_current_state = await self._ua_operation_mode.get_child("CurrentState")
115
+
116
+ # Set the current state and operation mode (also in OPC UA)
117
+ await self.set_current_state(INITIAL_STATE)
118
+ await self.set_current_operation_mode(INITIAL_OPERATION_MODE)
119
+
120
+ except BadNoMatch:
121
+ self.logger.debug("No machinery state machine found.")
122
+
123
+ @property
124
+ def current_state(self) -> MachineryItemState:
125
+ """Return the current machinery item state. Read-only property."""
126
+ return self._current_state
127
+
128
+ @property
129
+ def current_operation_mode(self) -> MachineryOperationMode:
130
+ """Return the current machinery operation mode. Read-only property."""
131
+ return self._current_operation_mode
132
+
133
+ async def set_current_state(self, state: MachineryItemState) -> None:
134
+ """Set the current state of this machinery item without any transition logic checks."""
135
+ assert isinstance(state, MachineryItemState)
136
+ if self._current_state == state and self.is_initialized:
137
+ return
138
+
139
+ self._current_state = state
140
+ if self._ua_state_machine_current_state is not None:
141
+ await write_value(
142
+ self._ua_state_machine_current_state,
143
+ state.localized_text,
144
+ variant_type=ua.VariantType.LocalizedText,
145
+ )
146
+
147
+ async def set_current_operation_mode(self, mode: MachineryOperationMode) -> None:
148
+ """Set the current operation mode of this machinery item without any transition logic checks."""
149
+ assert isinstance(mode, MachineryOperationMode)
150
+ if self._current_operation_mode == mode and self.is_initialized:
151
+ return
152
+
153
+ self._current_operation_mode = mode
154
+ if self._ua_operation_mode_current_state:
155
+ await write_value(
156
+ self._ua_operation_mode_current_state,
157
+ mode.localized_text,
158
+ variant_type=ua.VariantType.LocalizedText,
159
+ )
160
+
161
+ #####################################
162
+
163
+ async def __init_skill_set(self) -> None:
164
+ """Initialize the skill set `UaObjectContainer`."""
165
+ self.skill_set.parent = self # pyright: ignore[reportAttributeAccessIssue]
166
+ await self.skill_set.ua_create_node(self.ua_node, exist_ok=True) # pyright: ignore[reportAttributeAccessIssue]
167
+ await self.skill_set.init()
168
+
169
+ @property
170
+ def skill_set(self) -> SkillSet:
171
+ """(Untyped) skill set of this machinery item."""
172
+ return self._skill_set
173
+
174
+ async def add_skill(self, skill: _SkillType) -> _SkillType:
175
+ """Add the given skill instance to the asset."""
176
+ from opensmi.server import BaseSkill
177
+
178
+ assert isinstance(skill, BaseSkill), f"Given skill {skill} does not inherit BaseSkill!"
179
+ assert skill.name not in self.skill_set, f"Given skill {skill} already added!"
180
+
181
+ if not self.skill_set.is_initialized:
182
+ await self.__init_skill_set()
183
+
184
+ start_time = time.monotonic()
185
+
186
+ if not skill.is_initialized:
187
+ skill.parent = self # pyright: ignore[reportAttributeAccessIssue]
188
+ await skill.ua_create_node(self.skill_set.ua_node, remove_existing=True)
189
+ await skill.init()
190
+
191
+ self.skill_set[skill.name] = skill
192
+
193
+ self.logger.info("Added skill", skill=skill.name, elapsed=time.monotonic() - start_time)
194
+ return skill
195
+
196
+ async def add_skills(self, skills: Sequence[AbstractSkill]) -> None:
197
+ """Add given sequence of skill instances to the asset."""
198
+ for skill in skills:
199
+ await self.add_skill(skill)
200
+
201
+ #####################################
202
+
203
+ async def __init_method_set(self) -> None:
204
+ """Initialize the method set `UaObjectContainer`."""
205
+ self.method_set.parent = self # pyright: ignore[reportAttributeAccessIssue]
206
+ await self.method_set.ua_create_node(self.ua_node, exist_ok=True) # pyright: ignore[reportAttributeAccessIssue]
207
+ await self.method_set.init()
208
+
209
+ @property
210
+ def method_set(self) -> MethodSet:
211
+ """Return untyped method set `UaObjectContainer`. Read-only property."""
212
+ return self._method_set
213
+
214
+ async def add_method(self, method: _MethodType) -> _MethodType:
215
+ """Add the given method instance to the asset."""
216
+ from opensmi.server import BaseMethod
217
+
218
+ assert isinstance(method, BaseMethod), f"Given method {method} does not inherit BaseMethod!"
219
+ assert method.name not in self.method_set, f"Given method {method} already added!"
220
+
221
+ if not self.method_set.is_initialized:
222
+ await self.__init_method_set()
223
+
224
+ start_time = time.monotonic()
225
+
226
+ if not method.is_initialized:
227
+ method.parent = self # pyright: ignore[reportAttributeAccessIssue]
228
+ await method.ua_create_node(self.method_set.ua_node)
229
+ await method.init()
230
+
231
+ self.method_set[method.name] = method
232
+
233
+ self.logger.info("Added method", method=method.name, elapsed=time.monotonic() - start_time)
234
+ return method
235
+
236
+ async def add_methods(self, methods: Sequence[AbstractMethod]) -> None:
237
+ """Add given sequence of method instances to the asset."""
238
+ for method in methods:
239
+ await self.add_method(method)
240
+
241
+ #####################################
242
+ # FSM Conditions
243
+
244
+ # Raise UaStatusCodeError for correct OPC-UA status code answers instead of a misc one
245
+
246
+ async def condition_startup_completed(self, _user: UserAuthorization) -> bool:
247
+ """Check if startup was completed.
248
+
249
+ Startup is considered completed if either the corresponding startup skill (`BaseStartupSkill`)
250
+ is in `SkillState.RUNNING` or the machinery item has no such skill.
251
+ """
252
+ with contextlib.suppress(KeyError):
253
+ if self.startup_skill.current_state != SkillState.RUNNING:
254
+ await self.ua_log_error(f"Denied, skill '{self.startup_skill.path}' must be running!")
255
+ raise ua.UaStatusCodeError(ua.status_codes.StatusCodes.BadInvalidState)
256
+ # else: has the StartupSkill and it is running
257
+ return True # has no StartupSkill -> always ready
258
+
259
+ async def _condition_component_ready(self, user: UserAuthorization) -> bool:
260
+ return True # To implement custom checks that depend on the component
261
+
262
+ async def reset(self) -> None:
263
+ """Attempt to reset the machinery item.
264
+
265
+ If the state indicates resetting is required, it is safe to call when the machinery item is most states.
266
+
267
+ If a "Startup" skill for this machinery item exists, reset is expected to be performed by the startup skill.
268
+ If there is no "Startup" skill, then reset all skills and subcomponents.
269
+
270
+ :raises PyUaRuntimeError: If the machinery item is in state `MachineryItemState.NOT_AVAILABLE`
271
+ """
272
+ match self._current_state:
273
+ case MachineryItemState.EXECUTING | MachineryItemState.NOT_EXECUTING:
274
+ self.logger.debug(
275
+ "Skipping reset() of machinery item",
276
+ state=self._current_state.name,
277
+ )
278
+ return
279
+ case MachineryItemState.OUT_OF_SERVICE:
280
+ try:
281
+ startup_skill = self.startup_skill
282
+ self.logger.debug("Resetting with startup skill")
283
+ await self.reset_skills([startup_skill]) # make sure the startup skill is ready
284
+ if startup_skill.current_state == SkillState.READY:
285
+ await startup_skill.start()
286
+ await startup_skill.wait_for_state(SkillState.RUNNING)
287
+ else:
288
+ self.logger.debug(
289
+ "Startup skill is already in target state",
290
+ state=startup_skill.current_state.name,
291
+ )
292
+ except KeyError: # no startup skill found
293
+ self.logger.debug("Resetting without startup skill")
294
+ await self.reset_components()
295
+ await self.reset_skills()
296
+ case _:
297
+ msg = f"Cannot reset machinery item '{self.path}' from state='{self._current_state.name}'!"
298
+ raise OpenSmiRuntimeError(msg)
299
+
300
+ async def reset_components(self, components: Iterable[BaseComponent] | None = None) -> None:
301
+ """Reset given components. If None given, resets all own components."""
302
+ if components is None:
303
+ components = self._components
304
+
305
+ for component in components:
306
+ self.logger.debug("Resetting component...", component=str(component.path))
307
+ await component.reset()
308
+
309
+ async def reset_skills(self, skills: dict[str, AbstractSkill] | Iterable[AbstractSkill] | None = None) -> None:
310
+ """Reset all given skills. If None given, resets all own skills."""
311
+ if skills is None:
312
+ skills = self.skill_set
313
+ elif isinstance(skills, dict):
314
+ skills = skills.values()
315
+
316
+ try:
317
+ await reset_skills_parallel_and_wait(skills) # pyright: ignore[reportArgumentType]
318
+ except Exception as ex:
319
+ await self.ua_log_error(f"Error resetting skills: {ex}")
320
+ await self.set_current_state(MachineryItemState.OUT_OF_SERVICE)
321
+ # raise ua.UaStatusCodeError(ua.StatusCodes.BadInvalidState) from ex
322
+ raise
323
+
324
+ async def halt_components(self, components_to_halt: Iterable[str] | Iterable[BaseComponent] | None = None) -> None:
325
+ """Halt all components (None, default) of this machinery item or only specific ones.
326
+
327
+ :param components_to_halt: All components or only specific ones. Note: components by name will only be searched
328
+ for in this machinery item!
329
+ """
330
+ for component in self._components: # halt all requested components
331
+ if components_to_halt is not None and (
332
+ component.name not in components_to_halt # pyright: ignore[reportOperatorIssue]
333
+ or component not in components_to_halt # pyright: ignore[reportOperatorIssue]
334
+ ):
335
+ self.logger.debug("Skipping halting component, because it should not be halted.", component=component)
336
+ continue
337
+ if component.name.lower().startswith("port_"): # TODO(CaHa): Let each component decide, not like this
338
+ self.logger.debug("Skipping halting component, because it is a port.", component=component)
339
+ continue
340
+
341
+ try:
342
+ self.logger.debug("Trying to halt component...", component=component)
343
+ await component.halt(components_to_halt=components_to_halt)
344
+ except Exception:
345
+ await self.ua_log_error(f"Could not halt component '{component.full_name}'!")
346
+ self.logger.exception("Could not halt component!", component=component)
347
+
348
+ async def halt_skills(self, skills_to_halt: Iterable[str] | Iterable[AbstractSkill] | None = None) -> None:
349
+ """Halt all skills (``None``, default) of this machinery item or only specific ones.
350
+
351
+ Note: skills by name will only be searched for in this machinery item!
352
+ """
353
+ if skills_to_halt is None: # halt all own skills
354
+ await halt_skills_parallel_and_wait(self.skill_set)
355
+ else: # halt only specific skills
356
+ new_skills_to_halt: list[AbstractSkill] = []
357
+ for skill in skills_to_halt: # convert str into BaseSkill instances
358
+ if isinstance(skill, str):
359
+ try:
360
+ new_skills_to_halt.append(self.skill_set[skill])
361
+ except KeyError:
362
+ self.logger.warning("Could not find skill in own skill set!", skill_name=skill)
363
+ elif isinstance(skill, AbstractSkill):
364
+ new_skills_to_halt.append(skill)
365
+
366
+ await halt_skills_parallel_and_wait(new_skills_to_halt)
367
+
368
+ async def halt(
369
+ self,
370
+ *,
371
+ components_to_halt: Iterable[str] | Iterable[BaseComponent] | None = None,
372
+ skills_to_halt: Iterable[str] | Iterable[AbstractSkill] | None = None,
373
+ ) -> None:
374
+ """Halt the machinery item.
375
+
376
+ If a "Startup" skill for this machinery item exists, halt is expected to be performed by the startup skill.
377
+ Otherwise, halt all/no skills and all/no subcomponents.
378
+
379
+ Note: The startup skill should not simply call this method, it will not halt anything!
380
+
381
+ :param components_to_halt: Whether to halt all subcomponents (except Ports) (None, default) or specified ones.
382
+ :param skills_to_halt: Whether to halt all skills (None, default) or specified ones.
383
+ """
384
+ await self.set_current_state(MachineryItemState.OUT_OF_SERVICE)
385
+ await self.set_current_operation_mode(MachineryOperationMode.MAINTENANCE)
386
+
387
+ try:
388
+ startup_skill = self.startup_skill
389
+ self.logger.debug("Halting with startup skill")
390
+ await halt_skills_parallel_and_wait([startup_skill])
391
+ except KeyError: # no startup skill
392
+ self.logger.debug(
393
+ "Halting without startup skill", components_to_halt=components_to_halt, skills_to_halt=skills_to_halt
394
+ )
395
+ await asyncio.gather(self.halt_components(components_to_halt), self.halt_skills(skills_to_halt))
396
+
397
+ @lifecycle(
398
+ after=(
399
+ AttributesMixin.lifecycle_attributes,
400
+ MonitoringMixin.lifecycle_monitoring,
401
+ ParameterSetMixin.lifecycle_parameter_set,
402
+ )
403
+ )
404
+ async def lifecycle_machinery_item(self) -> AsyncGenerator[None]:
405
+ """Lifecycle method which calls `_init` for initialization and `_shutdown` for shutdown."""
406
+ await self._init()
407
+ yield
408
+ await self._shutdown()
409
+
410
+ @abstractmethod
411
+ async def _init(self) -> None:
412
+ pass
413
+
414
+ async def _shutdown(self) -> None:
415
+ for component in self._components:
416
+ try:
417
+ await component.shutdown()
418
+ except (Exception, asyncio.CancelledError):
419
+ # We don't know what might go wrong, catch all just in case
420
+ self.logger.exception("Sub-component shutdown error!", sub_component=component.name)
421
+
422
+ @property
423
+ def startup_skill(self) -> AbstractSkill:
424
+ """Return the startup skill of the machinery item.
425
+
426
+ :raises KeyError: If this machinery item has no startup skill.
427
+ """
428
+ from opensmi.server.base_startup_skill import BaseStartupSkill
429
+
430
+ return self.skill_set[BaseStartupSkill.NAME]
431
+
432
+ @override
433
+ async def condition_as_dependency_ready(self, _user: UserAuthorization) -> bool:
434
+ if self.current_state not in (MachineryItemState.EXECUTING, MachineryItemState.NOT_EXECUTING):
435
+ msg = f"Denied, required component '{self.full_name}' is not ready!"
436
+ await self.ua_log_error(msg)
437
+ raise ua.UaStatusCodeError(UaStatusCodes.BadStateNotActive)
438
+
439
+ return True
440
+
441
+
442
+ class BaseComponent(IdentificationMixin[MachineryComponentIdentification], BaseMachineryItem):
443
+ """Base class for all components (= OPC UA machinery items)."""
444
+
445
+ @override
446
+ async def _get_definition(self) -> UaObjectDefinition:
447
+ return UaObjectDefinition(object_type=SmartFactoryMachineSetNodeIds.ComponentType) # generic component type
@@ -0,0 +1,57 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Abstract base class for all methods."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from asyncua import ua
10
+ from asyncua.common.methods import uamethod
11
+ from asyncua.common.node import Node
12
+ from asyncua.ua import NodeId
13
+ from typing_extensions import override
14
+
15
+ from opensmi.server.base_callable import BaseCallable
16
+ from opensmi.server.interfaces import AbstractMethod
17
+ from opensmi.server.nodesets import SmartFactorySkillSetNodeIds
18
+ from opensmi.server.protocols import SessionProtocol
19
+ from opensmi.server.ua_object import UaObjectDefinition
20
+
21
+
22
+ class BaseMethod(BaseCallable, AbstractMethod):
23
+ """Abstract base class for all methods."""
24
+
25
+ @override
26
+ async def _get_definition(self) -> UaObjectDefinition:
27
+ return UaObjectDefinition(
28
+ object_type=SmartFactorySkillSetNodeIds.BaseMethodType,
29
+ instantiate_optional=True, # TODO(CaHa): instantiate only what is actually needed
30
+ )
31
+
32
+ @override
33
+ async def _get_sub_node(self) -> Node:
34
+ return self.ua_node # methods are not organized in sub nodes like skills are
35
+
36
+ @override
37
+ async def _init(self) -> None:
38
+ await super()._init()
39
+
40
+ ns = self.server.ua_get_namespace_index(SmartFactorySkillSetNodeIds)
41
+ node_call = await self.ua_node.get_child(f"{ns}:Call")
42
+ _session = self.server.ua_server.iserver.isession
43
+ _session.add_method_callback(node_call.nodeid, self._call)
44
+
45
+ @uamethod
46
+ async def _call(self, _parent: NodeId, session: SessionProtocol) -> ua.StatusCode:
47
+ try:
48
+ await self._condition_access_allowed(session.user)
49
+ await self._condition_startup_completed(session.user)
50
+ await self._condition_dependencies_ready(session.user)
51
+ await self.execute_method()
52
+ return ua.StatusCode(ua.UInt32(ua.status_codes.StatusCodes.Good))
53
+ except ua.UaStatusCodeError as e:
54
+ return ua.StatusCode(e.code)
55
+ except Exception:
56
+ self.logger.exception("Exception while executing method!")
57
+ return ua.StatusCode(ua.UInt32(ua.status_codes.StatusCodes.BadInternalError))
@@ -0,0 +1,20 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Base class for precondition checks for skills."""
6
+
7
+ from asyncua.ua import QualifiedName
8
+ from typing_extensions import override
9
+
10
+ from opensmi.server import BaseSkillFinite
11
+ from opensmi.server.nodesets import SmartFactorySkillSetNodeIds
12
+
13
+
14
+ class BasePreconditionCheck(BaseSkillFinite):
15
+ """Base class for precondition checks for skills."""
16
+
17
+ @override
18
+ async def _get_sub_node(self):
19
+ ns_index = self.server.ua_get_namespace_index(SmartFactorySkillSetNodeIds)
20
+ return await self.ua_node.get_child(QualifiedName("PreconditionCheck", ns_index))