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,633 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """Required Bindings: the StartupSkill's contract, and what a client sees at startup.
6
+
7
+ A Binding marked ``required=True`` means that the StartupSkill of the machinery item that declared
8
+ it does not reach ``Running`` until the Binding is Satisfied, which means its ROS2 counterpart is
9
+ present. If its deadline passes first, the Skill halts and opensmi's own supervision reports the
10
+ Machine ``OutOfService``. Satisfied is presence, never first data: a publisher that has
11
+ not spoken satisfies a Binding. :func:`satisfaction_of` holds the answer per kind, and both the
12
+ StartupSkill and the introspection Component's provenance report use it, so they cannot disagree.
13
+
14
+ Nothing waits before the endpoint opens. Every ``_init`` creates its nodes and returns, and the wait
15
+ happens inside ``_handle_starting``, so the Skill is observably ``Starting`` meanwhile. The Machine
16
+ and Component mixins add :class:`ROS2StartupSkill` themselves, because opensmi does not require a
17
+ StartupSkill; its starting handler waits for the declarations first and asks every child for its
18
+ verdict instead of stopping at the first.
19
+
20
+ Every Binding fires :data:`REQUIRED_BINDING_ABSENT` at its own deadline, and the halt at the last
21
+ one names every Binding that missed. A Binding lost after startup is reported
22
+ (:data:`REQUIRED_BINDING_LOST`) but never halts, so a restarted sensor node cannot tear a robot down
23
+ mid-goal; recovery is ``Reset`` plus ``Start``, and the check re-runs on every start. A normal boot
24
+ is quiet: no event when a Binding becomes satisfied, and none about a Binding that is not required.
25
+ The satisfaction facts are polled every :data:`CHECK_INTERVAL` seconds, since the kinds learn
26
+ presence in different ways and share no event stream.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import contextlib
33
+ from dataclasses import dataclass
34
+ from typing import TYPE_CHECKING, Any, Final, cast
35
+
36
+ from opensmi.core import SkillState
37
+ from opensmi.core.errors import OpenSmiError, OpenSmiRuntimeError
38
+ from opensmi.server.base_startup_skill import BaseStartupSkill
39
+
40
+ from opensmi.ros2.runtime.graph import EMPTY_GRAPH
41
+ from opensmi.ros2.server.access import SKILL_ACCESS_LEVEL
42
+ from opensmi.ros2.server.bindings import (
43
+ ActionBinding,
44
+ KeyedBinding,
45
+ LifecycleBinding,
46
+ MethodBinding,
47
+ MonitoringBinding,
48
+ ROS2ParameterBinding,
49
+ TFBinding,
50
+ is_required,
51
+ )
52
+ from opensmi.ros2.server.config import ROS2Config
53
+ from opensmi.ros2.server.errors import DeclarationError
54
+ from opensmi.ros2.server.events import Severity
55
+ from opensmi.ros2.server.lifecycle import RESTING
56
+
57
+ if TYPE_CHECKING:
58
+ from collections.abc import Awaitable, Callable, Sequence
59
+
60
+ from opensmi.server.base_machinery_item import BaseMachineryItem
61
+
62
+ from opensmi.ros2.runtime.graph import GraphSnapshot, GraphWatch
63
+ from opensmi.ros2.server.bindings import Binding
64
+
65
+ __all__ = [
66
+ "CHECK_INTERVAL",
67
+ "COMPONENT_NOT_RUNNING",
68
+ "LOSS_INTERVAL",
69
+ "REQUIRED_BINDING_ABSENT",
70
+ "REQUIRED_BINDING_LOST",
71
+ "Prerequisite",
72
+ "ROS2StartupSkill",
73
+ "StartupGate",
74
+ "close_startup_skills",
75
+ "prerequisites_of",
76
+ "satisfaction_of",
77
+ "wait_for",
78
+ ]
79
+
80
+ REQUIRED_BINDING_ABSENT: Final = "REQUIRED_BINDING_ABSENT"
81
+ """What a required Binding reports when its own deadline passed and it was still not Satisfied.
82
+
83
+ One event per Binding, at its own deadline. It is also the error code the halt carries on opensmi's
84
+ own Notification.
85
+ """
86
+
87
+ REQUIRED_BINDING_LOST: Final = "REQUIRED_BINDING_LOST"
88
+ """What a required Binding reports when it was Satisfied after startup and then was not.
89
+
90
+ A warning, since nothing is halted. Reported once per loss: a sensor that flaps twice is reported
91
+ twice. Coming back is not reported.
92
+ """
93
+
94
+ COMPONENT_NOT_RUNNING: Final = "COMPONENT_NOT_RUNNING"
95
+ """The error code a Machine's halt carries when a Component's StartupSkill did not come up.
96
+
97
+ It is not a BindingEvent, since its subject is a Component. The fault text names every Component
98
+ that did not reach ``Running``.
99
+ """
100
+
101
+ CHECK_INTERVAL: Final = 0.05
102
+ """Seconds between two readings of anything a starting StartupSkill is waiting on.
103
+
104
+ That is the satisfaction facts and a child Skill's ``CurrentState``. It is the granularity of "the
105
+ robot came up" for a client watching ``CurrentState``; each Binding's deadline is its own.
106
+ """
107
+
108
+ LOSS_INTERVAL: Final = 1.0
109
+ """Seconds between two readings of whether a Binding is still Satisfied, once nothing waits on it."""
110
+
111
+
112
+ @dataclass(frozen=True, slots=True, eq=False)
113
+ class Prerequisite:
114
+ """One required Binding, as the wait sees it: a deadline and a question to ask.
115
+
116
+ :func:`prerequisites_of` resolves the kinds once, so the wait is a loop over these. Compared by
117
+ identity, because two Components may carry Bindings of the same name.
118
+
119
+ :ivar binding: The Binding's name, which is what a ``BindingEvent`` says this is about.
120
+ :ivar path: The ROS2 topic, service, action or node path it names.
121
+ :ivar timeout: How many seconds from the start of the wait its deadline is.
122
+ :ivar satisfied: Whether its ROS2 counterpart is present, asked now. Cheap and synchronous.
123
+ :ivar reads_the_graph: Whether the answer comes from the Runtime's graph facet, which has to be
124
+ watched for it to be read at all.
125
+ """
126
+
127
+ binding: str
128
+ path: str
129
+ timeout: float
130
+ satisfied: Callable[[], bool]
131
+ reads_the_graph: bool = False
132
+
133
+
134
+ def prerequisites_of(machinery_item: Any) -> tuple[Prerequisite, ...]:
135
+ """Return what one machinery item's StartupSkill waits for, one entry per required Binding.
136
+
137
+ :param machinery_item: The Component or Machine whose declarations these are. One without
138
+ Bindings, such as every Machine, answers with nothing.
139
+ :raises DeclarationError: When a required Binding's kind has no answer to what Satisfied means
140
+ for it.
141
+ """
142
+ bindings: Sequence[Binding] = getattr(machinery_item, "ros2_bindings", ())
143
+ required = [binding for binding in bindings if is_required(binding)]
144
+ if not required:
145
+ return ()
146
+ default = _deployment_deadline(machinery_item)
147
+ return tuple(_prerequisite(machinery_item, binding, default) for binding in required)
148
+
149
+
150
+ def satisfaction_of(machinery_item: Any, binding: Any) -> Callable[[], bool] | None:
151
+ """Return how to ask whether one Binding is Satisfied, or ``None`` when the word does not apply.
152
+
153
+ Nothing is asked here, so this works while the Component is still being built. ``None`` means
154
+ the kind has no presence to read, as with a publishing Binding (we are the publisher). The
155
+ probe reads through ``getattr``, so an item that is not one of ours answers absent.
156
+
157
+ ====================== ======================================================================
158
+ Monitoring The subscription's publisher count, off its DDS match events. A Binding
159
+ that is not bound yet is not satisfied.
160
+ Keyed The subscription's publisher count, never membership.
161
+ Method The service is on the Runtime's last graph snapshot. This reads the
162
+ snapshot and starts no poll, so it answers absent where nothing watches
163
+ the graph; the StartupSkill's wait holds a watch open while it asks.
164
+ ROS2 parameter Every declared name is confirmed present on the node, read off
165
+ the parameter mirror.
166
+ Action The action is on the Runtime's last graph snapshot, like a service.
167
+ Lifecycle A publisher on each declared node's ``transition_event``.
168
+ TF Something other than this server publishes on a transform topic, never a
169
+ particular frame.
170
+ ====================== ======================================================================
171
+ """
172
+ if isinstance(binding, MonitoringBinding):
173
+ return lambda: bool(getattr(machinery_item, "ros2_monitoring_presence", {}).get(binding.name))
174
+ if isinstance(binding, KeyedBinding):
175
+ return lambda: bool(getattr(machinery_item, "ros2_keyed_presence", {}).get(binding.name))
176
+ if isinstance(binding, MethodBinding):
177
+ return lambda: binding.path in _graph_of(machinery_item).services
178
+ if isinstance(binding, ROS2ParameterBinding):
179
+ return lambda: _every_name_is_confirmed(machinery_item, binding)
180
+ if isinstance(binding, ActionBinding):
181
+ return lambda: binding.path in _graph_of(machinery_item).actions
182
+ if isinstance(binding, LifecycleBinding):
183
+ return lambda: _every_node_is_there(machinery_item, binding)
184
+ if isinstance(binding, TFBinding):
185
+ return lambda: bool(getattr(machinery_item, "ros2_transform_presence", {}).get(binding.name))
186
+ return None
187
+
188
+
189
+ def _reads_the_graph(binding: Any) -> bool:
190
+ """Return whether a kind's presence is read off the graph snapshot, which has to be watched."""
191
+ return isinstance(binding, (MethodBinding, ActionBinding))
192
+
193
+
194
+ def _prerequisite(machinery_item: Any, binding: Any, default: float) -> Prerequisite:
195
+ """Return one declaration as the wait sees it, with the probe its kind answers through.
196
+
197
+ :raises DeclarationError: When the Binding is required and its kind has no answer to what
198
+ Satisfied means for it.
199
+ """
200
+ satisfied = satisfaction_of(machinery_item, binding)
201
+ if satisfied is None:
202
+ message = (
203
+ f"the Binding {binding.name!r} is marked required and its kind ({type(binding).__name__}) has no "
204
+ f"answer to what Satisfied means for it; every kind that can be required answers in satisfaction_of"
205
+ )
206
+ raise DeclarationError(message)
207
+ return Prerequisite(
208
+ binding=binding.name,
209
+ path=binding.path,
210
+ timeout=binding.startup_timeout if binding.startup_timeout is not None else default,
211
+ satisfied=satisfied,
212
+ reads_the_graph=_reads_the_graph(binding),
213
+ )
214
+
215
+
216
+ def _deployment_deadline(machinery_item: Any) -> float:
217
+ """Return the default deadline of the deployment one machinery item is part of.
218
+
219
+ An item outside a Machine of ours gets the :class:`~opensmi.ros2.server.config.ROS2Config`
220
+ default.
221
+ """
222
+ config: Any = getattr(machinery_item, "ros2_config", None) or ROS2Config()
223
+ return float(config.startup_timeout)
224
+
225
+
226
+ def _every_name_is_confirmed(machinery_item: Any, binding: ROS2ParameterBinding) -> bool:
227
+ """Return whether every ROS2 parameter one declaration names is confirmed on its node.
228
+
229
+ A Binding whose mirror is not built yet (a Component mid-init) answers with its node path, so it
230
+ is not satisfied.
231
+ """
232
+ unconfirmed: Any = getattr(machinery_item, "ros2_unconfirmed_parameters", {})
233
+ return unconfirmed.get(binding.name, (binding.path,)) == ()
234
+
235
+
236
+ def _every_node_is_there(machinery_item: Any, binding: LifecycleBinding) -> bool:
237
+ """Return whether every node one lifecycle declaration follows is on the graph.
238
+
239
+ Asked of the Component's own StartupSkill, which follows the nodes.
240
+ """
241
+ try:
242
+ startup: Any = machinery_item.skill_set[BaseStartupSkill.NAME]
243
+ except (AttributeError, KeyError):
244
+ return False
245
+ presence: Any = getattr(startup, "node_presence", {})
246
+ return all(presence.get(path, False) for path in binding.observed)
247
+
248
+
249
+ def _graph_of(machinery_item: Any) -> GraphSnapshot:
250
+ """Return the Runtime's last graph snapshot, or an empty one without a Runtime."""
251
+ runtime = getattr(machinery_item, "runtime", None)
252
+ return EMPTY_GRAPH if runtime is None else runtime.graph.snapshot
253
+
254
+
255
+ async def wait_for(
256
+ prerequisites: Sequence[Prerequisite],
257
+ *,
258
+ report: Callable[[Prerequisite], Awaitable[None]],
259
+ interval: float = CHECK_INTERVAL,
260
+ ) -> tuple[Prerequisite, ...]:
261
+ """Wait until every prerequisite is Satisfied or its own deadline has passed.
262
+
263
+ There is no fail-fast and no shared deadline. A prerequisite that misses its deadline is
264
+ reported at once and counted as missed, even if it arrives later. A prerequisite that is met is
265
+ dropped and not asked again; if it goes away later, the gate's watch reports it as lost.
266
+
267
+ :param prerequisites: What to wait for. Empty returns at once.
268
+ :param report: How to announce one that missed its deadline, awaited at that deadline.
269
+ :param interval: Seconds between two readings.
270
+ :return: The prerequisites that missed their deadlines, in the order they did. Empty means the
271
+ wait was met.
272
+ """
273
+ if not prerequisites:
274
+ return ()
275
+ loop = asyncio.get_running_loop()
276
+ deadlines = {each: loop.time() + each.timeout for each in prerequisites}
277
+ pending = list(prerequisites)
278
+ missed: list[Prerequisite] = []
279
+ while pending:
280
+ now = loop.time()
281
+ waiting: list[Prerequisite] = []
282
+ for each in pending:
283
+ if each.satisfied():
284
+ continue
285
+ if deadlines[each] <= now:
286
+ missed.append(each)
287
+ await report(each)
288
+ continue
289
+ waiting.append(each)
290
+ pending = waiting
291
+ if pending:
292
+ await asyncio.sleep(max(0.0, min(interval, min(deadlines[each] for each in pending) - loop.time())))
293
+ return tuple(missed)
294
+
295
+
296
+ class StartupGate:
297
+ """One machinery item's required Bindings, as the wait and the watch that follow from them.
298
+
299
+ Held by its :class:`ROS2StartupSkill`. :meth:`wait` is called from the starting handler and
300
+ :meth:`close` from the halting one and from shutdown. The graph watch and the loss watcher exist
301
+ only between them.
302
+ """
303
+
304
+ def __init__(self, machinery_item: BaseMachineryItem) -> None:
305
+ """Resolve what this item will wait for, and refuse an item that could not report it.
306
+
307
+ This is resolved at init, not at the first start, because both failures are declaration
308
+ errors. Only how to ask is resolved here, never the answer.
309
+
310
+ :raises DeclarationError: When a required Binding's kind has no answer to what Satisfied
311
+ means for it, or when the item cannot raise a BindingEvent.
312
+ """
313
+ self._item = machinery_item
314
+ self._emit: Any = getattr(machinery_item, "emit_binding_event", None)
315
+ self._prerequisites = prerequisites_of(machinery_item)
316
+ self._watch: GraphWatch | None = None
317
+ self._watcher: asyncio.Task[None] | None = None
318
+ self._lost: set[Prerequisite] = set()
319
+ if self._prerequisites and self._emit is None:
320
+ message = (
321
+ f"{type(machinery_item).__name__} declares a required Binding and cannot raise a "
322
+ f"BindingEvent, which is where a prerequisite that never arrived is reported; a "
323
+ f"machinery item carrying ROS2 Bindings mixes in ROS2ComponentMixin"
324
+ )
325
+ raise DeclarationError(message)
326
+
327
+ @property
328
+ def prerequisites(self) -> tuple[Prerequisite, ...]:
329
+ """Return what this item's StartupSkill waits for, one entry per required Binding."""
330
+ return self._prerequisites
331
+
332
+ @property
333
+ def watching(self) -> bool:
334
+ """Return whether the gate is still following its prerequisites after a startup."""
335
+ return self._watcher is not None
336
+
337
+ async def wait(self) -> None:
338
+ """Wait for every required Binding, then keep an eye on them.
339
+
340
+ It re-runs on every start, so a resume after a crashed stack cannot claim ``Running`` on an
341
+ old check.
342
+
343
+ :raises OpenSmiRuntimeError: When anything missed its deadline, carrying
344
+ :data:`REQUIRED_BINDING_ABSENT` as its code.
345
+ """
346
+ await self.close()
347
+ prerequisites = self._prerequisites
348
+ if not prerequisites:
349
+ return
350
+ try:
351
+ await self._open_the_graph(prerequisites)
352
+ missed = await wait_for(prerequisites, report=self._report_absent)
353
+ except BaseException:
354
+ await self.close()
355
+ raise
356
+ if missed:
357
+ await self.close()
358
+ raise OpenSmiRuntimeError(_verdict(missed), error_code=REQUIRED_BINDING_ABSENT)
359
+ self._watcher = asyncio.create_task(self._follow(prerequisites), name="ros2-required-bindings")
360
+
361
+ async def close(self) -> None:
362
+ """Stop watching and let go of the graph. Idempotent.
363
+
364
+ Called on the way to ``Halted`` and again at shutdown, for a Component torn down while the
365
+ process goes on serving.
366
+ """
367
+ watcher, self._watcher = self._watcher, None
368
+ if watcher is not None:
369
+ watcher.cancel()
370
+ await asyncio.gather(watcher, return_exceptions=True)
371
+ if self._watch is not None:
372
+ await self._watch.close()
373
+ self._watch = None
374
+ self._lost = set()
375
+
376
+ async def _open_the_graph(self, prerequisites: Sequence[Prerequisite]) -> None:
377
+ """Start reading the graph, if anything here can only be answered from it.
378
+
379
+ The watch keeps the facet polling during the wait, and the read stops a service that is
380
+ already there from costing a poll interval. Machines with only topic, parameter or node
381
+ Bindings open neither.
382
+ """
383
+ if not any(each.reads_the_graph for each in prerequisites):
384
+ return
385
+ runtime = cast("Any", self._item).runtime # a Component with Bindings always has one
386
+ self._watch = runtime.graph.watch()
387
+ with contextlib.suppress(Exception):
388
+ # Never fatal: the poll behind the watch retries, and the wait has its own deadline.
389
+ await runtime.graph.refresh()
390
+
391
+ async def _follow(self, prerequisites: Sequence[Prerequisite]) -> None:
392
+ """Report a prerequisite that goes away after startup, and never act on it."""
393
+ while True:
394
+ await asyncio.sleep(LOSS_INTERVAL)
395
+ for each in prerequisites:
396
+ if each.satisfied():
397
+ self._lost.discard(each)
398
+ continue
399
+ if each in self._lost:
400
+ continue
401
+ self._lost.add(each)
402
+ await self._report(
403
+ each,
404
+ REQUIRED_BINDING_LOST,
405
+ Severity.WARNING,
406
+ f"{each.path} was there when {self._item.name} started and is not any more; a "
407
+ f"required Binding lost after startup is reported and never halts, because "
408
+ f"halting would let a restarted node tear this robot down mid-goal",
409
+ )
410
+
411
+ async def _report_absent(self, prerequisite: Prerequisite) -> None:
412
+ """Announce one prerequisite that missed its own deadline."""
413
+ await self._report(
414
+ prerequisite,
415
+ REQUIRED_BINDING_ABSENT,
416
+ Severity.ERROR,
417
+ f"{prerequisite.path} is required by {self._item.name} and was still not satisfied "
418
+ f"{prerequisite.timeout} seconds after its StartupSkill began starting; what is "
419
+ f"waited for is presence -- a publisher, a discovered server, a node answering -- and "
420
+ f"never first data, so this is absent rather than silent",
421
+ )
422
+
423
+ async def _report(self, prerequisite: Prerequisite, code: str, severity: Severity, text: str) -> None:
424
+ """Fire one BindingEvent, and never let the reporting be the fault."""
425
+ try:
426
+ await self._emit(
427
+ binding=prerequisite.binding,
428
+ path=prerequisite.path,
429
+ code=code,
430
+ severity=severity,
431
+ text=text,
432
+ )
433
+ except Exception:
434
+ self._item.logger.exception(
435
+ "Could not fire a BindingEvent about a required Binding",
436
+ binding=prerequisite.binding,
437
+ path=prerequisite.path,
438
+ code=code,
439
+ )
440
+
441
+
442
+ def _verdict(missed: Sequence[Prerequisite]) -> str:
443
+ """Return the fault text of a startup that ran out of time, naming every cause."""
444
+ listed = "; ".join(f"{each.binding} ({each.path}) after {each.timeout}s" for each in missed)
445
+ return (
446
+ f"{listed}. Every required Binding is waited for to its own deadline and the verdict is "
447
+ f"rendered at the last one, so this names every prerequisite that was not met rather "
448
+ f"than the first; recovery is Reset and Start, which checks again"
449
+ )
450
+
451
+
452
+ async def close_startup_skills(machinery_item: Any) -> None:
453
+ """Release every StartupSkill of ours on one machinery item. Idempotent.
454
+
455
+ A Machine's and a Component's shutdown both call it, to release the watch behind a required
456
+ Binding and the lifecycle Skill's subscriptions.
457
+ """
458
+ for skill in getattr(machinery_item, "skill_set", ()):
459
+ if isinstance(skill, ROS2StartupSkill):
460
+ await skill.close_startup()
461
+
462
+
463
+ class ROS2StartupSkill(BaseStartupSkill):
464
+ """The StartupSkill this package gives a machinery item that has not got a narrower one.
465
+
466
+ It stays ``Running`` once started. It waits for this item's required Bindings through the gate
467
+ and starts each child's StartupSkill and waits for it to run, because opensmi's own starting
468
+ handler stops at the first child that did not come up. A Machine gets one unless it
469
+ registers its own. A Component gets one when it declares a required Binding, and
470
+ :class:`opensmi.ros2.server.startup.ROS2LifecycleStartupSkill` when it declares a lifecycle one.
471
+ It is not suspendable, because opensmi's StartupSkill never is.
472
+ """
473
+
474
+ def __init__(self, *, minimum_access_level: int = SKILL_ACCESS_LEVEL, **kwargs: Any) -> None:
475
+ """Take the access level and hand opensmi the rest; the gate is built once there is a parent.
476
+
477
+ The default is the ROS2 settings' ``skill_access_level`` default, not opensmi's 2, because
478
+ the orchestrator must be able to start a machine with no operator present.
479
+
480
+ :param minimum_access_level: The level ``Start``, ``Halt`` and ``Reset`` need.
481
+ """
482
+ super().__init__(minimum_access_level=minimum_access_level, **kwargs)
483
+ self._startup_gate: StartupGate | None = None
484
+ # Trigger tasks fired at children, held so the loop does not collect one mid-transition.
485
+ self._fired: set[asyncio.Task[None]] = set()
486
+
487
+ @property
488
+ def gate(self) -> StartupGate:
489
+ """Return the required Bindings this Skill answers for, as the gate that waits on them."""
490
+ assert self._startup_gate is not None, "the gate is built when the Skill is added to its item"
491
+ return self._startup_gate
492
+
493
+ async def _init(self) -> None:
494
+ """Let opensmi build the Skill, then resolve what its item declared required.
495
+
496
+ :raises DeclarationError: When the item declares a required Binding and cannot raise a
497
+ BindingEvent.
498
+ """
499
+ await super()._init()
500
+ self._startup_gate = StartupGate(self.parent)
501
+
502
+ async def close_startup(self) -> None:
503
+ """Release everything this Skill holds outside the state machine. Idempotent.
504
+
505
+ The declaring item's shutdown calls it; a subclass that holds more releases it here and
506
+ calls up. opensmi's supervision task is stopped too, since it has no shutdown of its own and
507
+ would fail on nodes that are gone.
508
+ """
509
+ if self._startup_gate is not None:
510
+ await self._startup_gate.close()
511
+ status, self._handle_status_change_task = self._handle_status_change_task, None
512
+ if status is not None:
513
+ status.cancel()
514
+ await asyncio.gather(status, return_exceptions=True)
515
+
516
+ async def _handle_starting(self) -> None:
517
+ """Wait for this item's prerequisites, command its own robot, then bring its children up.
518
+
519
+ The prerequisites come first: a managed node that is not on the graph cannot be activated,
520
+ and the Skill should report that it is waiting for the node, not that the node did not
521
+ answer. Each child waits for its own prerequisites in its own handler.
522
+ """
523
+ await self.gate.wait()
524
+ await self._start_the_ros2_side()
525
+ await self._reset_children()
526
+ await self._start_children()
527
+
528
+ async def _start_the_ros2_side(self) -> None:
529
+ """Command whatever this item owns on the ROS2 side. The lifecycle Skill activates its nodes here."""
530
+
531
+ async def _handle_running(self) -> None:
532
+ """Do nothing: a started StartupSkill has nothing left to tick."""
533
+
534
+ async def _handle_halting(self) -> None:
535
+ """Stop answering for the prerequisites, then halt the Components and the other Skills.
536
+
537
+ This is opensmi's own halting handler, minus this Skill. opensmi's ``halt_skills`` waits for
538
+ every Skill of the item to be ``Halted`` and has not got an exception for the caller, so
539
+ called from here it would wait for the halt it is part of and fail after its timeout.
540
+ """
541
+ if self._startup_gate is not None:
542
+ await self._startup_gate.close()
543
+ await self.parent.halt_components()
544
+ await self.parent.halt_skills([skill for skill in self.parent.skill_set if skill is not self])
545
+
546
+ async def _reset_children(self) -> None:
547
+ """Run opensmi's own starting handler, without letting one child be the verdict.
548
+
549
+ Its reset raises at the first Component that halted. That is swallowed here, because
550
+ :meth:`_start_children` names every child that did not come up, and the rest of opensmi's
551
+ housekeeping still has to run.
552
+ """
553
+ try:
554
+ await super()._handle_starting()
555
+ except (OpenSmiError, TimeoutError) as error:
556
+ self.logger.debug(
557
+ "A child did not come up while opensmi was resetting it; the verdict is "
558
+ "rendered once every child has been asked",
559
+ fault=str(error),
560
+ )
561
+ await self.parent.reset_skills()
562
+
563
+ async def _start_children(self) -> None:
564
+ """Start every child's StartupSkill and wait for it to reach ``Running``.
565
+
566
+ :raises OpenSmiRuntimeError: When any child's StartupSkill did not reach ``Running``,
567
+ carrying :data:`COMPONENT_NOT_RUNNING` and naming every one of them.
568
+ """
569
+ faults = [fault for child in self._children() if (fault := await self._bring_up(child)) is not None]
570
+ if not faults:
571
+ return
572
+ message = (
573
+ f"{'; '.join(faults)}. A Machine is Running when its Components are, so a Component "
574
+ f"that did not come up halts this Skill rather than being started around; the "
575
+ f"Component's own StartupSkill and its events say which prerequisite it was waiting for"
576
+ )
577
+ raise OpenSmiRuntimeError(message, error_code=COMPONENT_NOT_RUNNING)
578
+
579
+ def _children(self) -> tuple[Any, ...]:
580
+ """Return the child machinery items that have a StartupSkill of their own, in order."""
581
+ return tuple(child for child in self.parent.components if BaseStartupSkill.NAME in child.skill_set)
582
+
583
+ async def _bring_up(self, child: Any) -> str | None:
584
+ """Bring one child's StartupSkill to ``Running``, and say why if it did not get there.
585
+
586
+ Each step is skipped where it has already happened, since resetting a running Component
587
+ would tear down a working robot.
588
+
589
+ :return: ``None`` when the child is running, or a phrase naming it and where it stopped.
590
+ """
591
+ startup: Any = child.skill_set[BaseStartupSkill.NAME]
592
+ deadline = self._deadline_for(child)
593
+ if startup.current_state is not SkillState.RUNNING:
594
+ if startup.current_state is not SkillState.READY:
595
+ await self._reach(startup, SkillState.READY, deadline, startup.reset(), f"reset-{child.name}")
596
+ if startup.current_state is SkillState.READY:
597
+ await self._reach(startup, SkillState.RUNNING, deadline, startup.start(), f"start-{child.name}")
598
+ if startup.current_state is SkillState.RUNNING:
599
+ return None
600
+ return f"the Component {child.name} is {startup.current_state.localized_text.Text} and not Running"
601
+
602
+ async def _reach(self, skill: Any, target: SkillState, deadline: float, trigger: Any, label: str) -> None:
603
+ """Fire one trigger at another Skill and watch until it settles, wherever that is.
604
+
605
+ The trigger is fired from a task of its own and watched, not awaited: ``AsyncMachine``
606
+ cancels the tasks processing a transition when the next one for that model begins and
607
+ swallows the ``CancelledError``. opensmi's ``wait_for_state`` is not used, because it raises
608
+ on ``Halted`` only if the Skill was not already there, so a child that halted early would
609
+ be reported as a timeout. The caller reads ``CurrentState`` for the verdict.
610
+ """
611
+ task: asyncio.Task[None] = asyncio.create_task(trigger, name=f"ros2-startup-{self.name}-{label}")
612
+ self._fired.add(task)
613
+ task.add_done_callback(self._fired.discard)
614
+ loop = asyncio.get_running_loop()
615
+ until = loop.time() + deadline
616
+ started_from = skill.current_state
617
+ moved = False
618
+ while loop.time() < until:
619
+ await asyncio.sleep(CHECK_INTERVAL)
620
+ state = skill.current_state
621
+ if state is target:
622
+ return
623
+ if task.done() and not task.cancelled() and task.exception() is not None:
624
+ # The trigger was refused and nothing will move, so do not wait out the deadline.
625
+ return
626
+ moved = moved or state is not started_from
627
+ if moved and state in RESTING:
628
+ return
629
+
630
+ def _deadline_for(self, child: Any) -> float:
631
+ """Return how long this Skill waits for one child: its longest required deadline plus ``startup_timeout``."""
632
+ slack = _deployment_deadline(self.parent)
633
+ return slack + max((each.timeout for each in prerequisites_of(child)), default=0.0)