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,331 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Container implementation for `UaVariable`."""
6
+
7
+ from collections.abc import AsyncGenerator, Iterator, Mapping
8
+ from types import UnionType
9
+ from typing import Any, Union, get_args, get_origin, get_type_hints
10
+
11
+ from asyncua import ua
12
+ from opensmi.core.errors import RequiredVariableMissingError
13
+ from opensmi.core.lifecycle_mixin import lifecycle
14
+ from opensmi.core.ua_node_util import get_properties
15
+ from typing_extensions import override
16
+
17
+ from opensmi.server.mixins.parent_mixin import ParentMixin
18
+ from opensmi.server.nodesets import (
19
+ DiNodeIds,
20
+ MachineryNodeIds,
21
+ SmartFactoryMachineSetNodeIds,
22
+ SmartFactorySkillSetNodeIds,
23
+ )
24
+ from opensmi.server.ua_object import UaObject, UaObjectDefinition
25
+ from opensmi.server.ua_variable import UaVariable
26
+
27
+
28
+ class UaVariableContainer(UaObject, ParentMixin[UaObject]):
29
+ """Base class for `UaVariable` containers. Also provides a Pythonic container interface."""
30
+
31
+ def __init__(
32
+ self,
33
+ *,
34
+ name: str,
35
+ minimum_access_level: int | None = None,
36
+ writable: bool = False,
37
+ **kwargs,
38
+ ) -> None:
39
+ """*Cooperative* constructor.
40
+
41
+ :param name: The name of the container.
42
+ :param minimum_access_level: The minimum access level of the container.
43
+ :param writable: Whether the all `UaVariable` of this container have external OPC UA write access.
44
+ """
45
+ super().__init__(
46
+ name=name,
47
+ minimum_access_level=minimum_access_level,
48
+ **kwargs,
49
+ )
50
+
51
+ # class variables of type UaVariable are used as templates, we need to instantiate our own private ones.
52
+ # find all variables, including inherited ones
53
+ for cls in reversed(type(self).__mro__): # type: ignore
54
+ for name, class_variable in cls.__dict__.items():
55
+ if isinstance(class_variable, UaVariable):
56
+ clone = class_variable.clone(name=name, writable=writable)
57
+ self.logger.debug(
58
+ "Cloned UaVariable template", name=name, class_variable=class_variable, cloned_variable=clone
59
+ )
60
+ setattr(self, name, clone)
61
+
62
+ def _check_required_variables(self, annotations: dict[str, object]) -> None:
63
+ """Check we have all required existing variables based on annotations."""
64
+ for name, annotation in annotations.items():
65
+ optional = False
66
+
67
+ if get_origin(annotation) in (Union, UnionType):
68
+ union_types = get_args(annotation)
69
+ optional = type(None) in union_types
70
+
71
+ # Remove None from the Union
72
+ annotation = next(arg for arg in union_types if arg is not type(None))
73
+
74
+ if get_origin(annotation) is not UaVariable:
75
+ self.logger.debug("Skipping unsupported annotation", name=name, annotation=annotation)
76
+ continue
77
+
78
+ if not optional and not hasattr(self, name):
79
+ msg = (
80
+ f"{self.__class__.__name__}: Could not find existing OPC UA variable for required "
81
+ f"UaVariable '{name}'!"
82
+ )
83
+ raise RequiredVariableMissingError(msg)
84
+
85
+ async def _init_existing_variables(self) -> None:
86
+ self.logger.debug("Initializing existing variables...")
87
+
88
+ annotations: dict[str, object] = {} # find all annotations, including inherited ones
89
+ for cls in reversed(self.__class__.__mro__): # type: ignore
90
+ annotations.update(get_type_hints(cls))
91
+
92
+ # create new UaVariable instances based on existing OPC UA variables
93
+ for ua_variable_node in await self.ua_node.get_children(nodeclassmask=ua.NodeClass.Variable):
94
+ browse_name = await ua_variable_node.read_browse_name()
95
+ variant_type = await ua_variable_node.read_data_type_as_variant_type()
96
+ value = await ua_variable_node.read_value()
97
+ match variant_type: # handle required special cases
98
+ case ua.VariantType.LocalizedText:
99
+ value = ua.LocalizedText(value)
100
+ case ua.VariantType.QualifiedName:
101
+ value = ua.QualifiedName(value)
102
+ try:
103
+ value = ua.uatypes.get_default_value(variant_type) if value is None else value
104
+ initial_value = ua.Variant(Value=value, VariantType=variant_type)
105
+ except ua.uaerrors.UaError as err:
106
+ self.logger.exception(
107
+ "Cannot get initial value", browse_name=browse_name, variant_type=variant_type, value=value, err=err
108
+ )
109
+ raise
110
+
111
+ properties = await get_properties(ua_variable_node, logger=self.logger)
112
+
113
+ # check if there is a class var (template)
114
+ variable_template = self.__class__.__dict__.get(str(browse_name.Name))
115
+ if variable_template is not None:
116
+ self.logger.debug("Found existing variable template, cloning!", browse_name=browse_name)
117
+ assert isinstance(variable_template, UaVariable)
118
+ assert not variable_template.is_initialized
119
+ variable = variable_template.clone(name=str(browse_name.Name))
120
+ else:
121
+ if browse_name.Name not in annotations:
122
+ self.logger.warning("Found existing variable without type annotations!", browse_name=browse_name)
123
+ variable = UaVariable(
124
+ name=str(browse_name.Name), # type: ignore
125
+ initial_value=initial_value,
126
+ unit=properties.unit,
127
+ range=properties.range,
128
+ )
129
+ variable.parent = self # pyright: ignore[reportAttributeAccessIssue]
130
+ variable.ua_node = ua_variable_node
131
+ await variable.init()
132
+ self.__setattr__(browse_name.Name, variable)
133
+
134
+ self.logger.debug(
135
+ "Added existing variable",
136
+ browse_name=browse_name,
137
+ inital_value=initial_value,
138
+ variant_type=variant_type,
139
+ )
140
+
141
+ self._check_required_variables(annotations)
142
+
143
+ @lifecycle
144
+ async def _lifecycle_container(self) -> AsyncGenerator[None]:
145
+ await self._init_existing_variables()
146
+
147
+ # initialize our private UaVariable instances
148
+ for variable in self:
149
+ if not variable.is_initialized:
150
+ variable.parent = self
151
+ await variable.ua_create_node(self.ua_node)
152
+ await variable.init()
153
+ yield
154
+
155
+ # @override
156
+ # async def _after_init(self) -> None:
157
+ # await super()._after_init()
158
+ #
159
+ # if len(self) == 0:
160
+ # self.logger.debug("Hiding OPC UA node", reason="Contains no variables.")
161
+ # await self._ua_hide_node()
162
+ #
163
+ # async def _ua_hide_node(self) -> None:
164
+ # """Hide our OPC UA node by deleting the reference to our parent."""
165
+ # await self.ua_node.delete_reference(
166
+ # target=self.parent.ua_node,
167
+ # reftype=ua.object_ids.ObjectIds.HasComponent,
168
+ # forward=False,
169
+ # )
170
+
171
+ async def reset_all(self) -> None:
172
+ """Reset all contained `UaVariable` to their initial value."""
173
+ for variable in self:
174
+ await variable.reset()
175
+
176
+ async def read_all(self) -> Mapping[str, Any]:
177
+ """Read all contained variables and return a mapping from variable name to value."""
178
+ return {var.name: await var.read() for var in self}
179
+
180
+ async def write_all(self, mapping: Mapping[str, Any]) -> None:
181
+ """Write to all given ``mapping`` of variables name and their values.
182
+
183
+ :raises KeyError: If no variable with given name in ``mapping`` exists.
184
+ :raises OutOfRangeError: if value of ``mapping`` is not within the range of the corresponding variable.
185
+ """
186
+ for name, value in mapping.items():
187
+ await self[name].write(value)
188
+
189
+ #
190
+ # Pythonic container interface
191
+ #
192
+
193
+ def __getitem__(self, name: str) -> UaVariable:
194
+ """Get a `UaVariable` by the given ``name``.
195
+
196
+ :raises KeyError: If no variable with given name exists.
197
+ """
198
+ if isinstance(variable := self.__dict__.get(name), UaVariable):
199
+ return variable
200
+ msg = f"No UaVariable named '{name}' contained in {self.path}!"
201
+ raise KeyError(msg)
202
+
203
+ def __contains__(self, key: object) -> bool:
204
+ """Whether a variable with given ``name`` exists in this container."""
205
+ return isinstance(key, str) and isinstance(self.__dict__.get(key), UaVariable)
206
+
207
+ def __len__(self) -> int:
208
+ """Return the number of contained `UaVariable`."""
209
+ return sum(1 for var in self.__dict__.values() if isinstance(var, UaVariable))
210
+
211
+ def __iter__(self) -> Iterator[UaVariable]:
212
+ """Iterate over the contained `UaVariable`."""
213
+ return (var for var in self.__dict__.values() if isinstance(var, UaVariable))
214
+
215
+
216
+ class ParameterSet(UaVariableContainer):
217
+ """Base class for the `ParameterSet` container within Machine, Skill, Method, etc."""
218
+
219
+ def __init__(self, *, minimum_access_level: int | None = None, **kwargs) -> None:
220
+ """*Cooperative* constructor."""
221
+ super().__init__(name="ParameterSet", minimum_access_level=minimum_access_level, writable=True, **kwargs)
222
+
223
+ @override
224
+ async def _get_definition(self) -> UaObjectDefinition:
225
+ return UaObjectDefinition(
226
+ object_type=DiNodeIds.FunctionalGroupType,
227
+ namespace_uri=SmartFactoryMachineSetNodeIds,
228
+ )
229
+
230
+
231
+ class Monitoring(UaVariableContainer):
232
+ """Base class for the `Monitoring` container within Machine, Skill, Method, etc."""
233
+
234
+ def __init__(self, **kwargs) -> None:
235
+ """*Cooperative* constructor."""
236
+ super().__init__(name="Monitoring", minimum_access_level=None, writable=False, **kwargs)
237
+
238
+ @override
239
+ async def _get_definition(self) -> UaObjectDefinition:
240
+ return UaObjectDefinition(
241
+ object_type=SmartFactoryMachineSetNodeIds.MonitoringType,
242
+ namespace_uri=SmartFactoryMachineSetNodeIds,
243
+ )
244
+
245
+
246
+ class Attributes(UaVariableContainer):
247
+ """Base class for the `Attributes` container within Machine, Skill, Method, etc."""
248
+
249
+ def __init__(self, **kwargs) -> None:
250
+ """*Cooperative* constructor."""
251
+ super().__init__(name="Attributes", minimum_access_level=None, writable=False, **kwargs)
252
+
253
+ @override
254
+ async def _get_definition(self) -> UaObjectDefinition:
255
+ return UaObjectDefinition(
256
+ object_type=DiNodeIds.FunctionalGroupType,
257
+ namespace_uri=SmartFactoryMachineSetNodeIds,
258
+ )
259
+
260
+
261
+ class FinalResultData(UaVariableContainer):
262
+ """Base class for the final result data container within skills (`BaseSkill`) and methods (`BaseMethod`)."""
263
+
264
+ def __init__(self, *, minimum_access_level: int | None = None, **kwargs) -> None:
265
+ """*Cooperative* constructor."""
266
+ super().__init__(name="FinalResultData", minimum_access_level=minimum_access_level, writable=False, **kwargs)
267
+
268
+ @override
269
+ async def _get_definition(self) -> UaObjectDefinition:
270
+ return UaObjectDefinition(
271
+ object_type=DiNodeIds.FunctionalGroupType,
272
+ namespace_uri=SmartFactorySkillSetNodeIds,
273
+ )
274
+
275
+
276
+ class Identification(UaVariableContainer):
277
+ """Abstract base class for the identification container.
278
+
279
+ See OPC UA Machinery companion specification: abstract type ``MachineryItemIdentificationType``.
280
+ """
281
+
282
+ def __init__(self, *, minimum_access_level: int | None = None, **kwargs) -> None:
283
+ """*Cooperative* constructor."""
284
+ super().__init__(name="Identification", minimum_access_level=minimum_access_level, writable=False, **kwargs)
285
+
286
+
287
+ class MachineryComponentIdentification(Identification):
288
+ """Base class for the identification container for machine and machinery items.
289
+
290
+ See OPC UA Machinery companion specification: ``MachineryComponentIdentificationType``.
291
+ """
292
+
293
+ AssetId: UaVariable[str] | None
294
+ ComponentName: UaVariable[ua.LocalizedText] | None
295
+ Manufacturer: UaVariable[ua.LocalizedText]
296
+ SerialNumber: UaVariable[str]
297
+
298
+ @override
299
+ async def _get_definition(self) -> UaObjectDefinition:
300
+ return UaObjectDefinition(
301
+ object_type=MachineryNodeIds.MachineryComponentIdentificationType,
302
+ namespace_uri=MachineryNodeIds,
303
+ reference_type=ua.object_ids.ObjectIds.HasAddIn,
304
+ )
305
+
306
+
307
+ class MachineIdentification(MachineryComponentIdentification):
308
+ """Identification container for machines (`BaseMachine`).
309
+
310
+ OPC UA property ``ProductInstanceUri`` is mandatory, and it uses another OPC UA type: ``MachineIdentificationType``.
311
+ """
312
+
313
+ ProductInstanceUri: UaVariable[str]
314
+
315
+ @override
316
+ async def _get_definition(self) -> UaObjectDefinition:
317
+ return UaObjectDefinition(
318
+ object_type=MachineryNodeIds.MachineIdentificationType,
319
+ namespace_uri=DiNodeIds,
320
+ reference_type=ua.object_ids.ObjectIds.HasAddIn,
321
+ )
322
+
323
+
324
+ async def init_container(*, parent: object, container: UaVariableContainer, exist_ok: bool = True) -> None:
325
+ """Initialize the given ``container`` container with ``parent``."""
326
+ assert isinstance(parent, UaObject)
327
+ assert container is not None
328
+
329
+ container.parent = parent
330
+ await container.ua_create_node(parent.ua_node, exist_ok=exist_ok)
331
+ await container.init()
opensmi/server/user.py ADDED
@@ -0,0 +1,154 @@
1
+ # SPDX-FileCopyrightText: 2026 OpenSMI Contributors
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """User (role), authentication and OPC UA representation."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ from collections.abc import AsyncGenerator, Iterator
11
+
12
+ from asyncua.common.node import Node
13
+ from asyncua.crypto.permission_rules import User as UaUser
14
+ from asyncua.crypto.permission_rules import UserRole
15
+ from asyncua.ua import Int32
16
+ from cryptography.exceptions import InvalidKey
17
+ from opensmi.core.lifecycle_mixin import lifecycle
18
+ from typing_extensions import override
19
+
20
+ from opensmi.server.common import get_scrypt_instance
21
+ from opensmi.server.config import UserConfiguration
22
+ from opensmi.server.mixins.parent_mixin import ParentMixin
23
+ from opensmi.server.nodesets import SmartFactoryMachineSetNodeIds
24
+ from opensmi.server.protocols import SessionProtocol, UserProtocol
25
+ from opensmi.server.ua_object import UaObject, UaObjectDefinition
26
+
27
+
28
+ class User(ParentMixin[UaObject], UaObject, UserProtocol):
29
+ """User (role), authentication and OPC UA representation."""
30
+
31
+ _ua_is_present: Node
32
+ """ OPC UA (dynamic) node indicating whether this user instance is present. """
33
+
34
+ _password: bytes | str
35
+
36
+ def __init__(self, *, config: UserConfiguration) -> None:
37
+ """Construct new user based on given configuration."""
38
+ super().__init__(name=config.name)
39
+ if config.password.startswith("base64:"):
40
+ encoded = config.password.removeprefix("base64:")
41
+ self._password = base64.b64decode(encoded)
42
+ else:
43
+ self._password = config.password
44
+
45
+ self._priority: int = config.priority
46
+ self._maximum_access_level: int = config.maximum_access_level
47
+ self._current_access_level: int = config.maximum_access_level
48
+ self.allow_multiple: bool = config.allow_multiple
49
+ self._sessions: set[SessionProtocol] = set()
50
+
51
+ @property
52
+ @override
53
+ def current_access_level(self) -> int:
54
+ return self._current_access_level
55
+
56
+ @current_access_level.setter
57
+ def current_access_level(self, access_level: int) -> None:
58
+ access_level = max(0, int(access_level))
59
+ if access_level > self.maximum_access_level:
60
+ msg = f"Given access level must be <= {self.maximum_access_level} for user '{self.name}'!"
61
+ raise ValueError(msg)
62
+ old_level = self._current_access_level
63
+ self._current_access_level = access_level
64
+ self.logger.info("Updated current access level", new_level=access_level, old_level=old_level)
65
+
66
+ @property
67
+ @override
68
+ def maximum_access_level(self) -> int:
69
+ return self._maximum_access_level
70
+
71
+ @property
72
+ @override
73
+ def priority(self) -> int:
74
+ return self._priority
75
+
76
+ @override
77
+ async def _get_definition(self) -> UaObjectDefinition:
78
+ return UaObjectDefinition(object_type=SmartFactoryMachineSetNodeIds.UserType)
79
+
80
+ @override
81
+ def _repr_items(self) -> Iterator[tuple[str, object]]:
82
+ yield "name", self.name
83
+ yield "access_level", f"{self.current_access_level}/{self.maximum_access_level}"
84
+ yield "no_of_sessions", len(self._sessions)
85
+
86
+ @lifecycle
87
+ async def lifecycle_ua_user(self) -> AsyncGenerator[None]:
88
+ """Initialize OPC UA representation."""
89
+ for child in await self.ua_node.get_children():
90
+ bname = await child.read_browse_name()
91
+ if bname.Name in ["Name", "UserRole"]:
92
+ await child.write_value(self.name)
93
+ elif bname.Name == "AllowMultiple":
94
+ await child.write_value(self.allow_multiple)
95
+ elif bname.Name == "UserLevel":
96
+ await child.write_value(str(self.priority))
97
+ elif bname.Name == "MaxAccessLevel":
98
+ await child.write_value(Int32(self.maximum_access_level))
99
+ elif bname.Name == "IsPresent":
100
+ self._ua_is_present = child
101
+ await self._ua_is_present.write_value(False)
102
+ elif bname.Name == "Language":
103
+ await child.write_value("en")
104
+ # TODO(CaHa): ID, CardUid
105
+ assert self._ua_is_present is not None
106
+ yield
107
+ # no shutdown
108
+
109
+ @property
110
+ @override
111
+ def role(self) -> UserRole:
112
+ return UserRole.User
113
+
114
+ @property
115
+ @override
116
+ def present(self) -> bool:
117
+ return any(session.is_activated for session in self._sessions)
118
+
119
+ @property
120
+ @override
121
+ def sessions(self) -> set[SessionProtocol]:
122
+ return set(self._sessions)
123
+
124
+ @override
125
+ async def add_session(self, session: SessionProtocol) -> None:
126
+ self.logger.debug("Adding session", session=session.name, sessions=len(self._sessions))
127
+ self._sessions.add(session)
128
+ await self._ua_is_present.write_value(True)
129
+
130
+ @override
131
+ async def remove_session(self, session: SessionProtocol) -> None:
132
+ self.logger.debug("Removing session", session=session.name, sessions=len(self._sessions))
133
+ self._sessions.remove(session)
134
+ if len(self._sessions) == 0:
135
+ await self._ua_is_present.write_value(False)
136
+
137
+ @override
138
+ def check_password(self, password: bytes | str | None) -> bool:
139
+ if password is None:
140
+ return False
141
+
142
+ if isinstance(self._password, bytes) and isinstance(password, bytes):
143
+ try:
144
+ get_scrypt_instance().verify(password, self._password)
145
+ except InvalidKey:
146
+ return False
147
+ else:
148
+ self.logger.warning("Using unencrypted password!")
149
+ return self._password == bytes(str(password), "utf-8").decode() # clear text (e.g. for test cases)
150
+
151
+ return True
152
+
153
+
154
+ INTERNAL_USER = UaUser(name="INTERNAL", role=UserRole.Admin)