phyelds-ros2 10.4.0__tar.gz

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.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: phyelds-ros2
3
+ Version: 10.4.0
4
+ Summary: ROS 2 integration for phyelds: aggregate programs on ROS 2 robots, one node per robot
5
+ License: Apache-2.0
6
+ Author: Davide Domini
7
+ Author-email: davide.domini@unibo.it
8
+ Requires-Python: >=3.12,<3.15
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Requires-Dist: phyelds (>=10.4.0,<11.0.0)
17
+ Project-URL: Homepage, https://github.com/phyelds/phyelds
18
+ Project-URL: Repository, https://github.com/phyelds/phyelds
19
+ Description-Content-Type: text/markdown
20
+
21
+ # phyelds-ros2
22
+
23
+ [ROS 2](https://docs.ros.org) integration for [phyelds](https://pypi.org/project/phyelds/):
24
+ run aggregate programs on ROS 2 robots, real or simulated, one node per robot.
25
+
26
+ ## Installation
27
+
28
+ Install it in the Python of your ROS 2 distribution, Jazzy or later (Python 3.12 or newer):
29
+
30
+ ```bash
31
+ pip install phyelds-ros2
32
+ ```
33
+
34
+ `rclpy` and the messages come with ROS 2.
35
+
36
+ ## Usage
37
+
38
+ Each robot runs a node in its own namespace, which names the robot:
39
+
40
+ ```bash
41
+ python -m phyelds.ros2 turtles:main --sense turtlesim --neighbourhood range --range 3.5 \
42
+ --source turtle1 --ros-args -r __ns:=/turtle2
43
+ ```
44
+
45
+ The node turns the topics of its robot into sensors and the outputs of its program into
46
+ messages, through `SensorTopic`s and `ActuatorTopic`s: odometry, turtlesim poses,
47
+ differential and holonomic `cmd_vel` drives and text are ready, `reading` and `command` wire
48
+ one field of any topic, and `--topics module:function` adds those of your own. The nodes
49
+ talk to each other on `/phyelds/messages`. A neighbourhood strategy decides which senders
50
+ are neighbours:
51
+
52
+ - `Reachable()`: whoever the network delivers; with `measure=True`, each message carries
53
+ the position of its sender, and neighbours come with their distance and vector;
54
+ - `WithinRange(radius)`: the senders within `radius` metres, from those positions.
55
+
56
+ `AggregateRosNode` is the node for a launcher in Python, and `AggregateNode` the rounds
57
+ without ROS.
58
+
59
+ See the [documentation](https://phyelds.github.io/phyelds/integration/ros2/).
60
+
@@ -0,0 +1,39 @@
1
+ # phyelds-ros2
2
+
3
+ [ROS 2](https://docs.ros.org) integration for [phyelds](https://pypi.org/project/phyelds/):
4
+ run aggregate programs on ROS 2 robots, real or simulated, one node per robot.
5
+
6
+ ## Installation
7
+
8
+ Install it in the Python of your ROS 2 distribution, Jazzy or later (Python 3.12 or newer):
9
+
10
+ ```bash
11
+ pip install phyelds-ros2
12
+ ```
13
+
14
+ `rclpy` and the messages come with ROS 2.
15
+
16
+ ## Usage
17
+
18
+ Each robot runs a node in its own namespace, which names the robot:
19
+
20
+ ```bash
21
+ python -m phyelds.ros2 turtles:main --sense turtlesim --neighbourhood range --range 3.5 \
22
+ --source turtle1 --ros-args -r __ns:=/turtle2
23
+ ```
24
+
25
+ The node turns the topics of its robot into sensors and the outputs of its program into
26
+ messages, through `SensorTopic`s and `ActuatorTopic`s: odometry, turtlesim poses,
27
+ differential and holonomic `cmd_vel` drives and text are ready, `reading` and `command` wire
28
+ one field of any topic, and `--topics module:function` adds those of your own. The nodes
29
+ talk to each other on `/phyelds/messages`. A neighbourhood strategy decides which senders
30
+ are neighbours:
31
+
32
+ - `Reachable()`: whoever the network delivers; with `measure=True`, each message carries
33
+ the position of its sender, and neighbours come with their distance and vector;
34
+ - `WithinRange(radius)`: the senders within `radius` metres, from those positions.
35
+
36
+ `AggregateRosNode` is the node for a launcher in Python, and `AggregateNode` the rounds
37
+ without ROS.
38
+
39
+ See the [documentation](https://phyelds.github.io/phyelds/integration/ros2/).
@@ -0,0 +1,37 @@
1
+ [tool.poetry]
2
+ name = "phyelds-ros2"
3
+ version = "10.4.0"
4
+ description = "ROS 2 integration for phyelds: aggregate programs on ROS 2 robots, one node per robot"
5
+ license = "Apache-2.0"
6
+ authors = [
7
+ "Davide Domini <davide.domini@unibo.it>",
8
+ "Gianluca Aguzzi <gianluca.aguzzi@unibo.it>"
9
+ ]
10
+ homepage = "https://github.com/phyelds/phyelds"
11
+ repository = "https://github.com/phyelds/phyelds"
12
+ readme = "README.md"
13
+
14
+ packages = [
15
+ { include = "phyelds/ros2", from = "src" },
16
+ ]
17
+
18
+ classifiers = [
19
+ "Operating System :: OS Independent",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ ]
22
+
23
+ [tool.poetry.dependencies]
24
+ python = ">=3.12,<3.15"
25
+ phyelds = "^10.4.0"
26
+
27
+ [tool.poetry.group.dev.dependencies]
28
+ pytest = "^9.0.3"
29
+ pylint = "^3.0.0"
30
+ flake8 = "^7.0.0"
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
34
+
35
+ [build-system]
36
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
37
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,20 @@
1
+ """
2
+ Run phyelds programs on ROS 2 robots, one node per robot.
3
+
4
+ Each node is a device: its messages travel as bytes on a topic that all the nodes share, and
5
+ a neighbourhood strategy decides which senders are its neighbours.
6
+ """
7
+ from phyelds.ros2.aggregate_node import AggregateNode
8
+ from phyelds.ros2.host import AggregateRosNode, main
9
+ from phyelds.ros2.neighbourhood import (
10
+ Neighbour,
11
+ Neighbourhood,
12
+ Reachable,
13
+ Transforms,
14
+ WithinRange,
15
+ )
16
+
17
+ __all__ = [
18
+ "AggregateNode", "AggregateRosNode", "Neighbour", "Neighbourhood", "Reachable", "Transforms",
19
+ "WithinRange", "main",
20
+ ]
@@ -0,0 +1,5 @@
1
+ """Run a program on this robot: ``python -m phyelds.ros2 module:function [options]``."""
2
+ from phyelds.ros2.host import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
@@ -0,0 +1,127 @@
1
+ """The rounds of an aggregate program on a ROS 2 node, apart from ROS: what it hears and sends."""
2
+ from collections.abc import Callable, Mapping
3
+ from typing import Any
4
+
5
+ from phyelds.ros2.message import pack, unpack
6
+ from phyelds.ros2.neighbourhood import Neighbour, Neighbourhood, Reachable
7
+ from phyelds.vm.device import Device
8
+
9
+
10
+ class AggregateNode: # pylint: disable=too-many-instance-attributes
11
+ """
12
+ Runs an aggregate program on one robot, from the messages its node hears on a shared topic.
13
+
14
+ The host gives it what the robot hears (``hear``) and what it senses on its topics
15
+ (``sense``), runs a round at each tick of its timer (``run_round``), publishes the bytes
16
+ it returns, and acts on the ``outputs``. The ``position`` sensor, in a frame all the nodes
17
+ share, is the one the neighbourhood measures from.
18
+
19
+ Args:
20
+ device_id: The id of the robot, unique among the nodes that share the topic.
21
+ program: The ``@aggregate`` function to run.
22
+ neighbourhood: Which senders are neighbours; ``Reachable()`` by default.
23
+ sensors: Extra sensors, read at each round, over those sensed on the topics.
24
+ paths: The path mode of the engine: the same on every node.
25
+ lifetime: For how many rounds the message of a silent neighbour is kept. Timers of
26
+ different nodes drift apart, so a neighbour may send twice or not at all between
27
+ two rounds: ``2`` keeps it through one round without a message.
28
+ """
29
+
30
+ def __init__( # pylint: disable=too-many-arguments
31
+ self,
32
+ device_id: str,
33
+ program: Callable[[], Any],
34
+ *,
35
+ neighbourhood: Neighbourhood | None = None,
36
+ sensors: Callable[[], Mapping[str, Any]] | None = None,
37
+ paths: str = "compact",
38
+ lifetime: int = 2,
39
+ ):
40
+ self.device_id = device_id
41
+ self.neighbourhood = Reachable() if neighbourhood is None else neighbourhood
42
+ self.sensors = sensors
43
+ self.lifetime = lifetime
44
+ self.readings: dict[str, Any] = {}
45
+ """The latest value of each sensor sensed on the topics."""
46
+ self._device = Device(device_id, program, paths=paths, lifetime=lifetime)
47
+ # sender -> [what the neighbourhood measured of it, rounds since it was heard]
48
+ self._measured: dict[Any, list] = {}
49
+
50
+ @property
51
+ def result(self) -> Any:
52
+ """The value the program computed in the last round."""
53
+ return self._device.result
54
+
55
+ @property
56
+ def outputs(self) -> dict[str, Any]:
57
+ """What the program stored with ``store`` in the last round."""
58
+ return self._device.outputs
59
+
60
+ @property
61
+ def position(self) -> Any:
62
+ """The ``position`` sensed on the topics; ``None`` until sensed."""
63
+ return self.readings.get("position")
64
+
65
+ def sense(self, readings: Mapping[str, Any]) -> None:
66
+ """
67
+ Take sensors sensed on a topic: they hold until sensed again.
68
+
69
+ Args:
70
+ readings: The sensors, by name.
71
+ """
72
+ self.readings.update(readings)
73
+
74
+ def hear(self, data: bytes) -> None:
75
+ """
76
+ Take a message heard on the shared topic, for the next round, if its sender is a neighbour.
77
+
78
+ Args:
79
+ data: The bytes a node published, possibly this one.
80
+ """
81
+ sender, header, payload = unpack(data)
82
+ if sender == self.device_id:
83
+ return
84
+ neighbour = self.neighbourhood.admit(header, self.position)
85
+ if neighbour is None:
86
+ return
87
+ self._measured[sender] = [neighbour, 0]
88
+ self._device.receive(sender, payload)
89
+
90
+ def run_round(self, time: float) -> bytes:
91
+ """
92
+ Run the program once.
93
+
94
+ Args:
95
+ time: The time of the node, in seconds: the ``time`` sensor.
96
+
97
+ Returns:
98
+ The bytes to publish on the shared topic.
99
+ """
100
+ payload = self._device.run_round(self._sense(time))
101
+ return pack(self.device_id, self.neighbourhood.header(self.position), payload)
102
+
103
+ def _sense(self, time: float) -> dict[str, Any]:
104
+ """
105
+ The sensors of this round.
106
+
107
+ ``neighbors_distances`` and ``neighbors_vectors`` hold the measured neighbours, empty
108
+ before any is, when the neighbourhood measures; they are left out when it does not, so
109
+ that the program shares positions instead.
110
+ """
111
+ for sender in list(self._measured):
112
+ self._measured[sender][1] += 1
113
+ if self._measured[sender][1] > self.lifetime:
114
+ del self._measured[sender]
115
+ neighbours: dict[Any, Neighbour] = {
116
+ sender: entry[0] for sender, entry in self._measured.items()
117
+ }
118
+ sensors: dict[str, Any] = {"time": time, "position": None, **self.readings}
119
+ distances = {
120
+ sender: n.distance for sender, n in neighbours.items() if n.distance is not None
121
+ }
122
+ vectors = {sender: n.vector for sender, n in neighbours.items() if n.vector is not None}
123
+ if self.neighbourhood.measures:
124
+ sensors["neighbors_distances"], sensors["neighbors_vectors"] = distances, vectors
125
+ if self.sensors is not None:
126
+ sensors.update(self.sensors())
127
+ return sensors
@@ -0,0 +1,311 @@
1
+ """
2
+ A ROS 2 node that runs an aggregate program on its robot: ``python -m phyelds.ros2``.
3
+
4
+ The node lives in the namespace of its robot. It senses the topics of its ``SensorTopic``s,
5
+ publishes the outputs of its program on those of its ``ActuatorTopic``s, and shares one
6
+ absolute topic with the other nodes for its messages. ``rclpy`` comes with ROS 2, and is
7
+ imported only here.
8
+ """
9
+ import argparse
10
+ import importlib
11
+ import sys
12
+ from collections.abc import Callable, Iterable, Mapping, Sequence
13
+ from typing import Any
14
+
15
+ from phyelds.ros2.aggregate_node import AggregateNode
16
+ from phyelds.ros2.neighbourhood import Neighbourhood, Reachable, Transforms, WithinRange
17
+ from phyelds.ros2.topics import (
18
+ ActuatorTopic,
19
+ SensorTopic,
20
+ differential_drive,
21
+ holonomic_drive,
22
+ laser_obstacle,
23
+ odometry,
24
+ text,
25
+ turtle_pose,
26
+ )
27
+
28
+ TOPIC = "/phyelds/messages"
29
+ """The topic all the nodes share, by default."""
30
+
31
+ SENSES = {"odom": odometry, "turtlesim": turtle_pose, "scan": laser_obstacle}
32
+ """The sensor topics the command line names, with ``--sense``."""
33
+
34
+ ACTS = ("differential", "holonomic", "label")
35
+ """The actuator topics the command line names, with ``--act``."""
36
+
37
+ NEIGHBOURHOODS = ("reachable", "range", "tf")
38
+ """The neighbourhoods the command line names, with ``--neighbourhood``."""
39
+
40
+
41
+ class AggregateRosNode: # pylint: disable=too-few-public-methods
42
+ """
43
+ A ROS 2 node that runs an aggregate program, one round at each tick of its timer.
44
+
45
+ The rounds follow the clock of the node, so they follow the simulation with ``use_sim_time``.
46
+
47
+ Args:
48
+ program: The ``@aggregate`` function to run.
49
+ node_name: The name of the node.
50
+ namespace: The namespace of the node, that of its robot; that of the command line if
51
+ ``None``.
52
+ device_id: The id of the robot; its namespace without slashes, or the node name in
53
+ the root namespace, if ``None``.
54
+ neighbourhood: Which senders are neighbours, or a function of the ``rclpy`` node that
55
+ builds the strategy, for one that needs the node, such as ``Transforms`` with
56
+ ``tf_locator``; ``Reachable()`` by default.
57
+ sensor_topics: The topics to sense; ``odometry()`` if ``None``.
58
+ actuator_topics: The topics to act on; ``differential_drive()`` and ``text()`` if
59
+ ``None``.
60
+ sensors: Extra sensors, read at each round.
61
+ period: The time between two rounds, in seconds.
62
+ topic: The topic all the nodes share.
63
+ paths: The path mode of the engine: the same on every node.
64
+ lifetime: For how many rounds the message of a silent neighbour is kept.
65
+ """
66
+
67
+ def __init__( # pylint: disable=too-many-arguments,too-many-locals
68
+ self,
69
+ program: Callable[[], Any],
70
+ *,
71
+ node_name: str = "phyelds",
72
+ namespace: str | None = None,
73
+ device_id: str | None = None,
74
+ neighbourhood: Neighbourhood | Callable[[Any], Neighbourhood] | None = None,
75
+ sensor_topics: Iterable[SensorTopic] | None = None,
76
+ actuator_topics: Iterable[ActuatorTopic] | None = None,
77
+ sensors: Callable[[], Mapping[str, Any]] | None = None,
78
+ period: float = 0.1,
79
+ topic: str = TOPIC,
80
+ paths: str = "compact",
81
+ lifetime: int = 2,
82
+ ):
83
+ # pylint: disable=import-error,import-outside-toplevel
84
+ from rclpy.node import Node
85
+ from rclpy.qos import QoSProfile, ReliabilityPolicy
86
+ from std_msgs.msg import UInt8MultiArray
87
+
88
+ self.node = Node(node_name) if namespace is None else Node(node_name, namespace=namespace)
89
+ if neighbourhood is not None and not hasattr(neighbourhood, "admit"):
90
+ neighbourhood = neighbourhood(self.node)
91
+ self.aggregate = AggregateNode(
92
+ device_id or self.node.get_namespace().strip("/") or self.node.get_name(),
93
+ program, neighbourhood=neighbourhood, sensors=sensors, paths=paths, lifetime=lifetime,
94
+ )
95
+ self.rounds = 0
96
+ """How many rounds the node has run."""
97
+ self._messages = UInt8MultiArray
98
+ # Messages are sent again at each round: a lost one is not worth waiting for.
99
+ qos = QoSProfile(depth=100, reliability=ReliabilityPolicy.BEST_EFFORT)
100
+ self._outbox = self.node.create_publisher(UInt8MultiArray, topic, qos)
101
+ self.node.create_subscription(UInt8MultiArray, topic, self._hear, qos)
102
+ for sensor in [odometry()] if sensor_topics is None else sensor_topics:
103
+ self.node.create_subscription(
104
+ _message_type(sensor.message_type), sensor.topic,
105
+ lambda message, read=sensor.read: self._sense(read, message), 10,
106
+ )
107
+ actuators = [differential_drive(), text()] if actuator_topics is None else actuator_topics
108
+ self._actuators = []
109
+ for actuator in actuators:
110
+ message_type = _message_type(actuator.message_type)
111
+ publisher = self.node.create_publisher(message_type, actuator.topic, 10)
112
+ self._actuators.append((actuator, message_type, publisher))
113
+ self.node.create_timer(period, self.run_round)
114
+
115
+ def run_round(self) -> None:
116
+ """Run the program once, publish its message, and act on its outputs."""
117
+ time = self.node.get_clock().now().nanoseconds / 1e9
118
+ message = self._messages()
119
+ message.data = self.aggregate.run_round(time)
120
+ self._outbox.publish(message)
121
+ self.rounds += 1
122
+ for actuator, message_type, publisher in self._actuators:
123
+ value = self.aggregate.outputs.get(actuator.output)
124
+ if value is None:
125
+ continue
126
+ command = message_type()
127
+ if actuator.write(command, value, self.aggregate.readings):
128
+ publisher.publish(command)
129
+
130
+ def _sense(
131
+ self, read: Callable[[Any, Mapping[str, Any]], Mapping[str, Any]], message: Any
132
+ ) -> None:
133
+ """Take the sensors a message of a sensor topic gives."""
134
+ self.aggregate.sense(read(message, self.aggregate.readings))
135
+
136
+ def _hear(self, message: Any) -> None:
137
+ """Take a message of the shared topic."""
138
+ self.aggregate.hear(bytes(message.data))
139
+
140
+
141
+ def main(argv: Sequence[str] | None = None) -> None:
142
+ """
143
+ Run the program that the command line names on this robot, until the node is shut down.
144
+
145
+ Args:
146
+ argv: The command line, ROS arguments included; ``sys.argv`` if ``None``.
147
+ """
148
+ # pylint: disable=import-error,import-outside-toplevel
149
+ import rclpy
150
+ from rclpy.executors import ExternalShutdownException
151
+ from rclpy.utilities import remove_ros_args
152
+
153
+ argv = list(sys.argv if argv is None else argv)
154
+ options = parser().parse_args(remove_ros_args(argv)[1:])
155
+ sensor_topics, actuator_topics = topics_of(options)
156
+ rclpy.init(args=argv)
157
+ host = AggregateRosNode(
158
+ options.program, device_id=options.id, neighbourhood=neighbourhood_of(options),
159
+ sensor_topics=sensor_topics, actuator_topics=actuator_topics,
160
+ sensors=lambda: {"source": host.aggregate.device_id == options.source},
161
+ period=options.period, topic=options.topic, lifetime=options.lifetime,
162
+ )
163
+ try:
164
+ rclpy.spin(host.node)
165
+ except (KeyboardInterrupt, ExternalShutdownException):
166
+ pass
167
+ finally:
168
+ host.node.destroy_node()
169
+ rclpy.try_shutdown()
170
+
171
+
172
+ def parser() -> argparse.ArgumentParser:
173
+ """The options of the command line, besides the ROS arguments."""
174
+ options = argparse.ArgumentParser(
175
+ prog="python -m phyelds.ros2", description="Run a program on this robot."
176
+ )
177
+ options.add_argument("program", type=_function, help="the program to run, as module:function")
178
+ options.add_argument("--id", help="the id of the robot; its namespace by default")
179
+ options.add_argument("--source", help="the id of the robot that senses source")
180
+ options.add_argument("--neighbourhood", choices=NEIGHBOURHOODS, default="reachable",
181
+ help="who is a neighbour: whoever is heard, whoever is within --range, or"
182
+ " whoever tf2 locates")
183
+ options.add_argument("--range", type=float, help="how far a robot reaches, in metres")
184
+ options.add_argument("--frame", help="with tf, the frame of the robot; ID/base_link by default")
185
+ options.add_argument("--fixed-frame", default="map",
186
+ help="with tf, the frame all the robots are located in (default map)")
187
+ options.add_argument("--measure", action="store_true",
188
+ help="with reachable, measure the neighbours from their positions")
189
+ options.add_argument("--sense", nargs="*", choices=tuple(SENSES), default=["odom"],
190
+ help="the topics to sense: odom, a turtlesim pose, a laser scan; or none")
191
+ options.add_argument("--act", nargs="*", choices=ACTS, default=["differential", "label"],
192
+ help="the outputs to act on: velocity, for a robot that turns or one that"
193
+ " moves in any direction, and label; or none")
194
+ options.add_argument("--topics", type=_function,
195
+ help="module:function that returns more SensorTopics and ActuatorTopics")
196
+ options.add_argument("--period", type=float, default=0.1,
197
+ help="the time between two rounds, in seconds")
198
+ options.add_argument("--max-speed", type=float, default=0.2, help="the top speed, in m/s")
199
+ options.add_argument("--turn-rate", type=float, default=1.0,
200
+ help="how fast the robot turns, in rad/s per radian off its velocity")
201
+ options.add_argument("--topic", default=TOPIC, help="the topic all the nodes share")
202
+ options.add_argument("--lifetime", type=int, default=2,
203
+ help="for how many rounds the message of a silent neighbour is kept")
204
+ return options
205
+
206
+
207
+ def neighbourhood_of(
208
+ options: argparse.Namespace,
209
+ ) -> Neighbourhood | Callable[[Any], Neighbourhood]:
210
+ """
211
+ The neighbourhood strategy the command line asks for.
212
+
213
+ Args:
214
+ options: The parsed command line.
215
+
216
+ Returns:
217
+ ``WithinRange`` for ``--neighbourhood range``; for ``--neighbourhood tf``, a function
218
+ of the node that builds ``Transforms`` on tf2; ``Reachable`` otherwise.
219
+
220
+ Raises:
221
+ ValueError: If ``--neighbourhood range`` comes without ``--range``.
222
+ """
223
+ if options.neighbourhood == "tf":
224
+ def transforms(node: Any) -> Neighbourhood:
225
+ frame = options.frame or f"{options.id or node.get_namespace().strip('/')}/base_link"
226
+ return Transforms(frame, tf_locator(node, options.fixed_frame), radius=options.range)
227
+
228
+ return transforms
229
+ if options.neighbourhood == "range":
230
+ if options.range is None:
231
+ raise ValueError("--neighbourhood range needs --range")
232
+ return WithinRange(options.range)
233
+ return Reachable(measure=options.measure)
234
+
235
+
236
+ def topics_of(options: argparse.Namespace) -> tuple[list[SensorTopic], list[ActuatorTopic]]:
237
+ """
238
+ The sensor and actuator topics the command line asks for.
239
+
240
+ Args:
241
+ options: The parsed command line.
242
+
243
+ Returns:
244
+ Those of ``--sense`` and ``--act``, then those that ``--topics`` returns.
245
+
246
+ Raises:
247
+ TypeError: If ``--topics`` returns something that is neither kind of topic.
248
+ """
249
+ sensor_topics = [SENSES[name]() for name in options.sense]
250
+ actuator_topics = [_act(name, options) for name in options.act]
251
+ for extra in options.topics() if options.topics is not None else ():
252
+ if isinstance(extra, SensorTopic):
253
+ sensor_topics.append(extra)
254
+ elif isinstance(extra, ActuatorTopic):
255
+ actuator_topics.append(extra)
256
+ else:
257
+ raise TypeError(f"--topics returned {extra!r}, not a SensorTopic or an ActuatorTopic")
258
+ return sensor_topics, actuator_topics
259
+
260
+
261
+ def _act(name: str, options: argparse.Namespace) -> ActuatorTopic:
262
+ """The actuator topic ``name``, one of ``ACTS``, with the speeds of the command line."""
263
+ if name == "differential":
264
+ return differential_drive(max_speed=options.max_speed, turn_rate=options.turn_rate)
265
+ if name == "holonomic":
266
+ return holonomic_drive(max_speed=options.max_speed)
267
+ return text()
268
+
269
+
270
+ def tf_locator(node: Any, fixed_frame: str = "map") -> Callable[[str], tuple[float, ...] | None]:
271
+ """
272
+ Where frames are in ``fixed_frame``, from the tf2 transforms ``node`` listens to.
273
+
274
+ Args:
275
+ node: The ``rclpy`` node that listens.
276
+ fixed_frame: The frame all the robots are located in.
277
+
278
+ Returns:
279
+ A function from a frame to its position, ``None`` while tf2 cannot transform it.
280
+ """
281
+ # pylint: disable=import-error,import-outside-toplevel
282
+ from rclpy.time import Time
283
+ from tf2_ros import Buffer, TransformException, TransformListener
284
+
285
+ buffer = Buffer()
286
+ node.tf_listener = TransformListener(buffer, node) # kept with the node, which it feeds
287
+
288
+ def locate(frame: str) -> tuple[float, ...] | None:
289
+ try:
290
+ translation = buffer.lookup_transform(fixed_frame, frame, Time()).transform.translation
291
+ except TransformException:
292
+ return None
293
+ return translation.x, translation.y, translation.z
294
+
295
+ return locate
296
+
297
+
298
+ def _message_type(name: str) -> type:
299
+ """The class of the message type ``name``, as ``"package/msg/Type"``."""
300
+ # pylint: disable=import-error,import-outside-toplevel
301
+ from rosidl_runtime_py.utilities import get_message
302
+
303
+ return get_message(name)
304
+
305
+
306
+ def _function(spec: str) -> Callable[..., Any]:
307
+ """The function that ``spec``, ``module:function``, names."""
308
+ module, _, function = spec.partition(":")
309
+ if not module or not function:
310
+ raise argparse.ArgumentTypeError(f"{spec!r} is not module:function")
311
+ return getattr(importlib.import_module(module), function)
@@ -0,0 +1,34 @@
1
+ """The bytes a node sends on the shared topic: its id, a header and the payload of its device."""
2
+ import json
3
+ from collections.abc import Mapping
4
+ from typing import Any
5
+
6
+
7
+ def pack(sender: Any, header: Mapping[str, Any], payload: bytes) -> bytes:
8
+ """
9
+ The message of ``sender``, with ``header`` before the ``payload`` of its device.
10
+
11
+ Args:
12
+ sender: The id of the device that sends, serialisable as JSON.
13
+ header: What the neighbourhood strategy of the receivers needs, serialisable as JSON.
14
+ payload: The bytes of the round of the device.
15
+
16
+ Returns:
17
+ One line of JSON, then the payload as it is.
18
+ """
19
+ return json.dumps([sender, dict(header)]).encode() + b"\n" + payload
20
+
21
+
22
+ def unpack(data: bytes) -> tuple[Any, dict[str, Any], bytes]:
23
+ """
24
+ The sender, the header and the payload of a message that ``pack`` built.
25
+
26
+ Args:
27
+ data: The bytes received.
28
+
29
+ Returns:
30
+ The sender, its header and the payload of its device.
31
+ """
32
+ line, _, payload = data.partition(b"\n")
33
+ sender, header = json.loads(line)
34
+ return sender, header, payload
@@ -0,0 +1,77 @@
1
+ """How a differential-drive robot follows the ``velocity`` a program sends, as a ROS 2 twist."""
2
+ import math
3
+ from collections.abc import Sequence
4
+
5
+ # Below this speed, in m/s, a target is taken as standing still: its direction is noise.
6
+ _STILL = 1e-9
7
+
8
+
9
+ def twist(
10
+ target: Sequence[float], *, yaw: float, max_speed: float, turn_rate: float = 1.0
11
+ ) -> tuple[float, float]:
12
+ """
13
+ The forward and angular speed that take a robot facing ``yaw`` along ``target``.
14
+
15
+ As on Webots and ARGoS, the robot turns towards the target velocity, in the frame of the
16
+ world, and drives forward as much as it already faces it, never backwards.
17
+
18
+ Args:
19
+ target: The velocity the program sent, in m/s, in the frame of the world.
20
+ yaw: Where the robot faces, in radians from the x axis of the world.
21
+ max_speed: The fastest the robot moves forward, in m/s.
22
+ turn_rate: How fast the robot turns, in rad/s for each radian it is off the target.
23
+
24
+ Returns:
25
+ The ``linear.x``, in m/s, and the ``angular.z``, in rad/s, of the twist.
26
+ """
27
+ x, y, *_ = target
28
+ speed = min(math.hypot(x, y), max_speed)
29
+ if speed < _STILL:
30
+ return 0.0, 0.0
31
+ angle = math.remainder(math.atan2(y, x) - yaw, math.tau)
32
+ return speed * max(0.0, math.cos(angle)), turn_rate * angle
33
+
34
+
35
+ def yaw_of(x: float, y: float, z: float, w: float) -> float:
36
+ """
37
+ Where a robot with the orientation of a ROS quaternion faces, about the vertical axis.
38
+
39
+ Args:
40
+ x: The x of the quaternion.
41
+ y: The y of the quaternion.
42
+ z: The z of the quaternion.
43
+ w: The w of the quaternion.
44
+
45
+ Returns:
46
+ The yaw, in radians from the x axis.
47
+ """
48
+ return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
49
+
50
+
51
+ def body_velocity(target: Sequence[float], *, yaw: float, max_speed: float) -> tuple[float, float]:
52
+ """
53
+ The velocity that takes a holonomic robot facing ``yaw`` along ``target``, in its own frame.
54
+
55
+ Args:
56
+ target: The velocity the program sent, in m/s, in the frame of the world.
57
+ yaw: Where the robot faces, in radians from the x axis of the world.
58
+ max_speed: The fastest the robot moves, in m/s.
59
+
60
+ Returns:
61
+ The ``linear.x``, forward, and ``linear.y``, to the left, of the twist, in m/s.
62
+ """
63
+ x, y, *_ = target
64
+ speed = math.hypot(x, y)
65
+ scale = 1.0 if speed <= max_speed else max_speed / speed
66
+ cos, sin = math.cos(yaw), math.sin(yaw)
67
+ return scale * (cos * x + sin * y), scale * (cos * y - sin * x)
68
+
69
+
70
+ def heading_of(yaw: float) -> tuple[float, float, float]:
71
+ """The ``heading`` sensor of a robot facing ``yaw``, in radians: a horizontal unit vector."""
72
+ return math.cos(yaw), math.sin(yaw), 0.0
73
+
74
+
75
+ def yaw_of_heading(heading: Sequence[float]) -> float:
76
+ """Where a robot with ``heading``, a horizontal vector, faces, in radians from the x axis."""
77
+ return math.atan2(heading[1], heading[0])
@@ -0,0 +1,181 @@
1
+ """
2
+ Who, among the nodes heard on the shared topic, is a neighbour: strategies a node is given.
3
+
4
+ A strategy adds to each message what the others need to judge its sender (``header``), and
5
+ judges each message heard (``admit``), from the position of the node that hears it.
6
+ """
7
+ import math
8
+ from collections.abc import Callable, Mapping, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Any, Protocol
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Neighbour:
15
+ """
16
+ A sender a strategy admits, with what it measured of it.
17
+
18
+ Attributes:
19
+ distance: How far the sender is, in metres; ``None`` if the strategy cannot tell.
20
+ vector: From this node to the sender, in the frame of the positions; ``None`` if the
21
+ strategy cannot tell.
22
+ """
23
+
24
+ distance: float | None = None
25
+ vector: tuple[float, ...] | None = None
26
+
27
+
28
+ class Neighbourhood(Protocol):
29
+ """
30
+ A strategy that decides the neighbours of a node.
31
+
32
+ Attributes:
33
+ measures: Whether it measures its neighbours: a node then always senses
34
+ ``neighbors_distances`` and ``neighbors_vectors``, empty before any is measured.
35
+ """
36
+
37
+ measures: bool
38
+
39
+ def header(self, position: Sequence[float] | None) -> dict[str, Any]:
40
+ """What to add to the message of a node at ``position``, ``None`` if unknown."""
41
+
42
+ def admit(
43
+ self, header: Mapping[str, Any], position: Sequence[float] | None
44
+ ) -> Neighbour | None:
45
+ """The sender of ``header``, as a neighbour of a node at ``position``, or ``None``."""
46
+
47
+
48
+ class Reachable:
49
+ """
50
+ The nodes this node hears are its neighbours: the network decides the neighbourhood.
51
+
52
+ On one host, a LAN or in a simulator, every node hears every other; on robots that talk
53
+ over an ad-hoc or mesh radio, the nodes heard are those in range. A node that stops
54
+ sending is forgotten after the ``lifetime`` of its messages.
55
+
56
+ Args:
57
+ measure: Whether each message carries the position of its sender, so that a
58
+ neighbour comes with its distance and vector when both positions are known.
59
+ Positions must then be in a frame all the nodes share.
60
+ """
61
+
62
+ def __init__(self, *, measure: bool = False):
63
+ self.measure = measure
64
+
65
+ @property
66
+ def measures(self) -> bool:
67
+ """Whether it measures its neighbours: with ``measure``."""
68
+ return self.measure
69
+
70
+ def header(self, position: Sequence[float] | None) -> dict[str, Any]:
71
+ """The position of the sender if measuring, ``None`` while it is unknown; else nothing."""
72
+ return _position_header(position) if self.measure else {}
73
+
74
+ def admit(
75
+ self, header: Mapping[str, Any], position: Sequence[float] | None
76
+ ) -> Neighbour | None:
77
+ """The sender, measured if possible: every sender heard is a neighbour."""
78
+ return _measured(header, position) or Neighbour()
79
+
80
+
81
+ class WithinRange:
82
+ """
83
+ The nodes within a radius are neighbours: each message carries the position of its sender.
84
+
85
+ Positions must be in a frame all the nodes share, such as ``map`` or the world of a simulator.
86
+
87
+ Args:
88
+ radius: How far a node reaches, in metres.
89
+ """
90
+
91
+ measures = True
92
+ """It measures its neighbours, from their positions."""
93
+
94
+ def __init__(self, radius: float):
95
+ self.radius = radius
96
+
97
+ def header(self, position: Sequence[float] | None) -> dict[str, Any]:
98
+ """The position of the sender, ``None`` while it is unknown."""
99
+ return _position_header(position)
100
+
101
+ def admit(
102
+ self, header: Mapping[str, Any], position: Sequence[float] | None
103
+ ) -> Neighbour | None:
104
+ """
105
+ The sender, with its distance and the vector to it, if it is within the radius.
106
+
107
+ A sender is not admitted while its position or that of this node is unknown.
108
+ """
109
+ neighbour = _measured(header, position)
110
+ if neighbour is None or neighbour.distance > self.radius:
111
+ return None
112
+ return neighbour
113
+
114
+
115
+ class Transforms:
116
+ """
117
+ Neighbours measured from transforms, such as those of tf2: each message carries the frame
118
+ of its sender, and both frames are located in a frame all the nodes share.
119
+
120
+ It suits robots whose positions come from a localisation, a motion capture system or a
121
+ simulator, published as transforms; ``phyelds.ros2.host.tf_locator`` locates frames with
122
+ tf2. Every sender whose frame is located is a neighbour, within ``radius`` if given.
123
+
124
+ Args:
125
+ frame: The frame of this robot, such as ``robot1/base_link``.
126
+ locate: Where a frame is, in the shared frame; ``None`` if it is not known.
127
+ radius: How far a robot reaches, in metres; ``None`` for no limit.
128
+ """
129
+
130
+ measures = True
131
+ """It measures its neighbours, from the transforms."""
132
+
133
+ def __init__(
134
+ self,
135
+ frame: str,
136
+ locate: Callable[[str], Sequence[float] | None],
137
+ *,
138
+ radius: float | None = None,
139
+ ):
140
+ self.frame = frame
141
+ self.locate = locate
142
+ self.radius = radius
143
+
144
+ def header(self, position: Sequence[float] | None) -> dict[str, Any]: # pylint: disable=unused-argument
145
+ """The frame of the sender."""
146
+ return {"frame": self.frame}
147
+
148
+ def admit( # pylint: disable=unused-argument
149
+ self, header: Mapping[str, Any], position: Sequence[float] | None
150
+ ) -> Neighbour | None:
151
+ """
152
+ The sender, with its distance and the vector to it, if both frames are located and it
153
+ is within the radius.
154
+ """
155
+ frame = header.get("frame")
156
+ there = None if frame is None else self.locate(frame)
157
+ here = self.locate(self.frame)
158
+ if there is None or here is None:
159
+ return None
160
+ neighbour = _between(here, there)
161
+ if self.radius is not None and neighbour.distance > self.radius:
162
+ return None
163
+ return neighbour
164
+
165
+
166
+ def _position_header(position: Sequence[float] | None) -> dict[str, Any]:
167
+ """A header with ``position``, ``None`` while it is unknown."""
168
+ return {"position": None if position is None else list(position)}
169
+
170
+
171
+ def _measured(header: Mapping[str, Any], position: Sequence[float] | None) -> Neighbour | None:
172
+ """The sender of ``header`` measured from ``position``; ``None`` if a position is unknown."""
173
+ if header.get("position") is None or position is None:
174
+ return None
175
+ return _between(position, header["position"])
176
+
177
+
178
+ def _between(here: Sequence[float], there: Sequence[float]) -> Neighbour:
179
+ """A neighbour at ``there``, measured from ``here``."""
180
+ vector = tuple(float(far - near) for far, near in zip(there, here))
181
+ return Neighbour(distance=math.hypot(*vector), vector=vector)
@@ -0,0 +1,233 @@
1
+ """
2
+ Which topics a node reads its sensors from, and writes the outputs of its program to.
3
+
4
+ A ``SensorTopic`` turns each message of a topic into sensors of the program; an
5
+ ``ActuatorTopic`` turns an output of the program into a message. Message types are named as
6
+ ROS names them, ``"package/msg/Type"``, and the conversions see only the fields of the
7
+ messages, so a robot of any kind is wired with the presets below, or with conversions of
8
+ one's own.
9
+ """
10
+ import math
11
+ from collections.abc import Callable, Mapping
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from phyelds.ros2.motion import body_velocity, heading_of, twist, yaw_of, yaw_of_heading
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class SensorTopic:
20
+ """
21
+ A topic whose messages the node senses.
22
+
23
+ Attributes:
24
+ topic: The topic, relative to the namespace of the robot unless absolute.
25
+ message_type: Its type, as ``"package/msg/Type"``.
26
+ read: From a message and the latest sensors, the sensors the message gives, by name;
27
+ they hold until the next one.
28
+ """
29
+
30
+ topic: str
31
+ message_type: str
32
+ read: Callable[[Any, Mapping[str, Any]], Mapping[str, Any]]
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ActuatorTopic:
37
+ """
38
+ A topic the node publishes an output of its program on, after each round.
39
+
40
+ Attributes:
41
+ output: The output of the program, such as ``"velocity"``.
42
+ topic: The topic, relative to the namespace of the robot unless absolute.
43
+ message_type: Its type, as ``"package/msg/Type"``.
44
+ write: Fills a new message from the value of the output and the latest sensors;
45
+ returns whether to publish it. Nothing is published in a round without the output.
46
+ """
47
+
48
+ output: str
49
+ topic: str
50
+ message_type: str
51
+ write: Callable[[Any, Any, Mapping[str, Any]], bool]
52
+
53
+
54
+ def odometry(topic: str = "odom") -> SensorTopic:
55
+ """
56
+ The ``position`` and ``heading`` of the robot, from a ``nav_msgs/Odometry``.
57
+
58
+ Args:
59
+ topic: The odometry topic.
60
+
61
+ Returns:
62
+ The sensor topic.
63
+ """
64
+ def read(message: Any, _sensors: Mapping[str, Any]) -> dict[str, Any]:
65
+ position, orientation = message.pose.pose.position, message.pose.pose.orientation
66
+ angle = yaw_of(orientation.x, orientation.y, orientation.z, orientation.w)
67
+ return {"position": (position.x, position.y, position.z), "heading": heading_of(angle)}
68
+
69
+ return SensorTopic(topic, "nav_msgs/msg/Odometry", read)
70
+
71
+
72
+ def turtle_pose(topic: str = "pose") -> SensorTopic:
73
+ """
74
+ The ``position`` and ``heading`` of a turtle of turtlesim, from a ``turtlesim/Pose``.
75
+
76
+ Args:
77
+ topic: The pose topic.
78
+
79
+ Returns:
80
+ The sensor topic.
81
+ """
82
+ def read(message: Any, _sensors: Mapping[str, Any]) -> dict[str, Any]:
83
+ return {"position": (message.x, message.y, 0.0), "heading": heading_of(message.theta)}
84
+
85
+ return SensorTopic(topic, "turtlesim/msg/Pose", read)
86
+
87
+
88
+ def laser_obstacle(topic: str = "scan") -> SensorTopic:
89
+ """
90
+ The ``obstacle``, from a ``sensor_msgs/LaserScan``: away from the nearest thing it sees.
91
+
92
+ The push points away from the nearest ray within the range of the scan, in the frame of
93
+ the world, and is as long as that ray is close: 1 at ``range_min``, 0 at ``range_max``.
94
+ It is zero when no ray sees anything, and ``None`` before the ``heading`` is sensed. As
95
+ on Webots and ARGoS, ``avoid_obstacles`` and the swarm blocks read it.
96
+
97
+ Args:
98
+ topic: The scan topic.
99
+
100
+ Returns:
101
+ The sensor topic.
102
+ """
103
+ def read(message: Any, sensors: Mapping[str, Any]) -> dict[str, Any]:
104
+ heading = sensors.get("heading")
105
+ if heading is None:
106
+ return {"obstacle": None}
107
+ seen = [
108
+ (distance, message.angle_min + index * message.angle_increment)
109
+ for index, distance in enumerate(message.ranges)
110
+ if message.range_min <= distance <= message.range_max
111
+ ]
112
+ if not seen:
113
+ return {"obstacle": (0.0, 0.0, 0.0)}
114
+ distance, angle = min(seen)
115
+ closeness = 1.0 - (distance - message.range_min) / (message.range_max - message.range_min)
116
+ towards = angle + yaw_of_heading(heading)
117
+ return {"obstacle": (-closeness * math.cos(towards), -closeness * math.sin(towards), 0.0)}
118
+
119
+ return SensorTopic(topic, "sensor_msgs/msg/LaserScan", read)
120
+
121
+
122
+ def reading(name: str, topic: str, message_type: str, *, field: str = "data") -> SensorTopic:
123
+ """
124
+ One field of the messages of a topic, as the sensor ``name``.
125
+
126
+ Args:
127
+ name: The name of the sensor, as the program senses it.
128
+ topic: The topic.
129
+ message_type: Its type, as ``"package/msg/Type"``.
130
+ field: The field of the message, ``data`` for the types of ``std_msgs``.
131
+
132
+ Returns:
133
+ The sensor topic.
134
+ """
135
+ def read(message: Any, _sensors: Mapping[str, Any]) -> dict[str, Any]:
136
+ return {name: getattr(message, field)}
137
+
138
+ return SensorTopic(topic, message_type, read)
139
+
140
+
141
+ def differential_drive(
142
+ topic: str = "cmd_vel", *, max_speed: float = 0.2, turn_rate: float = 1.0
143
+ ) -> ActuatorTopic:
144
+ """
145
+ The ``velocity`` of the program, as the twist of a robot that turns to move, such as a
146
+ differential drive or a car.
147
+
148
+ As on Webots and ARGoS, the robot turns towards the velocity, in the frame of the world,
149
+ and drives forward as much as it already faces it. Nothing is sent before the
150
+ ``heading`` is sensed.
151
+
152
+ Args:
153
+ topic: The ``geometry_msgs/Twist`` topic.
154
+ max_speed: The fastest the robot moves forward, in m/s.
155
+ turn_rate: How fast it turns, in rad/s for each radian it is off the velocity.
156
+
157
+ Returns:
158
+ The actuator topic.
159
+ """
160
+ def write(message: Any, value: Any, sensors: Mapping[str, Any]) -> bool:
161
+ heading = sensors.get("heading")
162
+ if heading is None:
163
+ return False
164
+ message.linear.x, message.angular.z = twist(
165
+ value, yaw=yaw_of_heading(heading), max_speed=max_speed, turn_rate=turn_rate
166
+ )
167
+ return True
168
+
169
+ return ActuatorTopic("velocity", topic, "geometry_msgs/msg/Twist", write)
170
+
171
+
172
+ def holonomic_drive(topic: str = "cmd_vel", *, max_speed: float = 0.2) -> ActuatorTopic:
173
+ """
174
+ The ``velocity`` of the program, as the twist of a robot that moves in any direction,
175
+ such as one with omni wheels: in the frame of the robot, without turning.
176
+
177
+ Nothing is sent before the ``heading`` is sensed.
178
+
179
+ Args:
180
+ topic: The ``geometry_msgs/Twist`` topic.
181
+ max_speed: The fastest the robot moves, in m/s.
182
+
183
+ Returns:
184
+ The actuator topic.
185
+ """
186
+ def write(message: Any, value: Any, sensors: Mapping[str, Any]) -> bool:
187
+ heading = sensors.get("heading")
188
+ if heading is None:
189
+ return False
190
+ message.linear.x, message.linear.y = body_velocity(
191
+ value, yaw=yaw_of_heading(heading), max_speed=max_speed
192
+ )
193
+ return True
194
+
195
+ return ActuatorTopic("velocity", topic, "geometry_msgs/msg/Twist", write)
196
+
197
+
198
+ def text(output: str = "label", topic: str = "label") -> ActuatorTopic:
199
+ """
200
+ An output of the program as text, on a ``std_msgs/String``.
201
+
202
+ Args:
203
+ output: The output, ``label`` by default.
204
+ topic: The topic.
205
+
206
+ Returns:
207
+ The actuator topic.
208
+ """
209
+ def write(message: Any, value: Any, _sensors: Mapping[str, Any]) -> bool:
210
+ message.data = str(value)
211
+ return True
212
+
213
+ return ActuatorTopic(output, topic, "std_msgs/msg/String", write)
214
+
215
+
216
+ def command(output: str, topic: str, message_type: str, *, field: str = "data") -> ActuatorTopic:
217
+ """
218
+ An output of the program, as it is, in one field of the messages of a topic.
219
+
220
+ Args:
221
+ output: The output of the program.
222
+ topic: The topic.
223
+ message_type: Its type, as ``"package/msg/Type"``.
224
+ field: The field of the message, ``data`` for the types of ``std_msgs``.
225
+
226
+ Returns:
227
+ The actuator topic.
228
+ """
229
+ def write(message: Any, value: Any, _sensors: Mapping[str, Any]) -> bool:
230
+ setattr(message, field, value)
231
+ return True
232
+
233
+ return ActuatorTopic(output, topic, message_type, write)