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,280 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """All abstract interfaces used in the server."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from abc import ABC, abstractmethod
10
+ from pathlib import PurePosixPath
11
+ from typing import TYPE_CHECKING
12
+
13
+ from asyncua import ua
14
+ from asyncua.common.methods import uamethod
15
+ from asyncua.common.node import Node
16
+ from asyncua.ua import NodeId
17
+ from asyncua.ua.status_codes import StatusCodes as UaStatusCodes
18
+ from opensmi.core import SkillState
19
+ from structlog.stdlib import BoundLogger
20
+ from typing_extensions import deprecated
21
+
22
+ from opensmi.server.protocols import SessionProtocol, UserAuthorization
23
+
24
+ if TYPE_CHECKING:
25
+ from opensmi.server._server import Server
26
+ from opensmi.server.lock import Lock
27
+ from opensmi.server.ua_object import UaObjectDefinition
28
+
29
+
30
+ class AbstractUaObject(ABC):
31
+ """Abstract interface for all `UaObject` implementations."""
32
+
33
+ @property
34
+ @abstractmethod
35
+ def name(self) -> str:
36
+ """Name of the UaObject."""
37
+
38
+ @property
39
+ @deprecated("Use path instead")
40
+ @abstractmethod
41
+ def full_name(self) -> str:
42
+ """Return the full name including the names of all parents, separated by '/'."""
43
+
44
+ @property
45
+ @abstractmethod
46
+ def path(self) -> PurePosixPath:
47
+ """Return the full path of the object."""
48
+
49
+ @property
50
+ @abstractmethod
51
+ def ua_node(self) -> Node:
52
+ """Raw OPC UA node.
53
+
54
+ Do not touch unless you know what you are doing!
55
+ """
56
+
57
+ @property
58
+ @abstractmethod
59
+ def server(self) -> Server:
60
+ """Server instance."""
61
+
62
+ @property
63
+ @abstractmethod
64
+ def logger(self) -> BoundLogger:
65
+ """Logger associated with the `UaObject` instance."""
66
+
67
+ @property
68
+ @abstractmethod
69
+ def lock(self) -> Lock:
70
+ """`Lock` instance protecting this `UaObject`."""
71
+
72
+ @abstractmethod
73
+ def access_allowed(self, user: UserAuthorization, *, lock_required: bool | None = None) -> bool:
74
+ """Check whether ``user`` is currently allowed access to this `UaObject`.
75
+
76
+ :param user: `User` to check.
77
+ :param lock_required: Whether the corresponding `Lock` must also be owned by ``user``. Default ``None`` uses
78
+ ``bypass_lock`` setting.
79
+ """
80
+
81
+ async def condition_as_dependency_ready(self, _user: UserAuthorization) -> bool:
82
+ """Check whether this object is ready as a dependency in composite skills, etc.
83
+
84
+ Subclasses that can be used as a dependency **must** override this method. Raises by default.
85
+
86
+ :return: Always ``True``, else an exception is raised.
87
+ :raises UaStatusCodeError: If any dependency is not ready.
88
+ """
89
+ raise ua.UaStatusCodeError(UaStatusCodes.BadStateNotActive)
90
+
91
+
92
+ class AbstractCallable(AbstractUaObject):
93
+ """Callable interface, shared base for `AbstractSkill` and `AbstractMethod`."""
94
+
95
+ @abstractmethod
96
+ async def _condition_dependencies_ready(self, _user: UserAuthorization) -> bool:
97
+ """Check whether **ALL** dependencies are ready (different meaning for different types).
98
+
99
+ :return: Always ``True``, else an exception is raised.
100
+ :raises UaStatusCodeError: If any dependency is not ready.
101
+ """
102
+
103
+ @abstractmethod
104
+ async def _condition_startup_completed(self, user: UserAuthorization) -> bool:
105
+ """Check whether the parent component/machine startup is completed."""
106
+
107
+ @abstractmethod
108
+ async def _condition_access_allowed(self, user: UserAuthorization) -> bool:
109
+ """Check if the provided ``user`` has access to this skill.
110
+
111
+ The `User` must either be an admin (asyncua internal user), or must own the `Lock` protecting this
112
+ skill and a current access level greater or equal to this skill's minimum access level.
113
+ """
114
+
115
+
116
+ class AbstractSkill(AbstractCallable):
117
+ """Skill interface for internal and external OPC UA access."""
118
+
119
+ @property
120
+ @abstractmethod
121
+ def is_finite(self) -> bool:
122
+ """Return ``True`` if this skill is finite.
123
+
124
+ This must be correct regardless where the logic is implemented (PLC, Remote, etc. vs. this Python instance).
125
+ """
126
+ raise NotImplementedError
127
+
128
+ @property
129
+ @abstractmethod
130
+ def current_state(self) -> SkillState:
131
+ """Current state of the skill."""
132
+ raise NotImplementedError
133
+
134
+ @abstractmethod
135
+ async def wait_for_state(self, state: SkillState) -> None:
136
+ """Blocks until this skill either reached the given ``state`` or was unexpectedly halted.
137
+
138
+ :param state: the state of this skill to wait for.
139
+ :raises SkillHaltedError: If skill has unexpectedly halted.
140
+ """
141
+
142
+ @property
143
+ @abstractmethod
144
+ def name(self) -> str:
145
+ """Name of the skill."""
146
+ raise NotImplementedError
147
+
148
+ @property
149
+ @abstractmethod
150
+ def ua_state_machine(self) -> Node:
151
+ """OPC UA base node of state machine."""
152
+
153
+ @abstractmethod
154
+ async def _get_definition(self) -> UaObjectDefinition: # for UaObject
155
+ """Return the instantiation definition for the main OPC UA node. Is called from `ua_create_node`."""
156
+
157
+ ######################################
158
+ # Internal skill interface (for composite skills)
159
+
160
+ @abstractmethod
161
+ async def start(self) -> None:
162
+ """Start the skill. Machine internal interface.
163
+
164
+ Similar to calling the OPC UA method ``start()``, except that exceptions are not handled.
165
+ """
166
+ raise NotImplementedError
167
+
168
+ @abstractmethod
169
+ async def suspend(self) -> None:
170
+ """Suspend the skill (if the skill is suspendable). Machine internal interface.
171
+
172
+ Similar to calling the OPC UA method ``suspend()``, except that exceptions are not handled.
173
+ """
174
+ raise NotImplementedError
175
+
176
+ @abstractmethod
177
+ async def reset(self) -> None:
178
+ """Reset the skill. Machine internal interface.
179
+
180
+ Similar to calling the OPC UA method ``reset()``, except that exceptions are not handled.
181
+ """
182
+ raise NotImplementedError
183
+
184
+ @abstractmethod
185
+ async def halt(self) -> None:
186
+ """Halt (Stop) the skill. Machine internal interface.
187
+
188
+ Similar to calling the OPC UA method ``halt()``, except that exceptions are not handled.
189
+ """
190
+ raise NotImplementedError
191
+
192
+ ######################################
193
+ # OPC-UA Callbacks
194
+
195
+ @uamethod
196
+ @abstractmethod
197
+ async def _ua_start(self, _parent: NodeId, session: SessionProtocol) -> ua.StatusCode:
198
+ """Handle the OPC UA ``start`` method invocation.
199
+
200
+ This callback is executed when an OPC UA client calls the ``start`` method. Do **not** raise
201
+ exceptions here, instead return the appropriate OPC UA status code!
202
+
203
+ :param _parent: Parent OPC UA ``NodeId``.
204
+ :param session: OPC UA Client session that issued the method request.
205
+ """
206
+ return ua.StatusCode(ua.UInt32(UaStatusCodes.BadNotImplemented))
207
+
208
+ @uamethod
209
+ @abstractmethod
210
+ async def _ua_suspend(self, _parent: NodeId, session: SessionProtocol) -> ua.StatusCode:
211
+ """Handle the OPC UA ``suspend`` method invocation.
212
+
213
+ This callback is executed when an OPC UA client calls the ``suspend`` method. Do **not** raise
214
+ exceptions here, instead return the appropriate OPC UA status code!
215
+
216
+ :param _parent: Parent OPC UA ``NodeId``.
217
+ :param session: OPC UA Client session that issued the method request.
218
+ """
219
+ return ua.StatusCode(ua.UInt32(UaStatusCodes.BadNotImplemented))
220
+
221
+ @uamethod
222
+ @abstractmethod
223
+ async def _ua_reset(self, _parent: NodeId, session: SessionProtocol) -> ua.StatusCode:
224
+ """Handle the OPC UA ``reset`` method invocation.
225
+
226
+ This callback is executed when an OPC UA client calls the ``reset`` method. Do **not** raise
227
+ exceptions here, instead return the appropriate OPC UA status code!
228
+
229
+ :param _parent: Parent OPC UA ``NodeId``.
230
+ :param session: OPC UA Client session that issued the method request.
231
+ """
232
+ return ua.StatusCode(ua.UInt32(UaStatusCodes.BadNotImplemented))
233
+
234
+ @uamethod
235
+ @abstractmethod
236
+ async def _ua_halt(self, _parent: NodeId, session: SessionProtocol) -> ua.StatusCode:
237
+ """Handle the OPC UA ``halt`` method invocation.
238
+
239
+ This callback is executed when an OPC UA client calls the ``halt`` method. Do **not** raise
240
+ exceptions here, instead return the appropriate OPC UA status code!
241
+
242
+ :param _parent: Parent OPC UA ``NodeId``.
243
+ :param session: OPC UA Client session that issued the method request.
244
+ """
245
+ return ua.StatusCode(ua.UInt32(UaStatusCodes.BadNotImplemented))
246
+
247
+ @abstractmethod
248
+ async def _condition_is_suspendable(self, _user: UserAuthorization) -> bool:
249
+ """Check whether this skill is suspendable.
250
+
251
+ :return: Always ``True``, else an exception is raised.
252
+ :raises UaStatusCodeError: If the skill is not suspendable.
253
+ """
254
+
255
+
256
+ class AbstractMethod(AbstractCallable):
257
+ """Interface for methods."""
258
+
259
+ @abstractmethod
260
+ async def execute_method(self) -> None:
261
+ """Implement subclass-specific method logic."""
262
+ raise NotImplementedError
263
+
264
+
265
+ class AbstractUaLogger(ABC):
266
+ """Abstract interface for OPC UA logging."""
267
+
268
+ @abstractmethod
269
+ async def ua_log_info(self, msg: str, *, severity: int = 0, source: AbstractUaObject | None = None) -> None:
270
+ """Log an informational message."""
271
+
272
+ @abstractmethod
273
+ async def ua_log_warning(self, msg: str, *, severity: int = 555, source: AbstractUaObject | None = None) -> None:
274
+ """Log a warning message."""
275
+
276
+ @abstractmethod
277
+ async def ua_log_error(
278
+ self, msg: str, *, severity: int = 999, code: str = "", source: AbstractUaObject | None = None
279
+ ) -> None:
280
+ """Log an error message, with an optional, application-specific error ``code``."""
opensmi/server/lock.py ADDED
@@ -0,0 +1,347 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """``UaObject`` for managing exclusive access to its parent and its children."""
6
+
7
+ import asyncio
8
+ import contextlib
9
+ import time
10
+ from asyncio import Task
11
+ from collections.abc import AsyncGenerator
12
+ from typing import Any, Never
13
+
14
+ from asyncua import ua
15
+ from asyncua.common.methods import uamethod
16
+ from asyncua.common.node import Node
17
+ from asyncua.crypto.permission_rules import UserRole
18
+ from asyncua.ua.status_codes import StatusCodes
19
+ from opensmi.core.lifecycle_mixin import lifecycle
20
+ from typing_extensions import override
21
+
22
+ from opensmi.server.mixins.parent_mixin import ParentMixin
23
+ from opensmi.server.nodesets import DiNodeIds
24
+ from opensmi.server.protocols import SessionProtocol, UserAuthorization
25
+ from opensmi.server.ua_object import UaObject, UaObjectDefinition
26
+
27
+
28
+ class Lock(UaObject, ParentMixin[UaObject]):
29
+ """Manages exclusive write/execute access rights to the parent `UaObject` and its children.
30
+
31
+ Locks are not hierarchical. A child (or children's child, etc.) with its own Lock will not be
32
+ influenced by this lock.
33
+
34
+ OPC UA clients first need to request the lock by calling ``InitLock()``. If granted, they now own the lock and get
35
+ exclusive write and execution rights. (reading, browsing, etc. is always possible). Ideally, clients release
36
+ the lock as soon as they are done by calling ``ExitLock()``. Locks are automatically released when the client
37
+ disconnects or is inactive for too long without calling ``RenewLock()``.
38
+
39
+ The request can also fail when the user does not have the required minimum access level for the lock, or the lock
40
+ is already hold by another client. If it's hold by another client, the client can request the lock by calling
41
+ ``BreakLock()``. It will succeed only when the priority of the requesting client are larger than of the lock owner.
42
+
43
+ Based on OPC UA Locking model (https://reference.opcfoundation.org/specs/OPC-10000-100/7).
44
+ """
45
+
46
+ # OPC UA variables we need to update regularly. They get initialized and checked in _init()
47
+ _ua_locking_user: Node
48
+ _ua_locked: Node
49
+ _ua_locking_client: Node
50
+ _ua_remaining_lock_time_ms: Node
51
+
52
+ _task_check_inactivity: Task[None]
53
+
54
+ def __init__(self, *, minimum_access_level: int | None = None, **kwargs: dict[str, Any]) -> None:
55
+ """Construct new ``Lock`` instance with given ``minimum_access_level``."""
56
+ super().__init__(
57
+ name="Lock",
58
+ minimum_access_level=minimum_access_level,
59
+ bypass_lock=False,
60
+ server=None,
61
+ **kwargs,
62
+ )
63
+
64
+ self._locking_user: UserAuthorization | None = None
65
+ self._locking_time: float = 0.0
66
+ """ Monotonic timestamp when the lock was granted to a user. Used for inactivity timeout. """
67
+ self._lock: asyncio.Lock = asyncio.Lock()
68
+ """ Used to guarantee atomic updates. """
69
+
70
+ async def init_lock(self, user: UserAuthorization, *, session: SessionProtocol | None = None) -> bool:
71
+ """Request exclusive access to nodes protected by this ``Lock``.
72
+
73
+ Request will fail if the lock is already owned or if ``user`` lacks necessary access rights.
74
+
75
+ :return: Whether ``user`` now owns this ``Lock``.
76
+ """
77
+ if self.locked or not self.access_allowed(user, lock_required=False):
78
+ return False
79
+
80
+ await self.update_locking_status(user, session=session, reason="Init Lock")
81
+ return True
82
+
83
+ async def break_lock(self, user: UserAuthorization, *, session: SessionProtocol | None = None) -> bool:
84
+ """Request exclusive access to nodes protected by this ``Lock``.
85
+
86
+ Request will fail if the lock is already owned by a user with higher ``User.priority`` than ``user``
87
+ or if ``user`` lacks necessary access rights. Warning: Will steal lock ownership from its current owner!
88
+
89
+ :return: Whether ``user`` now owns this ``Lock``.
90
+ """
91
+ if not self.access_allowed(user, lock_required=False):
92
+ return False
93
+ if self.locking_user and user.role != UserRole.Admin and user.priority <= self.locking_user.priority:
94
+ return False
95
+
96
+ await self.update_locking_status(user, session=session, reason="Break Lock")
97
+ return True
98
+
99
+ async def exit_lock(self, user: UserAuthorization) -> bool:
100
+ """Release exclusive access to nodes protected by this ``Lock``.
101
+
102
+ Will fail if ``user`` lacks necessary access rights or the lock is owned by another user.
103
+
104
+ :return: Whether the lock was released.
105
+ """
106
+ if not self.access_allowed(user, lock_required=True):
107
+ return False
108
+
109
+ await self.update_locking_status(None, reason="Exit Lock")
110
+ return True
111
+
112
+ async def renew_lock(self, user: UserAuthorization) -> bool:
113
+ """Renew the remaining lock time before the ownership is lost due to inactivity."""
114
+ if not self.access_allowed(user, lock_required=True):
115
+ return False
116
+
117
+ self._locking_time = time.monotonic()
118
+ await self._ua_remaining_lock_time_ms.write_value(self.max_inactive_time_ms)
119
+ return True
120
+
121
+ async def _check_inactivity_loop(self) -> Never:
122
+ while True:
123
+ if self.locked:
124
+ remaining_lock_time_ms = self.max_inactive_time_ms - int((time.monotonic() - self._locking_time) * 1000)
125
+ if remaining_lock_time_ms <= 0:
126
+ await self.update_locking_status(None, reason="Inactivity")
127
+ else:
128
+ await self._ua_remaining_lock_time_ms.write_value(remaining_lock_time_ms)
129
+ await asyncio.sleep(1)
130
+
131
+ @override
132
+ async def _get_definition(self) -> UaObjectDefinition:
133
+ return UaObjectDefinition(
134
+ object_type=DiNodeIds.LockingServicesType,
135
+ namespace_uri=DiNodeIds,
136
+ reference_type=ua.object_ids.ObjectIds.HasAddIn,
137
+ )
138
+
139
+ @lifecycle
140
+ async def _lifecycle_lock(self) -> AsyncGenerator[None]:
141
+ await self._init()
142
+ yield
143
+ await self._shutdown()
144
+
145
+ async def _init(self) -> None:
146
+ _ua_init_lock: Node | None = None
147
+ _ua_exit_lock: Node | None = None
148
+ _ua_break_lock: Node | None = None
149
+ _ua_renew_lock: Node | None = None
150
+
151
+ for node in await self.ua_node.get_children():
152
+ match (await node.read_browse_name()).Name: # ignore namespace
153
+ case "LockingUser":
154
+ self._ua_locking_user = node
155
+ case "Locked":
156
+ self._ua_locked = node
157
+ case "LockingClient":
158
+ self._ua_locking_client = node
159
+ case "RemainingLockTime":
160
+ self._ua_remaining_lock_time_ms = node
161
+ case "InitLock":
162
+ _ua_init_lock = node
163
+ case "ExitLock":
164
+ _ua_exit_lock = node
165
+ case "BreakLock":
166
+ _ua_break_lock = node
167
+ case "RenewLock":
168
+ _ua_renew_lock = node
169
+ case _:
170
+ pass
171
+
172
+ assert self._ua_remaining_lock_time_ms is not None
173
+ assert self._ua_locked is not None
174
+ assert self._ua_locking_client is not None
175
+ assert self._ua_locking_user is not None
176
+ assert _ua_init_lock is not None
177
+ assert _ua_exit_lock is not None
178
+ assert _ua_break_lock is not None
179
+ assert _ua_renew_lock is not None
180
+
181
+ await self.server.ua_server.historize_node_data_change(
182
+ [self._ua_locking_user, self._ua_locking_client], count=1000
183
+ )
184
+ await self.update_locking_status(None, reason="Initialization")
185
+
186
+ session = self.server.ua_server.iserver.isession
187
+ _ = session.add_method_callback(_ua_init_lock.nodeid, self._ua_init_lock) # pyright: ignore[reportAny]
188
+ _ = session.add_method_callback(_ua_exit_lock.nodeid, self._ua_exit_lock) # pyright: ignore[reportAny]
189
+ _ = session.add_method_callback(_ua_break_lock.nodeid, self._ua_break_lock) # pyright: ignore[reportAny]
190
+ _ = session.add_method_callback(_ua_renew_lock.nodeid, self._ua_renew_lock) # pyright: ignore[reportAny]
191
+
192
+ # according to spec
193
+ namespace_index = self.server.ua_get_namespace_index(DiNodeIds)
194
+ ua_max_inactive_lock_time = self.server.ua_server.get_node(f"ns={namespace_index};i=6387")
195
+ await ua_max_inactive_lock_time.write_value(self.max_inactive_time_ms)
196
+
197
+ self.server.access_control.on_session_closed.connect(self._on_session_closed)
198
+
199
+ self._task_check_inactivity = asyncio.create_task(
200
+ self._check_inactivity_loop(), name=f"{self.path}.inactivity_check"
201
+ )
202
+
203
+ self.logger.debug("Initialized lock")
204
+
205
+ async def _shutdown(self) -> None:
206
+ with contextlib.suppress(asyncio.CancelledError):
207
+ if (
208
+ hasattr(self, "_task_check_inactivity")
209
+ and self._task_check_inactivity
210
+ and self._task_check_inactivity.cancel()
211
+ ):
212
+ await self._task_check_inactivity
213
+
214
+ async def update_locking_status(
215
+ self, user: UserAuthorization | None, *, session: SessionProtocol | None = None, reason: str = ""
216
+ ) -> None:
217
+ """Update locking status based on ``user`` unconditionally.
218
+
219
+ :param user: ``User`` that will be set as the locking user. ``None`` for clearing the releasing the lock.
220
+ :param session: (Optional) session instance. Is unavailable for internal user(s).
221
+ :param reason: Short reason description. Only for logging purposes.
222
+ """
223
+ async with self._lock:
224
+ if user is None:
225
+ self.logger.info("Releasing lock", previous_user=str(self.locking_user), reason=reason)
226
+ self._locking_user = None
227
+ await self._ua_locking_client.write_value("")
228
+ await self._ua_locking_user.write_value("")
229
+ await self._ua_locked.write_value(False)
230
+ await self._ua_remaining_lock_time_ms.write_value(0)
231
+ else:
232
+ self.logger.info("New lock owner", user=str(user), previous_user=str(self.locking_user), reason=reason)
233
+ self._locking_user = user
234
+ self._locking_time = time.monotonic()
235
+ await self._ua_locking_user.write_value(user.name)
236
+ if session is not None: # session is not required for internal lock requests
237
+ # TODO(CaHa): locking client is supposed to be the client ApplicationUri
238
+ await self._ua_locking_client.write_value(str(session.name))
239
+ await self._ua_locked.write_value(True)
240
+ await self._ua_remaining_lock_time_ms.write_value(self.max_inactive_time_ms)
241
+
242
+ @override
243
+ def access_allowed(self, user: UserAuthorization, *, lock_required: bool | None = None) -> bool:
244
+ """Check whether ``user`` is allowed to access this lock."""
245
+ if lock_required is None:
246
+ lock_required = not self.bypass_lock
247
+
248
+ if user.role == UserRole.Admin: # internal is always allowed
249
+ return True
250
+
251
+ if lock_required and self._locking_user != user:
252
+ return False
253
+
254
+ return user.current_access_level >= self.minimum_access_level
255
+
256
+ async def _on_session_closed(self, session: SessionProtocol) -> None:
257
+ """Handle session closed events.
258
+
259
+ Used to check if the user of that session is owning a lock. If that is the case, it will be released.
260
+ """
261
+ if session.user == self.locking_user:
262
+ await self.update_locking_status(None, reason="Session closed")
263
+
264
+ # -----------------------------------------------------------------------------------------
265
+ # OPC UA method callback handlers
266
+ # -----------------------------------------------------------------------------------------
267
+
268
+ @uamethod # pyright: ignore[reportAny]
269
+ async def _ua_init_lock(
270
+ self, parent: ua.NodeId, session: SessionProtocol, context: str | None = None
271
+ ) -> int | ua.StatusCode:
272
+ self.logger.debug("UA InitLock() method called", user=str(session.user), context=context)
273
+ assert session.user is not None
274
+
275
+ if not self.access_allowed(session.user, lock_required=False):
276
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
277
+
278
+ if await self.init_lock(session.user, session=session):
279
+ return 0 # InitLockStatus = OK
280
+
281
+ # TODO(CaHa): spec wants InitLockStatus = -1 but asyncua says no
282
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadLocked))
283
+
284
+ @uamethod # pyright: ignore[reportAny]
285
+ async def _ua_exit_lock(self, parent: ua.NodeId, session: SessionProtocol) -> int | ua.StatusCode:
286
+ self.logger.debug("UA ExitLock() method called", user=str(session.user))
287
+ assert session.user is not None
288
+
289
+ if not self.access_allowed(session.user, lock_required=True):
290
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
291
+
292
+ if not self.locked:
293
+ return -1 # ExitLockStatus = E_NotLocked
294
+
295
+ if await self.exit_lock(session.user):
296
+ return 0 # ExitLockStatus = OK
297
+
298
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
299
+
300
+ @uamethod # pyright: ignore[reportAny]
301
+ async def _ua_break_lock(self, parent: ua.NodeId, session: SessionProtocol) -> int | ua.StatusCode:
302
+ self.logger.debug("UA BreakLock() method called", user=str(session.user))
303
+ assert session.user is not None
304
+
305
+ if not self.access_allowed(session.user, lock_required=False):
306
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
307
+
308
+ # BreakLockStatus:
309
+ # 0 = OK
310
+ # -1 = E_NotLocked
311
+ ret = 0 if self.locked else -1
312
+
313
+ if await self.break_lock(session.user, session=session):
314
+ return ret
315
+
316
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
317
+
318
+ @uamethod # pyright: ignore[reportAny]
319
+ async def _ua_renew_lock(self, parent: ua.NodeId, session: SessionProtocol) -> int | ua.StatusCode:
320
+ self.logger.debug("UA RenewLock() method called", user=str(session.user))
321
+ assert session.user is not None
322
+
323
+ if not self.access_allowed(session.user, lock_required=True):
324
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadUserAccessDenied))
325
+
326
+ if not self.locked:
327
+ return -1 # RenewLockStatus = E_NotLocked
328
+
329
+ if await self.renew_lock(session.user):
330
+ return 0 # RenewLockStatus = OK
331
+
332
+ return ua.StatusCode(ua.UInt32(StatusCodes.BadNothingToDo))
333
+
334
+ @property
335
+ def max_inactive_time_ms(self) -> int:
336
+ """Maximum time in milliseconds a lock owner is allowed to be inactive."""
337
+ return int(self.server.config.access_control.max_inactive_lock_time_milliseconds)
338
+
339
+ @property
340
+ def locked(self) -> bool:
341
+ """Whether this ``Lock`` is locked."""
342
+ return self._locking_user is not None
343
+
344
+ @property
345
+ def locking_user(self) -> UserAuthorization | None:
346
+ """``User`` instance owning this ``Lock`` or ``None`` if unlocked."""
347
+ return self._locking_user
@@ -0,0 +1,22 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Mixins for UaObjects."""
6
+
7
+ # Note: only export mixins the end-user is supposed to use
8
+ from .lockable_mixin import LockableMixin as LockableMixin
9
+ from .notification_mixins import NotificationForwarderMixin as NotificationForwarderMixin
10
+ from .notification_mixins import NotificationMixin as NotificationMixin
11
+ from .parent_mixin import ParentMixin as ParentMixin
12
+ from .requirements_mixin import RequirementsMixin as RequirementsMixin
13
+ from .spatial_object_mixin import SpatialObjectListMixin as SpatialObjectListMixin
14
+ from .spatial_object_mixin import SpatialObjectMixin as SpatialObjectMixin
15
+ from .ua_object_container_mixins import ComponentsMixin as ComponentsMixin
16
+ from .ua_object_container_mixins import MethodSetMixin as MethodSetMixin
17
+ from .ua_object_container_mixins import ResourcesMixin as ResourcesMixin
18
+ from .ua_object_container_mixins import SkillSetMixin as SkillSetMixin
19
+ from .ua_variable_container_mixins import AttributesMixin as AttributesMixin
20
+ from .ua_variable_container_mixins import FinalResultDataMixin as FinalResultDataMixin
21
+ from .ua_variable_container_mixins import MonitoringMixin as MonitoringMixin
22
+ from .ua_variable_container_mixins import ParameterSetMixin as ParameterSetMixin
@@ -0,0 +1,37 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Mixin for providing a `Lock` to an `UaObject`."""
6
+
7
+ from collections.abc import AsyncGenerator
8
+
9
+ from opensmi.core.lifecycle_mixin import lifecycle
10
+
11
+ from opensmi.server.lock import Lock
12
+ from opensmi.server.ua_object import UaObject
13
+
14
+
15
+ class LockableMixin:
16
+ """Mixin for providing a `Lock` to an `UaObject`."""
17
+
18
+ __lock: Lock | None = None
19
+
20
+ @lifecycle
21
+ async def lifecycle_lock(self) -> AsyncGenerator[None]:
22
+ """Initialize the `Lock` for an `UaObject`."""
23
+ self.lock.parent = self # pyright: ignore[reportAttributeAccessIssue]
24
+ await self.lock.ua_create_node(self.ua_node, exist_ok=True) # pyright: ignore[reportAttributeAccessIssue]
25
+ await self.lock.init()
26
+
27
+ yield
28
+
29
+ await self.lock.shutdown()
30
+
31
+ @property
32
+ def lock(self) -> Lock:
33
+ """Return the associated `Lock` for this `UaObject`."""
34
+ if self.__lock is None:
35
+ assert isinstance(self, UaObject)
36
+ self.__lock = Lock(minimum_access_level=self.minimum_access_level)
37
+ return self.__lock