OpenSMI-ROS2 0.1.0__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 (89) hide show
  1. opensmi/ros2/__init__.py +89 -0
  2. opensmi/ros2/__main__.py +11 -0
  3. opensmi/ros2/cli.py +143 -0
  4. opensmi/ros2/py.typed +0 -0
  5. opensmi/ros2/runtime/__init__.py +67 -0
  6. opensmi/ros2/runtime/_decode.py +101 -0
  7. opensmi/ros2/runtime/_encode.py +102 -0
  8. opensmi/ros2/runtime/_parser.py +147 -0
  9. opensmi/ros2/runtime/errors.py +141 -0
  10. opensmi/ros2/runtime/goal.py +232 -0
  11. opensmi/ros2/runtime/graph.py +288 -0
  12. opensmi/ros2/runtime/guard.py +213 -0
  13. opensmi/ros2/runtime/interface.py +140 -0
  14. opensmi/ros2/runtime/messages/__init__.py +503 -0
  15. opensmi/ros2/runtime/messages/industrial_msgs.py +62 -0
  16. opensmi/ros2/runtime/messages/industrial_msgs.pyi +159 -0
  17. opensmi/ros2/runtime/messages/motoros2_interfaces.py +79 -0
  18. opensmi/ros2/runtime/messages/motoros2_interfaces.pyi +307 -0
  19. opensmi/ros2/runtime/messages/neo_msgs2.py +55 -0
  20. opensmi/ros2/runtime/messages/neo_msgs2.pyi +138 -0
  21. opensmi/ros2/runtime/messages/neo_srvs2.py +72 -0
  22. opensmi/ros2/runtime/messages/neo_srvs2.pyi +224 -0
  23. opensmi/ros2/runtime/outcomes.py +103 -0
  24. opensmi/ros2/runtime/parameters.py +723 -0
  25. opensmi/ros2/runtime/publisher.py +125 -0
  26. opensmi/ros2/runtime/qos.py +394 -0
  27. opensmi/ros2/runtime/runtime.py +1171 -0
  28. opensmi/ros2/runtime/selection.py +150 -0
  29. opensmi/ros2/runtime/stamp.py +100 -0
  30. opensmi/ros2/runtime/subscription.py +354 -0
  31. opensmi/ros2/runtime/tf.py +714 -0
  32. opensmi/ros2/server/__init__.py +148 -0
  33. opensmi/ros2/server/access.py +109 -0
  34. opensmi/ros2/server/bindings/__init__.py +92 -0
  35. opensmi/ros2/server/bindings/_base.py +154 -0
  36. opensmi/ros2/server/bindings/action.py +133 -0
  37. opensmi/ros2/server/bindings/keyed.py +127 -0
  38. opensmi/ros2/server/bindings/lifecycle.py +131 -0
  39. opensmi/ros2/server/bindings/method.py +130 -0
  40. opensmi/ros2/server/bindings/monitoring.py +109 -0
  41. opensmi/ros2/server/bindings/parameter.py +133 -0
  42. opensmi/ros2/server/bindings/publisher.py +192 -0
  43. opensmi/ros2/server/bindings/registry.py +95 -0
  44. opensmi/ros2/server/bindings/tf.py +256 -0
  45. opensmi/ros2/server/browse_names.py +94 -0
  46. opensmi/ros2/server/component.py +334 -0
  47. opensmi/ros2/server/config.py +493 -0
  48. opensmi/ros2/server/containers.py +191 -0
  49. opensmi/ros2/server/drivers.py +421 -0
  50. opensmi/ros2/server/errors.py +159 -0
  51. opensmi/ros2/server/events.py +406 -0
  52. opensmi/ros2/server/introspection.py +850 -0
  53. opensmi/ros2/server/keyed.py +749 -0
  54. opensmi/ros2/server/lifecycle.py +238 -0
  55. opensmi/ros2/server/limits.py +66 -0
  56. opensmi/ros2/server/loader.py +977 -0
  57. opensmi/ros2/server/machine.py +225 -0
  58. opensmi/ros2/server/method.py +307 -0
  59. opensmi/ros2/server/mirror.py +582 -0
  60. opensmi/ros2/server/mutation.py +992 -0
  61. opensmi/ros2/server/nodesets/Opc.Ua.SmartFactory.ROS2.NodeSet2.xml +85 -0
  62. opensmi/ros2/server/nodesets/__init__.py +18 -0
  63. opensmi/ros2/server/nodesets/smart_factory_ros2.py +26 -0
  64. opensmi/ros2/server/parameters.py +704 -0
  65. opensmi/ros2/server/projection.py +1176 -0
  66. opensmi/ros2/server/projections/__init__.py +41 -0
  67. opensmi/ros2/server/projections/scope.py +222 -0
  68. opensmi/ros2/server/provenance.py +121 -0
  69. opensmi/ros2/server/publisher.py +781 -0
  70. opensmi/ros2/server/recipes.py +514 -0
  71. opensmi/ros2/server/required.py +633 -0
  72. opensmi/ros2/server/skill.py +363 -0
  73. opensmi/ros2/server/spatial.py +283 -0
  74. opensmi/ros2/server/startup.py +626 -0
  75. opensmi/ros2/server/status.py +107 -0
  76. opensmi/ros2/server/structures.py +135 -0
  77. opensmi/ros2/server/transforms/__init__.py +39 -0
  78. opensmi/ros2/server/transforms/conversions.py +58 -0
  79. opensmi/ros2/server/transforms/filing.py +340 -0
  80. opensmi/ros2/server/transforms/mirror.py +462 -0
  81. opensmi/ros2/server/transforms/outward.py +180 -0
  82. opensmi/ros2/server/transforms/records.py +195 -0
  83. opensmi/ros2/server/transforms/spatial.py +154 -0
  84. opensmi_ros2-0.1.0.dist-info/METADATA +183 -0
  85. opensmi_ros2-0.1.0.dist-info/RECORD +89 -0
  86. opensmi_ros2-0.1.0.dist-info/WHEEL +5 -0
  87. opensmi_ros2-0.1.0.dist-info/entry_points.txt +2 -0
  88. opensmi_ros2-0.1.0.dist-info/licenses/LICENSES/MIT.txt +18 -0
  89. opensmi_ros2-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,493 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Configuration: a generic dataclass loader, and the ROS2 settings an application injects.
