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,125 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """The Publisher handle: one topic's outward lifetime, and the checks in front of it.
6
+
7
+ The mirror of :class:`~opensmi.ros2.runtime.subscription.Subscription`, without a buffer: a publish
8
+ is push-only with no acknowledgement. Nothing here imports ``rclpy``.
9
+
10
+ :meth:`Publisher.publish` checks the payload type, fills unset header stamps from the Runtime's
11
+ ROS2 clock (:mod:`opensmi.ros2.runtime.stamp`), and runs the type-mismatch guard
12
+ (:mod:`opensmi.ros2.runtime.guard`) on the stamped message, so what reaches ``rclpy`` is what was
13
+ checked. The QoS profile is declared or defaulted, never discovered or adapted.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import TYPE_CHECKING, final
19
+
20
+ from opensmi.ros2.runtime.errors import ROS2RuntimeError
21
+ from opensmi.ros2.runtime.guard import require_sendable
22
+ from opensmi.ros2.runtime.qos import DEFAULT_PROFILE, Provenance, QoSProfile
23
+ from opensmi.ros2.runtime.stamp import stamped
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Awaitable, Callable
27
+
28
+ from opensmi.ros2.runtime.messages import Message
29
+
30
+ __all__ = ["Publisher"]
31
+
32
+
33
+ @final
34
+ class Publisher:
35
+ """A live publisher on one ROS2 topic, from :meth:`~opensmi.ros2.runtime.runtime.Runtime.advertise`."""
36
+
37
+ def __init__(
38
+ self,
39
+ *,
40
+ topic: str,
41
+ message_type: type[Message],
42
+ clock: Callable[[], tuple[int, int]],
43
+ send: Callable[[Message], Awaitable[None]],
44
+ release: Callable[[], Awaitable[None]],
45
+ qos: QoSProfile = DEFAULT_PROFILE,
46
+ provenance: Provenance = Provenance.DEFAULTED,
47
+ ) -> None:
48
+ """Bind a handle to the clock, the send step and the teardown the Runtime prepared."""
49
+ self._topic = topic
50
+ self._message_type = message_type
51
+ self._clock = clock
52
+ self._send = send
53
+ self._release = release
54
+ self._qos = qos
55
+ self._provenance = provenance
56
+ self._published = 0
57
+ self._closed = False
58
+
59
+ def __repr__(self) -> str:
60
+ """Return a representation naming the topic and the ROS2 type."""
61
+ state = "closed" if self._closed else "open"
62
+ return f"<Publisher {self._topic} {self._message_type.ros2.type_name} ({state})>"
63
+
64
+ @property
65
+ def topic(self) -> str:
66
+ """Return the ROS2 topic this publisher is on."""
67
+ return self._topic
68
+
69
+ @property
70
+ def message_type(self) -> type[Message]:
71
+ """Return the message dataclass every payload handed to this publisher must be."""
72
+ return self._message_type
73
+
74
+ @property
75
+ def closed(self) -> bool:
76
+ """Return whether this publisher's lifetime has ended."""
77
+ return self._closed
78
+
79
+ @property
80
+ def qos(self) -> QoSProfile:
81
+ """Return the QoS profile this publisher offers (fixed once advertised)."""
82
+ return self._qos
83
+
84
+ @property
85
+ def qos_provenance(self) -> Provenance:
86
+ """Return where that profile came from: ``DECLARED`` or ``DEFAULTED``, never discovered."""
87
+ return self._provenance
88
+
89
+ @property
90
+ def published(self) -> int:
91
+ """Return how many sends did not raise (ROS2 gives no acknowledgement, so not messages delivered)."""
92
+ return self._published
93
+
94
+ async def publish(self, message: Message) -> None:
95
+ """Fill the header stamp, check the payload and put one message on the topic.
96
+
97
+ :param message: The payload, as an instance of this publisher's message dataclass.
98
+ :raises ROS2RuntimeError: When this handle's lifetime has already ended.
99
+ :raises TypeError: When the payload is not an instance of the type advertised.
100
+ :raises FieldTypeMismatchError: When a field holds a value of the wrong Python type.
101
+ Refused here because ``rclpy`` aborts the process instead of raising.
102
+ :raises FieldValueOutOfRangeError: When a field is past its width or its declared bound.
103
+ :raises PublishFailedError: When ``rclpy`` refused to send it.
104
+ """
105
+ if self._closed:
106
+ text = f"the publisher on {self._topic} is closed and will send nothing further"
107
+ raise ROS2RuntimeError(text)
108
+ if not isinstance(message, self._message_type):
109
+ text = (
110
+ f"the message for {self._topic} is a {type(message).__name__}, and this publisher "
111
+ f"carries {self._message_type.ros2.type_name}"
112
+ )
113
+ raise TypeError(text)
114
+ seconds, nanoseconds = self._clock()
115
+ payload = stamped(message, seconds=seconds, nanoseconds=nanoseconds)
116
+ require_sendable(payload)
117
+ await self._send(payload)
118
+ self._published += 1
119
+
120
+ async def close(self) -> None:
121
+ """End this publisher, releasing its ROS2 endpoint. Idempotent."""
122
+ if self._closed:
123
+ return
124
+ self._closed = True
125
+ await self._release()
@@ -0,0 +1,394 @@
1
+ # SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """QoS: where a profile came from, and therefore how it may be treated.
6
+
7
+ A profile is declared (written on the Binding), discovered (computed from the topic's live
8
+ publishers) or defaulted (the middleware's reliable, volatile profile, for an outward endpoint
9
+ with nothing declared). This is its provenance, and one rule follows: the QoS of an endpoint adapts
10
+ if and only if it was discovered. Declared and defaulted profiles are honoured exactly.
11
+
12
+ Discovery picks, for each policy, the least demanding value any current publisher offers (see
13
+ :func:`resolve`), which is compatible with all of them regardless of order. Adaptation only ever
14
+ relaxes. The one exception is the bootstrap: a topic with no publisher at init is subscribed with
15
+ :data:`MOST_PERMISSIVE` and re-resolved once on the first publisher it matches, since a
16
+ ``VOLATILE`` request would match a ``TRANSIENT_LOCAL`` publisher and receive none of its history.
17
+
18
+ QoS is never fatal. A declared profile that clashes with a publisher is logged and reported as an
19
+ event, not refused at startup, since whether the publisher is up then is a matter of timing. Queue
20
+ depth is not part of a profile because it takes no part in matching.
21
+
22
+ Nothing here imports ``rclpy``. The :class:`Policy` values are the ``rmw`` policy-kind numbers.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import math
28
+ from dataclasses import dataclass, replace
29
+ from enum import Enum, IntEnum
30
+ from typing import TYPE_CHECKING, Final, final
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import Iterable, Sequence
34
+
35
+ __all__ = [
36
+ "DEFAULT_PROFILE",
37
+ "FOREVER",
38
+ "LATCHED",
39
+ "MOST_PERMISSIVE",
40
+ "SENSOR_DATA",
41
+ "Durability",
42
+ "EndpointInfo",
43
+ "Liveliness",
44
+ "Policy",
45
+ "Provenance",
46
+ "QoSIncompatibility",
47
+ "QoSNegotiation",
48
+ "QoSProfile",
49
+ "Reliability",
50
+ "most_permissive",
51
+ "resolve",
52
+ ]
53
+
54
+ FOREVER: Final = math.inf
55
+ """The duration a deadline or a liveliness lease has when there is none (``math.inf``).
56
+
57
+ ROS2 spells it ``INT64_MAX`` nanoseconds on the wire and as a zero duration in a fresh ``rclpy``
58
+ profile. Neither is usable in arithmetic.
59
+ """
60
+
61
+
62
+ class Reliability(Enum):
63
+ """Whether the middleware retries a sample until it is acknowledged.
64
+
65
+ ``BEST_EFFORT`` is the more permissive request: it matches a publisher offering either,
66
+ while a ``RELIABLE`` request matches only a ``RELIABLE`` publisher.
67
+ """
68
+
69
+ BEST_EFFORT = "best_effort"
70
+ RELIABLE = "reliable"
71
+
72
+
73
+ class Durability(Enum):
74
+ """Whether a publisher keeps its samples for subscribers that join later.
75
+
76
+ ``VOLATILE`` is the more permissive request, but it matches a ``TRANSIENT_LOCAL`` publisher
77
+ and receives none of its history.
78
+ """
79
+
80
+ VOLATILE = "volatile"
81
+ TRANSIENT_LOCAL = "transient_local"
82
+
83
+
84
+ class Liveliness(Enum):
85
+ """How a publisher asserts that it is still alive.
86
+
87
+ ``AUTOMATIC`` is the more permissive request: it matches a publisher that asserts either way.
88
+ """
89
+
90
+ AUTOMATIC = "automatic"
91
+ MANUAL_BY_TOPIC = "manual_by_topic"
92
+
93
+
94
+ class Policy(IntEnum):
95
+ """One matching policy, by the number ``rmw`` gives it.
96
+
97
+ Only policies that take part in matching are here. :data:`INVALID` is what an unrecognised
98
+ kind becomes. A Jazzy test checks the numbers against the live enumeration.
99
+ """
100
+
101
+ INVALID = 1
102
+ DURABILITY = 2
103
+ DEADLINE = 4
104
+ LIVELINESS = 8
105
+ RELIABILITY = 16
106
+ LIVELINESS_LEASE_DURATION = 256
107
+
108
+
109
+ class Provenance(Enum):
110
+ """Where a profile came from, and therefore whether it may be adapted.
111
+
112
+ :data:`DISCOVERED` adapts; the other two are honoured exactly. It belongs to an endpoint, not
113
+ a Binding: a TF Binding holds two discovered subscriptions and a declared publisher.
114
+ """
115
+
116
+ DECLARED = "declared"
117
+ DISCOVERED = "discovered"
118
+ DEFAULTED = "defaulted"
119
+
120
+
121
+ @dataclass(frozen=True, slots=True, kw_only=True)
122
+ class QoSProfile:
123
+ """The matching policies of one endpoint, and nothing else.
124
+
125
+ The defaults are the middleware's usual values, so a profile written with one keyword is the
126
+ middleware's own profile with that one change.
127
+
128
+ :ivar reliability: Whether samples are retried until acknowledged.
129
+ :ivar durability: Whether a publisher keeps its samples for late joiners.
130
+ :ivar deadline: The longest gap, in seconds, between samples that this endpoint promises
131
+ (offered) or tolerates (requested). :data:`FOREVER` means no deadline.
132
+ :ivar liveliness: How a publisher asserts that it is still alive.
133
+ :ivar lease: Seconds an assertion of liveliness stays good for. :data:`FOREVER` means no lease.
134
+ """
135
+
136
+ reliability: Reliability = Reliability.RELIABLE
137
+ durability: Durability = Durability.VOLATILE
138
+ deadline: float = FOREVER
139
+ liveliness: Liveliness = Liveliness.AUTOMATIC
140
+ lease: float = FOREVER
141
+
142
+ def __post_init__(self) -> None:
143
+ """Refuse a duration that is not a duration.
144
+
145
+ :raises ValueError: When the deadline or the lease is not a positive number of seconds.
146
+ Zero is refused because ``rclpy`` uses it for "middleware default"; write
147
+ :data:`FOREVER` instead.
148
+ """
149
+ for name, seconds in (("deadline", self.deadline), ("lease", self.lease)):
150
+ if seconds > 0:
151
+ continue
152
+ message = (
153
+ f"a QoS profile gives {name}={seconds!r}; it is a positive number of seconds, and "
154
+ f"the absence of one is spelled FOREVER rather than zero"
155
+ )
156
+ raise ValueError(message)
157
+
158
+ def __str__(self) -> str:
159
+ """Return the profile as one line for event texts and logs."""
160
+ return (
161
+ f"{self.reliability.value}/{self.durability.value}, deadline {_seconds(self.deadline)}, "
162
+ f"liveliness {self.liveliness.value} with a lease of {_seconds(self.lease)}"
163
+ )
164
+
165
+
166
+ DEFAULT_PROFILE: Final = QoSProfile()
167
+ """The middleware's default profile (reliable, volatile, no deadline, automatic liveliness).
168
+
169
+ A publishing endpoint uses it when nothing was declared. Under it the only reachable mismatches
170
+ are durability, which would replay stale commands to a late joiner, and deadline, a rate this
171
+ package does not control.
172
+ """
173
+
174
+ MOST_PERMISSIVE: Final = QoSProfile(
175
+ reliability=Reliability.BEST_EFFORT,
176
+ durability=Durability.VOLATILE,
177
+ deadline=FOREVER,
178
+ liveliness=Liveliness.AUTOMATIC,
179
+ lease=FOREVER,
180
+ )
181
+ """The request that matches every possible publisher and receives the least from them.
182
+
183
+ A discovered Binding with no publisher at init subscribes with it until its first match event.
184
+ Left in place it would drop a latched topic's history.
185
+ """
186
+
187
+ SENSOR_DATA: Final = QoSProfile(reliability=Reliability.BEST_EFFORT)
188
+ """Best effort, as high-rate sensors usually publish."""
189
+
190
+ LATCHED: Final = QoSProfile(durability=Durability.TRANSIENT_LOCAL)
191
+ """Transient local, for topics whose value is a fact rather than a stream (such as ``/tf_static``)."""
192
+
193
+
194
+ @dataclass(frozen=True, slots=True, kw_only=True)
195
+ class EndpointInfo:
196
+ """One endpoint on a topic, as the client library's publisher-info call reports it.
197
+
198
+ This is the input of :func:`resolve`, kept free of ``rclpy`` types.
199
+
200
+ :ivar node_name: The fully qualified name of the node that owns the endpoint. It takes no
201
+ part in matching but lets logs say which publisher forced a subscription down.
202
+ :ivar qos: What that endpoint offers.
203
+ """
204
+
205
+ node_name: str
206
+ qos: QoSProfile
207
+
208
+
209
+ @dataclass(frozen=True, slots=True, kw_only=True)
210
+ class QoSIncompatibility:
211
+ """One incompatibility the middleware reported, and what this package did about it.
212
+
213
+ :ivar topic: The ROS2 topic it happened on.
214
+ :ivar policy: The policy the middleware named. It reports only the last clash it found.
215
+ :ivar request: The profile the subscription was asking for when it fired.
216
+ :ivar adapted: What the subscription moved to, or ``None`` when it did not move (declared
217
+ profile, or already as permissive as the graph asks for).
218
+ :ivar provenance: Where the profile that clashed came from.
219
+ """
220
+
221
+ topic: str
222
+ policy: Policy
223
+ request: QoSProfile
224
+ adapted: QoSProfile | None
225
+ provenance: Provenance
226
+
227
+
228
+ def _clashes(request: QoSProfile, offer: QoSProfile) -> tuple[Policy, ...]:
229
+ """Return every policy on which a subscriber's request cannot be served by a publisher's offer.
230
+
231
+ Empty means the two match. A request is served when it asks for no more than the offer
232
+ promises: for the three enumerations no stronger, for the two durations no shorter (checked
233
+ against a live Jazzy graph). Nothing calls this at run time, since the middleware does the
234
+ matching; it states the rule so tests can assert that :func:`resolve` is compatible.
235
+ """
236
+ found: list[Policy] = []
237
+ if _rank(request.reliability) > _rank(offer.reliability):
238
+ found.append(Policy.RELIABILITY)
239
+ if _rank(request.durability) > _rank(offer.durability):
240
+ found.append(Policy.DURABILITY)
241
+ if request.deadline < offer.deadline:
242
+ found.append(Policy.DEADLINE)
243
+ if _rank(request.liveliness) > _rank(offer.liveliness):
244
+ found.append(Policy.LIVELINESS)
245
+ if request.lease < offer.lease:
246
+ found.append(Policy.LIVELINESS_LEASE_DURATION)
247
+ return tuple(found)
248
+
249
+
250
+ def most_permissive(profiles: Iterable[QoSProfile]) -> QoSProfile:
251
+ """Return the request that is, policy by policy, the least demanding of those given.
252
+
253
+ Adaptation relaxes with this too: combining the held profile with what the graph now resolves
254
+ to is what makes it only ever move down. With nothing to combine it returns
255
+ :data:`MOST_PERMISSIVE`.
256
+ """
257
+ held = list(profiles)
258
+ if not held:
259
+ return MOST_PERMISSIVE
260
+ combined, rest = held[0], held[1:]
261
+ for profile in rest:
262
+ combined = replace(
263
+ combined,
264
+ reliability=min(combined.reliability, profile.reliability, key=_rank),
265
+ durability=min(combined.durability, profile.durability, key=_rank),
266
+ deadline=max(combined.deadline, profile.deadline),
267
+ liveliness=min(combined.liveliness, profile.liveliness, key=_rank),
268
+ lease=max(combined.lease, profile.lease),
269
+ )
270
+ return combined
271
+
272
+
273
+ def resolve(endpoints: Iterable[EndpointInfo]) -> QoSProfile:
274
+ """Return the most permissive request compatible with every one of these publishers (discovery).
275
+
276
+ Pure and independent of the order of the endpoints. With no publishers it returns
277
+ :data:`MOST_PERMISSIVE`; :class:`QoSNegotiation` re-resolves once the first one appears.
278
+ """
279
+ return most_permissive(endpoint.qos for endpoint in endpoints)
280
+
281
+
282
+ @final
283
+ class QoSNegotiation:
284
+ """One endpoint's provenance, its current profile, and the two events that may move it.
285
+
286
+ The adaptation rule as a pure state machine: the Runtime re-subscribes when an event method
287
+ returns a new profile, and gets ``None`` when nothing moved.
288
+ """
289
+
290
+ def __init__(self, *, declared: QoSProfile | None, endpoints: Sequence[EndpointInfo] = ()) -> None:
291
+ """Settle the provenance and the opening profile from what was declared and what publishes.
292
+
293
+ :param declared: The profile written on the declaration, or ``None`` to discover one.
294
+ :param endpoints: Every publisher on the topic right now. Ignored when a profile was
295
+ declared, even if it is provably incompatible with what is publishing.
296
+ """
297
+ self._declared = declared
298
+ self._provenance = Provenance.DECLARED if declared is not None else Provenance.DISCOVERED
299
+ self._profile = declared if declared is not None else resolve(endpoints)
300
+ # A declaration has nothing to bootstrap; so does a discovery that already saw a publisher.
301
+ self._bootstrapped = declared is not None or bool(endpoints)
302
+
303
+ def __repr__(self) -> str:
304
+ """Return a representation naming the provenance and the profile."""
305
+ return f"<QoSNegotiation {self._provenance.value}: {self._profile}>"
306
+
307
+ @property
308
+ def profile(self) -> QoSProfile:
309
+ """Return the profile this endpoint is asking for right now."""
310
+ return self._profile
311
+
312
+ @property
313
+ def provenance(self) -> Provenance:
314
+ """Return where that profile came from, which decides whether it may move."""
315
+ return self._provenance
316
+
317
+ def on_first_publisher(self, endpoints: Sequence[EndpointInfo]) -> QoSProfile | None:
318
+ """Re-resolve once, against the first publishers this endpoint ever matched.
319
+
320
+ The only tightening in the rule, at most once: a discovered Binding whose topic was empty
321
+ at init asks for :data:`MOST_PERMISSIVE`, which would miss a latched publisher's history.
322
+
323
+ :param endpoints: Every publisher on the topic now. An empty list does not spend the
324
+ bootstrap.
325
+ :return: The profile to re-subscribe with, or ``None`` when nothing moved.
326
+ """
327
+ if self._bootstrapped or not endpoints:
328
+ return None
329
+ self._bootstrapped = True
330
+ return self._moved_to(resolve(endpoints))
331
+
332
+ def on_incompatibility(self, endpoints: Sequence[EndpointInfo]) -> QoSProfile | None:
333
+ """Relax towards what the graph now offers, if and only if this profile was discovered.
334
+
335
+ The result is the most permissive of what is held and what the current publishers resolve
336
+ to, so a departed publisher never tightens the subscription. It also spends the bootstrap,
337
+ since a later first-match tightening would undo this.
338
+
339
+ :param endpoints: Every publisher on the topic now. Empty relaxes the whole way.
340
+ :return: The profile to re-subscribe with, or ``None`` when nothing moved, which includes
341
+ every declared and defaulted profile.
342
+ """
343
+ self._bootstrapped = True
344
+ if self._provenance is not Provenance.DISCOVERED:
345
+ return None
346
+ return self._moved_to(most_permissive((self._profile, resolve(endpoints))))
347
+
348
+ def incompatibility(self, topic: str, policy: Policy, endpoints: Sequence[EndpointInfo]) -> QoSIncompatibility:
349
+ """Answer one incompatibility the middleware reported, as the record of what happened.
350
+
351
+ This is :meth:`on_incompatibility` plus the record, so the Runtime and test doubles share
352
+ one code path.
353
+
354
+ :return: What clashed, what was being asked for, and what this moved to, if anything.
355
+ """
356
+ request = self._profile
357
+ return QoSIncompatibility(
358
+ topic=topic,
359
+ policy=policy,
360
+ request=request,
361
+ adapted=self.on_incompatibility(endpoints),
362
+ provenance=self._provenance,
363
+ )
364
+
365
+ def _moved_to(self, profile: QoSProfile) -> QoSProfile | None:
366
+ """Take a newly resolved profile, answering ``None`` when it is the one already held."""
367
+ if profile == self._profile:
368
+ return None
369
+ self._profile = profile
370
+ return profile
371
+
372
+
373
+ def _rank(value: Reliability | Durability | Liveliness) -> int:
374
+ """Return how demanding a policy value is as a request; lower is more permissive."""
375
+ return _RANKS[value]
376
+
377
+
378
+ _RANKS: Final[dict[Reliability | Durability | Liveliness, int]] = {
379
+ Reliability.BEST_EFFORT: 0,
380
+ Reliability.RELIABLE: 1,
381
+ Durability.VOLATILE: 0,
382
+ Durability.TRANSIENT_LOCAL: 1,
383
+ Liveliness.AUTOMATIC: 0,
384
+ Liveliness.MANUAL_BY_TOPIC: 1,
385
+ }
386
+ """How demanding each enumerated policy value is, as a request.
387
+
388
+ The enumerations are string-valued (not ``IntEnum``) because TOML files name them.
389
+ """
390
+
391
+
392
+ def _seconds(value: float) -> str:
393
+ """Return a duration as the words an event text uses, instead of ``inf``."""
394
+ return "none" if value == FOREVER else f"{value}s"