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,582 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The inward mirror: ROS2 messages arrive, and a container's variables follow.
6
+
7
+ A Mirror keeps a UA variable container in sync with a foreign source, and a Binding is the
8
+ declaration that says which source. This mixin is the ROS2 to OPC UA direction, split by direction
9
+ and not by container, so a topic read into Monitoring and an action's feedback read into the same
10
+ place are one job on two sources. For each Binding it opens one subscription through the Runtime,
11
+ asks the mutation chokepoint for the Binding's nodes from the Projection's plan, writes what
12
+ arrives, derives the status code from the subscription's publisher count, and raises one
13
+ BindingEvent per QoS incompatibility. It holds no QoS (an adaptation swaps the ``rclpy``
14
+ subscription beneath a handle this mirror keeps) and no Nodes (it keeps the rendered plan, which knows
15
+ where each value goes).
16
+
17
+ A Binding has its nodes at boot even when its topic is absent from the graph, because the shape
18
+ comes from the declared type and a node that appears later is one a client's subscription never
19
+ recovers. Before the first message a client reads the plan's typed zero under
20
+ ``BadNoCommunication`` (nothing publishes) or ``BadWaitingForInitialData`` (a publisher, no sample);
21
+ the rule is :mod:`opensmi.ros2.server.status`'s. A Binding that declares no type cannot subscribe,
22
+ so it has no nodes at boot and waits on the Runtime's graph facet. When its topic appears it
23
+ subscribes and gains its nodes through the chokepoint, and the watch closes when the last such
24
+ Binding is bound.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ from dataclasses import dataclass, field
31
+ from typing import TYPE_CHECKING, Any, Final
32
+
33
+ from opensmi.ros2.runtime.errors import ROS2RuntimeError
34
+ from opensmi.ros2.runtime.selection import resolve_selection
35
+ from opensmi.ros2.server.errors import DeclarationError, DuplicateBindingNameError
36
+ from opensmi.ros2.server.events import Severity
37
+ from opensmi.ros2.server.mutation import NodeAddition, RenderedPlan, ROS2MutationMixin, ended
38
+ from opensmi.ros2.server.projection import ProjectionContext
39
+ from opensmi.ros2.server.projections import DEFAULT_REGISTRY
40
+ from opensmi.ros2.server.provenance import QOS_INCOMPATIBLE, BindingQoS, qos_clash_text
41
+ from opensmi.ros2.server.status import status_code
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Iterable, Mapping
45
+
46
+ from asyncua import ua
47
+
48
+ from opensmi.ros2.runtime.graph import GraphWatch
49
+ from opensmi.ros2.runtime.interface import RuntimeInterface
50
+ from opensmi.ros2.runtime.messages import Message
51
+ from opensmi.ros2.runtime.subscription import Subscription
52
+ from opensmi.ros2.server.bindings import MonitoringBinding
53
+ from opensmi.ros2.server.projection import Projection, ProjectionRegistry
54
+
55
+ __all__ = ["AMBIGUOUS_TOPIC_TYPE", "PAYLOAD_CAPPED", "UNUSABLE_TOPIC_TYPE", "ROS2InwardMirrorMixin"]
56
+
57
+ AMBIGUOUS_TOPIC_TYPE: Final = "AMBIGUOUS_TOPIC_TYPE"
58
+ """What an undeclared-type Binding reports when its topic carries more than one type.
59
+
60
+ It is reported and waited out, not resolved. The Binding stays unbound and binds if the disagreement
61
+ goes away.
62
+ """
63
+
64
+ PAYLOAD_CAPPED: Final = "PAYLOAD_CAPPED"
65
+ """What a Binding reports when a bulk payload reached this server's byte-string ceiling.
66
+
67
+ The cap itself is applied by the Projection. The event is reported once per Binding, so a 100 Hz
68
+ stream does not become an event storm.
69
+ """
70
+
71
+ UNUSABLE_TOPIC_TYPE: Final = "UNUSABLE_TOPIC_TYPE"
72
+ """What an undeclared-type Binding reports when the type its topic carries cannot be bound.
73
+
74
+ For a declared type these faults (a missing interface package, a selection matching nothing, a field
75
+ with no rendering) are fatal at init. Here the type arrived at run time, so the fault is reported
76
+ and the Binding is given up on.
77
+ """
78
+
79
+
80
+ @dataclass(slots=True)
81
+ class _Mirrored:
82
+ """One Binding, live: its subscription, what to write where, and the tasks doing it."""
83
+
84
+ binding: MonitoringBinding
85
+ subscription: Subscription
86
+ projection: Projection
87
+ context: ProjectionContext
88
+ nodes: RenderedPlan
89
+ # The last value of each entry of the plan, so a message is written whole and a status change with a typed
90
+ # value. Seeded with the plan's initials.
91
+ values: dict[str, object] = field(default_factory=dict)
92
+ writing: asyncio.Lock = field(default_factory=asyncio.Lock)
93
+ task: asyncio.Task[None] | None = None
94
+ status_task: asyncio.Task[None] | None = None
95
+ qos_task: asyncio.Task[None] | None = None
96
+ satisfied: bool = False
97
+ sampled: bool = False
98
+ reported_unknown_name: bool = False
99
+ reported_capped_payload: bool = False
100
+
101
+ def __post_init__(self) -> None:
102
+ """Start out holding the value each variable was declared with."""
103
+ self.values = self.nodes.initial
104
+
105
+ @property
106
+ def status(self) -> ua.StatusCode:
107
+ """Return the status code every variable of this Binding currently reads."""
108
+ return status_code(satisfied=self.satisfied, sampled=self.sampled)
109
+
110
+ @property
111
+ def qos(self) -> BindingQoS:
112
+ """Return this Binding's provenance entry, built from the subscription it is about."""
113
+ return BindingQoS.of(
114
+ self.binding.name,
115
+ self.binding.path,
116
+ self.subscription,
117
+ self.subscription.qos_incompatibilities,
118
+ )
119
+
120
+ def cancel(self) -> None:
121
+ """Ask this Binding's three tasks to stop, without waiting for any of them."""
122
+ for task in (self.task, self.status_task, self.qos_task):
123
+ if task is not None:
124
+ task.cancel()
125
+
126
+
127
+ async def _stopped(mirrored: _Mirrored) -> None:
128
+ """Stop following one Binding and close its subscription. Idempotent."""
129
+ mirrored.cancel()
130
+ await ended(mirrored.task)
131
+ await ended(mirrored.status_task)
132
+ await ended(mirrored.qos_task)
133
+ mirrored.task = mirrored.status_task = mirrored.qos_task = None
134
+ await mirrored.subscription.close()
135
+
136
+
137
+ class ROS2InwardMirrorMixin(ROS2MutationMixin):
138
+ """Keeps a machinery item's Monitoring variables in sync with the topics it declared.
139
+
140
+ Creating nodes is the mutation chokepoint's job, which this extends. Writing to them is this
141
+ mixin's.
142
+ """
143
+
144
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
145
+ """Start out mirroring nothing, and pass every argument to opensmi's constructor."""
146
+ super().__init__(*args, **kwargs)
147
+ self._mirrored: list[_Mirrored] = []
148
+ self._deferred: list[MonitoringBinding] = []
149
+ self._graph_watch: GraphWatch | None = None
150
+ self._graph_task: asyncio.Task[None] | None = None
151
+ self._runtime: RuntimeInterface | None = None
152
+ self._registry: ProjectionRegistry = DEFAULT_REGISTRY
153
+
154
+ @property
155
+ def ros2_subscriptions(self) -> tuple[Subscription, ...]:
156
+ """Return the subscription each bound Binding on this item opened, in the order they bound."""
157
+ return tuple(each.subscription for each in self._mirrored)
158
+
159
+ @property
160
+ def ros2_monitoring_presence(self) -> Mapping[str, bool]:
161
+ """Return, per Binding name, whether its topic has a publisher right now.
162
+
163
+ This is Satisfied for a topic read into Monitoring: presence, never first data. It is the
164
+ count the status code is written from, so a required Binding and its variables agree.
165
+ A Binding that declared no type and whose topic has not appeared is ``False``,
166
+ not missing.
167
+ """
168
+ deferred = {binding.name: False for binding in self._deferred}
169
+ return {**deferred, **{each.binding.name: each.satisfied for each in self._mirrored}}
170
+
171
+ @property
172
+ def ros2_qos_provenance(self) -> Mapping[str, BindingQoS]:
173
+ """Return, per Binding name, what its subscription asks for and where that came from.
174
+
175
+ A Binding still waiting for its topic is absent, because it has no endpoint yet.
176
+ """
177
+ return {each.binding.name: each.qos for each in self._mirrored}
178
+
179
+ @property
180
+ def ros2_unbound_bindings(self) -> tuple[MonitoringBinding, ...]:
181
+ """Return the Bindings still waiting for their topic to appear on the graph.
182
+
183
+ Empty on a Machine whose declarations all name their type, which then never reads the graph.
184
+ """
185
+ return tuple(self._deferred)
186
+
187
+ async def bind_topic_now(self, binding: MonitoringBinding, *, message_type: str) -> bool:
188
+ """Open one Binding while the server runs, and give it its nodes.
189
+
190
+ This is the client-driven exception. It lives here and not on the introspection
191
+ Component, so that an ad-hoc Binding is built exactly like a declared one.
192
+
193
+ :param binding: What to bind. Its ``name`` is what its variables are named for. It lives
194
+ until the server restarts.
195
+ :param message_type: The ROS2 type to subscribe with. It is required, because the caller has
196
+ just read it off the graph and a run-time Binding has no init at which a declared type
197
+ could be refused.
198
+ :return: Whether it happened. ``False`` means a mutation cap refused the nodes and the
199
+ subscription was closed again.
200
+ :raises DuplicateBindingNameError: When this item already has a Binding of that name.
201
+ :raises ROS2RuntimeError: When the type cannot be resolved or the subscription cannot be
202
+ opened.
203
+ :raises DeclarationError: When the Binding cannot be shaped (a selection matching nothing, a
204
+ field with no rendering).
205
+ """
206
+ self._require_an_unused_binding_name(binding.name)
207
+ opened = await self._open_binding(binding, message_type=message_type, at_init=False)
208
+ if opened is None:
209
+ return False
210
+ self._mirrored.append(opened)
211
+ await self._start_following(opened)
212
+ return True
213
+
214
+ def _require_an_unused_binding_name(self, name: str) -> None:
215
+ """Refuse a second Binding of one name on this item.
216
+
217
+ :raises DuplicateBindingNameError: When one is already bound or still waiting for its topic.
218
+ Without this check the chokepoint would refuse the first colliding variable and name a
219
+ field path instead of the Binding.
220
+ """
221
+ taken = {each.binding.name for each in self._mirrored} | {each.name for each in self._deferred}
222
+ if name not in taken:
223
+ return
224
+ message = (
225
+ f"{type(self).__name__} already has a Binding called {name!r}; a Binding's name is "
226
+ f"what its variables are named for, so two of one name would be one set of nodes "
227
+ f"with two things writing to it"
228
+ )
229
+ raise DuplicateBindingNameError(message)
230
+
231
+ async def _init_monitoring_mirror(
232
+ self,
233
+ bindings: Iterable[MonitoringBinding],
234
+ *,
235
+ runtime: RuntimeInterface,
236
+ registry: ProjectionRegistry = DEFAULT_REGISTRY,
237
+ ) -> None:
238
+ """Open, shape and start every Binding that declared a type, in declaration order.
239
+
240
+ Anything wrong with such a declaration is fatal at init (a missing interface package, a
241
+ pattern matching nothing, a field with no rendering, a name written twice), and whatever was
242
+ already opened is closed first. A Binding that declared no type is put aside, and one watch
243
+ on the graph facet covers all of them.
244
+ """
245
+ self._runtime = runtime
246
+ self._registry = registry
247
+ try:
248
+ for binding in bindings:
249
+ if binding.needs_the_graph:
250
+ self._deferred.append(binding)
251
+ continue
252
+ assert binding.message_type is not None, "only a Binding without a type needs the graph"
253
+ opened = await self._open_binding(binding, message_type=binding.message_type, at_init=True)
254
+ if opened is not None:
255
+ self._mirrored.append(opened)
256
+ except BaseException:
257
+ await self._stop_monitoring_mirror()
258
+ raise
259
+ for mirrored in self._mirrored:
260
+ await self._start_following(mirrored)
261
+ self._start_watching_the_graph()
262
+
263
+ async def _stop_monitoring_mirror(self) -> None:
264
+ """Stop following every Binding, close its subscription, and let go of the graph.
265
+
266
+ Idempotent. It runs before the Runtime stops, because a Component torn down on its own still
267
+ has to stop reading.
268
+ """
269
+ await ended(self._graph_task)
270
+ self._graph_task = None
271
+ if self._graph_watch is not None:
272
+ await self._graph_watch.close()
273
+ self._graph_watch = None
274
+ self._deferred = []
275
+ # Cancelled in one pass before any is awaited, so teardown does not wait out each Binding's tasks in
276
+ # turn.
277
+ for mirrored in self._mirrored:
278
+ mirrored.cancel()
279
+ for mirrored in self._mirrored:
280
+ await _stopped(mirrored)
281
+ self._mirrored = []
282
+
283
+ async def _start_following(self, mirrored: _Mirrored) -> None:
284
+ """Put the first status on one Binding's variables, then start its tasks.
285
+
286
+ The status is written here and not left to the publisher task, so the variables carry
287
+ ``BadNoCommunication`` from the moment they exist and never the ``Good`` that node creation
288
+ leaves.
289
+ """
290
+ await self._write_status(mirrored)
291
+ name = mirrored.binding.name
292
+ mirrored.task = asyncio.create_task(self._follow_binding(mirrored), name=f"ros2-monitoring-{name}")
293
+ mirrored.status_task = asyncio.create_task(self._follow_publishers(mirrored), name=f"ros2-publishers-{name}")
294
+ mirrored.qos_task = asyncio.create_task(self._follow_qos(mirrored), name=f"ros2-qos-{name}")
295
+
296
+ def _start_watching_the_graph(self) -> None:
297
+ """Open one watch covering every Binding still waiting for its topic, if there are any.
298
+
299
+ With none, nothing is opened: the facet reads the graph only while a watch is open.
300
+ """
301
+ if not self._deferred or self._runtime is None:
302
+ return
303
+ self._graph_watch = self._runtime.graph.watch()
304
+ self._graph_task = asyncio.create_task(self._follow_graph(), name="ros2-monitoring-graph")
305
+
306
+ async def _follow_graph(self) -> None:
307
+ """Bind each waiting Binding as its topic appears, then stop watching."""
308
+ watch = self._graph_watch
309
+ if watch is None: # pragma: no cover -- the caller opens it before starting this task
310
+ return
311
+ async for delta in watch:
312
+ for binding in tuple(self._deferred):
313
+ # Appearing and being retyped both answer the Binding's question, what its topic carries. A
314
+ # cleared `AMBIGUOUS_TOPIC_TYPE` arrives as the second.
315
+ types = delta.topics.types_now_on(binding.path)
316
+ if types is None:
317
+ continue
318
+ try:
319
+ await self._bind_from_the_graph(binding, types)
320
+ except Exception:
321
+ # A runtime condition is never fatal, and an unreported failure on this
322
+ # unawaited task would end the poll silently.
323
+ self.logger.exception(
324
+ "Could not bind a topic that appeared on the graph",
325
+ binding=binding.name,
326
+ topic=binding.path,
327
+ )
328
+ if not self._deferred:
329
+ # Nothing is waiting any more, so nothing needs the graph read again.
330
+ await watch.close()
331
+ return
332
+
333
+ async def _bind_from_the_graph(self, binding: MonitoringBinding, types: tuple[str, ...]) -> None:
334
+ """Give one waiting Binding its subscription and its nodes, or report why it has neither."""
335
+ if len(types) != 1:
336
+ listed = ", ".join(types)
337
+ await self.emit_binding_event(
338
+ binding=binding.name,
339
+ path=binding.path,
340
+ code=AMBIGUOUS_TOPIC_TYPE,
341
+ severity=Severity.WARNING,
342
+ text=f"{binding.path} carries more than one type ({listed}), so its shape is not decidable",
343
+ )
344
+ return
345
+ try:
346
+ opened = await self._open_binding(binding, message_type=types[0], at_init=False)
347
+ except (ROS2RuntimeError, DeclarationError) as error:
348
+ self._deferred.remove(binding)
349
+ await self.emit_binding_event(
350
+ binding=binding.name,
351
+ path=binding.path,
352
+ code=UNUSABLE_TOPIC_TYPE,
353
+ severity=Severity.ERROR,
354
+ text=f"{binding.path} carries {types[0]}, which this Binding cannot be built from: {error}",
355
+ )
356
+ return
357
+ self._deferred.remove(binding)
358
+ if opened is None:
359
+ return
360
+ self._mirrored.append(opened)
361
+ await self._start_following(opened)
362
+
363
+ async def _open_binding(
364
+ self,
365
+ binding: MonitoringBinding,
366
+ *,
367
+ message_type: str,
368
+ at_init: bool,
369
+ ) -> _Mirrored | None:
370
+ """Subscribe, shape the plan, and ask the chokepoint for the nodes of one Binding.
371
+
372
+ :return: The live Binding, or ``None`` when a cap refused its nodes (the subscription is
373
+ closed again).
374
+ """
375
+ runtime = self._require_runtime()
376
+ subscription = await runtime.subscribe(
377
+ topic=binding.path,
378
+ message_type=message_type,
379
+ depth=binding.depth,
380
+ qos=binding.qos,
381
+ )
382
+ try:
383
+ resolved_type = subscription.message_type
384
+ context = ProjectionContext(
385
+ registry=self._registry,
386
+ selected=resolve_selection(resolved_type, binding.selection),
387
+ qualifier=self.ros2_projection_qualifier,
388
+ byte_string_ceiling=self._byte_string_ceiling,
389
+ )
390
+ projection = self._registry.find(resolved_type.ros2.type_name)
391
+ [nodes] = await self.mutate_address_space(
392
+ [
393
+ NodeAddition(
394
+ binding=binding.name,
395
+ path=binding.path,
396
+ container=self.monitoring,
397
+ plan=projection.shape(resolved_type, context),
398
+ message_type=resolved_type,
399
+ root=binding.name,
400
+ group=binding.group,
401
+ )
402
+ ],
403
+ at_init=at_init,
404
+ )
405
+ except BaseException:
406
+ await subscription.close()
407
+ raise
408
+ if nodes is None:
409
+ await subscription.close()
410
+ return None
411
+ return _Mirrored(
412
+ binding=binding,
413
+ subscription=subscription,
414
+ projection=projection,
415
+ context=context,
416
+ nodes=nodes,
417
+ )
418
+
419
+ def _require_runtime(self) -> RuntimeInterface:
420
+ """Return the Runtime this mirror was initialised with.
421
+
422
+ :raises DeclarationError: When there is none (a wiring fault).
423
+ """
424
+ if self._runtime is None: # pragma: no cover -- every path here runs after init
425
+ message = f"{type(self).__name__} has no Runtime; its Monitoring was never initialised"
426
+ raise DeclarationError(message)
427
+ return self._runtime
428
+
429
+ async def _follow_binding(self, mirrored: _Mirrored) -> None:
430
+ """Write the messages of one Binding until the subscription closes, throttled by ``max_rate``."""
431
+ if mirrored.binding.max_rate is not None:
432
+ await self._follow_binding_limited(mirrored, 1.0 / mirrored.binding.max_rate)
433
+ return
434
+ async for message in mirrored.subscription:
435
+ await self._write_message_safely(mirrored, message)
436
+
437
+ async def _follow_binding_limited(self, mirrored: _Mirrored, window: float) -> None:
438
+ """Write at most one message per ``window`` seconds: the newest, never losing the last.
439
+
440
+ The first message after a quiet spell is written at once. A message arriving inside a window
441
+ replaces the one waiting, and the waiting one is written when the window ends. The throttle
442
+ sits in front of the Projection, so a replaced message is never decoded.
443
+ """
444
+ loop = asyncio.get_running_loop()
445
+ messages = aiter(mirrored.subscription)
446
+ arrival = asyncio.ensure_future(anext(messages))
447
+ waiting: Message | None = None
448
+ open_at = 0.0 # the earliest moment the next write may happen
449
+ try:
450
+ while True:
451
+ timeout = None if waiting is None else max(0.0, open_at - loop.time())
452
+ done, _ = await asyncio.wait({arrival}, timeout=timeout)
453
+ if arrival in done:
454
+ try:
455
+ message = arrival.result()
456
+ except StopAsyncIteration:
457
+ return
458
+ arrival = asyncio.ensure_future(anext(messages))
459
+ if loop.time() < open_at:
460
+ waiting = message
461
+ continue
462
+ elif waiting is not None:
463
+ message = waiting
464
+ else: # pragma: no cover -- no timeout means no waiting message, and then arrival is all we wait on
465
+ continue
466
+ waiting = None
467
+ open_at = loop.time() + window
468
+ await self._write_message_safely(mirrored, message)
469
+ finally:
470
+ arrival.cancel()
471
+
472
+ async def _write_message_safely(self, mirrored: _Mirrored, message: Message) -> None:
473
+ """Write one message, and survive whatever it could not be written as."""
474
+ try:
475
+ await self._write_message(mirrored, message)
476
+ except Exception:
477
+ # A runtime condition is never fatal. One unwritable value must not end the stream.
478
+ self.logger.exception(
479
+ "Could not write a message to its Monitoring variables",
480
+ binding=mirrored.binding.name,
481
+ topic=mirrored.binding.path,
482
+ )
483
+
484
+ async def _follow_publishers(self, mirrored: _Mirrored) -> None:
485
+ """Write the status code every time the topic gains or loses its publishers.
486
+
487
+ The count arrives on the subscription's DDS match events, without reading the graph. The
488
+ first one arrives at once, so a Binding nobody publishes starts at ``BadNoCommunication``.
489
+ """
490
+ async for count in mirrored.subscription.publisher_counts():
491
+ mirrored.satisfied = count > 0
492
+ try:
493
+ await self._write_status(mirrored)
494
+ except Exception:
495
+ self.logger.exception(
496
+ "Could not write a status code to its Monitoring variables",
497
+ binding=mirrored.binding.name,
498
+ topic=mirrored.binding.path,
499
+ )
500
+
501
+ async def _follow_qos(self, mirrored: _Mirrored) -> None:
502
+ """Raise one BindingEvent for every QoS incompatibility the middleware reports.
503
+
504
+ Any adaptation has already happened beneath the handle. The event tells a client that it
505
+ happened, on which policy, and whether anything will change.
506
+ """
507
+ async for incompatibility in mirrored.subscription.follow_qos_incompatibilities():
508
+ try:
509
+ await self.emit_binding_event(
510
+ binding=mirrored.binding.name,
511
+ path=mirrored.binding.path,
512
+ code=QOS_INCOMPATIBLE,
513
+ severity=Severity.WARNING if incompatibility.adapted is not None else Severity.ERROR,
514
+ text=qos_clash_text(mirrored.binding.path, incompatibility),
515
+ )
516
+ except Exception:
517
+ # A runtime condition is never fatal; a failed event must not end the stream.
518
+ self.logger.exception(
519
+ "Could not report a QoS incompatibility",
520
+ binding=mirrored.binding.name,
521
+ topic=mirrored.binding.path,
522
+ )
523
+
524
+ async def _write_message(self, mirrored: _Mirrored, message: Message) -> None:
525
+ """Decode one message and write it once, to the nodes of its Binding."""
526
+ async with mirrored.writing:
527
+ mirrored.sampled = True
528
+ for name, value in mirrored.projection.decode(message, mirrored.context).items():
529
+ if name not in mirrored.nodes.entries:
530
+ self._report_unknown_name(mirrored, name)
531
+ continue
532
+ mirrored.values[name] = value
533
+ await self._report_a_capped_payload(mirrored, name, value)
534
+ await mirrored.nodes.write(mirrored.values, mirrored.status)
535
+
536
+ async def _write_status(self, mirrored: _Mirrored) -> None:
537
+ """Re-write every node of one Binding under the status its publishers now imply.
538
+
539
+ The value goes with it, because a status written alone leaves the variant null.
540
+ """
541
+ async with mirrored.writing:
542
+ await mirrored.nodes.write(mirrored.values, mirrored.status)
543
+
544
+ async def _report_a_capped_payload(self, mirrored: _Mirrored, name: str, value: object) -> None:
545
+ """Say once, as a BindingEvent, that a bulk payload reached this server's ceiling.
546
+
547
+ The test is the length against the ceiling, because the cap is applied in a pure function
548
+ that cannot report. A buffer as long as the ceiling is a cut one.
549
+ """
550
+ ceiling = self._byte_string_ceiling
551
+ if mirrored.reported_capped_payload or not ceiling:
552
+ return
553
+ if not isinstance(value, (bytes, bytearray)) or len(value) < ceiling:
554
+ return
555
+ mirrored.reported_capped_payload = True
556
+ await self.emit_binding_event(
557
+ binding=mirrored.binding.name,
558
+ path=mirrored.binding.path,
559
+ code=PAYLOAD_CAPPED,
560
+ severity=Severity.WARNING,
561
+ text=(
562
+ f"{name} reached this server's byte-string ceiling of {ceiling} bytes; a payload "
563
+ f"larger than that is cut to it, and the ceiling is on the server's "
564
+ f"MaxByteStringLength"
565
+ ),
566
+ )
567
+
568
+ def _report_unknown_name(self, mirrored: _Mirrored, name: str) -> None:
569
+ """Report, once per Binding, a Projection whose decode names what its shape never created.
570
+
571
+ Unreachable with the shipped Projection. A curated one whose halves disagree is exposed only
572
+ by a message, so it is reported instead of raised, and the value is not written.
573
+ """
574
+ if mirrored.reported_unknown_name:
575
+ return
576
+ mirrored.reported_unknown_name = True
577
+ self.logger.error(
578
+ "A Projection decoded a name its shape never created; those values are not written",
579
+ binding=mirrored.binding.name,
580
+ projection=mirrored.projection.type_name,
581
+ name=name,
582
+ )