6
+
7
+ ROS2 settings are their own TOML file and dataclass, not a ``[ros2]`` table in the opensmi server
8
+ configuration, because that tree is closed and refuses keys it does not know. The application loads
9
+ :class:`ROS2Config` itself and hands it to the Runtime and the Machine mixin.
10
+
11
+ A setting lives here and not on a declaration when it is true of the Machine (one ROS2 Domain ID)
12
+ and not of one object on it. :class:`TransformConfig` is the case: the transform topics and the TF
13
+ poll period look like Binding keywords, but one Domain ID has one frame network and one poll. Such a
14
+ value declared per object is refused and named here instead.
15
+
16
+ The two settings dataclasses raise :class:`~opensmi.ros2.server.errors.DeclarationError` on
17
+ contradictory values. The loader raises ``ValueError`` and ``TypeError`` only.
18
+
19
+ The loader is one function over any dataclass and also reads the Binding TOML of
20
+ :mod:`opensmi.ros2.server.bindings`. It behaves like ``opensmi.core.config.load_dataclass``, including
21
+ ``ValueError`` on an unknown key, with two differences:
22
+
23
+ * It converts a TOML array into a ``tuple`` when the field asks for one, since the declarations are
24
+ frozen and a list would make them unhashable.
25
+ * A TOML file can name no Python class. A field whose type is not a string, number, boolean, time or a
26
+ container of those (enums and nested dataclasses are built from them) is refused a value, so an
27
+ editable file cannot run code. Custom implementation classes and callables are Python-side keywords
28
+ only. The machine file (:mod:`opensmi.ros2.server.loader`) reaches a few by importing a named path
29
+ and handing the object in through ``supplied``.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import collections.abc as abc
35
+ import datetime as dt
36
+ import inspect
37
+ import sys
38
+ import tomllib
39
+ from dataclasses import dataclass, fields, is_dataclass
40
+ from enum import Enum, IntEnum
41
+ from pathlib import Path
42
+ from types import UnionType
43
+ from typing import TYPE_CHECKING, Any, Final, TypeVar, Union, get_args, get_origin, get_type_hints
44
+
45
+ from opensmi.ros2.runtime.tf import TF_DEPTH, TF_STATIC_TOPIC, TF_TOPIC
46
+ from opensmi.ros2.server.access import LISTING_ACCESS_LEVEL, MUTATOR_ACCESS_LEVEL, SKILL_ACCESS_LEVEL
47
+ from opensmi.ros2.server.errors import DeclarationError
48
+
49
+ if TYPE_CHECKING:
50
+ from collections.abc import Mapping
51
+
52
+ __all__ = [
53
+ "TF_INTERVAL",
54
+ "TF_QUIET_AFTER",
55
+ "FieldError",
56
+ "ROS2Config",
57
+ "TransformConfig",
58
+ "declarable_keys",
59
+ "from_dict",
60
+ "load_toml",
61
+ "python_keys",
62
+ ]
63
+
64
+ _T = TypeVar("_T")
65
+
66
+ _TOML_SCALARS: Final = (str, int, float, bool, dt.datetime, dt.date, dt.time)
67
+ """Every Python type a TOML document can produce a value of."""
68
+
69
+
70
+ TF_INTERVAL: Final = 1.0
71
+ """How many seconds pass between polls of the frame network, unless a deployment says otherwise."""
72
+
73
+ TF_QUIET_AFTER: Final = 5.0
74
+ """How many seconds a frame may go unpublished before it is quiet, by default.
75
+
76
+ This has to clear the slowest publisher on the robot: a diagnostic frame republished every two
77
+ seconds is healthy. A deployment that knows its publishers can tighten it.
78
+ """
79
+
80
+
81
+ class FieldError(ValueError, TypeError):
82
+ """A TOML value does not fit the field it was written under.
83
+
84
+ Both a :class:`ValueError` and a :class:`TypeError`, since the conversion raises either. It adds
85
+ which field, so a caller reading a whole file can report the place and carry on.
86
+
87
+ :ivar field: The field name, dotted when the value sat inside a nested table.
88
+ :ivar reason: What was wrong with the value, without the field name.
89
+ """
90
+
91
+ def __init__(self, field: str, reason: str) -> None:
92
+ """Remember the field and the reason, and say both."""
93
+ super().__init__(f"{field}: {reason}")
94
+ self.field = field
95
+ self.reason = reason
96
+
97
+
98
+ @dataclass(frozen=True, slots=True, kw_only=True)
99
+ class TransformConfig:
100
+ """Where this Machine reads TF from, and how often the frame network is sampled.
101
+
102
+ One Runtime is one Domain ID and one frame network, and one Machine runs one poll over the
103
+ ownership partition of every declared head. So these values are declared once here, not per
104
+ object. A :class:`~opensmi.ros2.server.bindings.TFBinding` keeps what is true of its object: head
105
+ frame, exclusions, alternatives. Reached as :attr:`ROS2Config.transforms`; in the settings file::
106
+
107
+ [transforms]
108
+ path = "/robot/tf"
109
+ static_path = "/robot/tf_static"
110
+ interval = 0.5
111
+ quiet_after = 2.0
112
+
113
+ :ivar path: The transform topic, ``/tf`` unless remapped.
114
+ :ivar static_path: The static transform topic, always read as well. When this Machine publishes a
115
+ frame of its own there, it uses :data:`~opensmi.ros2.runtime.tf.TF_STATIC_QOS`. What it
116
+ requests on both topics is discovered from the publishers.
117
+ :ivar depth: How many messages each of the two subscriptions buffers.
118
+ :ivar quiet_after: Seconds a frame may go unpublished before its Location reads
119
+ ``BadNoCommunication`` (see :func:`~opensmi.ros2.server.status.transform_status`). A static
120
+ frame is exempt, so this only has to clear the slowest moving publisher.
121
+ :ivar interval: Seconds between polls of the frame network. Inward is a poll, not a write per
122
+ message, because ``/tf`` carries one message per publisher per control cycle.
123
+ """
124
+
125
+ path: str = TF_TOPIC
126
+ static_path: str = TF_STATIC_TOPIC
127
+ depth: int = TF_DEPTH
128
+ interval: float = TF_INTERVAL
129
+ quiet_after: float = TF_QUIET_AFTER
130
+
131
+ def __post_init__(self) -> None:
132
+ """Refuse settings that contradict themselves.
133
+
134
+ :raises DeclarationError: When either topic is unnamed, both name one topic, the
135
+ subscriptions buffer nothing, or the poll period or the staleness window is not positive.
136
+ """
137
+ for name, topic in (("path", self.path), ("static_path", self.static_path)):
138
+ if topic:
139
+ continue
140
+ message = (
141
+ f"the transform settings give {name}={topic!r}, which names no ROS2 topic; both "
142
+ f"transform topics are read and always, because a system whose frames are all "
143
+ f"static publishes every one of them on the static one and none on the other"
144
+ )
145
+ raise DeclarationError(message)
146
+ if self.path == self.static_path:
147
+ message = (
148
+ f"the transform settings read both kinds of transform from {self.path!r}; they "
149
+ f"are two topics because a message on the static one marks its frames constant, "
150
+ f"so reading one topic as both would say a frame that moves never will"
151
+ )
152
+ raise DeclarationError(message)
153
+ if self.depth < 1:
154
+ message = (
155
+ f"the transform settings give depth={self.depth!r}; it is how many messages each "
156
+ f"transform subscription buffers, so it holds at least one message and a "
157
+ f"subscription that buffered none would be one that reads nothing"
158
+ )
159
+ raise DeclarationError(message)
160
+ if self.interval <= 0:
161
+ message = (
162
+ f"the transform settings give interval={self.interval!r}; it is how many seconds "
163
+ f"pass between polls of the frame network, so it is a positive number and there "
164
+ f"is no way to spell a poll that has already happened"
165
+ )
166
+ raise DeclarationError(message)
167
+ if self.quiet_after <= 0:
168
+ message = (
169
+ f"the transform settings give quiet_after={self.quiet_after!r}; it is how long a "
170
+ f"frame may go unpublished before its Location reads BadNoCommunication, so it is "
171
+ f"a positive number and a window of zero would call every frame stale the instant "
172
+ f"it arrived"
173
+ )
174
+ raise DeclarationError(message)
175
+
176
+ @property
177
+ def topics(self) -> tuple[str, str]:
178
+ """Return both transform topics, which is what a reader of these settings subscribes to."""
179
+ return (self.path, self.static_path)
180
+
181
+
182
+ @dataclass(frozen=True, slots=True, kw_only=True)
183
+ class ROS2Config:
184
+ """The ROS2 settings of one Machine, which is the unit of one Domain ID.
185
+
186
+ The first four fields are the Runtime's constructor keywords, so a Runtime can be built from a
187
+ loaded config field by field. The Machine mixin takes the whole object.
188
+
189
+ :ivar domain_id: The ROS2 Domain ID this Machine's Runtime is confined to.
190
+ :ivar node_name: The name of the single ``rclpy`` Node the Runtime owns.
191
+ :ivar namespace: The ROS2 namespace for that node, or ``None`` for the root.
192
+ :ivar stop_timeout: How long, in seconds, stopping waits for the executor thread.
193
+ :ivar startup_timeout: Seconds a required Binding has to become satisfied before its StartupSkill
194
+ gives up on it. A declaration can override it with its own ``startup_timeout``; a Binding that
195
+ is not required has no deadline. A Machine's StartupSkill also allows each Component this much
196
+ slack beyond that Component's own deadlines.
197
+ :ivar transforms: Where the TF Bindings read the frame network from and how often it is polled;
198
+ the ``[transforms]`` table in the settings file. See :class:`TransformConfig`.
199
+ :ivar listing_access_level: Access level the introspection Component's read-only listings
200
+ require. They answer without the Lock whatever this is. Default
201
+ :data:`~opensmi.ros2.server.access.LISTING_ACCESS_LEVEL`.
202
+ :ivar skill_access_level: Access level a Skill requires, on top of the Lock. Default
203
+ :data:`~opensmi.ros2.server.access.SKILL_ACCESS_LEVEL`.
204
+ :ivar introspection_access_level: Access level the introspection mutators (``BindTopic``,
205
+ ``CallService``) require, on top of the Lock. Default
206
+ :data:`~opensmi.ros2.server.access.MUTATOR_ACCESS_LEVEL`. All three defaults follow opensmi's
207
+ default user table; a site with a different table sets its own.
208
+ :ivar debug_goal_outcome_booleans: Whether an action Skill also exposes ``succeeded``,
209
+ ``aborted`` and ``canceled`` booleans in its FinalResultData. A debugging aid, off by default:
210
+ the goal outcome drives the Skill's state machine, and the booleans beside ``CurrentState``
211
+ can disagree with it.
212
+ """
213
+
214
+ domain_id: int = 0
215
+ node_name: str = "opensmi_ros2"
216
+ namespace: str | None = None
217
+ stop_timeout: float = 5.0
218
+ startup_timeout: float = 30.0
219
+ transforms: TransformConfig = TransformConfig()
220
+ listing_access_level: int = LISTING_ACCESS_LEVEL
221
+ skill_access_level: int = SKILL_ACCESS_LEVEL
222
+ introspection_access_level: int = MUTATOR_ACCESS_LEVEL
223
+ debug_goal_outcome_booleans: bool = False
224
+
225
+ @classmethod
226
+ def from_toml(cls, path: str | Path) -> ROS2Config:
227
+ """Read these settings from a TOML file; a key the file omits keeps its default.
228
+
229
+ :raises ValueError: When the file carries a key this class does not declare.
230
+ :raises DeclarationError: When the access levels contradict each other.
231
+ """
232
+ return from_dict(cls, load_toml(path))
233
+
234
+ def __post_init__(self) -> None:
235
+ """Refuse an introspection level below the Skill level.
236
+
237
+ :raises DeclarationError: When ``introspection_access_level`` is below ``skill_access_level``.
238
+ A mutator changes a live robot, so it asks at least as much as starting a Skill.
239
+ """
240
+ if self.introspection_access_level >= self.skill_access_level:
241
+ return
242
+ message = (
243
+ f"the ROS2 settings give introspection_access_level="
244
+ f"{self.introspection_access_level!r}; binding a topic and calling a service ad hoc "
245
+ f"change what a live robot does, so they ask at least the level a Skill asks, which "
246
+ f"is skill_access_level={self.skill_access_level!r}"
247
+ )
248
+ raise DeclarationError(message)
249
+
250
+
251
+ def load_toml(path: str | Path) -> dict[str, Any]:
252
+ """Load a TOML file into a dictionary."""
253
+ with Path(path).open("rb") as source:
254
+ return tomllib.load(source)
255
+
256
+
257
+ def from_dict(data_cls: type[_T], data: Mapping[str, Any], *, supplied: Mapping[str, Any] | None = None) -> _T:
258
+ """Build a dataclass instance from a TOML table.
259
+
260
+ :param supplied: Values for fields a TOML table cannot produce a value of (a class or a
261
+ callable), which the caller has obtained some other way. They are passed to the
262
+ constructor as they are. A name in both ``data`` and here is the caller's mistake.
263
+
264
+ :raises TypeError: When the target is not a dataclass, or a table was expected and something
265
+ else arrived.
266
+ :raises FieldError: When a value does not fit its field: the wrong TOML type, an enum member
267
+ that does not exist, a nested table that is not one. A :class:`ValueError` and a
268
+ :class:`TypeError`, naming the field.
269
+ :raises ValueError: When the table carries a key the dataclass does not declare, or a key whose
270
+ field a TOML file cannot produce a value for (a string would otherwise sit where a callable
271
+ belongs).
272
+ """
273
+ if not is_dataclass(data_cls):
274
+ message = f"{data_cls.__name__} is not a dataclass"
275
+ raise TypeError(message)
276
+
277
+ hints = _hints(data_cls)
278
+ unknown = set(data) - {field.name for field in fields(data_cls)}
279
+ if unknown:
280
+ listed = ", ".join(sorted(unknown))
281
+ message = f"unknown configuration option(s) for {data_cls.__name__}: {listed}"
282
+ raise ValueError(message)
283
+
284
+ for name in data:
285
+ _require_expressible(data_cls, name, hints[name])
286
+
287
+ # An omitted key is not passed as None, so the dataclass default decides.
288
+ converted: dict[str, Any] = {}
289
+ for name, value in data.items():
290
+ try:
291
+ converted[name] = _convert(value, hints[name])
292
+ except FieldError as error:
293
+ nested = f"{name}.{error.field}"
294
+ raise FieldError(nested, error.reason) from error
295
+ except (ValueError, TypeError) as error:
296
+ raise FieldError(name, str(error)) from error
297
+ return data_cls(**converted, **(supplied or {}))
298
+
299
+
300
+ class _Unresolved:
301
+ """The annotation of a field that cannot be evaluated at run time, so no TOML value fits it."""
302
+
303
+
304
+ def _hints(data_cls: type) -> dict[str, Any]:
305
+ """Return the type hints of a dataclass, field by field where they cannot be had at once.
306
+
307
+ A field annotated with a type-checker-only alias maps to :class:`_Unresolved`, a Python-side keyword.
308
+ """
309
+ try:
310
+ return get_type_hints(data_cls)
311
+ except (NameError, TypeError):
312
+ pass
313
+ hints: dict[str, Any] = {}
314
+ for base in reversed(data_cls.__mro__):
315
+ module = sys.modules.get(base.__module__)
316
+ scope = dict(vars(module)) if module else {}
317
+ for name, annotation in inspect.get_annotations(base).items():
318
+ try:
319
+ hints[name] = eval(annotation, scope) if isinstance(annotation, str) else annotation
320
+ except (NameError, TypeError):
321
+ hints[name] = _Unresolved
322
+ return hints
323
+
324
+
325
+ def declarable_keys(data_cls: type) -> tuple[str, ...]:
326
+ """Return the fields of a dataclass that a TOML table can set, in declaration order.
327
+
328
+ The complement stays Python-side: a callable or a class has no TOML spelling.
329
+ """
330
+ hints = _hints(data_cls)
331
+ return tuple(field.name for field in fields(data_cls) if _expressible(hints[field.name]))
332
+
333
+
334
+ def python_keys(data_cls: type) -> tuple[str, ...]:
335
+ """Return the fields of a dataclass that a TOML table cannot set: the complement of :func:`declarable_keys`.
336
+
337
+ A caller that lets a file name one by import path passes the imported object to :func:`from_dict`
338
+ as ``supplied``.
339
+ """
340
+ hints = _hints(data_cls)
341
+ return tuple(field.name for field in fields(data_cls) if not _expressible(hints[field.name]))
342
+
343
+
344
+ def _require_expressible(data_cls: type, name: str, target: Any) -> None:
345
+ """Refuse a key whose field is not something a TOML document can produce a value for.
346
+
347
+ :raises ValueError: When the field's type is not a TOML scalar, an enum, a dataclass, or a
348
+ container of those (a callable or class would arrive as a string).
349
+ """
350
+ if _expressible(target):
351
+ return
352
+ message = (
353
+ f"{data_cls.__name__}.{name} is a {target!r}, which a TOML file cannot produce a value "
354
+ f"of; a file declares names, paths, patterns and numbers, and anything that has to be a "
355
+ f"Python object is a Python-side keyword"
356
+ )
357
+ raise ValueError(message)
358
+
359
+
360
+ def _file_members(union: Any) -> list[Any]:
361
+ """Return the members of a union a file can write: not ``None``, and not ``type`` beside a name.
362
+
363
+ A class alternative (``str | type``) is the Python spelling of what the file writes as a name.
364
+ """
365
+ members = [each for each in get_args(union) if each is not type(None)]
366
+ named = [each for each in members if each is not type]
367
+ return named or members
368
+
369
+
370
+ def _expressible(target: Any) -> bool:
371
+ """Return whether a TOML document can produce a value of one field's declared type.
372
+
373
+ ``object`` takes any TOML value as it was read, for a field that checks its own shape later.
374
+ """
375
+ if target is object:
376
+ return True
377
+ origin = get_origin(target)
378
+ if origin in (Union, UnionType):
379
+ return all(_expressible(each) for each in _file_members(target))
380
+ if origin in (list, tuple, dict, set, frozenset, abc.Mapping, abc.Collection, abc.Sequence):
381
+ return all(_expressible(each) for each in get_args(target) if each is not Ellipsis)
382
+ if not isinstance(target, type):
383
+ return False
384
+ return is_dataclass(target) or issubclass(target, (*_TOML_SCALARS, Enum))
385
+
386
+
387
+ def _convert(value: Any, target: Any) -> Any:
388
+ """Convert one TOML value into the type its field declares."""
389
+ # TOML has no null, so this only ever fires for a caller building the table by hand.
390
+ if value is None:
391
+ return None
392
+
393
+ origin = get_origin(target)
394
+
395
+ if origin in (Union, UnionType):
396
+ rest = _file_members(target)
397
+ if len(rest) == 1:
398
+ return _convert(value, rest[0])
399
+
400
+ if isinstance(target, type) and issubclass(target, Enum):
401
+ return _as_enum(value, target)
402
+
403
+ if isinstance(target, type) and is_dataclass(target):
404
+ if not isinstance(value, dict):
405
+ message = f"expected a TOML table for {target.__name__}, got {type(value).__name__}"
406
+ raise TypeError(message)
407
+ return from_dict(target, value)
408
+
409
+ if origin is list:
410
+ (item,) = get_args(target)
411
+ return [_convert(each, item) for each in value]
412
+
413
+ if origin is tuple:
414
+ return _as_tuple(value, target)
415
+
416
+ if origin in (abc.Collection, abc.Sequence, dict, abc.Mapping):
417
+ return _as_container(value, origin, get_args(target))
418
+
419
+ return _require_scalar(value, target)
420
+
421
+
422
+ def _as_container(value: Any, origin: Any, arguments: tuple[Any, ...]) -> Any:
423
+ """Return a TOML array or table as the read-only container a frozen declaration annotates.
424
+
425
+ An array becomes a tuple and a table a dict, with its keys converted to the key type.
426
+ """
427
+ if origin in (abc.Collection, abc.Sequence):
428
+ if not isinstance(value, list):
429
+ message = f"expected an array, got {type(value).__name__} {value!r}"
430
+ raise TypeError(message)
431
+ return tuple(_convert(each, arguments[0]) for each in value)
432
+ if not isinstance(value, dict):
433
+ message = f"expected a table, got {type(value).__name__} {value!r}"
434
+ raise TypeError(message)
435
+ key_type, value_type = arguments
436
+ return {_convert_key(key, key_type): _convert(each, value_type) for key, each in value.items()}
437
+
438
+
439
+ def _convert_key(key: Any, target: Any) -> Any:
440
+ """Convert a table key, which TOML always spells as a string, into the type the field wants."""
441
+ if target is int and isinstance(key, str):
442
+ try:
443
+ return int(key)
444
+ except ValueError as error:
445
+ message = f"the key {key!r} is not an integer"
446
+ raise ValueError(message) from error
447
+ return _convert(key, target)
448
+
449
+
450
+ def _require_scalar(value: Any, target: Any) -> Any:
451
+ """Return a value after checking it is the TOML scalar its field declares.
452
+
453
+ Only bool, int, float and str are checked. An int may stand where a float is wanted, and a bool is
454
+ never a number.
455
+ """
456
+ if target is bool:
457
+ accepted = isinstance(value, bool)
458
+ elif target is int:
459
+ accepted = isinstance(value, int) and not isinstance(value, bool)
460
+ elif target is float:
461
+ accepted = isinstance(value, (int, float)) and not isinstance(value, bool)
462
+ elif target is str:
463
+ accepted = isinstance(value, str)
464
+ else:
465
+ return value
466
+ if not accepted:
467
+ message = f"expected {target.__name__}, got {type(value).__name__} {value!r}"
468
+ raise TypeError(message)
469
+ return value
470
+
471
+
472
+ def _as_enum(value: Any, target: type[Enum]) -> Enum:
473
+ """Return the enum member a TOML value names, or say which ones exist."""
474
+ try:
475
+ return target(value)
476
+ except ValueError as error:
477
+ if isinstance(value, str) and issubclass(target, IntEnum) and value in target.__members__:
478
+ return target[value] # an int enum may be spelled by member name
479
+ valid = ", ".join(repr(member.value) for member in target)
480
+ message = f"invalid value {value!r} for {target.__name__}; expected one of: {valid}"
481
+ raise ValueError(message) from error
482
+
483
+
484
+ def _as_tuple(value: Any, target: Any) -> tuple[Any, ...]:
485
+ """Return a TOML array as the tuple a frozen declaration holds.
486
+
487
+ ``tuple[str, ...]`` converts element by element, a fixed-length tuple position by position.
488
+ """
489
+ arguments = get_args(target)
490
+ variadic = 2 # a variadic tuple is spelled with exactly two arguments: an element type and an ellipsis
491
+ if len(arguments) == variadic and arguments[1] is Ellipsis:
492
+ return tuple(_convert(each, arguments[0]) for each in value)
493
+ return tuple(_convert(each, argument) for each, argument in zip(value, arguments, strict=True))
@@ -0,0 +1,191 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The variable containers a Skill and a Method both fill from a Projection plan.
6
+
7
+ opensmi gives a Skill and a Method a ParameterSet, a Monitoring and a FinalResultData container.
8
+ This module renders their variables from a plan, writes them from a message and resets them to
9
+ their declared values. It knows nothing about which ROS2 message lands in which container; that
10
+ belongs to :mod:`opensmi.ros2.server.method` and the Skills.
11
+
12
+ A top-level field of the message is a child of the container, named by its own browse name
13
+ without the Binding prefix, because the callable's node already carries the Binding's name
14
+ (``SetMode/Mode``). A nested message is a complex Variable. The variables are declared
15
+ once at init, so they bypass the capped mutation chokepoint but share its
16
+ :meth:`~opensmi.ros2.server.mutation.ROS2MutationMixin.render_plan`.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import TYPE_CHECKING, Any, ClassVar
23
+
24
+ from opensmi.ros2.server.errors import DeclarationError
25
+ from opensmi.ros2.server.status import GOOD, status_value
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Mapping, Sequence
29
+
30
+ from asyncua import ua
31
+ from opensmi.server import UaVariable
32
+ from opensmi.server.ua_variable_containers import UaVariableContainer
33
+ from structlog.stdlib import BoundLogger
34
+
35
+ from opensmi.ros2.runtime.messages import Message
36
+ from opensmi.ros2.server.mutation import RenderedPlan
37
+ from opensmi.ros2.server.projection import PlanEntry
38
+
39
+ __all__ = ["ROS2ContainerMixin", "VariableContainer"]
40
+
41
+
42
+ @dataclass(slots=True, kw_only=True)
43
+ class VariableContainer:
44
+ """One of a callable's variable containers, as everything a write to it needs.
45
+
46
+ opensmi's container holds the variables by name only, so this adds what the plan rendered into
47
+ it and the value of every entry, since a message is written whole.
48
+
49
+ :ivar name: What the container is called, for a refusal a reader has to act on.
50
+ :ivar container: opensmi's own container, shared and not copied.
51
+ :ivar rendered: The nodes the plan became, once they are created.
52
+ :ivar values: The value of each entry by its plan name, as last written.
53
+ """
54
+
55
+ name: str
56
+ container: UaVariableContainer
57
+ rendered: RenderedPlan | None = None
58
+ values: dict[str, object] = field(default_factory=dict)
59
+
60
+ @property
61
+ def nodes(self) -> RenderedPlan:
62
+ """Return the rendered plan.
63
+
64
+ :raises DeclarationError: When the container was not created yet.
65
+ """
66
+ if self.rendered is None: # pragma: no cover -- every callable creates its containers at init
67
+ message = f"the {self.name} was read or written before its variables were created"
68
+ raise DeclarationError(message)
69
+ return self.rendered
70
+
71
+
72
+ class ROS2ContainerMixin:
73
+ """How a Skill and a Method build, write and clear their variable containers.
74
+
75
+ Mixed in ahead of opensmi's callable class. The annotated names below are what it expects to
76
+ find on that class.
77
+
78
+ :cvar callable_kind: What a refusal calls the owner, ``Skill`` or ``Method``.
79
+ """
80
+
81
+ callable_kind: ClassVar[str]
82
+
83
+ if TYPE_CHECKING:
84
+
85
+ @property
86
+ def name(self) -> str:
87
+ """Return the callable's name, which is its Binding's."""
88
+ ...
89
+
90
+ @property
91
+ def logger(self) -> BoundLogger:
92
+ """Return the logger opensmi gives every object."""
93
+ ...
94
+
95
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
96
+ """Pass every argument on to opensmi's callable.
97
+
98
+ Only here for the type checker: without it ``super().__init__(name=...)`` in a Skill or
99
+ Method resolves to this mixin and reports unknown keywords.
100
+ """
101
+ super().__init__(*args, **kwargs)
102
+
103
+ async def _create(
104
+ self,
105
+ plan: Sequence[PlanEntry],
106
+ container: VariableContainer,
107
+ *,
108
+ message_type: type[Message],
109
+ writable: bool = False,
110
+ ) -> None:
111
+ """Render one plan in one container, and record it on it.
112
+
113
+ Every name is checked before any variable is made, so a failing plan leaves nothing
114
+ half-built.
115
+
116
+ :param message_type: The ROS2 type the plan was shaped from.
117
+ :raises UnprojectableFieldError: When an entry is an Object.
118
+ :raises DuplicateVariableNameError: When a name is already taken in that container.
119
+ :raises DeclarationError: When the machinery item cannot render a plan, because it does not
120
+ carry the ROS2 mixins.
121
+ """
122
+ item: Any = getattr(self, "parent", None)
123
+ render = getattr(item, "render_plan", None)
124
+ if render is None:
125
+ message = (
126
+ f"the {self.callable_kind} {self.name!r} renders nodes of its own, and the Component it is "
127
+ f"on cannot create them; a Component carrying ROS2 Bindings mixes in ROS2ComponentMixin"
128
+ )
129
+ raise DeclarationError(message)
130
+ rendered: RenderedPlan = await render(
131
+ container.container,
132
+ plan,
133
+ message_type=message_type,
134
+ qualifier=f"{item.ros2_projection_qualifier}.{self.name}.{container.name}",
135
+ where=self._named(container),
136
+ writable=writable,
137
+ )
138
+ container.rendered = rendered
139
+ container.values = rendered.initial
140
+
141
+ async def _write_values(self, container: VariableContainer, values: Mapping[str, object]) -> None:
142
+ """Write a name-to-value map into one container, skipping names it has no variable for."""
143
+ nodes = container.nodes
144
+ for name, value in values.items():
145
+ if name not in nodes.entries:
146
+ self._report_unknown_name(container, name)
147
+ continue
148
+ container.values[name] = value
149
+ await nodes.write(container.values)
150
+
151
+ async def _reset_values(self, container: VariableContainer) -> None:
152
+ """Put every variable of one container back to the plan's ``initial`` value.
153
+
154
+ That is a typed zero only where the declaration says so; a curated Projection may choose
155
+ another value.
156
+ """
157
+ container.values = container.nodes.initial
158
+ await container.nodes.write(container.values)
159
+
160
+ async def _read_values(self, container: VariableContainer) -> dict[str, object]:
161
+ """Read one container into the plan's values, by name.
162
+
163
+ Elements of a structure array come back as maps of their fields, the form a Projection
164
+ builds a message from. Raises ``ValueError`` for a value that is not an array of the
165
+ variable's structure, which the write check normally prevents.
166
+ """
167
+ return await container.nodes.read()
168
+
169
+ async def _write(self, variable: UaVariable[Any], value: object, variant_type: ua.VariantType) -> None:
170
+ """Write one value to a variable's node with the variant type the plan decided.
171
+
172
+ Written on the node, so no write check runs: the value comes from ROS2 or the declaration.
173
+ """
174
+ await variable.ua_node.write_value(status_value(value, variant_type, GOOD))
175
+
176
+ def _named(self, container: VariableContainer) -> str:
177
+ """Return how a refusal names one of these containers, from a reader's side."""
178
+ return f"the {container.name} of the {self.callable_kind} {self.name!r}"
179
+
180
+ def _report_unknown_name(self, container: VariableContainer, name: str) -> None:
181
+ """Log a decoded name its shape never created, and skip the value.
182
+
183
+ Unreachable with the generic Projection. A curated one whose halves disagree only shows
184
+ up with a message, so it is logged and not raised.
185
+ """
186
+ self.logger.error(
187
+ "A Projection decoded a name its shape never created; that value was not written",
188
+ binding=self.name,
189
+ container=container.name,
190
+ name=name,
191
+ )