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,299 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Abstract base skill **without** state machine logic."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ from collections.abc import AsyncGenerator
11
+ from contextlib import asynccontextmanager
12
+
13
+ from asyncua import ua
14
+ from asyncua.common.node import Node
15
+ from asyncua.ua import QualifiedName
16
+ from asyncua.ua.status_codes import StatusCodes as UaStatusCodes
17
+ from asyncua.ua.uaerrors import BadNoMatch
18
+ from opensmi.core import SkillState
19
+ from opensmi.core.errors import OpenSmiRuntimeError, SkillHaltedError
20
+ from opensmi.core.ua_node_util import get_child_without_ns, get_node_id
21
+ from typing_extensions import override
22
+
23
+ from opensmi.server.base_callable import BaseCallable
24
+ from opensmi.server.interfaces import AbstractSkill
25
+ from opensmi.server.nodesets import SmartFactoryMachineSetNodeIds, SmartFactorySkillSetNodeIds
26
+ from opensmi.server.protocols import UserAuthorization
27
+
28
+
29
+ class BaseSkill(BaseCallable, AbstractSkill):
30
+ """Abstract base skill **without** state machine logic.
31
+
32
+ For skills with logic in Python, there is `FiniteSkillLogicMixin` and `ContinuousSkillLogicMixin`.
33
+
34
+ Derived classes must implement at least the ``reset()``, ``start()`` and ``halt()`` methods for a non-suspendable
35
+ skill. The ``_condition_skill_ready()`` method can be overridden in order to add skill specific conditions
36
+ before the ``start()`` method is allowed to be executed by the state machine.
37
+ """
38
+
39
+ _ua_state_machine: Node
40
+ """OPC UA base node of state machine."""
41
+ _ua_current_state: Node
42
+ """OPC UA node if the state variable of the state machine."""
43
+
44
+ def __init__(
45
+ self,
46
+ *,
47
+ name: str | None = None,
48
+ suspendable: bool = False,
49
+ minimum_access_level: int | None = None,
50
+ precondition_check: BaseSkill | None = None,
51
+ feasibility_check: BaseSkill | None = None,
52
+ **kwargs,
53
+ ) -> None:
54
+ """*Cooperative* Constructor. Create a new skill instance.
55
+
56
+ :param name: name of the skill.
57
+ :param suspendable: whether the skill can be suspended/resumed.
58
+ :param minimum_access_level: Minimum required access level to start the skill (see User for more info).
59
+ :param precondition_check: Optional reference to corresponding separate precondition check for this skill.
60
+ :param feasibility_check: Optional reference to corresponding separate feasibility check for this skill.
61
+ """
62
+ super().__init__(name=name, minimum_access_level=minimum_access_level, **kwargs)
63
+
64
+ self._suspendable = suspendable
65
+ self._precondition_check = precondition_check
66
+ self._feasibility_check = feasibility_check
67
+ self._called_skills: list[BaseSkill] = []
68
+ self._current_state = SkillState.HALTED
69
+ self._condition = asyncio.Condition() # for wait_for_state
70
+
71
+ @override
72
+ async def _get_sub_node(self) -> Node:
73
+ assert self._ua_node is not None
74
+ return await get_child_without_ns(self._ua_node, display_name="SkillExecution")
75
+
76
+ @override
77
+ async def _init(self) -> None:
78
+ ua_sub_node = await self._get_sub_node() # either SkillExecution, PreconditionCheck or FeasibilityCheck
79
+
80
+ ns_skill_set = self.server.ua_get_namespace_index(SmartFactorySkillSetNodeIds)
81
+ ns_machine_set = self.server.ua_get_namespace_index(SmartFactoryMachineSetNodeIds)
82
+
83
+ self._ua_state_machine = await ua_sub_node.get_child(QualifiedName("StateMachine", ns_skill_set))
84
+ self._ua_current_state = await self.ua_state_machine.get_child("CurrentState")
85
+
86
+ node_start = await self.ua_state_machine.get_child(f"{ns_machine_set}:Start")
87
+ node_halt = await self.ua_state_machine.get_child(f"{ns_machine_set}:Halt")
88
+ node_reset = await self.ua_state_machine.get_child(f"{ns_machine_set}:Reset")
89
+
90
+ _session = self.server.ua_server.iserver.isession
91
+ _session.add_method_callback(node_start.nodeid, self._ua_start)
92
+ _session.add_method_callback(node_halt.nodeid, self._ua_halt)
93
+ _session.add_method_callback(node_reset.nodeid, self._ua_reset)
94
+
95
+ try:
96
+ node_suspend = await self.ua_state_machine.get_child(f"{ns_machine_set}:Suspend")
97
+ except BadNoMatch:
98
+ node_suspend = None
99
+
100
+ if self._suspendable: # checks are not suspendable at all (?!)
101
+ if node_suspend is not None:
102
+ _session.add_method_callback(node_suspend.nodeid, self._ua_suspend)
103
+ else:
104
+ suspend_node_id = get_node_id(self.ua_state_machine, name="Suspend", ns_idx=ns_machine_set)
105
+ await self.ua_state_machine.add_method(suspend_node_id, f"{ns_machine_set}:Suspend", self._ua_suspend)
106
+ elif node_suspend is not None:
107
+ await node_suspend.delete() # suspend method must not exist for skills that cannot be suspended
108
+
109
+ await super()._init() # cooperative _init() after we are done with the mandatory stuff
110
+
111
+ #####################################
112
+
113
+ assert self._ua_node is not None
114
+ _ua_precondition_check = await self._ua_node.get_child(f"{ns_skill_set}:PreconditionCheck")
115
+ if self._precondition_check is None:
116
+ await _ua_precondition_check.delete()
117
+ self.logger.debug("Removed unused PreconditionCheck")
118
+ else:
119
+ raise NotImplementedError # TODO(CaHa): Implement or remove
120
+ # self._precondition_check.parent = self.parent
121
+ # await self._precondition_check.ua_create_node(_ua_precondition_check)
122
+ # await self._precondition_check.init()
123
+
124
+ _ua_feasibility_check = await self._ua_node.get_child(f"{ns_skill_set}:FeasibilityCheck")
125
+ if self._feasibility_check is None:
126
+ # no recursive delete to improve startup speed
127
+ await _ua_feasibility_check.delete()
128
+ self.logger.debug("Removed unused FeasibilityCheck")
129
+ else:
130
+ raise NotImplementedError # TODO(CaHa): Implement or remove
131
+ # self._feasibility_check.parent = self.parent
132
+ # await self._feasibility_check.ua_create_node(_ua_feasibility_check)
133
+ # await self._feasibility_check.init()
134
+
135
+ async def _write_current_state(self, state: SkillState) -> None:
136
+ """Write the given ``state`` without any transition logic checks.
137
+
138
+ Does nothing if given ``state`` is already ``current_state``.
139
+ """
140
+ assert isinstance(state, SkillState), f"'{state}' is not of type SkillStates"
141
+
142
+ if state == self.current_state and self.is_initialized:
143
+ return
144
+
145
+ self.logger.info("Updating current state", new_state=state, old_state=self.current_state)
146
+
147
+ async with self._condition:
148
+ self._current_state = state
149
+ self._condition.notify_all()
150
+
151
+ await self._ua_current_state.write_value(state.localized_text)
152
+
153
+ @property
154
+ @override
155
+ def current_state(self) -> SkillState:
156
+ """Return the current state of the skill."""
157
+ return self._current_state
158
+
159
+ @property
160
+ @override
161
+ def ua_state_machine(self) -> Node:
162
+ return self._ua_state_machine
163
+
164
+ ######################################
165
+ # FSM Conditions
166
+
167
+ # Raise UaStatusCodeError for correct OPC-UA status code answers instead of a misc one
168
+
169
+ @override
170
+ async def _condition_is_suspendable(self, _user: UserAuthorization) -> bool:
171
+ if not self._suspendable:
172
+ await self.ua_log_error(f"Denied, skill '{self.full_name}' is not suspendable!")
173
+ raise ua.UaStatusCodeError(UaStatusCodes.BadNotImplemented)
174
+ return True
175
+
176
+ @override
177
+ async def wait_for_state(self, state: SkillState) -> None:
178
+ if self._current_state == state:
179
+ return
180
+
181
+ source_state = self._current_state
182
+ self.logger.debug("Waiting for state...", source_state=source_state.name, target_state=state.name)
183
+
184
+ async with self._condition:
185
+ await self._condition.wait_for(
186
+ lambda: self._current_state == state or self._current_state == SkillState.HALTED
187
+ )
188
+
189
+ if self._current_state == SkillState.HALTED and state != SkillState.HALTED:
190
+ msg = f"Skill '{self.path}' halted unexpectedly while waiting for state '{state.name}'!"
191
+ raise SkillHaltedError(msg)
192
+
193
+ async def _halt_running_called_skills(self):
194
+ for skill in self._called_skills:
195
+ if skill.current_state == SkillState.RUNNING:
196
+ try:
197
+ await skill.halt()
198
+ except (Exception, asyncio.CancelledError):
199
+ self.logger.exception("Could not halt running skill! Skipping!", skill_name=skill.full_name)
200
+
201
+ @asynccontextmanager
202
+ async def call_other_finite_skill(
203
+ self,
204
+ skill: BaseSkill,
205
+ *,
206
+ wait_for_completion: bool = True,
207
+ timeout: float | None = 60.0,
208
+ reset_after_completion: bool = True,
209
+ ) -> AsyncGenerator:
210
+ """Call another finite skill from this skill.
211
+
212
+ :param skill: the finite skill to call.
213
+ :param wait_for_completion: should this method block until the timeout is reached or the skill is completed?
214
+ :param timeout: timeout in seconds, can be disabled by setting it to None.
215
+ :param reset_after_completion: should the called skill be reset after completion?
216
+
217
+ :raises TypeError: if given ``skill`` is not finite.
218
+ :raises asyncio.TimeoutError: if the ``timeout`` is reached.
219
+ """
220
+ if skill is None or not skill.is_finite:
221
+ msg = "Wrong type of skill given, a finite skill is required!"
222
+ raise TypeError(msg)
223
+
224
+ logger = self.logger.bind(other_skill=skill.path)
225
+
226
+ if skill not in getattr(self, "_dependencies", ()):
227
+ logger.warning("Calling other skill that is not in dependencies!")
228
+
229
+ if skill not in self._called_skills: # only add it the first time it is called
230
+ self._called_skills.append(skill)
231
+
232
+ match skill.current_state:
233
+ case SkillState.READY:
234
+ pass # Already in Ready, nothing to do
235
+ case SkillState.COMPLETED: # Safe to reset
236
+ self.logger.info("Resetting completed skill dependency...", skill=skill.path)
237
+ await skill.reset()
238
+ async with asyncio.timeout(timeout):
239
+ await skill.wait_for_state(SkillState.READY)
240
+ case _: # Potentially unsafe to reset
241
+ msg = f"Other skill in unsupported state '{skill.current_state.name}'!"
242
+ raise OpenSmiRuntimeError(msg)
243
+
244
+ logger.debug("Trying to start skill...")
245
+ await skill.start()
246
+
247
+ yield
248
+
249
+ if not wait_for_completion:
250
+ return # we are done
251
+ # else:
252
+ logger.debug("Waiting for other skill to be completed.", timeout=timeout)
253
+ async with asyncio.timeout(timeout):
254
+ await skill.wait_for_state(SkillState.COMPLETED)
255
+
256
+ if reset_after_completion and skill.is_finite:
257
+ # reset seems not to be suitable for conti skills
258
+ logger.debug("Trying to reset other skill after completion...")
259
+ await skill.reset() # needs to be reset to be ready again (Skill V3+)
260
+ logger.debug("Waiting for other skill to be ready again.", timeout=timeout)
261
+ async with asyncio.timeout(timeout):
262
+ await skill.wait_for_state(SkillState.READY)
263
+
264
+ # TODO(CaHa): asynccontextmanager for continuous skills?
265
+ async def call_other_continuous_skill(
266
+ self,
267
+ skill: BaseSkill,
268
+ *,
269
+ wait_for_running: bool = True,
270
+ timeout: float | None = 10.0,
271
+ ) -> None:
272
+ """Call another continuous skill from this skill.
273
+
274
+ :param skill: the continuous skill to call.
275
+ :param wait_for_running: should this method block until the timeout is reached or the skill is running?
276
+ :param timeout: timeout in seconds, can be disabled by setting it to None.
277
+
278
+ :raises TypeError: if given ``skill`` is not continuous.
279
+ :raises asyncio.TimeoutError: if the ``timeout`` is reached.
280
+ """
281
+ if skill is None or skill.is_finite:
282
+ msg = "Wrong type of skill given, a continuous skill is required!"
283
+ raise TypeError(msg)
284
+
285
+ logger = self.logger.bind(other_skill=skill.path)
286
+
287
+ if skill not in getattr(self, "_dependencies", ()):
288
+ logger.warning("Calling other skill that is not in dependencies!")
289
+
290
+ if skill not in self._called_skills: # only add it the first time it is called
291
+ self._called_skills.append(skill)
292
+
293
+ logger.debug("Trying to start other skill...")
294
+ await skill.start()
295
+
296
+ if wait_for_running:
297
+ logger.debug("Waiting for other skill to be running", timeout=timeout)
298
+ async with asyncio.timeout(timeout):
299
+ await skill.wait_for_state(SkillState.RUNNING)
@@ -0,0 +1,111 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ from typing import TYPE_CHECKING, Any, Final, Never
9
+
10
+ from opensmi.core import MachineryItemState, MachineryOperationMode, SkillState
11
+ from typing_extensions import override
12
+
13
+ from opensmi.server import BaseSkillContinuous
14
+ from opensmi.server.mixins import ParentMixin
15
+ from opensmi.server.nodesets import SmartFactoryMachineSetNodeIds
16
+ from opensmi.server.ua_object import UaObjectDefinition
17
+
18
+ if TYPE_CHECKING:
19
+ from opensmi.server.base_machinery_item import BaseMachineryItem as BaseMachineryItem
20
+ from opensmi.server.protocols import UserAuthorization
21
+
22
+
23
+ class BaseStartupSkill(ParentMixin["BaseMachineryItem"], BaseSkillContinuous):
24
+ """The base for every startup skill. Manges status and mode changes of the parent `BaseMachineryItem`.
25
+
26
+ - Startup skill not running --> `MachineryItemState.OUT_OF_SERVICE` state
27
+ - 1+ finite skills running --> `MachineryItemState.EXECUTING` state / `MachineryOperationMode.PROCESSING` mode
28
+ - 0 finite skills running --> `MachineryItemState.NOT_EXECUTING` state / ``MachineryOperationMode.SETUP`` mode
29
+
30
+ (see SF-KL Skill specification V4).
31
+
32
+ Startup skills are never suspendable and have neither separate precondition nor feasibility checks.
33
+
34
+ The default implementation resets all subcomponents and skills of the parent component when in state
35
+ `SkillState.STARTING` and halts all when in state `SkillState.HALTING`.
36
+ Override the corresponding ``_handle_*`` methods for custom behavior.
37
+ """
38
+
39
+ NAME: Final[str] = "StartupSkill"
40
+ _handle_status_change_task: asyncio.Task | None = None
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ minimum_access_level: int = 2,
46
+ handle_status_change: bool = True,
47
+ **kwargs: dict[str, Any],
48
+ ) -> None:
49
+ """*Cooperative* constructor."""
50
+ super().__init__(
51
+ name=BaseStartupSkill.NAME,
52
+ suspendable=False,
53
+ minimum_access_level=minimum_access_level,
54
+ precondition_check=None,
55
+ feasibility_check=None,
56
+ **kwargs,
57
+ )
58
+
59
+ if handle_status_change:
60
+ self._handle_status_change_task = asyncio.create_task(
61
+ self._handle_status_changes(), name=f"{self.name}_handle_status_changes"
62
+ )
63
+
64
+ @override
65
+ async def _condition_startup_completed(self, user: UserAuthorization) -> bool:
66
+ """Return ``True``.
67
+
68
+ A Startup skill in state `SkillState.RUNNING` is required for parent's "Startup" being completed.
69
+ A normal skill would check through the parent, but we need to always be able to start.
70
+ """
71
+ return True
72
+
73
+ async def _handle_status_changes(self) -> Never:
74
+ while True:
75
+ await asyncio.sleep(0.1) # TODO(CaHa): Event based?
76
+
77
+ if self.current_state != SkillState.RUNNING:
78
+ await self.parent.set_current_state(MachineryItemState.OUT_OF_SERVICE)
79
+ await self.parent.set_current_operation_mode(MachineryOperationMode.NONE)
80
+ continue
81
+ # else:
82
+ # we only consider finite skills
83
+ finite_skill_states: list[SkillState] = [
84
+ skill.current_state for skill in self.parent.skill_set if skill.is_finite
85
+ ]
86
+
87
+ # there is at least 1 finite skill running/suspended
88
+ if finite_skill_states.count(SkillState.RUNNING) > 0 or finite_skill_states.count(SkillState.SUSPENDED) > 0:
89
+ await self.parent.set_current_state(MachineryItemState.EXECUTING)
90
+ await self.parent.set_current_operation_mode(MachineryOperationMode.PROCESSING)
91
+ else:
92
+ await self.parent.set_current_state(MachineryItemState.NOT_EXECUTING)
93
+ await self.parent.set_current_operation_mode(MachineryOperationMode.SETUP)
94
+
95
+ @override
96
+ async def _handle_starting(self) -> None:
97
+ await self.parent.reset_components()
98
+ await self.parent.reset_skills()
99
+
100
+ @override
101
+ async def _handle_halting(self) -> None:
102
+ # this skill is important for the machine/component to function correctly,
103
+ # so halt the machine/component if this skill is halted
104
+ await self.parent.halt_components()
105
+ await self.parent.halt_skills()
106
+
107
+ @override
108
+ async def _get_definition(self) -> UaObjectDefinition:
109
+ definition = await super()._get_definition()
110
+ definition.namespace_uri = SmartFactoryMachineSetNodeIds # the StartupSkill must be in this namespace
111
+ return definition
@@ -0,0 +1,93 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import base64
9
+ import os
10
+ from collections.abc import Iterable
11
+ from typing import Final
12
+
13
+ import structlog
14
+ from asyncua.ua.uaerrors import BadInvalidState
15
+ from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
16
+ from opensmi.core import SkillState
17
+ from opensmi.core.errors import OpenSmiRuntimeError
18
+ from transitions import MachineError
19
+
20
+ from opensmi.server.interfaces import AbstractSkill
21
+
22
+ _LOGGER = structlog.get_logger("opensmi.common")
23
+
24
+
25
+ async def reset_skill_and_wait(skill: AbstractSkill, *, timeout: float | None = 60.0) -> None:
26
+ """Reset the given skill and wait until it finished (successfully reached Ready state or Halted on failure).
27
+
28
+ Note: This will only wait for the 'Halting' skill state, but not for other skill transition states!
29
+ """
30
+ # we need to wait for skills still in halting state to reach halted
31
+ if skill.current_state == SkillState.HALTING:
32
+ async with asyncio.timeout(timeout):
33
+ await skill.wait_for_state(SkillState.HALTED)
34
+
35
+ if skill.current_state in (SkillState.HALTED, SkillState.SUSPENDED, SkillState.COMPLETED):
36
+ _LOGGER.debug("Resetting skill...", skill_name=skill.path)
37
+ await skill.reset()
38
+ # resetting takes time, we need to wait until the skill is actually ready!
39
+ async with asyncio.timeout(timeout):
40
+ await skill.wait_for_state(SkillState.READY)
41
+
42
+
43
+ async def halt_skill_and_wait(skill: AbstractSkill, *, timeout: float | None = 60.0) -> None:
44
+ """Halt the given skill and wait until it finished and is in the Halted state."""
45
+ try:
46
+ _LOGGER.debug("Trying to halt skill...", skill_name=skill.path)
47
+ await skill.halt()
48
+ # halting takes time, we need to wait until the skill is actually halted!
49
+ async with asyncio.timeout(timeout):
50
+ await skill.wait_for_state(SkillState.HALTED)
51
+ except (BadInvalidState, MachineError):
52
+ pass # assume that skill is already halted
53
+ except (Exception, asyncio.CancelledError) as ex:
54
+ msg = f"Could not halt skill '{skill.name}'!"
55
+ raise OpenSmiRuntimeError(msg) from ex
56
+
57
+
58
+ async def reset_skills_parallel_and_wait(skills: Iterable[AbstractSkill], *, timeout: float | None = 60.0) -> None:
59
+ """Reset all given skills in 'parallel'."""
60
+ tasks = [asyncio.create_task(reset_skill_and_wait(skill)) for skill in skills]
61
+ for coro in asyncio.as_completed(tasks, timeout=timeout):
62
+ await coro # may raise
63
+
64
+
65
+ async def halt_skills_parallel_and_wait(skills: Iterable[AbstractSkill], *, timeout: float | None = 60.0) -> None:
66
+ """Halt all given skills in 'parallel'."""
67
+ tasks = [asyncio.create_task(halt_skill_and_wait(skill)) for skill in skills]
68
+ for coro in asyncio.as_completed(tasks, timeout=timeout):
69
+ await coro # may raise
70
+
71
+
72
+ SECRET_KEY_NAME: Final[str] = "OPEN_SMI_SECRET_KEY"
73
+ """The name of the environment variable containing the secret key/pepper."""
74
+
75
+
76
+ def get_scrypt_instance() -> Scrypt:
77
+ """Return initialized Scrypt instance.
78
+
79
+ The pepper is read from base64 encoded environment variable.
80
+
81
+ :raises RuntimeError: If either the pepper environment variable is missing or does not contain valid Base64.
82
+ """
83
+ try:
84
+ pepper = base64.b64decode(os.environ[SECRET_KEY_NAME], validate=True)
85
+ # We intentionally use a deployment-specific pepper as the Scrypt salt to
86
+ # ensure embedded password hashes cannot be verified without the pepper.
87
+ return Scrypt(salt=pepper, length=32, n=2**14, r=8, p=1)
88
+ except KeyError:
89
+ msg = f"{SECRET_KEY_NAME} environment variable is not set."
90
+ raise RuntimeError(msg) from None
91
+ except ValueError as err:
92
+ msg = f"{SECRET_KEY_NAME} is not valid Base64."
93
+ raise RuntimeError(msg) from err
@@ -0,0 +1,124 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Configuration data classes and functions to load them from TOML files."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from enum import Enum
11
+
12
+ from opensmi.core import LogFormat
13
+
14
+
15
+ class HistoryOption(Enum):
16
+ """Backend to use for OPC UA historic data access."""
17
+
18
+ MEMORY = "memory"
19
+ SQLITE = "sqlite"
20
+
21
+
22
+ @dataclass(slots=True, kw_only=True)
23
+ class DiscoveryConfiguration:
24
+ """OPC UA discovery related configuration."""
25
+
26
+ register: bool = False
27
+ server_address: str = "opc.tcp://localhost:4840"
28
+
29
+
30
+ @dataclass(slots=True, kw_only=True)
31
+ class LoggingConfiguration:
32
+ """Logging related configuration."""
33
+
34
+ format: LogFormat = LogFormat.AUTOMATIC
35
+ minimum_levels: dict[str, str] = field(
36
+ default_factory=lambda: {
37
+ "opensmi.Server": "INFO",
38
+ "opensmi": "WARNING",
39
+ "asyncua": "ERROR",
40
+ }
41
+ )
42
+
43
+
44
+ @dataclass(slots=True, kw_only=True)
45
+ class UaServerConfiguration:
46
+ """OPC UA server related configuration."""
47
+
48
+ name: str = "UNNAMED OpenSMI Server"
49
+ namespace_uri: str = "urn:smartfactory.de:machine:XYZ" # unique(!) application URI
50
+ """URI of namespace index 1 (machine-specifics)"""
51
+ endpoint_address: str = "opc.tcp://0.0.0.0:4841/server"
52
+
53
+ encryption: bool = False
54
+ certificate: str = "server_certificate.der"
55
+ private_key: str = "server_private_key.pem"
56
+
57
+ history_db: HistoryOption = HistoryOption.MEMORY
58
+
59
+
60
+ @dataclass(slots=True, kw_only=True)
61
+ class UserConfiguration:
62
+ """`User` (role) related configuration."""
63
+
64
+ name: str
65
+ """Name of the user."""
66
+
67
+ password: str
68
+ """ The password of the user. Cleartext or peppered and base64-encoded when prefixed with ``base64:``"""
69
+
70
+ priority: int
71
+ """ Priority of the user, used when breaking the lock. Higher priority users can break the lock of lower
72
+ priority users. """
73
+
74
+ maximum_access_level: int
75
+ """ Maximum access level of the user. All actions (interacting with skills, writing variables, etc.) require a
76
+ certain access level. Higher is better. """
77
+
78
+ allow_multiple: bool = False
79
+ """ Are multiple logins from different clients allowed? """
80
+
81
+
82
+ @dataclass(slots=True, kw_only=True)
83
+ class AccessControlConfiguration:
84
+ """`AccessControl` related configuration."""
85
+
86
+ users: list[UserConfiguration] = field(
87
+ default_factory=lambda: [
88
+ UserConfiguration(
89
+ name="visitor", password="visitor", priority=0, maximum_access_level=0, allow_multiple=True
90
+ ),
91
+ UserConfiguration(
92
+ name="planner", password="planner", priority=5, maximum_access_level=5, allow_multiple=False
93
+ ),
94
+ UserConfiguration(
95
+ name="orchestrator", password="orchestrator", priority=10, maximum_access_level=10, allow_multiple=False
96
+ ),
97
+ UserConfiguration(
98
+ name="remote", password="remote", priority=15, maximum_access_level=15, allow_multiple=False
99
+ ),
100
+ UserConfiguration(
101
+ name="operator", password="operator", priority=20, maximum_access_level=20, allow_multiple=False
102
+ ),
103
+ UserConfiguration(
104
+ name="watchdog", password="watchdog", priority=25, maximum_access_level=20, allow_multiple=False
105
+ ),
106
+ UserConfiguration(
107
+ name="developer", password="developer", priority=100, maximum_access_level=100, allow_multiple=False
108
+ ),
109
+ ]
110
+ )
111
+ max_inactive_lock_time_milliseconds: int = 10 * 60 * 1000 # 10 minutes before lock must be renewed
112
+ minimum_access_level: int = 1
113
+ allow_reconnection_from_same_host: bool = True
114
+
115
+
116
+ @dataclass(slots=True, kw_only=True)
117
+ class ServerConfiguration:
118
+ """`Server` related configuration."""
119
+
120
+ debug: bool = False
121
+ logging: LoggingConfiguration = field(default_factory=LoggingConfiguration)
122
+ ua_server: UaServerConfiguration = field(default_factory=UaServerConfiguration)
123
+ discovery: DiscoveryConfiguration = field(default_factory=DiscoveryConfiguration)
124
+ access_control: AccessControlConfiguration = field(default_factory=AccessControlConfiguration)