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,723 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The parameter facet: a ROS2 node's parameters, read one at a time and written non-atomically.
6
+
7
+ A ROS2 parameter is a named, typed configuration value on a ROS2 node, read and written over the
8
+ node's parameter services and observable on ``/parameter_events``. Three behaviours of the
9
+ library (verified on Jazzy) shape this module:
10
+
11
+ * A read takes one name. ``get_parameters`` and ``describe_parameters`` answer with an empty list
12
+ and no error when any one name is undeclared, so a batched read would blank every value on one
13
+ typo.
14
+ * A write is never atomic. ``set_parameters`` reports per parameter, while the atomic variant
15
+ discards the whole batch when one name is undeclared. The atomic call is not wrapped.
16
+ * One subscription to ``/parameter_events`` serves all watches and demultiplexes by node. It is
17
+ open only while a watch exists. The topic also fires for changes a node makes to itself, and
18
+ these are passed on.
19
+
20
+ :class:`ParameterType` has the nine declarable members of ``rcl_interfaces/msg/ParameterType``.
21
+ A value crossing this module is a :class:`ParameterValue`: one of those types and a plain Python
22
+ value. The facet reads and writes through callables the Runtime supplies, so nothing here imports
23
+ ``rclpy``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ from collections import deque
30
+ from dataclasses import dataclass
31
+ from enum import Enum
32
+ from typing import TYPE_CHECKING, Any, Final, TypeAlias, final
33
+
34
+ import structlog
35
+
36
+ from opensmi.ros2.runtime.errors import SubscriptionClosedError
37
+ from opensmi.ros2.runtime.messages import PrimitiveType, SequenceType, StringType
38
+
39
+ if TYPE_CHECKING:
40
+ from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Iterable, Mapping, Sequence
41
+
42
+ from opensmi.ros2.runtime.messages import FieldType, Message
43
+
44
+ __all__ = [
45
+ "CALL_TIMEOUT",
46
+ "DESCRIBE_PARAMETERS_TYPE",
47
+ "EVENT_DEPTH",
48
+ "GET_PARAMETERS_TYPE",
49
+ "LIST_PARAMETERS_TYPE",
50
+ "PARAMETER_EVENTS_TOPIC",
51
+ "PARAMETER_EVENT_TYPE",
52
+ "SERVER_TIMEOUT",
53
+ "SET_PARAMETERS_TYPE",
54
+ "DescribeFunction",
55
+ "EventFunction",
56
+ "ListFunction",
57
+ "ParameterDescription",
58
+ "ParameterFacet",
59
+ "ParameterRange",
60
+ "ParameterReading",
61
+ "ParameterType",
62
+ "ParameterUpdate",
63
+ "ParameterValue",
64
+ "ParameterWatch",
65
+ "ReadFunction",
66
+ "SetOutcome",
67
+ "WriteFunction",
68
+ "absolute",
69
+ "describe_request",
70
+ "description_of",
71
+ "get_request",
72
+ "list_request",
73
+ "names_of",
74
+ "outcomes_of",
75
+ "reading_of",
76
+ "set_request",
77
+ "update_of",
78
+ ]
79
+
80
+ PARAMETER_EVENTS_TOPIC: Final = "/parameter_events"
81
+ """The one topic every ROS2 node announces its parameter changes on."""
82
+
83
+ PARAMETER_EVENT_TYPE: Final = "rcl_interfaces/msg/ParameterEvent"
84
+ """The type carried on :data:`PARAMETER_EVENTS_TOPIC`."""
85
+
86
+ GET_PARAMETERS_TYPE: Final = "rcl_interfaces/srv/GetParameters"
87
+ """The service type behind ``<node>/get_parameters``."""
88
+
89
+ SET_PARAMETERS_TYPE: Final = "rcl_interfaces/srv/SetParameters"
90
+ """The service type behind ``<node>/set_parameters``, which reports per parameter."""
91
+
92
+ LIST_PARAMETERS_TYPE: Final = "rcl_interfaces/srv/ListParameters"
93
+ """The service type behind ``<node>/list_parameters``, which answers what a node declares."""
94
+
95
+ DESCRIBE_PARAMETERS_TYPE: Final = "rcl_interfaces/srv/DescribeParameters"
96
+ """The service type behind ``<node>/describe_parameters``, asked one name at a time."""
97
+
98
+ SERVER_TIMEOUT: Final = 10.0
99
+ """Seconds a parameter call waits for the node's service to appear.
100
+
101
+ ROS2 supplies no deadline: a parameter-service call to a node that is not running produces no
102
+ error and no result.
103
+ """
104
+
105
+ CALL_TIMEOUT: Final = 30.0
106
+ """Seconds to wait for the answer once a parameter request has gone."""
107
+
108
+ EVENT_DEPTH: Final = 100
109
+ """How many parameter events one subscription and one watch buffer.
110
+
111
+ Deeper than a Monitoring Binding's because the buffer is shared by every node on the graph, and
112
+ a dropped event leaves a UA Parameter holding a value the node no longer has.
113
+ """
114
+
115
+ _LOGGER = structlog.get_logger("opensmi.ros2.runtime.parameters")
116
+
117
+
118
+ class ParameterType(Enum):
119
+ """The declarable members of ``rcl_interfaces/msg/ParameterType``.
120
+
121
+ Nine of the ten codes: ``PARAMETER_NOT_SET`` is a reading, never a declaration, and arrives
122
+ as a :class:`ParameterReading` that is present and holds nothing. The member value is the
123
+ constant name without its ``PARAMETER_`` prefix, lower-cased, for use in declarations.
124
+ """
125
+
126
+ BOOL = "bool"
127
+ INTEGER = "integer"
128
+ DOUBLE = "double"
129
+ STRING = "string"
130
+ BYTE_ARRAY = "byte_array"
131
+ BOOL_ARRAY = "bool_array"
132
+ INTEGER_ARRAY = "integer_array"
133
+ DOUBLE_ARRAY = "double_array"
134
+ STRING_ARRAY = "string_array"
135
+
136
+ @property
137
+ def code(self) -> int:
138
+ """Return the number ``rcl_interfaces/msg/ParameterType`` gives this type."""
139
+ return _CODES[self]
140
+
141
+ @property
142
+ def value_field(self) -> str:
143
+ """Return the field of ``rcl_interfaces/msg/ParameterValue`` that carries this type."""
144
+ return f"{self.value}_value"
145
+
146
+ @property
147
+ def field_type(self) -> FieldType:
148
+ """Return the ROS2 field type a value of this type is.
149
+
150
+ An ``integer`` is an ``int64``, a ``double`` is a ``float64`` and a ``byte_array`` is a
151
+ sequence of ``uint8``, so a parameter value goes through the same conversion as a message
152
+ field (:func:`opensmi.ros2.server.projection.ros2_value`).
153
+ """
154
+ return _FIELD_TYPES[self]
155
+
156
+
157
+ _FIELD_TYPES: Final[Mapping[ParameterType, FieldType]] = {
158
+ ParameterType.BOOL: PrimitiveType(name="bool"),
159
+ ParameterType.INTEGER: PrimitiveType(name="int64"),
160
+ ParameterType.DOUBLE: PrimitiveType(name="float64"),
161
+ ParameterType.STRING: StringType(),
162
+ ParameterType.BYTE_ARRAY: SequenceType(element=PrimitiveType(name="uint8")),
163
+ ParameterType.BOOL_ARRAY: SequenceType(element=PrimitiveType(name="bool")),
164
+ ParameterType.INTEGER_ARRAY: SequenceType(element=PrimitiveType(name="int64")),
165
+ ParameterType.DOUBLE_ARRAY: SequenceType(element=PrimitiveType(name="float64")),
166
+ ParameterType.STRING_ARRAY: SequenceType(element=StringType()),
167
+ }
168
+ """What each declarable parameter type is, in the package's field-type model."""
169
+
170
+ _CODES: Final[Mapping[ParameterType, int]] = {
171
+ ParameterType.BOOL: 1,
172
+ ParameterType.INTEGER: 2,
173
+ ParameterType.DOUBLE: 3,
174
+ ParameterType.STRING: 4,
175
+ ParameterType.BYTE_ARRAY: 5,
176
+ ParameterType.BOOL_ARRAY: 6,
177
+ ParameterType.INTEGER_ARRAY: 7,
178
+ ParameterType.DOUBLE_ARRAY: 8,
179
+ ParameterType.STRING_ARRAY: 9,
180
+ }
181
+ """The constants of ``rcl_interfaces/msg/ParameterType``, written out so member order cannot renumber them."""
182
+
183
+ _BY_CODE: Final[Mapping[int, ParameterType]] = {code: each for each, code in _CODES.items()}
184
+
185
+ _EMPTY_VALUE: Final[Mapping[str, object]] = {
186
+ "type": 0, # PARAMETER_NOT_SET
187
+ "bool_value": False,
188
+ "integer_value": 0,
189
+ "double_value": 0.0,
190
+ "string_value": "",
191
+ "byte_array_value": b"",
192
+ "bool_array_value": (),
193
+ "integer_array_value": (),
194
+ "double_array_value": (),
195
+ "string_array_value": (),
196
+ }
197
+ """Every field of ``rcl_interfaces/msg/ParameterValue`` at its zero.
198
+
199
+ Message dataclasses have no defaults, so a value is built with all ten fields and the relevant one
200
+ overwritten. A field added upstream raises a missing-argument ``TypeError`` here.
201
+ """
202
+
203
+
204
+ @dataclass(frozen=True, slots=True, kw_only=True)
205
+ class ParameterValue:
206
+ """One ROS2 parameter value, as the declaration typed it.
207
+
208
+ :ivar type: Which of the union's typed fields this value belongs in.
209
+ :ivar value: The value as a plain Python object: ``bool``, ``int``, ``float``, ``str``,
210
+ ``bytes`` for a byte array, or ``tuple`` for the other arrays.
211
+ """
212
+
213
+ type: ParameterType
214
+ value: object
215
+
216
+
217
+ @dataclass(frozen=True, slots=True, kw_only=True)
218
+ class ParameterReading:
219
+ """What one look at one ROS2 parameter found: not present, present without a value, or a value.
220
+
221
+ :ivar name: The ROS2 parameter name, dotted as the node spells it.
222
+ :ivar present: Whether the node declares that name at all.
223
+ :ivar value: What the node holds, or ``None`` when the name is declared but unset
224
+ (``PARAMETER_NOT_SET``). Always ``None`` when ``present`` is ``False``.
225
+ """
226
+
227
+ name: str
228
+ present: bool
229
+ value: ParameterValue | None = None
230
+
231
+
232
+ @dataclass(frozen=True, slots=True, kw_only=True)
233
+ class SetOutcome:
234
+ """What a ROS2 node answered about one parameter of a write.
235
+
236
+ A refusal is an answer. A call that does not happen (no server, or one that went quiet) is
237
+ raised by the Runtime instead.
238
+
239
+ :ivar successful: ``SetParametersResult.successful``.
240
+ :ivar reason: ``SetParametersResult.reason``, verbatim. It is only ever the node's own text,
241
+ for example "speed_limit out of range. Min: 0, Max: 100, value: 5000".
242
+ :ivar answered: Whether the node said anything about this parameter. ``False`` means it
243
+ answered the batch with fewer results than names; the write is neither a success nor a
244
+ refusal with words.
245
+ """
246
+
247
+ successful: bool
248
+ reason: str = ""
249
+ answered: bool = True
250
+
251
+
252
+ @dataclass(frozen=True, slots=True, kw_only=True)
253
+ class ParameterRange:
254
+ """The range a ROS2 node declares for one numeric parameter, inclusive at both ends.
255
+
256
+ A ``ParameterDescriptor`` carries at most one ``floating_point_range`` or ``integer_range``;
257
+ this is either of them.
258
+
259
+ :ivar low: ``from_value``, the smallest value the node accepts.
260
+ :ivar high: ``to_value``, the largest value the node accepts.
261
+ :ivar step: The node's ``step``. Zero means any value between the two bounds.
262
+ """
263
+
264
+ low: float
265
+ high: float
266
+ step: float = 0
267
+
268
+ def admits(self, value: float) -> bool:
269
+ """Return whether a value lies between the two bounds, both included.
270
+
271
+ The step is not checked: the node applies it with a tolerance it does not publish.
272
+ """
273
+ return self.low <= value <= self.high
274
+
275
+
276
+ @dataclass(frozen=True, slots=True, kw_only=True)
277
+ class ParameterDescription:
278
+ """What a ROS2 node says about one of its parameters, beyond the value it holds.
279
+
280
+ Everything an operator needs to write a declaration for the parameter.
281
+
282
+ :ivar name: The ROS2 parameter name, dotted as the node spells it.
283
+ :ivar present: Whether the node declares that name at all.
284
+ :ivar type: The type the node declares it as, or ``None`` when the node answered a code with
285
+ no member here (``PARAMETER_NOT_SET``). Always ``None`` when ``present`` is ``False``.
286
+ :ivar description: The node's own one-line description, verbatim; empty if it gave none.
287
+ :ivar additional_constraints: The node's own free text about what it accepts, verbatim.
288
+ :ivar read_only: Whether the node refuses every write. Such a parameter is still declarable,
289
+ and every write to it is then refused, so this is a warning and not an error.
290
+ :ivar dynamic_typing: Whether the node lets the parameter change type. A declaration names
291
+ one type, so declaring such a parameter narrows what the node allows.
292
+ :ivar range: The numeric range the node declares, or ``None``.
293
+ """
294
+
295
+ name: str
296
+ present: bool
297
+ type: ParameterType | None = None
298
+ description: str = ""
299
+ additional_constraints: str = ""
300
+ read_only: bool = False
301
+ dynamic_typing: bool = False
302
+ range: ParameterRange | None = None
303
+
304
+
305
+ @dataclass(frozen=True, slots=True, kw_only=True)
306
+ class ParameterUpdate:
307
+ """What one ``/parameter_events`` message says about one node.
308
+
309
+ :ivar node: The fully qualified name of the node the change happened on.
310
+ :ivar readings: One reading per parameter the event names. A deleted parameter arrives as a
311
+ reading that is not present, like a read of an undeclared name.
312
+ """
313
+
314
+ node: str
315
+ readings: tuple[ParameterReading, ...]
316
+
317
+
318
+ ReadFunction: TypeAlias = "Callable[[str, str], Awaitable[ParameterReading]]"
319
+ """How the facet reads one parameter: the node path and one name."""
320
+
321
+ WriteFunction: TypeAlias = "Callable[[str, Mapping[str, ParameterValue]], Awaitable[Mapping[str, SetOutcome]]]"
322
+ """How the facet writes: the node path and a batch, answered per parameter."""
323
+
324
+ EventFunction: TypeAlias = "Callable[[], AsyncGenerator[ParameterUpdate, None]]"
325
+ """How the facet follows ``/parameter_events``: one generator, closed with the last watch."""
326
+
327
+ ListFunction: TypeAlias = "Callable[[str], Awaitable[tuple[str, ...]]]"
328
+ """How the facet lists: the node path, and every parameter name that node declares."""
329
+
330
+ DescribeFunction: TypeAlias = "Callable[[str, str], Awaitable[ParameterDescription]]"
331
+ """How the facet describes: the node path and one name."""
332
+
333
+
334
+ @final
335
+ class ParameterWatch:
336
+ """One consumer's view of one ROS2 node's parameter changes, and its lifetime.
337
+
338
+ Handed out by :meth:`ParameterFacet.watch`. Close it when done: the shared subscription closes
339
+ with the last watch.
340
+ """
341
+
342
+ def __init__(self, *, node: str, facet: ParameterFacet, release: Callable[[ParameterWatch], None]) -> None:
343
+ """Bind a watch to one node's name and the facet's deregistration."""
344
+ self._node = node
345
+ self._facet = facet
346
+ self._release = release
347
+ self._updates: deque[ParameterUpdate] = deque(maxlen=EVENT_DEPTH)
348
+ self._arrival = asyncio.Event()
349
+ self._closed = False
350
+
351
+ def __repr__(self) -> str:
352
+ """Return a representation naming the node and the watch's state."""
353
+ return f"<ParameterWatch {self._node} ({'closed' if self._closed else 'open'})>"
354
+
355
+ @property
356
+ def node(self) -> str:
357
+ """Return the fully qualified ROS2 node name this watch follows."""
358
+ return self._node
359
+
360
+ @property
361
+ def closed(self) -> bool:
362
+ """Return whether this watch's lifetime has ended."""
363
+ return self._closed
364
+
365
+ def deliver(self, update: ParameterUpdate) -> None:
366
+ """Hand this watch one update. Only the facet's demux calls it."""
367
+ if len(self._updates) == self._updates.maxlen:
368
+ # A dropped event leaves a UA Parameter stale, so it is logged, not just counted.
369
+ _LOGGER.warning(
370
+ "A parameter event was dropped because its consumer is behind",
371
+ node=self._node,
372
+ depth=EVENT_DEPTH,
373
+ )
374
+ self._updates.append(update)
375
+ self._arrival.set()
376
+
377
+ async def receive(self) -> ParameterUpdate:
378
+ """Await the next parameter change on this node.
379
+
380
+ :raises SubscriptionClosedError: When the watch has been closed.
381
+ """
382
+ while not self._updates:
383
+ if self._closed:
384
+ message = f"this parameter watch on {self._node} is closed; its events are no longer delivered"
385
+ raise SubscriptionClosedError(message)
386
+ # No await between clear and wait, so `deliver` (same loop) cannot slip in between.
387
+ self._arrival.clear()
388
+ await self._arrival.wait()
389
+ return self._updates.popleft()
390
+
391
+ def __aiter__(self) -> AsyncIterator[ParameterUpdate]:
392
+ """Return an iterator yielding updates until the watch is closed."""
393
+ return self._stream()
394
+
395
+ async def _stream(self) -> AsyncIterator[ParameterUpdate]:
396
+ """Yield updates until the watch is closed, then stop cleanly."""
397
+ while True:
398
+ try:
399
+ yield await self.receive()
400
+ except SubscriptionClosedError:
401
+ return
402
+
403
+ async def close(self) -> None:
404
+ """End this watch, and with it the shared subscription if it was the last one.
405
+
406
+ Idempotent.
407
+ """
408
+ if self._closed:
409
+ return
410
+ self._closed = True
411
+ self._arrival.set()
412
+ self._release(self)
413
+ await self._facet.settle()
414
+
415
+
416
+ @final
417
+ class ParameterFacet:
418
+ """The ROS2 parameters of every node on one Machine's graph.
419
+
420
+ Obtain it from :attr:`opensmi.ros2.runtime.runtime.Runtime.parameters`; the constructor
421
+ arguments are the Runtime's plumbing.
422
+ """
423
+
424
+ def __init__(
425
+ self,
426
+ *,
427
+ read: ReadFunction,
428
+ write: WriteFunction,
429
+ events: EventFunction,
430
+ list_names: ListFunction,
431
+ describe: DescribeFunction,
432
+ ) -> None:
433
+ """Describe a facet without calling anything.
434
+
435
+ :param read: How to read one parameter of one node.
436
+ :param write: How to write a batch to one node, per parameter.
437
+ :param events: How to follow ``/parameter_events``. Opened on the first watch and closed
438
+ with the last.
439
+ :param list_names: How to ask one node what parameters it declares.
440
+ :param describe: How to ask one node about one of those names.
441
+ """
442
+ self._read = read
443
+ self._write = write
444
+ self._events = events
445
+ self._list = list_names
446
+ self._describe = describe
447
+ self._watches: list[ParameterWatch] = []
448
+ self._stream: AsyncGenerator[ParameterUpdate, None] | None = None
449
+ self._task: asyncio.Task[None] | None = None
450
+ self._reads = 0
451
+ self._writes = 0
452
+
453
+ def __repr__(self) -> str:
454
+ """Return a representation naming how many watches are open and what it has done."""
455
+ return f"<ParameterFacet watching {len(self._watches)} nodes after {self._reads} reads, {self._writes} writes>"
456
+
457
+ @property
458
+ def _watching(self) -> bool:
459
+ """Return whether ``/parameter_events`` is subscribed (exactly while a watch is open)."""
460
+ return self._task is not None
461
+
462
+ async def get(self, *, node: str, name: str) -> ParameterReading:
463
+ """Read one parameter of one ROS2 node.
464
+
465
+ A name the node does not have is not an error: it comes back as a reading that is not
466
+ present.
467
+
468
+ :param node: The ROS2 node path. A leading ``/`` is added when it is missing.
469
+ :param name: The ROS2 parameter name, dotted as the node spells it.
470
+ :raises ServiceUnavailableError: When the node's parameter services do not answer.
471
+ :raises ServiceCallTimeoutError: When the request went and no answer came back in time.
472
+ """
473
+ self._reads += 1
474
+ return await self._read(absolute(node), name)
475
+
476
+ async def set(self, *, node: str, values: Mapping[str, ParameterValue]) -> Mapping[str, SetOutcome]:
477
+ """Write parameters to one ROS2 node, never atomically, and report per parameter.
478
+
479
+ Every valid entry lands and each refusal is named, even when others in the batch fail.
480
+
481
+ :param node: The ROS2 node path. A leading ``/`` is added when it is missing.
482
+ :param values: What to write, by ROS2 parameter name.
483
+ :return: One outcome per name asked for. An empty batch is not a call and answers empty.
484
+ :raises ServiceUnavailableError: When the node's parameter services do not answer.
485
+ :raises ServiceCallTimeoutError: When the request went and no answer came back in time.
486
+ """
487
+ if not values:
488
+ return {}
489
+ self._writes += 1
490
+ return await self._write(absolute(node), values)
491
+
492
+ async def list(self, *, node: str) -> tuple[str, ...]:
493
+ """Return every ROS2 parameter name one node declares, in the order the node gave them.
494
+
495
+ This covers the whole node at once, since no names are asked for. A node with no
496
+ parameters and a node that answered nothing both give an empty tuple. Counted as a read.
497
+
498
+ :param node: The ROS2 node path. A leading ``/`` is added when it is missing.
499
+ :raises ServiceUnavailableError: When the node's parameter services do not answer.
500
+ :raises ServiceCallTimeoutError: When the request went and no answer came back in time.
501
+ """
502
+ self._reads += 1
503
+ return await self._list(absolute(node))
504
+
505
+ async def describe(self, *, node: str, name: str) -> ParameterDescription:
506
+ """Describe one parameter of one ROS2 node: its type, description and constraints.
507
+
508
+ A name the node does not have comes back as a description that is not present. Counted
509
+ as a read.
510
+
511
+ :param node: The ROS2 node path. A leading ``/`` is added when it is missing.
512
+ :param name: The ROS2 parameter name, dotted as the node spells it.
513
+ :raises ServiceUnavailableError: When the node's parameter services do not answer.
514
+ :raises ServiceCallTimeoutError: When the request went and no answer came back in time.
515
+ """
516
+ self._reads += 1
517
+ return await self._describe(absolute(node), name)
518
+
519
+ def watch(self, node: str) -> ParameterWatch:
520
+ """Follow one ROS2 node's parameter changes, subscribing if nothing was watching yet.
521
+
522
+ :param node: The ROS2 node path. A leading ``/`` is added when it is missing.
523
+ :return: A handle carrying the updates and its own lifetime. Close it when the consumer
524
+ is done: the subscription closes with the last watch.
525
+ """
526
+ watch = ParameterWatch(node=absolute(node), facet=self, release=self._watches.remove)
527
+ self._watches.append(watch)
528
+ self._start()
529
+ return watch
530
+
531
+ async def settle(self) -> None:
532
+ """Close the shared subscription if nothing is watching. Called by a watch as it closes."""
533
+ if self._watches or self._task is None:
534
+ return
535
+ # Both taken before the await: a watch opened meanwhile starts its own task and stream,
536
+ # and reading the fields afterwards would close that new subscription instead.
537
+ task, self._task = self._task, None
538
+ stream, self._stream = self._stream, None
539
+ task.cancel()
540
+ await asyncio.gather(task, return_exceptions=True)
541
+ # Closed here, not in the task: finalising a generator during cancellation can be
542
+ # interrupted and would leak the subscription.
543
+ if stream is not None:
544
+ await stream.aclose()
545
+
546
+ async def close(self) -> None:
547
+ """End every watch and close the subscription, which is what stopping the Runtime does."""
548
+ for watch in tuple(self._watches):
549
+ await watch.close()
550
+ await self.settle()
551
+
552
+ def _start(self) -> None:
553
+ """Open the one subscription, unless it is already open or nothing is watching."""
554
+ if self._task is not None or not self._watches:
555
+ return
556
+ self._task = asyncio.create_task(self._follow(), name="ros2-parameter-events")
557
+
558
+ async def _follow(self) -> None:
559
+ """Demux ``/parameter_events`` onto the watches, by node, until cancelled."""
560
+ stream = self._events()
561
+ self._stream = stream
562
+ try:
563
+ async for update in stream:
564
+ for watch in tuple(self._watches):
565
+ if watch.node == update.node:
566
+ watch.deliver(update)
567
+ except Exception:
568
+ # Nobody awaits this task, so log: otherwise every Parameter silently stops following.
569
+ _LOGGER.exception("Stopped following /parameter_events")
570
+
571
+
572
+ def absolute(node: str) -> str:
573
+ """Return a ROS2 node path with the leading ``/`` that ``/parameter_events`` uses.
574
+
575
+ A path without the slash would match no event.
576
+ """
577
+ return node if node.startswith("/") else f"/{node}"
578
+
579
+
580
+ def get_request(request_type: type[Message], name: str) -> Message:
581
+ """Return the ``GetParameters`` request for exactly one name."""
582
+ return _built(request_type, names=(name,))
583
+
584
+
585
+ def reading_of(name: str, response: Message) -> ParameterReading:
586
+ """Return what a ``GetParameters`` response says about the one name it was asked for.
587
+
588
+ An empty list means the node has no such parameter (and arrives without an error).
589
+ """
590
+ values: Sequence[Message] = _field(response, "values")
591
+ if not values:
592
+ return ParameterReading(name=name, present=False)
593
+ return ParameterReading(name=name, present=True, value=_value_of(values[0]))
594
+
595
+
596
+ def _value_of(raw: Message) -> ParameterValue | None:
597
+ """Return one ``rcl_interfaces/msg/ParameterValue`` as a typed value, or ``None`` when unset.
598
+
599
+ A code with no member here also gives ``None``, so a wrong value is never shown.
600
+ """
601
+ parameter_type = _BY_CODE.get(int(_field(raw, "type")))
602
+ if parameter_type is None:
603
+ return None
604
+ return ParameterValue(type=parameter_type, value=_field(raw, parameter_type.value_field))
605
+
606
+
607
+ def list_request(request_type: type[Message]) -> Message:
608
+ """Return the ``ListParameters`` request for every name (no prefixes, depth zero is ``DEPTH_RECURSIVE``)."""
609
+ return _built(request_type, prefixes=(), depth=0)
610
+
611
+
612
+ def names_of(response: Message) -> tuple[str, ...]:
613
+ """Return the parameter names a ``ListParameters`` response carries, in the node's own order."""
614
+ result = _field(response, "result")
615
+ return tuple(str(each) for each in _field(result, "names"))
616
+
617
+
618
+ def describe_request(request_type: type[Message], name: str) -> Message:
619
+ """Return the ``DescribeParameters`` request asking about exactly one name."""
620
+ return _built(request_type, names=(name,))
621
+
622
+
623
+ def description_of(name: str, response: Message) -> ParameterDescription:
624
+ """Return what a ``DescribeParameters`` response says about the one name it was asked for.
625
+
626
+ An empty list means the node has no such parameter, as for a read.
627
+ """
628
+ descriptors: Sequence[Message] = _field(response, "descriptors")
629
+ if not descriptors:
630
+ return ParameterDescription(name=name, present=False)
631
+ descriptor = descriptors[0]
632
+ return ParameterDescription(
633
+ name=name,
634
+ present=True,
635
+ type=_BY_CODE.get(int(_field(descriptor, "type"))),
636
+ description=str(_field(descriptor, "description")),
637
+ additional_constraints=str(_field(descriptor, "additional_constraints")),
638
+ read_only=bool(_field(descriptor, "read_only")),
639
+ dynamic_typing=bool(_field(descriptor, "dynamic_typing")),
640
+ range=_range_of(descriptor),
641
+ )
642
+
643
+
644
+ def _range_of(descriptor: Message) -> ParameterRange | None:
645
+ """Return the one range a ``ParameterDescriptor`` declares, or ``None``.
646
+
647
+ At most one of the two range fields is filled, with at most one element.
648
+ """
649
+ for named in ("floating_point_range", "integer_range"):
650
+ declared: Sequence[Message] = _field(descriptor, named)
651
+ if declared:
652
+ each = declared[0]
653
+ return ParameterRange(
654
+ low=_field(each, "from_value"),
655
+ high=_field(each, "to_value"),
656
+ step=_field(each, "step"),
657
+ )
658
+ return None
659
+
660
+
661
+ def set_request(request_type: type[Message], values: Mapping[str, ParameterValue]) -> Message:
662
+ """Return the ``SetParameters`` request writing a batch, in the order it was given.
663
+
664
+ The order matters: results come back positionally and :func:`outcomes_of` pairs them by it.
665
+ """
666
+ parameter_type = request_type.ros2_nested["parameters"]
667
+ value_type = parameter_type.ros2_nested["value"]
668
+ written = tuple(
669
+ _built(parameter_type, name=name, value=_raw_value(value_type, each)) for name, each in values.items()
670
+ )
671
+ return _built(request_type, parameters=written)
672
+
673
+
674
+ def outcomes_of(names: Iterable[str], response: Message) -> Mapping[str, SetOutcome]:
675
+ """Return what a ``SetParameters`` response says, per parameter, paired back with its name.
676
+
677
+ Names missing from a short answer are marked unsuccessful and unanswered, with no reason text,
678
+ because :attr:`SetOutcome.reason` must only ever hold the node's own words.
679
+ """
680
+ results: Sequence[Message] = _field(response, "results")
681
+ outcomes: dict[str, SetOutcome] = {}
682
+ for index, name in enumerate(names):
683
+ if index >= len(results):
684
+ outcomes[name] = SetOutcome(successful=False, answered=False)
685
+ continue
686
+ result = results[index]
687
+ outcomes[name] = SetOutcome(
688
+ successful=bool(_field(result, "successful")),
689
+ reason=str(_field(result, "reason")),
690
+ )
691
+ return outcomes
692
+
693
+
694
+ def update_of(message: Message) -> ParameterUpdate:
695
+ """Return one ``/parameter_events`` message as an update.
696
+
697
+ New and changed parameters, then deleted ones as readings that are not present.
698
+ """
699
+ readings = [
700
+ ParameterReading(name=str(_field(each, "name")), present=True, value=_value_of(_field(each, "value")))
701
+ for named in ("new_parameters", "changed_parameters")
702
+ for each in _field(message, named)
703
+ ]
704
+ readings += [
705
+ ParameterReading(name=str(_field(each, "name")), present=False)
706
+ for each in _field(message, "deleted_parameters")
707
+ ]
708
+ return ParameterUpdate(node=str(_field(message, "node")), readings=tuple(readings))
709
+
710
+
711
+ def _raw_value(value_type: type[Message], value: ParameterValue) -> Message:
712
+ """Return one typed value as the ``rcl_interfaces/msg/ParameterValue`` that carries it."""
713
+ return _built(value_type, **{**_EMPTY_VALUE, "type": value.type.code, value.type.value_field: value.value})
714
+
715
+
716
+ def _built(message_type: type[Message], **fields: object) -> Message:
717
+ """Build one message dataclass from its field names (they are only known at run time)."""
718
+ return message_type(**fields)
719
+
720
+
721
+ def _field(message: Message, name: str) -> Any:
722
+ """Return one field of a message dataclass by name (its fields are not statically known)."""
723
+ return getattr(message, name)