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.
- opensmi/ros2/__init__.py +89 -0
- opensmi/ros2/__main__.py +11 -0
- opensmi/ros2/cli.py +143 -0
- opensmi/ros2/py.typed +0 -0
- opensmi/ros2/runtime/__init__.py +67 -0
- opensmi/ros2/runtime/_decode.py +101 -0
- opensmi/ros2/runtime/_encode.py +102 -0
- opensmi/ros2/runtime/_parser.py +147 -0
- opensmi/ros2/runtime/errors.py +141 -0
- opensmi/ros2/runtime/goal.py +232 -0
- opensmi/ros2/runtime/graph.py +288 -0
- opensmi/ros2/runtime/guard.py +213 -0
- opensmi/ros2/runtime/interface.py +140 -0
- opensmi/ros2/runtime/messages/__init__.py +503 -0
- opensmi/ros2/runtime/messages/industrial_msgs.py +62 -0
- opensmi/ros2/runtime/messages/industrial_msgs.pyi +159 -0
- opensmi/ros2/runtime/messages/motoros2_interfaces.py +79 -0
- opensmi/ros2/runtime/messages/motoros2_interfaces.pyi +307 -0
- opensmi/ros2/runtime/messages/neo_msgs2.py +55 -0
- opensmi/ros2/runtime/messages/neo_msgs2.pyi +138 -0
- opensmi/ros2/runtime/messages/neo_srvs2.py +72 -0
- opensmi/ros2/runtime/messages/neo_srvs2.pyi +224 -0
- opensmi/ros2/runtime/outcomes.py +103 -0
- opensmi/ros2/runtime/parameters.py +723 -0
- opensmi/ros2/runtime/publisher.py +125 -0
- opensmi/ros2/runtime/qos.py +394 -0
- opensmi/ros2/runtime/runtime.py +1171 -0
- opensmi/ros2/runtime/selection.py +150 -0
- opensmi/ros2/runtime/stamp.py +100 -0
- opensmi/ros2/runtime/subscription.py +354 -0
- opensmi/ros2/runtime/tf.py +714 -0
- opensmi/ros2/server/__init__.py +148 -0
- opensmi/ros2/server/access.py +109 -0
- opensmi/ros2/server/bindings/__init__.py +92 -0
- opensmi/ros2/server/bindings/_base.py +154 -0
- opensmi/ros2/server/bindings/action.py +133 -0
- opensmi/ros2/server/bindings/keyed.py +127 -0
- opensmi/ros2/server/bindings/lifecycle.py +131 -0
- opensmi/ros2/server/bindings/method.py +130 -0
- opensmi/ros2/server/bindings/monitoring.py +109 -0
- opensmi/ros2/server/bindings/parameter.py +133 -0
- opensmi/ros2/server/bindings/publisher.py +192 -0
- opensmi/ros2/server/bindings/registry.py +95 -0
- opensmi/ros2/server/bindings/tf.py +256 -0
- opensmi/ros2/server/browse_names.py +94 -0
- opensmi/ros2/server/component.py +334 -0
- opensmi/ros2/server/config.py +493 -0
- opensmi/ros2/server/containers.py +191 -0
- opensmi/ros2/server/drivers.py +421 -0
- opensmi/ros2/server/errors.py +159 -0
- opensmi/ros2/server/events.py +406 -0
- opensmi/ros2/server/introspection.py +850 -0
- opensmi/ros2/server/keyed.py +749 -0
- opensmi/ros2/server/lifecycle.py +238 -0
- opensmi/ros2/server/limits.py +66 -0
- opensmi/ros2/server/loader.py +977 -0
- opensmi/ros2/server/machine.py +225 -0
- opensmi/ros2/server/method.py +307 -0
- opensmi/ros2/server/mirror.py +582 -0
- opensmi/ros2/server/mutation.py +992 -0
- opensmi/ros2/server/nodesets/Opc.Ua.SmartFactory.ROS2.NodeSet2.xml +85 -0
- opensmi/ros2/server/nodesets/__init__.py +18 -0
- opensmi/ros2/server/nodesets/smart_factory_ros2.py +26 -0
- opensmi/ros2/server/parameters.py +704 -0
- opensmi/ros2/server/projection.py +1176 -0
- opensmi/ros2/server/projections/__init__.py +41 -0
- opensmi/ros2/server/projections/scope.py +222 -0
- opensmi/ros2/server/provenance.py +121 -0
- opensmi/ros2/server/publisher.py +781 -0
- opensmi/ros2/server/recipes.py +514 -0
- opensmi/ros2/server/required.py +633 -0
- opensmi/ros2/server/skill.py +363 -0
- opensmi/ros2/server/spatial.py +283 -0
- opensmi/ros2/server/startup.py +626 -0
- opensmi/ros2/server/status.py +107 -0
- opensmi/ros2/server/structures.py +135 -0
- opensmi/ros2/server/transforms/__init__.py +39 -0
- opensmi/ros2/server/transforms/conversions.py +58 -0
- opensmi/ros2/server/transforms/filing.py +340 -0
- opensmi/ros2/server/transforms/mirror.py +462 -0
- opensmi/ros2/server/transforms/outward.py +180 -0
- opensmi/ros2/server/transforms/records.py +195 -0
- opensmi/ros2/server/transforms/spatial.py +154 -0
- opensmi_ros2-0.1.0.dist-info/METADATA +183 -0
- opensmi_ros2-0.1.0.dist-info/RECORD +89 -0
- opensmi_ros2-0.1.0.dist-info/WHEEL +5 -0
- opensmi_ros2-0.1.0.dist-info/entry_points.txt +2 -0
- opensmi_ros2-0.1.0.dist-info/licenses/LICENSES/MIT.txt +18 -0
- opensmi_ros2-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""The one field-selection mechanism: include and exclude globs over ROS2 field paths.
|
|
6
|
+
|
|
7
|
+
Every Binding that narrows a message uses it; it is a pure function of a message dataclass.
|
|
8
|
+
|
|
9
|
+
* A pattern is tested against a leaf and against each of its ancestors, so ``exclude=("pose",)``
|
|
10
|
+
removes every field under ``pose``.
|
|
11
|
+
* Exclude wins. Include narrows first, exclude removes after.
|
|
12
|
+
* A pattern that matches nothing is fatal, as is a selection that leaves no field.
|
|
13
|
+
|
|
14
|
+
Patterns are ``fnmatch`` globs matched against the whole path, with ``/`` an ordinary character:
|
|
15
|
+
``*`` crosses levels, so ``*/position/*`` reaches a position at any depth. A repeated message
|
|
16
|
+
field (``sequence<PoseStamped>``) is a leaf: it can be selected by name, but nothing inside it can.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from dataclasses import field as dataclass_field
|
|
23
|
+
from fnmatch import fnmatchcase
|
|
24
|
+
from typing import TYPE_CHECKING
|
|
25
|
+
|
|
26
|
+
from opensmi.ros2.runtime.errors import FieldSelectionError
|
|
27
|
+
from opensmi.ros2.runtime.messages import NestedType
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
|
31
|
+
|
|
32
|
+
from opensmi.ros2.runtime.messages import Message
|
|
33
|
+
|
|
34
|
+
__all__ = ["FieldSelection", "field_paths", "resolve_selection"]
|
|
35
|
+
|
|
36
|
+
SEPARATOR = "/"
|
|
37
|
+
"""What joins a field path, and what a UA variable name is joined with."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
41
|
+
class FieldSelection:
|
|
42
|
+
"""Which fields of a message type a Binding exposes.
|
|
43
|
+
|
|
44
|
+
:ivar include: Patterns narrowing the message to what they match. Empty means every field,
|
|
45
|
+
which is the ordinary case: a Binding that wants the whole message says nothing.
|
|
46
|
+
:ivar exclude: Patterns removing what they match, after ``include`` has narrowed.
|
|
47
|
+
:ivar rename: New names by exact field path. The Binding checks a name against the naming
|
|
48
|
+
rule; :func:`resolve_selection` checks the path is rendered.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
include: tuple[str, ...] = ()
|
|
52
|
+
exclude: tuple[str, ...] = ()
|
|
53
|
+
rename: Mapping[str, str] = dataclass_field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def patterns(self) -> tuple[str, ...]:
|
|
57
|
+
"""Return every declared pattern (include, then exclude)."""
|
|
58
|
+
return (*self.include, *self.exclude)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def field_paths(message_type: type[Message]) -> tuple[str, ...]:
|
|
62
|
+
"""Return every field path a message type reaches, in ROS2 declaration order.
|
|
63
|
+
|
|
64
|
+
Interior paths are included, so ``pose`` appears beside ``pose/position/x``.
|
|
65
|
+
"""
|
|
66
|
+
return tuple(path for path, _ in _walk(message_type, ""))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def resolve_selection(message_type: type[Message], selection: FieldSelection) -> frozenset[str]:
|
|
70
|
+
"""Return the field paths that survive a selection, interior paths included.
|
|
71
|
+
|
|
72
|
+
:raises FieldSelectionError: When a declared pattern matches no path of the type.
|
|
73
|
+
:raises FieldSelectionError: When nothing survives.
|
|
74
|
+
:raises FieldSelectionError: When ``rename`` names a path that is not rendered: unknown or removed.
|
|
75
|
+
"""
|
|
76
|
+
walked = tuple(_walk(message_type, ""))
|
|
77
|
+
_require_every_pattern_matches(message_type, selection, [path for path, _ in walked])
|
|
78
|
+
|
|
79
|
+
surviving: set[str] = set()
|
|
80
|
+
for path, leaf in walked:
|
|
81
|
+
if not leaf:
|
|
82
|
+
continue
|
|
83
|
+
if selection.include and not _matched(path, selection.include):
|
|
84
|
+
continue
|
|
85
|
+
if _matched(path, selection.exclude):
|
|
86
|
+
continue
|
|
87
|
+
surviving.update(_ancestors_or_self(path))
|
|
88
|
+
if not surviving and any(leaf for _, leaf in walked):
|
|
89
|
+
# Only where the type had leaves: `std_msgs/Empty` has none, and an empty result is right for it.
|
|
90
|
+
message = (
|
|
91
|
+
f"the include and exclude patterns leave {message_type.ros2.type_name} with no field "
|
|
92
|
+
f"at all; a Binding with no variables is a declaration nobody meant"
|
|
93
|
+
)
|
|
94
|
+
raise FieldSelectionError(message)
|
|
95
|
+
_require_renames_to_be_rendered(message_type, selection, surviving)
|
|
96
|
+
return frozenset(surviving)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _require_renames_to_be_rendered(
|
|
100
|
+
message_type: type[Message],
|
|
101
|
+
selection: FieldSelection,
|
|
102
|
+
rendered: set[str],
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Refuse a rename of a path the Binding does not render."""
|
|
105
|
+
missing = sorted(path for path in selection.rename if path not in rendered)
|
|
106
|
+
if not missing:
|
|
107
|
+
return
|
|
108
|
+
listed = ", ".join(repr(path) for path in missing)
|
|
109
|
+
message = (
|
|
110
|
+
f"rename names {listed}, which {message_type.ros2.type_name} does not render with this selection; "
|
|
111
|
+
f"rendered fields are {', '.join(sorted(rendered))}"
|
|
112
|
+
)
|
|
113
|
+
raise FieldSelectionError(message)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _walk(message_type: type[Message], prefix: str) -> Iterator[tuple[str, bool]]:
|
|
117
|
+
"""Yield every path below a message type, paired with whether it is a leaf."""
|
|
118
|
+
for field in message_type.ros2.fields:
|
|
119
|
+
path = f"{prefix}{field.name}"
|
|
120
|
+
nested = message_type.ros2_nested.get(field.name)
|
|
121
|
+
if nested is not None and isinstance(field.field_type, NestedType):
|
|
122
|
+
yield path, False
|
|
123
|
+
yield from _walk(nested, f"{path}{SEPARATOR}")
|
|
124
|
+
else:
|
|
125
|
+
yield path, True
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _require_every_pattern_matches(
|
|
129
|
+
message_type: type[Message],
|
|
130
|
+
selection: FieldSelection,
|
|
131
|
+
paths: Sequence[str],
|
|
132
|
+
) -> None:
|
|
133
|
+
"""Refuse a declaration carrying a pattern that matches no path of this message type."""
|
|
134
|
+
unmatched = [pattern for pattern in selection.patterns if not any(fnmatchcase(path, pattern) for path in paths)]
|
|
135
|
+
if not unmatched:
|
|
136
|
+
return
|
|
137
|
+
listed = ", ".join(repr(pattern) for pattern in sorted(set(unmatched)))
|
|
138
|
+
message = f"{listed} matches no field of {message_type.ros2.type_name}; its fields are {', '.join(paths)}"
|
|
139
|
+
raise FieldSelectionError(message)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _matched(path: str, patterns: Iterable[str]) -> bool:
|
|
143
|
+
"""Return whether a pattern matches this path or any path it hangs below."""
|
|
144
|
+
return any(fnmatchcase(each, pattern) for each in _ancestors_or_self(path) for pattern in patterns)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _ancestors_or_self(path: str) -> tuple[str, ...]:
|
|
148
|
+
"""Return ``a``, ``a/b``, ``a/b/c`` for ``a/b/c``: the path and everything carrying it."""
|
|
149
|
+
parts = path.split(SEPARATOR)
|
|
150
|
+
return tuple(SEPARATOR.join(parts[: index + 1]) for index in range(len(parts)))
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""Filling a message header's timestamp, so that no declaration has to hand-write a clock.
|
|
6
|
+
|
|
7
|
+
A client writing a pose into a Skill's Parameters says where, not when, so the adapter fills the
|
|
8
|
+
time. It fills a stamp only where it is still zero, which is ROS2's convention for unset (``tf2``
|
|
9
|
+
reads it as "latest available"); a stamp a client wrote is kept.
|
|
10
|
+
|
|
11
|
+
A stamp is a field named ``stamp`` whose message has exactly the fields ``sec`` and ``nanosec``.
|
|
12
|
+
The name is part of the test because ``builtin_interfaces/msg/Duration`` has the same two fields.
|
|
13
|
+
The clock belongs to the Runtime, since a ROS2 node may run on simulated time.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from functools import cache
|
|
19
|
+
from typing import TYPE_CHECKING, Final
|
|
20
|
+
|
|
21
|
+
from opensmi.ros2.runtime.messages import Message, NestedType, PrimitiveType
|
|
22
|
+
|
|
23
|
+
if TYPE_CHECKING:
|
|
24
|
+
from opensmi.ros2.runtime.messages import MessageDescription
|
|
25
|
+
|
|
26
|
+
__all__ = ["NANOSECONDS_FIELD", "SECONDS_FIELD", "STAMP_FIELD", "stamp_paths", "stamped"]
|
|
27
|
+
|
|
28
|
+
STAMP_FIELD: Final = "stamp"
|
|
29
|
+
"""The one field name this module fills."""
|
|
30
|
+
|
|
31
|
+
SECONDS_FIELD: Final = "sec"
|
|
32
|
+
"""The whole-seconds field of a ``builtin_interfaces/msg/Time``."""
|
|
33
|
+
|
|
34
|
+
NANOSECONDS_FIELD: Final = "nanosec"
|
|
35
|
+
"""The remainder field of a ``builtin_interfaces/msg/Time``. The TF facet reuses both names."""
|
|
36
|
+
|
|
37
|
+
_TIME_FIELDS: Final = {
|
|
38
|
+
SECONDS_FIELD: PrimitiveType(name="int32"),
|
|
39
|
+
NANOSECONDS_FIELD: PrimitiveType(name="uint32"),
|
|
40
|
+
}
|
|
41
|
+
"""The shape that identifies ``builtin_interfaces/msg/Time``."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@cache
|
|
45
|
+
def stamp_paths(message_type: type[Message]) -> tuple[tuple[str, ...], ...]:
|
|
46
|
+
"""Return the field-name chain of every stamp reachable in one message type.
|
|
47
|
+
|
|
48
|
+
A repeated message field is not descended into: a client that authored a list of waypoints
|
|
49
|
+
authored their times too (:mod:`opensmi.ros2.runtime.tf` writes its own for a ``TFMessage``).
|
|
50
|
+
"""
|
|
51
|
+
found: list[tuple[str, ...]] = []
|
|
52
|
+
for field in message_type.ros2.fields:
|
|
53
|
+
nested = message_type.ros2_nested.get(field.name)
|
|
54
|
+
if nested is None or not isinstance(field.field_type, NestedType):
|
|
55
|
+
continue
|
|
56
|
+
if field.name == STAMP_FIELD and _is_a_time(nested.ros2):
|
|
57
|
+
found.append((field.name,))
|
|
58
|
+
continue
|
|
59
|
+
found.extend((field.name, *below) for below in stamp_paths(nested))
|
|
60
|
+
return tuple(found)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def stamped(message: Message, *, seconds: int, nanoseconds: int) -> Message:
|
|
64
|
+
"""Return the message with every stamp that is still zero filled from one clock reading.
|
|
65
|
+
|
|
66
|
+
One clock reading serves the whole message. The same object is returned when nothing needed filling.
|
|
67
|
+
|
|
68
|
+
:param seconds: The whole seconds of the ROS2 clock, for the ``sec`` field.
|
|
69
|
+
:param nanoseconds: The remainder, for the ``nanosec`` field.
|
|
70
|
+
"""
|
|
71
|
+
for path in stamp_paths(type(message)):
|
|
72
|
+
message = _filled(message, path, seconds, nanoseconds)
|
|
73
|
+
return message
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _filled(message: Message, path: tuple[str, ...], seconds: int, nanoseconds: int) -> Message:
|
|
77
|
+
"""Return the message with the stamp at one chain filled, or the message itself if it is set."""
|
|
78
|
+
name, rest = path[0], path[1:]
|
|
79
|
+
held = getattr(message, name)
|
|
80
|
+
if rest:
|
|
81
|
+
replaced = _filled(held, rest, seconds, nanoseconds)
|
|
82
|
+
elif getattr(held, SECONDS_FIELD) or getattr(held, NANOSECONDS_FIELD):
|
|
83
|
+
return message
|
|
84
|
+
else:
|
|
85
|
+
replaced = type(held)(**{SECONDS_FIELD: seconds, NANOSECONDS_FIELD: nanoseconds})
|
|
86
|
+
if replaced is held:
|
|
87
|
+
return message
|
|
88
|
+
return _with(message, name, replaced)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _with(message: Message, name: str, value: Message) -> Message:
|
|
92
|
+
"""Return a copy of one message with one field replaced; other fields are carried by reference."""
|
|
93
|
+
fields = {field.name: getattr(message, field.name) for field in message.ros2.fields}
|
|
94
|
+
fields[name] = value
|
|
95
|
+
return type(message)(**fields)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _is_a_time(described: MessageDescription) -> bool:
|
|
99
|
+
"""Return whether a message description is ``builtin_interfaces/msg/Time``'s shape."""
|
|
100
|
+
return {field.name: field.field_type for field in described.fields} == _TIME_FIELDS
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Technologie-Initiative SmartFactory KL e.V.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""The Subscription handle: one topic's lifetime and its signals, in one object.
|
|
6
|
+
|
|
7
|
+
Messages are awaited one at a time or iterated. The handle also reports type-hash mismatches, the
|
|
8
|
+
publisher count, and the QoS profile with its provenance. It
|
|
9
|
+
stays the same across a QoS adaptation: the ``rclpy`` subscription underneath is re-created while
|
|
10
|
+
this object, its buffer and its consumers are untouched. The publisher count comes from DDS match
|
|
11
|
+
events, so the graph poll is not needed for subscribed topics.
|
|
12
|
+
|
|
13
|
+
The write side is a separate object, :class:`SubscriptionSink`, held only by the Runtime, so a
|
|
14
|
+
Component author cannot inject messages. Nothing here imports ``rclpy``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
from collections import deque
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import TYPE_CHECKING, final
|
|
23
|
+
|
|
24
|
+
from opensmi.ros2.runtime.errors import LoopAffinityError, SubscriptionClosedError
|
|
25
|
+
from opensmi.ros2.runtime.qos import MOST_PERMISSIVE, Provenance, QoSIncompatibility, QoSProfile
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
29
|
+
|
|
30
|
+
from opensmi.ros2.runtime.messages import Message
|
|
31
|
+
|
|
32
|
+
__all__ = ["Subscription", "SubscriptionSink", "TypeHashMismatch", "TypeHashMismatchWarning"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TypeHashMismatchWarning(UserWarning):
|
|
36
|
+
"""A publisher's type hash differs from the one this Runtime built its dataclass against.
|
|
37
|
+
|
|
38
|
+
A warning, not an error: the message is probably still decodable.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
43
|
+
class TypeHashMismatch:
|
|
44
|
+
"""A publisher whose type hash differs from the one this Runtime built its dataclass against.
|
|
45
|
+
|
|
46
|
+
:ivar topic: The ROS2 topic both endpoints are on.
|
|
47
|
+
:ivar node_name: The fully qualified name of the publishing node.
|
|
48
|
+
:ivar topic_type: The type name that publisher advertises.
|
|
49
|
+
:ivar published_hash: The publisher's type hash, as ROS2 spells it.
|
|
50
|
+
:ivar expected_hash: The type hash of this Runtime's own subscription on that topic.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
topic: str
|
|
54
|
+
node_name: str
|
|
55
|
+
topic_type: str
|
|
56
|
+
published_hash: str
|
|
57
|
+
expected_hash: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@final
|
|
61
|
+
class SubscriptionSink:
|
|
62
|
+
"""The write side of a :class:`Subscription`; every method runs on the Runtime's event loop."""
|
|
63
|
+
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
*,
|
|
67
|
+
depth: int,
|
|
68
|
+
qos: QoSProfile = MOST_PERMISSIVE,
|
|
69
|
+
provenance: Provenance = Provenance.DISCOVERED,
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Open a sink buffering at most ``depth`` messages, affine to the running loop.
|
|
72
|
+
|
|
73
|
+
:param depth: How many messages may wait for a consumer. When the buffer is full the
|
|
74
|
+
oldest is dropped, since a Monitoring variable wants the newest value.
|
|
75
|
+
:param qos: The profile the subscription opened with.
|
|
76
|
+
:param provenance: Where that profile came from.
|
|
77
|
+
:raises RuntimeError: When constructed with no running event loop.
|
|
78
|
+
:raises ValueError: When ``depth`` is below 1.
|
|
79
|
+
"""
|
|
80
|
+
if depth < 1:
|
|
81
|
+
message = f"a subscription depth must be at least 1, not {depth}"
|
|
82
|
+
raise ValueError(message)
|
|
83
|
+
# Captured because `asyncio.Event` binds to the first loop that awaits it; another loop
|
|
84
|
+
# would hang without an error.
|
|
85
|
+
self._loop = asyncio.get_running_loop()
|
|
86
|
+
self._messages: deque[Message] = deque(maxlen=depth)
|
|
87
|
+
self._arrival = asyncio.Event()
|
|
88
|
+
self._mismatches: list[TypeHashMismatch] = []
|
|
89
|
+
self._publishers = 0
|
|
90
|
+
self._matched = asyncio.Event()
|
|
91
|
+
self._qos = qos
|
|
92
|
+
self._provenance = provenance
|
|
93
|
+
self._incompatibilities: list[QoSIncompatibility] = []
|
|
94
|
+
self._incompatible = asyncio.Event()
|
|
95
|
+
self._closed = False
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def closed(self) -> bool:
|
|
99
|
+
"""Return whether the subscription's lifetime has ended."""
|
|
100
|
+
return self._closed
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def type_hash_mismatches(self) -> tuple[TypeHashMismatch, ...]:
|
|
104
|
+
"""Return every type-hash disagreement seen on this topic so far."""
|
|
105
|
+
return tuple(self._mismatches)
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def publisher_count(self) -> int:
|
|
109
|
+
"""Return how many publishers this subscription is currently matched with."""
|
|
110
|
+
return self._publishers
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def qos(self) -> QoSProfile:
|
|
114
|
+
"""Return the QoS profile the subscription is currently asking for."""
|
|
115
|
+
return self._qos
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def qos_provenance(self) -> Provenance:
|
|
119
|
+
"""Return where that profile came from, and therefore whether it may adapt."""
|
|
120
|
+
return self._provenance
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def qos_incompatibilities(self) -> tuple[QoSIncompatibility, ...]:
|
|
124
|
+
"""Return every incompatibility the middleware has reported on this topic so far."""
|
|
125
|
+
return tuple(self._incompatibilities)
|
|
126
|
+
|
|
127
|
+
def note_qos(self, profile: QoSProfile) -> None:
|
|
128
|
+
"""Record the profile this subscription asks for, after a re-subscription made it true."""
|
|
129
|
+
self._qos = profile
|
|
130
|
+
|
|
131
|
+
def note_incompatibility(self, incompatibility: QoSIncompatibility) -> bool:
|
|
132
|
+
"""Record one incompatibility the middleware reported, unless it is one already recorded.
|
|
133
|
+
|
|
134
|
+
Deduplicated by policy and request, so a flapping publisher cannot produce an unbounded
|
|
135
|
+
list or an event storm. A clash after an adaptation counts as new, since the request moved.
|
|
136
|
+
|
|
137
|
+
:return: Whether this was new. The caller logs only then.
|
|
138
|
+
"""
|
|
139
|
+
seen = (incompatibility.policy, incompatibility.request)
|
|
140
|
+
if any((each.policy, each.request) == seen for each in self._incompatibilities):
|
|
141
|
+
return False
|
|
142
|
+
self._incompatibilities.append(incompatibility)
|
|
143
|
+
self._incompatible.set()
|
|
144
|
+
return True
|
|
145
|
+
|
|
146
|
+
async def await_incompatibilities(self, seen: int) -> int:
|
|
147
|
+
"""Await more incompatibilities than have been seen, and return how many there now are.
|
|
148
|
+
|
|
149
|
+
:raises SubscriptionClosedError: When the subscription closes while waiting.
|
|
150
|
+
:raises LoopAffinityError: When awaited on a loop other than this sink's.
|
|
151
|
+
"""
|
|
152
|
+
self.require_own_loop()
|
|
153
|
+
while len(self._incompatibilities) <= seen:
|
|
154
|
+
if self._closed:
|
|
155
|
+
message = "this subscription is closed and will report no further incompatibilities"
|
|
156
|
+
raise SubscriptionClosedError(message)
|
|
157
|
+
# No await between clear and wait, so no report can slip into the gap (same loop).
|
|
158
|
+
self._incompatible.clear()
|
|
159
|
+
await self._incompatible.wait()
|
|
160
|
+
return len(self._incompatibilities)
|
|
161
|
+
|
|
162
|
+
def note_publishers(self, count: int) -> None:
|
|
163
|
+
"""Accept the publisher count a match event reported (a missed event costs nothing)."""
|
|
164
|
+
if count == self._publishers:
|
|
165
|
+
return
|
|
166
|
+
self._publishers = count
|
|
167
|
+
self._matched.set()
|
|
168
|
+
|
|
169
|
+
async def await_publishers(self, seen: int) -> int:
|
|
170
|
+
"""Await a publisher count other than one already seen, and return it.
|
|
171
|
+
|
|
172
|
+
:raises SubscriptionClosedError: When the subscription closes while waiting.
|
|
173
|
+
:raises LoopAffinityError: When awaited on a loop other than this sink's.
|
|
174
|
+
"""
|
|
175
|
+
self.require_own_loop()
|
|
176
|
+
while self._publishers == seen:
|
|
177
|
+
if self._closed:
|
|
178
|
+
message = "this subscription is closed and will match no further publishers"
|
|
179
|
+
raise SubscriptionClosedError(message)
|
|
180
|
+
# No await between clear and wait, so no match can slip into the gap (same loop).
|
|
181
|
+
self._matched.clear()
|
|
182
|
+
await self._matched.wait()
|
|
183
|
+
return self._publishers
|
|
184
|
+
|
|
185
|
+
def deliver(self, message: Message) -> None:
|
|
186
|
+
"""Accept one decoded message, dropping the oldest buffered one if the buffer is full."""
|
|
187
|
+
self._messages.append(message)
|
|
188
|
+
self._arrival.set()
|
|
189
|
+
|
|
190
|
+
def note_type_hash_mismatch(self, mismatch: TypeHashMismatch) -> None:
|
|
191
|
+
"""Record a type-hash disagreement seen on this topic."""
|
|
192
|
+
self._mismatches.append(mismatch)
|
|
193
|
+
|
|
194
|
+
def close(self) -> None:
|
|
195
|
+
"""End the stream, waking every consumer waiting on it."""
|
|
196
|
+
self.require_own_loop()
|
|
197
|
+
self._closed = True
|
|
198
|
+
self._arrival.set()
|
|
199
|
+
self._matched.set()
|
|
200
|
+
self._incompatible.set()
|
|
201
|
+
|
|
202
|
+
def require_own_loop(self) -> None:
|
|
203
|
+
"""Refuse an operation running on a loop other than the one this sink was opened on.
|
|
204
|
+
|
|
205
|
+
:raises LoopAffinityError: When the running loop is not this sink's.
|
|
206
|
+
"""
|
|
207
|
+
if asyncio.get_running_loop() is not self._loop:
|
|
208
|
+
message = (
|
|
209
|
+
"this subscription is affine to the event loop it was opened on; this call is on "
|
|
210
|
+
"another one, which would wait on messages that are being delivered elsewhere"
|
|
211
|
+
)
|
|
212
|
+
raise LoopAffinityError(message)
|
|
213
|
+
|
|
214
|
+
async def take(self) -> Message:
|
|
215
|
+
"""Await the next buffered message.
|
|
216
|
+
|
|
217
|
+
:raises SubscriptionClosedError: When the subscription is closed and the buffer is empty.
|
|
218
|
+
:raises LoopAffinityError: When awaited on a loop other than this sink's.
|
|
219
|
+
"""
|
|
220
|
+
self.require_own_loop()
|
|
221
|
+
while not self._messages:
|
|
222
|
+
if self._closed:
|
|
223
|
+
message = "this subscription is closed and has no buffered messages left"
|
|
224
|
+
raise SubscriptionClosedError(message)
|
|
225
|
+
# No await between clear and wait, so no message can slip into the gap (same loop).
|
|
226
|
+
self._arrival.clear()
|
|
227
|
+
await self._arrival.wait()
|
|
228
|
+
return self._messages.popleft()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@final
|
|
232
|
+
class Subscription:
|
|
233
|
+
"""A live subscription to one ROS2 topic, from :meth:`RuntimeInterface.subscribe`.
|
|
234
|
+
|
|
235
|
+
Iterate it (``async for message in subscription``) or await :meth:`receive`; end it with
|
|
236
|
+
:meth:`close`.
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
def __init__(
|
|
240
|
+
self,
|
|
241
|
+
*,
|
|
242
|
+
topic: str,
|
|
243
|
+
message_type: type[Message],
|
|
244
|
+
sink: SubscriptionSink,
|
|
245
|
+
release: Callable[[], Awaitable[None]],
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Bind a handle to the sink and the teardown the Runtime prepared for it."""
|
|
248
|
+
self._topic = topic
|
|
249
|
+
self._message_type = message_type
|
|
250
|
+
self._sink = sink
|
|
251
|
+
self._release = release
|
|
252
|
+
|
|
253
|
+
def __repr__(self) -> str:
|
|
254
|
+
"""Return a representation naming the topic and the ROS2 type."""
|
|
255
|
+
state = "closed" if self._sink.closed else "open"
|
|
256
|
+
return f"<Subscription {self._topic} {self._message_type.ros2.type_name} ({state})>"
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def topic(self) -> str:
|
|
260
|
+
"""Return the ROS2 topic this subscription is on."""
|
|
261
|
+
return self._topic
|
|
262
|
+
|
|
263
|
+
@property
|
|
264
|
+
def message_type(self) -> type[Message]:
|
|
265
|
+
"""Return the message dataclass every payload from this subscription is an instance of."""
|
|
266
|
+
return self._message_type
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def type_hash_mismatches(self) -> tuple[TypeHashMismatch, ...]:
|
|
270
|
+
"""Return every publisher seen whose type hash is not the one built against (stale definition)."""
|
|
271
|
+
return self._sink.type_hash_mismatches
|
|
272
|
+
|
|
273
|
+
@property
|
|
274
|
+
def publisher_count(self) -> int:
|
|
275
|
+
"""Return how many publishers this subscription is matched with right now.
|
|
276
|
+
|
|
277
|
+
Zero means nobody is on the other end, which differs from a matched topic that is silent;
|
|
278
|
+
a Monitoring variable's status code distinguishes the two.
|
|
279
|
+
"""
|
|
280
|
+
return self._sink.publisher_count
|
|
281
|
+
|
|
282
|
+
@property
|
|
283
|
+
def qos(self) -> QoSProfile:
|
|
284
|
+
"""Return the QoS profile in force; it moves only when a discovered profile adapts."""
|
|
285
|
+
return self._sink.qos
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def qos_provenance(self) -> Provenance:
|
|
289
|
+
"""Return where the profile came from: ``DISCOVERED`` (may adapt) or ``DECLARED`` (never moves)."""
|
|
290
|
+
return self._sink.qos_provenance
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def qos_incompatibilities(self) -> tuple[QoSIncompatibility, ...]:
|
|
294
|
+
"""Return every QoS incompatibility the middleware has reported on this topic."""
|
|
295
|
+
return self._sink.qos_incompatibilities
|
|
296
|
+
|
|
297
|
+
async def follow_qos_incompatibilities(self) -> AsyncIterator[QoSIncompatibility]:
|
|
298
|
+
"""Yield every QoS incompatibility reported on this topic, from the first one onwards.
|
|
299
|
+
|
|
300
|
+
Recorded entries arrive without waiting, and any adaptation an entry caused has already
|
|
301
|
+
happened. The iteration ends when the subscription closes.
|
|
302
|
+
"""
|
|
303
|
+
seen = 0
|
|
304
|
+
while True:
|
|
305
|
+
try:
|
|
306
|
+
total = await self._sink.await_incompatibilities(seen)
|
|
307
|
+
except SubscriptionClosedError:
|
|
308
|
+
return
|
|
309
|
+
recorded = self._sink.qos_incompatibilities
|
|
310
|
+
for each in recorded[seen:total]:
|
|
311
|
+
yield each
|
|
312
|
+
seen = total
|
|
313
|
+
|
|
314
|
+
async def publisher_counts(self) -> AsyncIterator[int]:
|
|
315
|
+
"""Yield the publisher count now, and again each time it changes.
|
|
316
|
+
|
|
317
|
+
The first value arrives without waiting. The iteration ends when the subscription closes.
|
|
318
|
+
"""
|
|
319
|
+
seen = -1 # no real count is -1, so the first iteration yields the current one
|
|
320
|
+
while True:
|
|
321
|
+
try:
|
|
322
|
+
seen = await self._sink.await_publishers(seen)
|
|
323
|
+
except SubscriptionClosedError:
|
|
324
|
+
return
|
|
325
|
+
yield seen
|
|
326
|
+
|
|
327
|
+
async def receive(self) -> Message:
|
|
328
|
+
"""Await the next message.
|
|
329
|
+
|
|
330
|
+
:raises SubscriptionClosedError: When the subscription is closed and nothing is buffered.
|
|
331
|
+
"""
|
|
332
|
+
return await self._sink.take()
|
|
333
|
+
|
|
334
|
+
def __aiter__(self) -> AsyncIterator[Message]:
|
|
335
|
+
"""Return an iterator yielding messages until the subscription is closed."""
|
|
336
|
+
return self._stream()
|
|
337
|
+
|
|
338
|
+
async def _stream(self) -> AsyncIterator[Message]:
|
|
339
|
+
"""Yield messages until the subscription is closed, then stop cleanly."""
|
|
340
|
+
while True:
|
|
341
|
+
try:
|
|
342
|
+
yield await self._sink.take()
|
|
343
|
+
except SubscriptionClosedError:
|
|
344
|
+
return
|
|
345
|
+
|
|
346
|
+
async def close(self) -> None:
|
|
347
|
+
"""End this subscription, releasing its ROS2 resources.
|
|
348
|
+
|
|
349
|
+
Idempotent.
|
|
350
|
+
"""
|
|
351
|
+
if self._sink.closed:
|
|
352
|
+
return
|
|
353
|
+
self._sink.close()
|
|
354
|
+
await self._release()
|