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,850 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """One Component per Machine that answers what is on the ROS2 graph and what this adapter is bound to.
6
+
7
+ Every Machine with a Runtime gets this Component, on by default. It carries nine Methods:
8
+
9
+ - ``ListTopics``, ``ListServices`` and ``ListActions``: what is on the ROS2 graph, with an optional
10
+ substring filter. The graph is refreshed once per call, not polled.
11
+ - ``ListROS2Parameters``: the ROS2 parameters one node declares.
12
+ - ``DescribeROS2Parameter``: type, description, constraints and flags of one such parameter.
13
+ - ``ListBindings``: every Binding on this Machine: kind, ROS2 path, required or not, satisfied or
14
+ not, how long it has been waiting, and its QoS provenance.
15
+ - ``ListRecentEvents``: the last N BindingEvents this Machine fired.
16
+ - ``BindTopic``: bind a topic to look at it. Ephemeral: the nodes hang under this Component's own
17
+ Monitoring and live until the server restarts.
18
+ - ``CallService``: call a service once. Request and response are JSON in the Method's own
19
+ ParameterSet and FinalResultData, so no nodes are created.
20
+
21
+ The seven read-only Methods answer at the listing level with the Machine's Lock bypassed, and
22
+ their arguments are writable the same way. The two mutators need the Lock and a higher level. No
23
+ Method waits for startup to complete, so a Machine whose startup hangs can still be inspected.
24
+ Every Method browses for every authenticated user, and a client without the access level is
25
+ refused on use. Ad-hoc Bindings go through
26
+ :meth:`~opensmi.ros2.server.mirror.ROS2InwardMirrorMixin.bind_topic_now`, so they are capped and
27
+ counted like any other mutation. There is no ad-hoc goal sending: an action worth driving is worth
28
+ declaring.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import asyncio
34
+ import datetime as dt
35
+ import json
36
+ from dataclasses import dataclass
37
+ from typing import TYPE_CHECKING, Any, ClassVar, Final, NoReturn
38
+
39
+ from asyncua import ua
40
+ from asyncua.ua.status_codes import StatusCodes
41
+ from opensmi.server import BaseComponent, FinalResultData, ParameterSet, UaVariable
42
+ from opensmi.server.mixins import FinalResultDataMixin, ParameterSetMixin
43
+ from typing_extensions import override
44
+
45
+ from opensmi.ros2.runtime.errors import ROS2RuntimeError
46
+ from opensmi.ros2.runtime.guard import require_sendable
47
+ from opensmi.ros2.runtime.selection import FieldSelection
48
+ from opensmi.ros2.server.access import LISTING_ACCESS_LEVEL, ROS2ArgumentVariable, ROS2GatedMethod
49
+ from opensmi.ros2.server.bindings import MonitoringBinding, is_required
50
+ from opensmi.ros2.server.component import ROS2ComponentMixin
51
+ from opensmi.ros2.server.errors import DeclarationError
52
+ from opensmi.ros2.server.events import root_of
53
+ from opensmi.ros2.server.method import TRANSPORT_STATUS, default_request_from, default_response_to
54
+ from opensmi.ros2.server.mutation import add_plan_variable
55
+ from opensmi.ros2.server.projection import PlanObject, PlanVariable, flat_name, narrowed, shaped
56
+ from opensmi.ros2.server.required import LOSS_INTERVAL, satisfaction_of
57
+
58
+ if TYPE_CHECKING:
59
+ from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
60
+
61
+ from opensmi.server.protocols import UserAuthorization
62
+
63
+ from opensmi.ros2.runtime.graph import GraphSnapshot
64
+ from opensmi.ros2.runtime.interface import RuntimeInterface
65
+ from opensmi.ros2.runtime.messages import Message
66
+ from opensmi.ros2.server.bindings import Binding
67
+ from opensmi.ros2.server.events import BindingEventRecord
68
+ from opensmi.ros2.server.projection import PlanEntry, ProjectionContext
69
+ from opensmi.ros2.server.provenance import BindingQoS
70
+
71
+ __all__ = [
72
+ "INTROSPECTION_ID",
73
+ "INTROSPECTION_NAME",
74
+ "BindTopic",
75
+ "BindingReport",
76
+ "CallService",
77
+ "DescribeROS2Parameter",
78
+ "ListActions",
79
+ "ListBindings",
80
+ "ListROS2Parameters",
81
+ "ListRecentEvents",
82
+ "ListServices",
83
+ "ListTopics",
84
+ "ROS2GraphListing",
85
+ "ROS2IntrospectionComponent",
86
+ "ROS2ListingMethod",
87
+ "ROS2MutatorMethod",
88
+ "WaitingClock",
89
+ "machinery_items",
90
+ "qos_entries_of",
91
+ "reports_of",
92
+ "waiting_key",
93
+ ]
94
+
95
+ INTROSPECTION_NAME: Final = "ROS2Introspection"
96
+ """What the Component browses as. It is the same on every Machine."""
97
+
98
+ INTROSPECTION_ID: Final = "ros2_introspection"
99
+ """The Component's asset id, which it writes into its identification."""
100
+
101
+ _ENTRIES: Final = "Entries"
102
+ """The array of lines every Method here answers with."""
103
+
104
+ _COUNT: Final = "Count"
105
+ """How many lines :data:`_ENTRIES` carries, so a client can branch without reading them."""
106
+
107
+ _AD_HOC_DEPTH: Final = 1
108
+ """How many messages an ad-hoc subscription buffers (a declared Binding buffers ten)."""
109
+
110
+
111
+ def _utc_now() -> dt.datetime:
112
+ """Return the wall clock, in UTC."""
113
+ return dt.datetime.now(dt.UTC)
114
+
115
+
116
+ @dataclass(frozen=True, slots=True, kw_only=True)
117
+ class BindingReport:
118
+ """One Binding, as the provenance report answers for it.
119
+
120
+ Everything is read off state that is already kept current, so a report puts nothing on the wire.
121
+
122
+ :ivar item: The path of the machinery item that declares it.
123
+ :ivar binding: The Binding's name.
124
+ :ivar kind: The declaration class.
125
+ :ivar path: The ROS2 topic, service, action or node path it names.
126
+ :ivar required: Whether its item's StartupSkill will not reach ``Running`` without it.
127
+ :ivar satisfied: Whether its ROS2 counterpart is present, or ``None`` where presence does not
128
+ apply (a publishing Binding, where this adapter is the publisher).
129
+ :ivar waiting_since: When it last stopped being Satisfied, or ``None`` when it is satisfied
130
+ now or was never answerable. See :class:`WaitingClock`.
131
+ :ivar qos: What its ROS2 endpoint asks for and where that came from, or ``None`` for a kind
132
+ with no single endpoint of its own (a Method, an action, a ROS2-parameter Binding, the TF
133
+ Binding) or a Binding still waiting for its topic.
134
+ """
135
+
136
+ item: str
137
+ binding: str
138
+ kind: str
139
+ path: str
140
+ required: bool
141
+ satisfied: bool | None
142
+ waiting_since: dt.datetime | None = None
143
+ qos: BindingQoS | None = None
144
+
145
+ def __str__(self) -> str:
146
+ """Return the one line an operator reads out of the report."""
147
+ state = "n/a" if self.satisfied is None else ("satisfied" if self.satisfied else "absent")
148
+ waiting = f" since {self.waiting_since.isoformat(timespec='seconds')}" if self.waiting_since else ""
149
+ marked = "required" if self.required else "optional"
150
+ profile = "no endpoint" if self.qos is None else f"{self.qos.provenance.value} {self.qos.profile}"
151
+ adapted = f", adapted {self.qos.adaptations} time(s)" if self.qos and self.qos.adaptations else ""
152
+ return (
153
+ f"{self.item}/{self.binding} [{self.kind}] {self.path} -- "
154
+ f"{marked}, {state}{waiting}; QoS: {profile}{adapted}"
155
+ )
156
+
157
+
158
+ class WaitingClock:
159
+ """When each Binding last stopped being Satisfied.
160
+
161
+ The introspection Component samples the same booleans the status codes are written from, once
162
+ every :data:`~opensmi.ros2.server.required.LOSS_INTERVAL` seconds and again whenever a report
163
+ is asked for, and remembers the first sample at which each Binding was not satisfied. Sampling
164
+ reads flags other tasks already maintain, so it puts nothing on the wire and never starts the
165
+ graph poll.
166
+ """
167
+
168
+ def __init__(self, now: Callable[[], dt.datetime] = _utc_now) -> None:
169
+ """Start out knowing nothing.
170
+
171
+ :param now: Reads the wall clock. Tests inject their own.
172
+ """
173
+ self._now = now
174
+ self._since: dict[tuple[str, str], dt.datetime] = {}
175
+
176
+ def __repr__(self) -> str:
177
+ """Return a representation naming how many Bindings are currently waiting."""
178
+ return f"<WaitingClock, {len(self._since)} waiting>"
179
+
180
+ def note(self, key: tuple[str, str], *, satisfied: bool | None) -> None:
181
+ """Record one sample of one Binding's satisfaction.
182
+
183
+ A satisfied Binding, or one whose kind has no presence to read, forgets its waiting time,
184
+ so a sensor that returns and leaves again is reported waiting since the second departure.
185
+ """
186
+ if satisfied is None or satisfied:
187
+ self._since.pop(key, None)
188
+ return
189
+ self._since.setdefault(key, self._now())
190
+
191
+ def waiting_since(self, key: tuple[str, str]) -> dt.datetime | None:
192
+ """Return when one Binding last stopped being Satisfied, or ``None`` if it has not."""
193
+ return self._since.get(key)
194
+
195
+
196
+ def waiting_key(machinery_item: Any, binding: str) -> tuple[str, str]:
197
+ """Return how the clock files one Binding: the item's path, and the Binding's name."""
198
+ path = getattr(machinery_item, "path", None)
199
+ return (type(machinery_item).__name__ if path is None else str(path), binding)
200
+
201
+
202
+ def machinery_items(machine: Any) -> Iterator[Any]:
203
+ """Yield a Machine and every Component under it, depth first, in the order they were added."""
204
+ yield machine
205
+ for component in getattr(machine, "components", ()):
206
+ yield from machinery_items(component)
207
+
208
+
209
+ def qos_entries_of(machinery_item: Any) -> Mapping[str, BindingQoS]:
210
+ """Return every provenance entry one machinery item can answer for, by Binding name.
211
+
212
+ The sources are a Monitoring Binding's subscription, a Keyed Binding's subscription, and a
213
+ publishing Binding's publisher (which hangs on its Skill). An item that is not one of ours
214
+ contributes nothing. The TF Binding is absent, as :mod:`opensmi.ros2.server.provenance` says:
215
+ its endpoints belong to the Machine.
216
+ """
217
+ entries: dict[str, BindingQoS] = {}
218
+ entries.update(getattr(machinery_item, "ros2_qos_provenance", None) or {})
219
+ entries.update(getattr(machinery_item, "ros2_keyed_qos_provenance", None) or {})
220
+ for skill in getattr(machinery_item, "skill_set", ()):
221
+ published = getattr(skill, "ros2_qos_provenance", None)
222
+ if published is not None and not isinstance(published, dict):
223
+ entries[published.binding] = published
224
+ return entries
225
+
226
+
227
+ def reports_of(machinery_item: Any, clock: WaitingClock) -> tuple[BindingReport, ...]:
228
+ """Return one report row per Binding one machinery item declares.
229
+
230
+ Presence is probed with :func:`~opensmi.ros2.server.required.satisfaction_of`, the same cascade
231
+ the StartupSkill waits on, so the report and the StartupSkill cannot disagree.
232
+ """
233
+ entries = qos_entries_of(machinery_item)
234
+ bindings: Sequence[Binding] = getattr(machinery_item, "ros2_bindings", ())
235
+ rows: list[BindingReport] = []
236
+ for binding in bindings:
237
+ probe = satisfaction_of(machinery_item, binding)
238
+ satisfied = None if probe is None else probe()
239
+ key = waiting_key(machinery_item, binding.name)
240
+ clock.note(key, satisfied=satisfied)
241
+ rows.append(
242
+ BindingReport(
243
+ item=key[0],
244
+ binding=binding.name,
245
+ kind=type(binding).__name__,
246
+ path=_path_of(machinery_item, binding),
247
+ required=is_required(binding),
248
+ satisfied=satisfied,
249
+ waiting_since=clock.waiting_since(key),
250
+ qos=entries.get(binding.name),
251
+ )
252
+ )
253
+ return tuple(rows)
254
+
255
+
256
+ def _path_of(machinery_item: Any, binding: Any) -> str:
257
+ """Return the ROS2 path a report row names; for the TF Binding, the Machine's two TF topics."""
258
+ declared = getattr(binding, "path", None)
259
+ if declared is not None:
260
+ return str(declared)
261
+ config = getattr(machinery_item, "ros2_config", None)
262
+ topics: Sequence[str] = getattr(getattr(config, "transforms", None), "topics", ())
263
+ return " + ".join(topics) or "(no ROS2 path)"
264
+
265
+
266
+ class ROS2ListingMethod(
267
+ ParameterSetMixin[ParameterSet],
268
+ FinalResultDataMixin[FinalResultData],
269
+ ROS2GatedMethod,
270
+ ):
271
+ """A read-only Method answering with a list of lines, at the listing level and without the Lock.
272
+
273
+ FinalResultData holds a ``Count`` and an ``Entries`` array of strings, and the subclass
274
+ declares its arguments as Parameters in :meth:`_init`. The answers are strings because they
275
+ are prose for a person reading an HMI panel. A subclass implements :meth:`answer`.
276
+ """
277
+
278
+ bypasses_the_lock: ClassVar[bool] = True
279
+
280
+ def __init__(self, *, name: str, minimum_access_level: int = LISTING_ACCESS_LEVEL, **kwargs: Any) -> None:
281
+ """Name the Method and give it the level its kind requires."""
282
+ super().__init__(name=name, minimum_access_level=minimum_access_level, **kwargs)
283
+
284
+ @property
285
+ def component(self) -> Any:
286
+ """Return the introspection Component."""
287
+ return self.parent
288
+
289
+ @property
290
+ def runtime(self) -> RuntimeInterface:
291
+ """Return the Machine's Runtime."""
292
+ runtime: RuntimeInterface = self.component.runtime
293
+ return runtime
294
+
295
+ @override
296
+ async def _init(self) -> None:
297
+ """Let opensmi build the Method, then add the two result variables every one has."""
298
+ await super()._init()
299
+ await add_plan_variable(
300
+ self.final_result_data,
301
+ _COUNT,
302
+ PlanVariable(name=_COUNT, source="", initial=0, variant_type=ua.VariantType.Int32),
303
+ None,
304
+ )
305
+ await add_plan_variable(
306
+ self.final_result_data,
307
+ _ENTRIES,
308
+ PlanVariable(name=_ENTRIES, source="", initial=[], variant_type=ua.VariantType.String),
309
+ None,
310
+ )
311
+
312
+ async def _add_argument(self, name: str, initial: object, variant_type: ua.VariantType) -> None:
313
+ """Create one writable argument. A listing's is writable without the Lock, a mutator's is not."""
314
+ variable_type = ROS2ArgumentVariable if self.bypasses_the_lock else UaVariable
315
+ variable: UaVariable[Any] = variable_type(
316
+ ua.Variant(initial, variant_type),
317
+ name=name,
318
+ writable=True,
319
+ minimum_access_level=self.minimum_access_level,
320
+ )
321
+ await self.parameter_set.add(variable)
322
+
323
+ @override
324
+ async def _condition_startup_completed(self, user: UserAuthorization) -> bool:
325
+ """Answer yes: nothing here commands the robot, and one asks most when startup failed."""
326
+ del user
327
+ return True
328
+
329
+ @override
330
+ async def execute_method(self) -> None:
331
+ """Answer the call, writing the count beside the lines."""
332
+ await self._write_lines(list(await self.answer()))
333
+
334
+ async def answer(self) -> Sequence[str]:
335
+ """Do whatever this Method does, and return the lines it answers with.
336
+
337
+ Implemented by each subclass.
338
+ """
339
+ raise NotImplementedError
340
+
341
+ async def _write_lines(self, lines: Sequence[str]) -> None:
342
+ """Write one answer into the two result variables."""
343
+ await self.final_result_data[_COUNT].write(len(lines))
344
+ await self.final_result_data[_ENTRIES].write(list(lines))
345
+
346
+ async def _text_parameter(self, name: str) -> str:
347
+ """Return one string Parameter, stripped."""
348
+ value = await self.parameter_set[name].read()
349
+ return str(value or "").strip()
350
+
351
+ async def _refreshed_graph(self) -> GraphSnapshot:
352
+ """Read the ROS2 graph once. No poll keeps running."""
353
+ return await self.runtime.graph.refresh()
354
+
355
+ async def _refuse(self, code: int, text: str) -> NoReturn:
356
+ """Log the reason on the Notification, then refuse with a status code.
357
+
358
+ ``Call`` can only answer a status code, so the reason travels as a Notification message.
359
+
360
+ :raises UaStatusCodeError: Always.
361
+ """
362
+ await self.ua_log_error(text)
363
+ raise ua.UaStatusCodeError(code)
364
+
365
+ async def _require_an_argument(self, value: str, name: str, what: str) -> None:
366
+ """Refuse a call whose text argument was left empty.
367
+
368
+ :raises UaStatusCodeError: ``BadInvalidArgument``.
369
+ """
370
+ if value:
371
+ return
372
+ await self._refuse(StatusCodes.BadInvalidArgument, f"write {name} before calling: it is {what}")
373
+
374
+ async def _one_type_on(self, path: str, names: Mapping[str, tuple[str, ...]], argument: str) -> str:
375
+ """Return the one ROS2 type a graph name carries, or refuse to guess between several.
376
+
377
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when the name is not on the graph or
378
+ carries more than one type.
379
+ """
380
+ types = names.get(path, ())
381
+ if len(types) == 1:
382
+ return types[0]
383
+ found = "is not on the ROS2 graph" if not types else f"carries more than one type ({', '.join(types)})"
384
+ return await self._refuse(
385
+ StatusCodes.BadInvalidArgument,
386
+ f"{path} {found}, so name the type in {argument}",
387
+ )
388
+
389
+ async def _answered(self, call: Awaitable[Any]) -> Any:
390
+ """Await one ROS2 call, turning transport failures into UA status codes.
391
+
392
+ :raises UaStatusCodeError: The code :data:`~opensmi.ros2.server.method.TRANSPORT_STATUS`
393
+ gives, when the call did not happen. Declared service Methods use the same table.
394
+ """
395
+ try:
396
+ return await call
397
+ except tuple(TRANSPORT_STATUS) as error:
398
+ code = next(each for kind, each in TRANSPORT_STATUS.items() if isinstance(error, kind))
399
+ await self._refuse(code, str(error))
400
+
401
+
402
+ class ROS2MutatorMethod(ROS2ListingMethod):
403
+ """A Method that changes something, and therefore needs the Lock as well as a level."""
404
+
405
+ bypasses_the_lock: ClassVar[bool] = False
406
+
407
+ def __init__(self, *, name: str, minimum_access_level: int, **kwargs: Any) -> None: # pyright: ignore[reportIncompatibleMethodOverride]
408
+ """Register the Method at the deployment's mutator level, which has no default."""
409
+ super().__init__(name=name, minimum_access_level=minimum_access_level, **kwargs)
410
+
411
+
412
+ def _matching(names: Mapping[str, tuple[str, ...]], wanted: str) -> list[str]:
413
+ """Return one graph vocabulary as sorted lines, narrowed by a substring."""
414
+ return [f"{name} {', '.join(names[name]) or 'no type'}" for name in sorted(names) if not wanted or wanted in name]
415
+
416
+
417
+ class ROS2GraphListing(ROS2ListingMethod):
418
+ """One of the ROS2 graph's three vocabularies, narrowed by a substring.
419
+
420
+ :cvar vocabulary: Which field of a graph snapshot this Method answers from.
421
+ """
422
+
423
+ vocabulary: ClassVar[str]
424
+
425
+ @override
426
+ async def _init(self) -> None:
427
+ """Add the one argument: a substring to narrow the listing by."""
428
+ await super()._init()
429
+ await self._add_argument("Filter", "", ua.VariantType.String)
430
+
431
+ @override
432
+ async def answer(self) -> Sequence[str]:
433
+ """Return every entry whose ROS2 name contains the filter, or every one when it is empty."""
434
+ snapshot = await self._refreshed_graph()
435
+ names: Mapping[str, tuple[str, ...]] = getattr(snapshot, self.vocabulary)
436
+ return _matching(names, await self._text_parameter("Filter"))
437
+
438
+
439
+ class ListTopics(ROS2GraphListing):
440
+ """Every topic on the ROS2 graph, with the types advertised on it."""
441
+
442
+ vocabulary: ClassVar[str] = "topics"
443
+
444
+
445
+ class ListServices(ROS2GraphListing):
446
+ """Every service on the ROS2 graph, with its types."""
447
+
448
+ vocabulary: ClassVar[str] = "services"
449
+
450
+
451
+ class ListActions(ROS2GraphListing):
452
+ """Every action on the ROS2 graph, with its types."""
453
+
454
+ vocabulary: ClassVar[str] = "actions"
455
+
456
+
457
+ class ListROS2Parameters(ROS2ListingMethod):
458
+ """Every ROS2 parameter one node declares, in the order the node declared them.
459
+
460
+ This calls the node's own ``list_parameters`` service, so a node that is not running fails
461
+ like any other transport failure.
462
+ """
463
+
464
+ @override
465
+ async def _init(self) -> None:
466
+ """Add the one argument: which ROS2 node to ask."""
467
+ await super()._init()
468
+ await self._add_argument("Node", "", ua.VariantType.String)
469
+
470
+ @override
471
+ async def answer(self) -> Sequence[str]:
472
+ """Return every parameter name the named node declares.
473
+
474
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when no node was named, and the code
475
+ the transport table gives when the node's parameter services did not answer.
476
+ """
477
+ node = await self._text_parameter("Node")
478
+ await self._require_an_argument(node, "Node", "the ROS2 node whose parameters to list")
479
+ return list(await self._answered(self.runtime.parameters.list(node=node)))
480
+
481
+
482
+ class DescribeROS2Parameter(ROS2ListingMethod):
483
+ """What one ROS2 node says about one of its parameters (type, description, constraints, flags).
484
+
485
+ It does not read the value. To read a value, declare the parameter on a Component.
486
+ """
487
+
488
+ @override
489
+ async def _init(self) -> None:
490
+ """Add the two arguments: which node, and which of its parameters."""
491
+ await super()._init()
492
+ await self._add_argument("Node", "", ua.VariantType.String)
493
+ await self._add_argument("Name", "", ua.VariantType.String)
494
+
495
+ @override
496
+ async def answer(self) -> Sequence[str]:
497
+ """Return the description as a handful of lines, or say the node has no such name.
498
+
499
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when either argument is missing, and
500
+ the transport code when the node's parameter services did not answer.
501
+ """
502
+ node = await self._text_parameter("Node")
503
+ name = await self._text_parameter("Name")
504
+ await self._require_an_argument(node, "Node", "the ROS2 node the parameter lives on")
505
+ await self._require_an_argument(name, "Name", "the ROS2 parameter to describe")
506
+ described = await self._answered(self.runtime.parameters.describe(node=node, name=name))
507
+ if not described.present:
508
+ return [f"{node} does not declare {name!r}"]
509
+ declared = "not set (the node declares it and it holds nothing)"
510
+ if described.type is not None:
511
+ declared = described.type.value
512
+ return [
513
+ f"name: {described.name}",
514
+ f"type: {declared}",
515
+ f"description: {described.description or '(none)'}",
516
+ f"constraints: {described.additional_constraints or '(none)'}",
517
+ f"read_only: {described.read_only}",
518
+ f"dynamic_typing: {described.dynamic_typing}",
519
+ ]
520
+
521
+
522
+ class ListBindings(ROS2ListingMethod):
523
+ """Every Binding on this Machine, with its provenance and its state."""
524
+
525
+ @override
526
+ async def _init(self) -> None:
527
+ """Add the one argument: a substring narrowing it to one item, Binding or ROS2 path."""
528
+ await super()._init()
529
+ await self._add_argument("Filter", "", ua.VariantType.String)
530
+
531
+ @override
532
+ async def answer(self) -> Sequence[str]:
533
+ """Return one line per Binding, narrowed by a substring of its item, name or path."""
534
+ wanted = await self._text_parameter("Filter")
535
+ return [
536
+ str(report)
537
+ for report in self.component.binding_reports()
538
+ if not wanted or wanted in report.item or wanted in report.binding or wanted in report.path
539
+ ]
540
+
541
+
542
+ class ListRecentEvents(ROS2ListingMethod):
543
+ """The last N BindingEvents this Machine fired, oldest first.
544
+
545
+ An OPC UA event is a moment, so a client that was not subscribed at the time cannot learn it
546
+ happened. The last :data:`~opensmi.ros2.server.events.RECENT_EVENTS` are kept, which makes
547
+ conditions with no state variable (a QoS clash, a failed publish, a key collision, a cap
548
+ reached) answerable.
549
+ """
550
+
551
+ @override
552
+ async def _init(self) -> None:
553
+ """Add the two arguments: how many to answer with, and a code to narrow them by."""
554
+ await super()._init()
555
+ # `Newest` rather than `Count`: every Method already answers with a `Count` in FinalResultData.
556
+ await self._add_argument("Newest", 0, ua.VariantType.Int32)
557
+ await self._add_argument("Code", "", ua.VariantType.String)
558
+
559
+ @override
560
+ async def answer(self) -> Sequence[str]:
561
+ """Return the last N kept events, oldest first, narrowed by code where one was given."""
562
+ wanted = await self._text_parameter("Code")
563
+ count = int(await self.parameter_set["Newest"].read() or 0)
564
+ kept: Sequence[BindingEventRecord] = self.component.recent_events()
565
+ matching = [str(each) for each in kept if not wanted or each.code == wanted]
566
+ # Zero means everything kept; the ring is bounded, so that cannot be unbounded.
567
+ return matching if count <= 0 else matching[-count:]
568
+
569
+
570
+ class BindTopic(ROS2MutatorMethod):
571
+ """Bind a ROS2 topic to this Component's Monitoring, ephemerally, to look at it.
572
+
573
+ It creates an ordinary Monitoring Binding through the mutation chokepoint, so what an operator
574
+ sees is what the written declaration would show. Nothing reaches disk and nothing is unbound:
575
+ the Binding lives until the server restarts.
576
+ """
577
+
578
+ @override
579
+ async def _init(self) -> None:
580
+ """Add the three arguments: what to call it, which topic, and which type."""
581
+ await super()._init()
582
+ await self._add_argument("Name", "", ua.VariantType.String)
583
+ await self._add_argument("Topic", "", ua.VariantType.String)
584
+ await self._add_argument("MessageType", "", ua.VariantType.String)
585
+
586
+ @override
587
+ async def answer(self) -> Sequence[str]:
588
+ """Bind the topic and say what was made, or say why nothing was.
589
+
590
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when a name or a topic is missing, when
591
+ the type was neither given nor decidable from the graph, or when the name is taken;
592
+ ``BadOutOfRange`` when a mutation cap refused the nodes.
593
+ """
594
+ name = await self._text_parameter("Name")
595
+ topic = await self._text_parameter("Topic")
596
+ declared = await self._text_parameter("MessageType")
597
+ await self._require_an_argument(name, "Name", "what to call the Binding, which its variables are named for")
598
+ await self._require_an_argument(topic, "Topic", "the ROS2 topic to bind")
599
+ message_type = declared or await self._one_type_on(
600
+ topic,
601
+ (await self._refreshed_graph()).topics,
602
+ "MessageType",
603
+ )
604
+ try:
605
+ binding = MonitoringBinding(name=name, path=topic, message_type=message_type, depth=_AD_HOC_DEPTH)
606
+ bound = await self.component.bind_ad_hoc(binding)
607
+ except (ROS2RuntimeError, DeclarationError) as error:
608
+ await self._refuse(StatusCodes.BadInvalidArgument, str(error))
609
+ if not bound:
610
+ await self._refuse(
611
+ StatusCodes.BadOutOfRange,
612
+ f"binding {topic} as {name!r} would take this Machine past a mutation cap, so "
613
+ f"nothing was created; raise mutation_node_cap on this Component, or restart the "
614
+ f"server to start from what was declared",
615
+ )
616
+ return [
617
+ f"bound {topic} ({message_type}) as {name!r} under this Component's Monitoring",
618
+ "it is ephemeral: it lives until this server restarts",
619
+ ]
620
+
621
+
622
+ class CallService(ROS2MutatorMethod):
623
+ """Call one ROS2 service once, ad hoc, without creating any nodes.
624
+
625
+ The request and the response are JSON, keyed by the node path of each field joined with dots
626
+ (``Mode.Mode`` for the variable ``Mode/Mode``), so ``{"Mode.Mode": 2, "Label": "wide"}`` is the
627
+ request a declared Method's Parameters would have been. A field left out holds the type's own zero.
628
+ """
629
+
630
+ @override
631
+ async def _init(self) -> None:
632
+ """Add the three arguments: which service, which type, and the request as JSON."""
633
+ await super()._init()
634
+ await self._add_argument("Service", "", ua.VariantType.String)
635
+ await self._add_argument("ServiceType", "", ua.VariantType.String)
636
+ await self._add_argument("Request", "{}", ua.VariantType.String)
637
+
638
+ @override
639
+ async def answer(self) -> Sequence[str]:
640
+ """Send one request and answer with the response as JSON.
641
+
642
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when the service or its type is missing
643
+ or the request is not a JSON object this type can be built from; ``BadTypeMismatch``
644
+ when a value the request carries is not one the ROS2 type can hold; and the code
645
+ :data:`~opensmi.ros2.server.method.TRANSPORT_STATUS` gives when the call did not
646
+ happen.
647
+ """
648
+ service = await self._text_parameter("Service")
649
+ await self._require_an_argument(service, "Service", "the ROS2 service to call")
650
+ service_type = await self._text_parameter("ServiceType") or await self._one_type_on(
651
+ service,
652
+ (await self._refreshed_graph()).services,
653
+ "ServiceType",
654
+ )
655
+ values = await self._request_values(await self._text_parameter("Request") or "{}")
656
+ request = await self._built(service_type, values)
657
+ response = await self._answered(
658
+ self.runtime.call_service(service=service, service_type=service_type, request=request)
659
+ )
660
+ read = default_response_to(response, self._context(type(response)))
661
+ return [f"{service} answered {type(response).ros2.type_name}", _as_json(read)]
662
+
663
+ async def _built(self, service_type: str, values: Mapping[str, object]) -> Message:
664
+ """Build the request message with :func:`~opensmi.ros2.server.method.default_request_from`.
665
+
666
+ It also checks that the message can be sent, so a value ROS2 would abort the process over
667
+ becomes a status code.
668
+
669
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when the type cannot be resolved or the
670
+ request cannot be built from what was given, and ``BadTypeMismatch`` when a value is
671
+ not one the ROS2 type can hold.
672
+ """
673
+ try:
674
+ types = self.runtime.describe_service(service_type)
675
+ context = self._context(types.request)
676
+ supplied = dict(_initials(shaped(types.request, context)))
677
+ unknown = sorted(set(values) - set(supplied))
678
+ if unknown:
679
+ message = (
680
+ f"{service_type} has no field(s) {', '.join(unknown)}; a request names the "
681
+ f"node paths of a declared Method's Parameters, joined with dots, which for "
682
+ f"this type are: {', '.join(sorted(supplied))}"
683
+ )
684
+ raise DeclarationError(message) # noqa: TRY301 -- refused below with the rest
685
+ supplied.update(values)
686
+ request = default_request_from(types.request, supplied, context)
687
+ except (ROS2RuntimeError, DeclarationError) as error:
688
+ await self._refuse(StatusCodes.BadInvalidArgument, str(error))
689
+ try:
690
+ require_sendable(request)
691
+ except ROS2RuntimeError as error:
692
+ await self._refuse(StatusCodes.BadTypeMismatch, str(error))
693
+ return request
694
+
695
+ async def _request_values(self, text: str) -> Mapping[str, object]:
696
+ """Return the typed request as field paths to values.
697
+
698
+ :raises UaStatusCodeError: ``BadInvalidArgument`` when the text is not a JSON object.
699
+ """
700
+ try:
701
+ parsed = json.loads(text)
702
+ except ValueError as error:
703
+ await self._refuse(
704
+ StatusCodes.BadInvalidArgument,
705
+ f"Request is not JSON: {error}. It is an object keyed by the node paths of a "
706
+ f"declared Method's Parameters, joined with dots, so "
707
+ f'{{"Mode.Mode": 2}} -- and {{}} sends the type as the zeros a declared '
708
+ f"Method's untouched Parameters would have sent",
709
+ )
710
+ if not isinstance(parsed, dict):
711
+ await self._refuse(
712
+ StatusCodes.BadInvalidArgument,
713
+ f"Request is a JSON {type(parsed).__name__} and has to be an object: the field "
714
+ f"path is what says which field a value is for",
715
+ )
716
+ return parsed
717
+
718
+ def _context(self, message_type: type[Message]) -> ProjectionContext:
719
+ """Return the Component's Projection context for one type, so ad-hoc calls render like declared ones."""
720
+ return narrowed(self.component.ros2_projection_context, message_type, FieldSelection())
721
+
722
+
723
+ class ROS2IntrospectionComponent(ROS2ComponentMixin, BaseComponent):
724
+ """The Component every Machine with a Runtime carries, and the ad-hoc Bindings it holds.
725
+
726
+ It declares no Bindings of its own, so its Monitoring is empty at boot and fills with whatever
727
+ an operator binds through :class:`BindTopic`. A Machine may replace it through
728
+ :attr:`~opensmi.ros2.server.machine.ROS2MachineMixin.introspection_component_type`.
729
+ """
730
+
731
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
732
+ """Start out holding no ad-hoc Bindings and nothing sampled."""
733
+ kwargs.setdefault("name", INTROSPECTION_NAME)
734
+ super().__init__(*args, **kwargs)
735
+ self._ad_hoc: set[str] = set()
736
+ self._clock = WaitingClock()
737
+ self._sampler: asyncio.Task[None] | None = None
738
+
739
+ @property
740
+ def ad_hoc_bindings(self) -> frozenset[str]:
741
+ """Return the names of the Bindings an operator created, rather than a deployment."""
742
+ return frozenset(self._ad_hoc)
743
+
744
+ @property
745
+ def machine(self) -> Any:
746
+ """Return the Machine this Component reports for, which is the one it hangs under."""
747
+ return root_of(self)
748
+
749
+ def binding_reports(self) -> tuple[BindingReport, ...]:
750
+ """Return one report row per Binding on this Machine, sampling the clock as it goes."""
751
+ return tuple(report for item in machinery_items(self.machine) for report in reports_of(item, self._clock))
752
+
753
+ def recent_events(self) -> tuple[BindingEventRecord, ...]:
754
+ """Return the BindingEvents this Machine has kept, oldest first."""
755
+ kept: tuple[BindingEventRecord, ...] = getattr(self.machine, "ros2_recent_events", ())
756
+ return kept
757
+
758
+ async def bind_ad_hoc(self, binding: MonitoringBinding) -> bool:
759
+ """Bind one topic on behalf of an operator, and remember that it was theirs.
760
+
761
+ :return: Whether it happened; ``False`` means a mutation cap refused the nodes.
762
+ :raises DuplicateBindingNameError: When the name is taken on this Component.
763
+ :raises ROS2RuntimeError: When the type cannot be resolved or the subscription cannot be
764
+ opened.
765
+ """
766
+ if not await self.bind_topic_now(binding, message_type=binding.message_type or ""):
767
+ return False
768
+ self._ad_hoc.add(binding.name)
769
+ # Here `ros2_bindings` grows with the address space, so the report covers ad-hoc Bindings.
770
+ self._resolved_bindings = (*self.ros2_bindings, binding)
771
+ return True
772
+
773
+ async def _write_identification(self) -> None:
774
+ """Identify this Component as part of the Machine: its manufacturer, and its serial with the asset id."""
775
+ identification: Any = getattr(self.machine, "identification", None)
776
+ manufacturer: Any = ua.LocalizedText(INTROSPECTION_NAME)
777
+ serial = ""
778
+ if identification is not None and identification is not self.identification:
779
+ manufacturer = await identification.Manufacturer.read()
780
+ serial = str(await identification.SerialNumber.read() or "")
781
+ await self.identification.Manufacturer.write(manufacturer)
782
+ await self.identification.SerialNumber.write(f"{serial}/{INTROSPECTION_ID}" if serial else INTROSPECTION_ID)
783
+
784
+ @override
785
+ async def _init(self) -> None:
786
+ """Build the mirror with no Bindings, add the nine Methods, then start sampling.
787
+
788
+ The empty mirror still gives the Component its Runtime and Projection registry, which an
789
+ ad-hoc bind needs. Nothing is subscribed yet.
790
+ """
791
+ await super()._init()
792
+ await self._init_monitoring_mirror((), runtime=self.runtime, registry=self.ros2_projections)
793
+ config = self.ros2_config
794
+ for listing_type in (
795
+ ListTopics,
796
+ ListServices,
797
+ ListActions,
798
+ ListROS2Parameters,
799
+ DescribeROS2Parameter,
800
+ ListBindings,
801
+ ListRecentEvents,
802
+ ):
803
+ await self.add_method(
804
+ listing_type(name=listing_type.__name__, minimum_access_level=config.listing_access_level)
805
+ )
806
+ for mutator_type in (BindTopic, CallService):
807
+ await self.add_method(
808
+ mutator_type(name=mutator_type.__name__, minimum_access_level=config.introspection_access_level)
809
+ )
810
+ self._sampler = asyncio.create_task(self._sample(), name="ros2-introspection-waiting")
811
+
812
+ @override
813
+ async def _shutdown(self) -> None:
814
+ """Stop sampling, then let the Component release its ad-hoc subscriptions."""
815
+ sampler, self._sampler = self._sampler, None
816
+ if sampler is not None:
817
+ sampler.cancel()
818
+ await asyncio.gather(sampler, return_exceptions=True)
819
+ await super()._shutdown()
820
+
821
+ async def _sample(self) -> None:
822
+ """Sample every Binding's satisfaction on a slow timer. A failure is logged and the loop continues."""
823
+ while True:
824
+ await asyncio.sleep(LOSS_INTERVAL)
825
+ try:
826
+ self.binding_reports()
827
+ except Exception:
828
+ self.logger.exception("Could not sample what this Machine is bound to; the clock continues")
829
+
830
+
831
+ def _initials(plan: Sequence[PlanEntry], prefix: str = "") -> Iterator[tuple[str, object]]:
832
+ """Yield the value each variable of a Projection's plan would have been created holding.
833
+
834
+ A declared Method's Parameters start from these values, so an ad-hoc request that names only
835
+ some fields sends the same message a declared Method would.
836
+ """
837
+ for entry in plan:
838
+ name = flat_name(prefix, entry.full_name)
839
+ if isinstance(entry, PlanObject):
840
+ yield from _initials(entry.children, name)
841
+ continue
842
+ yield name, entry.initial
843
+
844
+
845
+ def _as_json(values: Mapping[str, object]) -> str:
846
+ """Return one response's values as JSON, keyed by the flat field paths a request uses.
847
+
848
+ Values that are not JSON types (a ``bytes`` payload above all) are rendered with ``str``.
849
+ """
850
+ return json.dumps(dict(values), default=str, sort_keys=True)