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,749 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Keyed Binding: one ROS2 path, many OPC UA objects, membership taken from the messages.
6
+
7
+ A Keyed Binding's message carries a repeated field, and a key inside each element names the object
8
+ it belongs to: ``/diagnostics`` keyed by ``status[]`` on ``hardware_id`` and ``name``. Membership
9
+ is the content-driven case. Each member is a variable group in the Binding's Monitoring that
10
+ carries the variables the element type's Projection shapes (a nested message is a complex
11
+ Variable), browses under its key with the characters of a RelativePath replaced
12
+ (:func:`member_browse_name`), shows the raw key as its DisplayName and holds it as a ``String[]``
13
+ variable. The Binding's name is the group above the members. Members are created
14
+ through the mutation chokepoint, so the caps and one model-change event per batch apply, and they
15
+ are never removed. Two keys that sanitise to one browse name are reported once as a BindingEvent
16
+ and the second gets no member.
17
+
18
+ An optional declared state field adds two things: a BindingEvent when a member's state changes
19
+ (at the severity the declaration maps it to), and one variable holding the highest state any
20
+ member holds. Nothing reads the aggregate back, so a foreign publisher cannot halt a Machine
21
+ . The mechanism is generic and has no diagnostics-specific code.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import re
28
+ from dataclasses import dataclass, field, replace
29
+ from typing import TYPE_CHECKING, Any, Final, TypeGuard
30
+
31
+ from asyncua import ua
32
+
33
+ from opensmi.ros2.runtime.messages import is_single_value, repeated_message
34
+ from opensmi.ros2.runtime.selection import resolve_selection
35
+ from opensmi.ros2.server.errors import DeclarationError, UnprojectableFieldError
36
+ from opensmi.ros2.server.events import Severity
37
+ from opensmi.ros2.server.mutation import NodeAddition, RenderedPlan, ROS2MutationMixin, ended, require_unused_name
38
+ from opensmi.ros2.server.projection import (
39
+ EnumDataType,
40
+ PlanVariable,
41
+ ProjectionContext,
42
+ )
43
+ from opensmi.ros2.server.projections import DEFAULT_REGISTRY
44
+ from opensmi.ros2.server.provenance import QOS_INCOMPATIBLE, BindingQoS, qos_clash_text
45
+ from opensmi.ros2.server.status import status_code
46
+
47
+ if TYPE_CHECKING:
48
+ from collections.abc import Iterable, Mapping, Sequence
49
+
50
+ from opensmi.server.ua_variable_containers import UaVariableContainer
51
+
52
+ from opensmi.ros2.runtime.interface import RuntimeInterface
53
+ from opensmi.ros2.runtime.messages import Message
54
+ from opensmi.ros2.runtime.subscription import Subscription
55
+ from opensmi.ros2.server.bindings import KeyedBinding
56
+ from opensmi.ros2.server.projection import PlanEntry, Projection, ProjectionRegistry
57
+
58
+ __all__ = [
59
+ "KEY",
60
+ "KEY_COLLISION",
61
+ "MEMBER_STATE_CHANGED",
62
+ "ROS2KeyedMirrorMixin",
63
+ "member_browse_name",
64
+ "member_key",
65
+ "severity_of",
66
+ "state_changed",
67
+ "worst_state",
68
+ ]
69
+
70
+ KEY: Final = "Key"
71
+ """The browse name of the raw-key variable on every member (DisplayName ``key``).
72
+
73
+ A Binding whose element type already has a field that browses as this is refused at init.
74
+ """
75
+
76
+ _KEY_DISPLAY: Final = "key"
77
+ """The DisplayName of the raw-key variable."""
78
+
79
+ KEY_COLLISION: Final = "KEY_COLLISION"
80
+ """The BindingEvent code a second key that sanitises onto an existing member carries."""
81
+
82
+ MEMBER_STATE_CHANGED: Final = "MEMBER_STATE_CHANGED"
83
+ """The BindingEvent code a member's declared state field changing value carries."""
84
+
85
+ WORST: Final = "Worst"
86
+ """What the aggregate variable's name is built from: ``Worst<State>``, such as ``WorstLevel``."""
87
+
88
+ _UNNAMED: Final = "unnamed"
89
+ """What a key with nothing usable in it browses as, because refusing would drop the member."""
90
+
91
+ _RESERVED: Final = re.compile(r"[/.<>:#!&]")
92
+ """The characters the OPC UA RelativePath text form reserves. Each in a member's key becomes one
93
+ underscore, so a generic client never has to escape a key."""
94
+
95
+
96
+ def _is_a_number(value: object) -> TypeGuard[int]:
97
+ """Return whether a state value is a number to order and look labels or bands up by.
98
+
99
+ ``bool`` is excluded: a state field is not a flag.
100
+ """
101
+ return isinstance(value, int) and not isinstance(value, bool)
102
+
103
+
104
+ def member_key(element: Message, key_fields: Sequence[str]) -> tuple[str, ...]:
105
+ """Return the key one element of a repeated field carries, field by field.
106
+
107
+ The fields are read in declaration order and rendered as text. Key fields are validated as
108
+ scalar leaves when the Binding is built.
109
+
110
+ :param element: One element of the Binding's repeated field, as it crossed the seam.
111
+ :param key_fields: The ROS2 field names the declaration keys on.
112
+ """
113
+ return tuple(str(getattr(element, name)) for name in key_fields)
114
+
115
+
116
+ def member_browse_name(key: Sequence[str]) -> str:
117
+ """Return the browse name a member is filed under: each reserved character of its key becomes ``_``.
118
+
119
+ The parts of a multi-field key are joined with ``_``. ``"robot 1: left motor"`` browses as
120
+ ``"robot 1_ left motor"`` and the raw key is the DisplayName. The mapping is not injective, and
121
+ the caller refuses a collision.
122
+ """
123
+ return "_".join(_RESERVED.sub("_", part) for part in key) or _UNNAMED
124
+
125
+
126
+ def state_changed(previous: object, current: object) -> bool:
127
+ """Return whether writing ``current`` over ``previous`` is a transition worth an event.
128
+
129
+ A member is created holding the plan's initial (for a level, the first declared constant), so a
130
+ healthy unit announces nothing when it first appears and a broken one does.
131
+ """
132
+ return previous != current
133
+
134
+
135
+ def worst_state(states: Iterable[object], *, initial: object) -> object:
136
+ """Return the highest state any member holds, or ``initial`` when no member holds one.
137
+
138
+ Highest by the ROS2 constants' numbering, which for ``DiagnosticStatus`` is the worst level.
139
+ Non-numeric states have no order, so the aggregate stays at ``initial``.
140
+
141
+ :param states: What each member's state variable currently reads.
142
+ :param initial: What the aggregate was created holding, which is what an empty set reads.
143
+ """
144
+ numbers = [each for each in states if _is_a_number(each)]
145
+ return max(numbers) if numbers else initial
146
+
147
+
148
+ def severity_of(state: object, severities: Mapping[int, Severity]) -> Severity:
149
+ """Return the house band a transition into one state is reported at.
150
+
151
+ The map comes from the declaration (see :class:`~opensmi.ros2.server.events.Severity`). With no
152
+ map every transition is ``INFO``; with a map, a value outside it is a ``WARNING``.
153
+ """
154
+ if not severities:
155
+ return Severity.INFO
156
+ if _is_a_number(state) and state in severities:
157
+ return severities[state]
158
+ return Severity.WARNING
159
+
160
+
161
+ @dataclass(slots=True)
162
+ class _Member:
163
+ """One member of a Keyed Binding: its key, the nodes it became, and what they read."""
164
+
165
+ key: tuple[str, ...]
166
+ browse: str
167
+ rendered: RenderedPlan
168
+ values: dict[str, object] = field(default_factory=dict)
169
+
170
+ def __post_init__(self) -> None:
171
+ """Start out holding whatever the plan created each variable with."""
172
+ self.values = self.rendered.initial
173
+
174
+
175
+ @dataclass(slots=True)
176
+ class _Keyed:
177
+ """One Keyed Binding, live: its subscription, the plan each member is built from, its members."""
178
+
179
+ binding: KeyedBinding
180
+ subscription: Subscription
181
+ projection: Projection
182
+ context: ProjectionContext
183
+ element_type: type[Message]
184
+ group: UaVariableContainer
185
+ plan: tuple[PlanEntry, ...]
186
+ state_name: str | None
187
+ aggregate: PlanVariable | None
188
+ aggregate_name: str | None
189
+ aggregate_nodes: RenderedPlan | None = None
190
+ members: dict[tuple[str, ...], _Member] = field(default_factory=dict)
191
+ claimed: dict[str, tuple[str, ...]] = field(default_factory=dict)
192
+ refused: set[tuple[str, ...]] = field(default_factory=set)
193
+ aggregate_value: object = None
194
+ writing: asyncio.Lock = field(default_factory=asyncio.Lock)
195
+ task: asyncio.Task[None] | None = None
196
+ status_task: asyncio.Task[None] | None = None
197
+ qos_task: asyncio.Task[None] | None = None
198
+ satisfied: bool = False
199
+ sampled: bool = False
200
+ capped: bool = False
201
+ reported_unknown_name: bool = False
202
+
203
+ def __post_init__(self) -> None:
204
+ """Start out with the aggregate reading what its node was created holding."""
205
+ self.aggregate_value = None if self.aggregate is None else self.aggregate.initial
206
+
207
+ @property
208
+ def status(self) -> ua.StatusCode:
209
+ """Return the status code every variable of this Binding currently reads."""
210
+ return status_code(satisfied=self.satisfied, sampled=self.sampled)
211
+
212
+ def elements(self, message: Message) -> tuple[Message, ...]:
213
+ """Return the repeated field of one message, which is the Binding's whole subject."""
214
+ return tuple(getattr(message, self.binding.repeated_field))
215
+
216
+ def state_of(self, member: _Member) -> object:
217
+ """Return what one member's declared state variable reads, or ``None`` if there is none."""
218
+ if self.state_name is None:
219
+ return None
220
+ return member.values.get(self.state_name)
221
+
222
+
223
+ class ROS2KeyedMirrorMixin(ROS2MutationMixin):
224
+ """Keeps a machinery item's Keyed Bindings' members in sync with what arrives on their topics.
225
+
226
+ Mixed in ahead of opensmi's class. The mutation chokepoint it extends creates the nodes; this
227
+ mixin decides which nodes there should be. It runs loops parallel to the inward mirror's
228
+ (stream, publisher count, QoS) on purpose, since sharing them would need a callback at every
229
+ step.
230
+ """
231
+
232
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
233
+ """Start out with no Keyed Bindings, and pass every argument to opensmi."""
234
+ super().__init__(*args, **kwargs)
235
+ self._keyed: list[_Keyed] = []
236
+ self._keyed_runtime: RuntimeInterface | None = None
237
+ self._keyed_registry: ProjectionRegistry = DEFAULT_REGISTRY
238
+
239
+ @property
240
+ def ros2_keyed_presence(self) -> Mapping[str, bool]:
241
+ """Return, per Keyed Binding name, whether its topic has a publisher right now.
242
+
243
+ Presence works as for a topic read into Monitoring and does not depend on membership: a
244
+ Binding with a publisher but no member yet is a robot with nothing to report.
245
+ """
246
+ return {each.binding.name: each.satisfied for each in self._keyed}
247
+
248
+ @property
249
+ def ros2_members(self) -> Mapping[str, tuple[str, ...]]:
250
+ """Return, per Keyed Binding name, the browse name of each member it has created.
251
+
252
+ In creation order. Members are append-only, so this only grows.
253
+ """
254
+ return {each.binding.name: tuple(member.browse for member in each.members.values()) for each in self._keyed}
255
+
256
+ @property
257
+ def ros2_keyed_qos_provenance(self) -> Mapping[str, BindingQoS]:
258
+ """Return, per Keyed Binding name, what its subscription asks for and where it came from.
259
+
260
+ The counterpart of
261
+ :attr:`~opensmi.ros2.server.mirror.ROS2InwardMirrorMixin.ros2_qos_provenance`.
262
+ """
263
+ return {
264
+ each.binding.name: BindingQoS.of(
265
+ each.binding.name,
266
+ each.binding.path,
267
+ each.subscription,
268
+ each.subscription.qos_incompatibilities,
269
+ )
270
+ for each in self._keyed
271
+ }
272
+
273
+ async def _init_keyed_mirror(
274
+ self,
275
+ bindings: Iterable[KeyedBinding],
276
+ *,
277
+ runtime: RuntimeInterface,
278
+ registry: ProjectionRegistry = DEFAULT_REGISTRY,
279
+ ) -> None:
280
+ """Open, shape and start every Keyed Binding, in declaration order.
281
+
282
+ Fatal at init on a bad declaration: a field that does not repeat a message, a key field
283
+ that is not a scalar leaf, a state field the Projection never renders, an element type
284
+ that is not installed. What a message carries is never fatal. Only the
285
+ aggregate is created here; members appear with messages.
286
+ """
287
+ self._keyed_runtime = runtime
288
+ self._keyed_registry = registry
289
+ try:
290
+ for binding in bindings:
291
+ self._keyed.append(await self._open_keyed(binding))
292
+ except BaseException:
293
+ await self._stop_keyed_mirror()
294
+ raise
295
+ for keyed in self._keyed:
296
+ await self._start_following_keyed(keyed)
297
+
298
+ async def _stop_keyed_mirror(self) -> None:
299
+ """Stop following every Keyed Binding and close its subscription.
300
+
301
+ Idempotent. Runs before the Runtime is stopped, so a Component torn down on its own
302
+ still stops reading.
303
+ """
304
+ for keyed in self._keyed:
305
+ for task in (keyed.task, keyed.status_task, keyed.qos_task):
306
+ if task is not None:
307
+ task.cancel()
308
+ for keyed in self._keyed:
309
+ await ended(keyed.task)
310
+ await ended(keyed.status_task)
311
+ await ended(keyed.qos_task)
312
+ keyed.task = keyed.status_task = keyed.qos_task = None
313
+ await keyed.subscription.close()
314
+ self._keyed = []
315
+
316
+ async def _open_keyed(self, binding: KeyedBinding) -> _Keyed:
317
+ """Subscribe, shape the member plan, and create one Keyed Binding's aggregate."""
318
+ runtime = self._require_keyed_runtime()
319
+ subscription = await runtime.subscribe(
320
+ topic=binding.path,
321
+ message_type=binding.message_type,
322
+ depth=binding.depth,
323
+ qos=binding.qos,
324
+ )
325
+ try:
326
+ element_type = _repeated_element(subscription.message_type, binding)
327
+ context = ProjectionContext(
328
+ registry=self._keyed_registry,
329
+ selected=resolve_selection(element_type, binding.selection),
330
+ qualifier=self.ros2_projection_qualifier,
331
+ byte_string_ceiling=self._byte_string_ceiling,
332
+ )
333
+ projection = self._keyed_registry.find(element_type.ros2.type_name)
334
+ _require_scalar_key_fields(element_type, binding)
335
+ # Looked up in the shaped plan, so naming the raw key as state field is refused.
336
+ shaped = projection.shape(element_type, context)
337
+ state = _state_entry(shaped, binding, element_type, context.qualifier)
338
+ plan = _with_state(_member_plan(shaped, binding), state)
339
+ parent = self.monitoring
340
+ if binding.group is not None:
341
+ parent = await self.machinery_group(parent, binding.group)
342
+ require_unused_name(binding.name, (parent,), "this Monitoring")
343
+ group = await parent.add_group(binding.name)
344
+ aggregate = (
345
+ None if state is None else replace(state, name=f"{WORST}{state.name}", display_name=None, above=())
346
+ )
347
+ keyed = _Keyed(
348
+ binding=binding,
349
+ subscription=subscription,
350
+ projection=projection,
351
+ context=context,
352
+ element_type=element_type,
353
+ group=group,
354
+ plan=plan,
355
+ state_name=None if state is None else state.full_name,
356
+ aggregate=aggregate,
357
+ aggregate_name=None if aggregate is None else aggregate.full_name,
358
+ )
359
+ await self._create_aggregate(keyed)
360
+ except BaseException:
361
+ await subscription.close()
362
+ raise
363
+ return keyed
364
+
365
+ async def _create_aggregate(self, keyed: _Keyed) -> None:
366
+ """Create the aggregate variable in the Binding's group, beside the members, at init."""
367
+ if keyed.aggregate is None:
368
+ return
369
+ [keyed.aggregate_nodes] = await self.mutate_address_space(
370
+ [
371
+ NodeAddition(
372
+ binding=keyed.binding.name,
373
+ path=keyed.binding.path,
374
+ container=keyed.group,
375
+ plan=(keyed.aggregate,),
376
+ message_type=keyed.element_type,
377
+ )
378
+ ],
379
+ at_init=True,
380
+ )
381
+
382
+ async def _start_following_keyed(self, keyed: _Keyed) -> None:
383
+ """Put the first status on what a Keyed Binding already has, then start its tasks."""
384
+ await self._write_keyed_status(keyed)
385
+ name = keyed.binding.name
386
+ keyed.task = asyncio.create_task(self._follow_keyed(keyed), name=f"ros2-keyed-{name}")
387
+ keyed.status_task = asyncio.create_task(self._follow_keyed_publishers(keyed), name=f"ros2-keyed-pub-{name}")
388
+ keyed.qos_task = asyncio.create_task(self._follow_keyed_qos(keyed), name=f"ros2-keyed-qos-{name}")
389
+
390
+ async def _follow_keyed_qos(self, keyed: _Keyed) -> None:
391
+ """Raise one BindingEvent for every QoS incompatibility reported on this Binding's topic.
392
+
393
+ Like the inward mirror's ``_follow_qos``, with the same code.
394
+ """
395
+ async for incompatibility in keyed.subscription.follow_qos_incompatibilities():
396
+ try:
397
+ await self.emit_binding_event(
398
+ binding=keyed.binding.name,
399
+ path=keyed.binding.path,
400
+ code=QOS_INCOMPATIBLE,
401
+ severity=Severity.WARNING if incompatibility.adapted is not None else Severity.ERROR,
402
+ text=qos_clash_text(keyed.binding.path, incompatibility),
403
+ )
404
+ except Exception:
405
+ # Never fatal; one failed event must not end the stream.
406
+ self.logger.exception(
407
+ "Could not report a QoS incompatibility",
408
+ binding=keyed.binding.name,
409
+ topic=keyed.binding.path,
410
+ )
411
+
412
+ async def _follow_keyed(self, keyed: _Keyed) -> None:
413
+ """Write every message of one Keyed Binding, until the subscription closes."""
414
+ async for message in keyed.subscription:
415
+ try:
416
+ await self._write_keyed_message(keyed, message)
417
+ except Exception:
418
+ # Never fatal; a Binding that stopped reading would go quiet silently.
419
+ self.logger.exception(
420
+ "Could not write a keyed message to its members",
421
+ binding=keyed.binding.name,
422
+ topic=keyed.binding.path,
423
+ )
424
+
425
+ async def _follow_keyed_publishers(self, keyed: _Keyed) -> None:
426
+ """Write the status code every time the topic gains or loses its publishers."""
427
+ async for count in keyed.subscription.publisher_counts():
428
+ keyed.satisfied = count > 0
429
+ try:
430
+ await self._write_keyed_status(keyed)
431
+ except Exception:
432
+ self.logger.exception(
433
+ "Could not write a status code to a Keyed Binding's members",
434
+ binding=keyed.binding.name,
435
+ topic=keyed.binding.path,
436
+ )
437
+
438
+ async def _write_keyed_message(self, keyed: _Keyed, message: Message) -> None:
439
+ """Give every element of one message its member, creating the ones that are new."""
440
+ transitions: list[tuple[_Member, object, object]] = []
441
+ async with keyed.writing:
442
+ keyed.sampled = True
443
+ elements = keyed.elements(message)
444
+ await self._create_new_members(keyed, elements)
445
+ for element in elements:
446
+ member = keyed.members.get(member_key(element, keyed.binding.key))
447
+ if member is None:
448
+ continue
449
+ transition = await self._write_member(keyed, member, element)
450
+ if transition is not None:
451
+ transitions.append(transition)
452
+ await self._write_aggregate(keyed)
453
+ # Outside the lock and after the values are written, so a woken client reads the new state.
454
+ for member, previous, current in transitions:
455
+ await self._report_transition(keyed, member, previous, current)
456
+
457
+ async def _create_new_members(self, keyed: _Keyed, elements: Sequence[Message]) -> None:
458
+ """Add every key this message names for the first time, in one mutation.
459
+
460
+ One chokepoint call gives one model-change event for the whole batch. A key that cannot
461
+ have a member (its browse name is taken by another key or by something else on this
462
+ Monitoring, or a cap closed the Binding) is reported once and remembered as refused, so a
463
+ 10 Hz topic raises one event and not one per message.
464
+ """
465
+ binding = keyed.binding
466
+ additions: list[NodeAddition] = []
467
+ pending: list[tuple[tuple[str, ...], str]] = []
468
+ for element in elements:
469
+ key = member_key(element, binding.key)
470
+ if key in keyed.members or key in keyed.refused or key in {each for each, _ in pending}:
471
+ continue
472
+ browse = member_browse_name(key)
473
+ taken = keyed.claimed.get(browse) or next((each for each, name in pending if name == browse), None)
474
+ if taken is not None:
475
+ keyed.refused.add(key)
476
+ await self._report_collision(keyed, key, taken, browse)
477
+ continue
478
+ if browse in keyed.group:
479
+ # The name belongs to something that is not a member, e.g. the aggregate (an id
480
+ # called `WorstLevel`). Asked before the chokepoint so one bad name does not
481
+ # take the rest of the batch down.
482
+ keyed.refused.add(key)
483
+ await self._report_collision(keyed, key, (), browse)
484
+ continue
485
+ if keyed.capped:
486
+ keyed.refused.add(key)
487
+ continue
488
+ pending.append((key, browse))
489
+ additions.append(
490
+ NodeAddition(
491
+ binding=binding.name,
492
+ path=binding.path,
493
+ container=keyed.group,
494
+ plan=_keyed_plan(keyed.plan, key),
495
+ message_type=keyed.element_type,
496
+ member=(browse, "_".join(key)),
497
+ )
498
+ )
499
+ if not additions:
500
+ return
501
+ created = await self.mutate_address_space(additions)
502
+ for (key, browse), nodes in zip(pending, created, strict=True):
503
+ if nodes is None:
504
+ # A cap refused it, and has already reported itself.
505
+ keyed.capped = True
506
+ keyed.refused.add(key)
507
+ continue
508
+ keyed.claimed[browse] = key
509
+ keyed.members[key] = _Member(key=key, browse=browse, rendered=nodes)
510
+
511
+ async def _write_member(
512
+ self,
513
+ keyed: _Keyed,
514
+ member: _Member,
515
+ element: Message,
516
+ ) -> tuple[_Member, object, object] | None:
517
+ """Decode one element onto its member's variables and return the state transition, if any.
518
+
519
+ The caller reports it once the values are on their nodes.
520
+ """
521
+ previous = keyed.state_of(member)
522
+ for name, value in keyed.projection.decode(element, keyed.context).items():
523
+ if name not in member.rendered.entries:
524
+ self._report_unknown_keyed_name(keyed, name)
525
+ continue
526
+ member.values[name] = value
527
+ # Every variable, not just the decoded ones: the raw key is not in a decode and all
528
+ # carry the status, which also gives a new member its first status.
529
+ await member.rendered.write(member.values, keyed.status)
530
+ current = keyed.state_of(member)
531
+ if keyed.state_name is None or not state_changed(previous, current):
532
+ return None
533
+ return member, previous, current
534
+
535
+ async def _write_aggregate(self, keyed: _Keyed) -> None:
536
+ """Write the highest state any member holds, when this Binding has such a variable."""
537
+ if keyed.aggregate is None or keyed.aggregate_name is None or keyed.aggregate_nodes is None:
538
+ return
539
+ keyed.aggregate_value = worst_state(
540
+ (keyed.state_of(member) for member in keyed.members.values()),
541
+ initial=keyed.aggregate.initial,
542
+ )
543
+ await keyed.aggregate_nodes.write({keyed.aggregate_name: keyed.aggregate_value}, keyed.status)
544
+
545
+ async def _write_keyed_status(self, keyed: _Keyed) -> None:
546
+ """Re-write everything this Binding owns under the status its publishers now imply.
547
+
548
+ The value goes with it: a status written alone leaves the variant null.
549
+ """
550
+ async with keyed.writing:
551
+ for member in keyed.members.values():
552
+ await member.rendered.write(member.values, keyed.status)
553
+ # Recomputed so the aggregate's value is decided in one place.
554
+ await self._write_aggregate(keyed)
555
+
556
+ async def _report_transition(self, keyed: _Keyed, member: _Member, previous: object, current: object) -> None:
557
+ """Fire the BindingEvent for a member's state change."""
558
+ await self.emit_binding_event(
559
+ binding=keyed.binding.name,
560
+ path=keyed.binding.path,
561
+ code=MEMBER_STATE_CHANGED,
562
+ severity=severity_of(current, keyed.binding.severities),
563
+ text=(
564
+ f"{member.browse} moved {keyed.binding.state_field} from "
565
+ f"{_labelled(previous, keyed.binding.states)} to {_labelled(current, keyed.binding.states)}"
566
+ ),
567
+ )
568
+
569
+ async def _report_collision(
570
+ self,
571
+ keyed: _Keyed,
572
+ key: tuple[str, ...],
573
+ claimed: tuple[str, ...],
574
+ browse: str,
575
+ ) -> None:
576
+ """Say, as a BindingEvent, that a key has no member because its name is already taken.
577
+
578
+ :param claimed: The key that holds the name, where one does. Empty when the name belongs
579
+ to something that is not a member -- this Binding's own aggregate, say.
580
+ """
581
+ self.logger.error(
582
+ "Refused a member whose key collides with a name already taken",
583
+ binding=keyed.binding.name,
584
+ key=list(key),
585
+ browse_name=browse,
586
+ )
587
+ held_by = f"{list(claimed)} already holds" if claimed else "is already taken on this Monitoring"
588
+ await self.emit_binding_event(
589
+ binding=keyed.binding.name,
590
+ path=keyed.binding.path,
591
+ code=KEY_COLLISION,
592
+ severity=Severity.ERROR,
593
+ text=(
594
+ f"the key {list(key)} browses as {browse!r}, which {held_by}; it has no member, "
595
+ f"because sharing one would file two things under one name"
596
+ ),
597
+ )
598
+
599
+ def _report_unknown_keyed_name(self, keyed: _Keyed, name: str) -> None:
600
+ """Log once per Binding a decoded name its shape never created.
601
+
602
+ Unreachable with the shipped Projections; a curated one whose halves disagree only shows
603
+ up with a message.
604
+ """
605
+ if keyed.reported_unknown_name:
606
+ return
607
+ keyed.reported_unknown_name = True
608
+ self.logger.error(
609
+ "A Projection decoded a name its shape never created; those values are not written",
610
+ binding=keyed.binding.name,
611
+ projection=keyed.projection.type_name,
612
+ name=name,
613
+ )
614
+
615
+ def _require_keyed_runtime(self) -> RuntimeInterface:
616
+ """Return the Runtime this mirror was initialised with.
617
+
618
+ :raises DeclarationError: When there is none, which is a wiring fault and never a
619
+ ROS2 condition.
620
+ """
621
+ if self._keyed_runtime is None: # pragma: no cover -- every path here runs after init
622
+ message = f"{type(self).__name__} has no Runtime; its Keyed Bindings were never initialised"
623
+ raise DeclarationError(message)
624
+ return self._keyed_runtime
625
+
626
+
627
+ def _repeated_element(message_type: type[Message], binding: KeyedBinding) -> type[Message]:
628
+ """Return the message type one Binding's repeated field carries.
629
+
630
+ :raises UnprojectableFieldError: When the named field does not exist or does not repeat a
631
+ message.
632
+ """
633
+ nested = repeated_message(message_type, binding.repeated_field)
634
+ if nested is None:
635
+ listed = ", ".join(each.name for each in message_type.ros2.fields) or "nothing"
636
+ message = (
637
+ f"the Keyed Binding {binding.name!r} keys on {binding.repeated_field!r} of "
638
+ f"{message_type.ros2.type_name}, which is not a field that repeats a message; its "
639
+ f"fields are {listed}, and a Keyed Binding renders one member per element of one of "
640
+ f"them"
641
+ )
642
+ raise UnprojectableFieldError(message)
643
+ return nested
644
+
645
+
646
+ def _require_scalar_key_fields(element_type: type[Message], binding: KeyedBinding) -> None:
647
+ """Refuse a key field that cannot name a member.
648
+
649
+ :raises DeclarationError: When a key field is absent from the element type, or is not a
650
+ scalar leaf of it.
651
+ """
652
+ for name in binding.key:
653
+ described = next((each for each in element_type.ros2.fields if each.name == name), None)
654
+ if described is not None and is_single_value(described.field_type):
655
+ continue
656
+ listed = ", ".join(each.name for each in element_type.ros2.fields) or "nothing"
657
+ message = (
658
+ f"the Keyed Binding {binding.name!r} keys on {name!r}, which is not a single value of "
659
+ f"{element_type.ros2.type_name}; its fields are {listed}, and a key names a member"
660
+ )
661
+ raise DeclarationError(message)
662
+
663
+
664
+ def _member_plan(shaped: tuple[PlanEntry, ...], binding: KeyedBinding) -> tuple[PlanEntry, ...]:
665
+ """Return the plan one member is built from: the raw key, then whatever the Projection shaped.
666
+
667
+ :raises DeclarationError: When the element type already renders something called :data:`KEY`.
668
+ """
669
+ if any(isinstance(entry, PlanVariable) and entry.name == KEY for entry in shaped):
670
+ message = (
671
+ f"the Keyed Binding {binding.name!r} renders a member with a {KEY!r} of its own, and "
672
+ f"{KEY!r} is where every member carries its raw key; exclude that field from this "
673
+ f"Binding, or curate the type with a Projection that renames it"
674
+ )
675
+ raise DeclarationError(message)
676
+ return (
677
+ PlanVariable(
678
+ name=KEY,
679
+ source=binding.repeated_field,
680
+ initial=[],
681
+ variant_type=ua.VariantType.String,
682
+ display_name=_KEY_DISPLAY,
683
+ ),
684
+ *shaped,
685
+ )
686
+
687
+
688
+ def _state_entry(
689
+ plan: tuple[PlanEntry, ...],
690
+ binding: KeyedBinding,
691
+ element_type: type[Message],
692
+ qualifier: str,
693
+ ) -> PlanVariable | None:
694
+ """Return the variable a Binding's declared state field renders as, with its labels named.
695
+
696
+ The labels come from the declaration, not the Projection, so the member's state variable and
697
+ the aggregate share one enumeration.
698
+
699
+ :raises DeclarationError: When the element's Projection renders no variable of that name (the
700
+ field was excluded or renamed).
701
+ """
702
+ if binding.state_field is None:
703
+ return None
704
+ found = next(
705
+ (entry for entry in plan if isinstance(entry, PlanVariable) and entry.source == binding.state_field), None
706
+ )
707
+ if not isinstance(found, PlanVariable):
708
+ listed = ", ".join(entry.full_name for entry in plan) or "nothing"
709
+ message = (
710
+ f"the Keyed Binding {binding.name!r} names {binding.state_field!r} as its state "
711
+ f"field, and a member of it renders {listed}; an excluded or renamed field leaves "
712
+ f"nothing to watch"
713
+ )
714
+ raise DeclarationError(message)
715
+ if not binding.states:
716
+ return found
717
+ local = element_type.ros2.type_name.rpartition("/")[2]
718
+ parts = (qualifier, local, binding.state_field)
719
+ return replace(
720
+ found,
721
+ # An OPC UA enumeration is an Int32; the value written is the ROS2 constant.
722
+ variant_type=ua.VariantType.Int32,
723
+ datatype=EnumDataType(
724
+ name="_".join(part for part in parts if part),
725
+ values=tuple(sorted(binding.states.items())),
726
+ ),
727
+ )
728
+
729
+
730
+ def _with_state(plan: tuple[PlanEntry, ...], state: PlanVariable | None) -> tuple[PlanEntry, ...]:
731
+ """Return the member plan with the state field's variable as the state entry describes it."""
732
+ if state is None:
733
+ return plan
734
+ return tuple(state if entry.full_name == state.full_name else entry for entry in plan)
735
+
736
+
737
+ def _keyed_plan(plan: tuple[PlanEntry, ...], key: tuple[str, ...]) -> tuple[PlanEntry, ...]:
738
+ """Return one member's plan, with its raw key as the initial value of the key variable.
739
+
740
+ The node is created holding the key, so a client never reads it empty.
741
+ """
742
+ return tuple(replace(entry, initial=list(key)) if entry.name == KEY else entry for entry in plan)
743
+
744
+
745
+ def _labelled(state: object, states: Mapping[int, str]) -> str:
746
+ """Return a state value as an event's text should read it: the label, and the number."""
747
+ if _is_a_number(state) and state in states:
748
+ return f"{states[state]} ({state})"
749
+ return str(state)