Core Concepts
What is ROS 2 ?
ROS 2 is a middleware based on a strongly-typed, anonymous publish/subscribe mechanism that allows for message passing between different processes.
At the heart of any ROS 2 system is the ROS graph. The ROS graph refers to the network of nodes in a ROS system and the connections between them by which they communicate.
A robot is made up of many parts working at the same time: sensors producing data, algorithms making decisions, and motors carrying out commands. Putting all of them into one big program quickly makes it hard to develop, test and reuse, since every part is tightly coupled to the others.
Despite its name, ROS 2 (Robot Operating System 2) is not an operating system. It provides the communication layer, tools and conventions to split a robot application into many small programs called nodes, each responsible for one thing, which exchange data with each other through named channels.
camera ──/image──→ detector ──/detections──→ planner ──/cmd_vel──→ motors
↑
│ /plan_path (service)
ui_app
Notice that detector doesn't know where /image comes from, nor who consumes /detections. Replacing the real camera with a simulator or a recording requires no change to the rest of the system.
Some characteristics worth noting:
Decoupled: Nodes only agree on channel names and data types, so they can be developed, tested and replaced independently.No central master: Unlike ROS 1 which relies on a master (roscore) to register nodes, nodes in ROS 2 discover each other automatically through the underlyingDDSmiddleware, as long as they are on the same network and share the sameROS_DOMAIN_ID.Language agnostic: Nodes written in Python (rclpy) and C++ (rclcpp) work together seamlessly as long as they agree on the message types.
ROS 2 is released as distributions, such as Humble (2022) and Jazzy (2024). Examples in this note are based on Jazzy and written in Python.
The concepts of ROS 2 build on top of each other, and this note goes through them from the bottom up:
Launch file start and configure many nodes with one command
↑
Parameter configure a node at startup without touching code
↑
Interface the data types carried by topics and services (.msg / .srv)
↑
Topic / Service how nodes talk: data stream v.s request/response
↑
Node one process with one responsibility
↑
Package unit of code to build, install and depend on
↑
Workspace where packages are built, installed and sourced
First Look with Turtlesim
turtlesim is a tiny 2D simulator shipped with ROS 2, which makes it a handy "robot" to play with before writing any code.
# Run in every terminal, or add to ~/.bashrc
source /opt/ros/jazzy/setup.bash
# Terminal 1: the simulator window
ros2 run turtlesim turtlesim_node
# Terminal 2: drive the turtle with arrow keys
ros2 run turtlesim turtle_teleop_key
# Terminal 3: visualize the nodes and the topic between them
rqt_graph
turtle_teleop_key publishes velocity commands to the /turtle1/cmd_vel topic, which turtlesim_node subscribes to. Two independent processes with a topic in between, that is ROS 2 in a nutshell.
Workspace
A workspace is a folder that contains ROS 2 packages, and is where packages are built and installed by the build tool colcon.
ros2_ws/
├── src/ ← packages live here, the only folder to edit
├── build/ ← intermediate files from colcon
├── install/ ← built packages, what actually runs
└── log/
An important point is that the code being run is not the code in src/, but the copy installed into install/ by colcon. Thus every change follows the same cycle, run from the workspace root:
Edit (src/) → colcon build → source install/setup.bash → ros2 run / ros2 launch
# Create a workspace and build it
mkdir -p ~/ros2_ws/src && cd ~/ros2_ws
colcon build
# Make the current terminal aware of the packages in this workspace
source install/setup.bash
# Build a single package only
colcon build --packages-select my_py_pkg
# Link Python, launch and YAML files instead of copying them
colcon build --symlink-install
Sourcing only affects the current terminal. A newly opened terminal knows nothing about the workspace until it is sourced, so it is common to add source ~/ros2_ws/install/setup.bash to ~/.bashrc.
With --symlink-install, changes made to existing Python, launch and YAML files take effect without rebuilding. However, rebuilding is still required when adding a new executable to setup.py, modifying package.xml or adding interfaces.
❓ Why does ros2 run say Package not found ?
Most likely the terminal hasn't been sourced, or the package hasn't been built since it was created. Run colcon build and source install/setup.bash from the workspace root.
Package
A package is the unit of code that is built, installed and depended on as a whole. A Python package can be created inside src/ with:
cd ~/ros2_ws/src
ros2 pkg create my_py_pkg --build-type ament_python --dependencies rclpy
my_py_pkg/
├── package.xml ← name, version and dependencies
├── setup.py ← registers executables
├── setup.cfg ← where executables are installed, so ros2 run can find them
├── resource/my_py_pkg ← marker file for the package index
├── my_py_pkg/ ← Python modules (nodes) go here
│ └── __init__.py
└── test/
Two files need to be updated for every new node:
package.xml: Add a<depend>for each package imported, such asrclpy,example_interfacesor a custom interface package. colcon also relies on it to determine the build order, so a missing dependency might work locally but break on a clean build.setup.py: Register the node as an executable underconsole_scripts, in the form of"<executable> = <module>:<function>".
entry_points={
'console_scripts': [
"py_node = my_py_pkg.my_first_node:main",
"robot_news_station = my_py_pkg.robot_news_station:main",
],
},
Note that a node actually involves three different names, which is a common source of confusion:
File name: The Python module, e.g.my_first_node.py, referenced by the entry point insetup.py.Executable name: The left side of the entry point, e.g.py_node, used byros2 run my_py_pkg py_nodeand launch files.Node name: The name passed to the node's constructor, e.g.py_test, which is what shows up in the ROS graph and can be overridden at runtime.
Packages come in two build types:
ament_python: For Python nodes.ament_cmake: For C++ nodes, but also for custom interfaces (even in a Python-only project) and packages holding only launch and config files.
❓ Why does ros2 run say No executable found ?
The node is either not registered under console_scripts in setup.py, or the package hasn't been rebuilt after registering it.
Node
A node is a participant in the ROS 2 graph, which uses a client library to communicate with other nodes. Nodes can communicate with other nodes within the same process, in a different process, or on a different machine. Nodes are typically the unit of computation in a ROS graph; each node should do one logical thing.
Every Python node follows the same skeleton:
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
class MyNode(Node):
def __init__(self):
super().__init__("py_test") # node name in the ROS graph
self.counter_ = 0
self.get_logger().info("Hello world")
self.create_timer(1.0, self.timer_callback)
def timer_callback(self):
self.get_logger().info("Hello " + str(self.counter_))
self.counter_ += 1
def main(args=None):
rclpy.init(args=args) # 1. initialize ROS 2 communication
node = MyNode() # 2. create the node
rclpy.spin(node) # 3. keep the node alive and run callbacks until Ctrl+C
rclpy.shutdown() # 4. clean up
if __name__ == "__main__":
main()
Unlike a script, a node doesn't run from top to bottom. The constructor only registers callbacks (timers, subscriptions, services, ...), and rclpy.spin() then hands control over to an executor, which waits for events and runs the corresponding callbacks.
rclpy.init() → __init__ registers callbacks → spin(): wait for event → run callback → repeat → shutdown()
By default, callbacks of a node run one at a time on a single thread, meaning that a slow or blocking callback freezes the whole node.
# Run a node
ros2 run my_py_pkg py_node
# List running nodes and inspect one of them
ros2 node list
ros2 node info /py_test
# Rename the node at runtime
ros2 run my_py_pkg py_node --ros-args -r __node:=py_test2
Node names should be unique in the graph, and ros2 node list warns when two nodes share the same name. To run the same executable more than once, rename the node at runtime as above.
Since every node starts from the same skeleton, it is handy to keep it as a template to copy from. Examples below follow the convention of suffixing member attributes with an underscore (e.g. self.counter_), and omit main() as it stays the same.
Topic
Topics are one of the three primary styles of interfaces provided by ROS 2. Topics should be used for continuous data streams, like sensor data, robot state, etc.
A topic is a named channel following the publish/subscribe pattern, where publishers send messages to the topic and every subscriber of the topic receives them. The communication is one-way and anonymous: publishers don't know who is listening, subscribers don't know who is sending, and there can be any number of either.
robot_news_station (C3PO) ──┐
robot_news_station (BB8) ──┼──→ /robot_news ──┬──→ smartphone
robot_news_station (...) ──┘ └──→ any other subscriber
Below is a publisher sending a message every 0.5 second, and a subscriber logging the received messages:
from example_interfaces.msg import String
class RobotNewsStationNode(Node):
def __init__(self):
super().__init__("robot_news_station")
self.publisher_ = self.create_publisher(String, "robot_news", 10)
self.timer_ = self.create_timer(0.5, self.publish_news)
def publish_news(self):
msg = String()
msg.data = "Hi, this is C3PO from the robot news station."
self.publisher_.publish(msg)
from example_interfaces.msg import String
class SmartphoneNode(Node):
def __init__(self):
super().__init__("smartphone")
self.subscriber_ = self.create_subscription(
String, "robot_news", self.callback_robot_news, 10)
def callback_robot_news(self, msg: String):
self.get_logger().info(msg.data)
A few things to notice:
- A publisher and a subscriber are connected only if both the topic name and the message type match.
10is the QoS queue size, which is how many messages are buffered when the receiver can't keep up.- Combining a timer with a publisher is the standard way to publish at a fixed rate.
- A node can be both a publisher and a subscriber. Chaining subscribe → process → publish is how data pipelines are built in ROS 2.
Example: a node that subscribes, processes and republishes
number_counter subscribes to /number, adds each received value to a counter, and publishes the total to /number_count.
from example_interfaces.msg import Int64
class NumberCounterNode(Node):
def __init__(self):
super().__init__("number_counter")
self.counter_ = 0
self.number_count_publisher_ = self.create_publisher(Int64, "number_count", 10)
self.number_subscriber_ = self.create_subscription(
Int64, "number", self.callback_number, 10)
def callback_number(self, msg: Int64):
self.counter_ += msg.data
new_msg = Int64()
new_msg.data = self.counter_
self.number_count_publisher_.publish(new_msg)
Topics can be inspected and debugged from the terminal:
# List topics, then show the type and publisher/subscriber counts of one
ros2 topic list
ros2 topic info /robot_news
# Print incoming messages and measure the publish rate
ros2 topic echo /robot_news
ros2 topic hz /robot_news
# Publish from the terminal at 2 Hz
ros2 topic pub -r 2 /robot_news example_interfaces/msg/String "{data: 'hello'}"
# Remap the topic name at runtime
ros2 run my_py_pkg robot_news_station --ros-args -r robot_news:=my_news
# Record a topic to disk and replay it later
ros2 bag record -o news_bag /robot_news
ros2 bag play news_bag
Since publishers and subscribers are anonymous, ros2 topic pub and ros2 bag play can stand in for a real publisher, making it possible to test a subscriber without the hardware or node that normally feeds it.
❓ Why is my subscriber not receiving anything ?
Compare the topic name and message type on both sides with ros2 topic list and ros2 topic info. A typo in the name or a different message type means the two never connect, so nothing is received.
Service
In ROS 2, a service refers to a remote procedure call. In other words, a node can make a remote procedure call to another node which will do a computation and return a result.
While topics are for streaming data, services follow a request/response pattern, much like calling a function on another node. A service client sends a request to a service server, which processes it and sends a response back.
request {a: 3, b: 8}
add_two_ints_client ─────────────────────→ add_two_ints_server
←─────────────────────
response {sum: 11}
Services are suitable when an answer is needed or something should be done once, such as computing a value, changing a setting or spawning an entity. There can be any number of clients, but there should only be one server per service name. Moreover, services are expected to return quickly, since the client is generally waiting on the result.
Server
from example_interfaces.srv import AddTwoInts
class AddTwoIntsServerNode(Node):
def __init__(self):
super().__init__("add_two_ints_server")
self.server_ = self.create_service(
AddTwoInts, "add_two_ints", self.callback_add_two_ints)
def callback_add_two_ints(self, request: AddTwoInts.Request, response: AddTwoInts.Response):
response.sum = request.a + request.b
return response # the callback must return the response
Client
A client sends a request with call_async(), which immediately returns a future that will hold the response once it arrives. There are two ways to wait for the result.
For a one-off script without a node class, spin until the future completes:
def main(args=None):
rclpy.init(args=args)
node = Node("add_two_ints_client_no_oop")
client = node.create_client(AddTwoInts, "add_two_ints")
while not client.wait_for_service(1.0):
node.get_logger().warn("Waiting for Add Two Ints server...")
request = AddTwoInts.Request()
request.a = 3
request.b = 8
future = client.call_async(request)
rclpy.spin_until_future_complete(node, future)
node.get_logger().info(f"3 + 8 = {future.result().sum}")
rclpy.shutdown()
Inside a node, register a callback on the future instead of waiting for it:
from functools import partial
class AddTwoIntsClient(Node):
def __init__(self):
super().__init__("add_two_ints_client")
self.client_ = self.create_client(AddTwoInts, "add_two_ints")
def call_add_two_ints(self, a, b):
while not self.client_.wait_for_service(1.0):
self.get_logger().warn("Waiting for Add Two Ints server...")
request = AddTwoInts.Request()
request.a = a
request.b = b
future = self.client_.call_async(request)
future.add_done_callback(
partial(self.callback_call_add_two_ints, request=request))
def callback_call_add_two_ints(self, future, request):
response = future.result()
self.get_logger().info(f"{request.a} + {request.b} = {response.sum}")
def main(args=None):
rclpy.init(args=args)
node = AddTwoIntsClient()
node.call_add_two_ints(2, 7)
node.call_add_two_ints(1, 4) # several requests can be in flight at once
rclpy.spin(node) # responses are handled as they arrive
rclpy.shutdown()
functools.partial is used to pass extra context, such as the original request, to the done callback.
A spinning node receives service responses through the same executor that runs its callbacks. If a callback blocks until the response arrives (e.g. a synchronous client.call()), the executor is stuck in that callback and can never deliver the response, so the node deadlocks. Spinning again inside a callback with spin_until_future_complete() doesn't work either. Inside a node, always use call_async() with add_done_callback().
# List services and show the type of one
ros2 service list
ros2 service type /add_two_ints
# Call a service from the terminal
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 3, b: 5}"
# Remap the service name at runtime
ros2 run my_py_pkg add_two_ints_server --ros-args -r add_two_ints:=add_ints
Topic v.s Service
| Topic | Service | |
|---|---|---|
| Pattern | Publish/subscribe, one-way | Request/response |
| Cardinality | Many publishers → many subscribers | Many clients → one server |
| Use for | Continuous data such as sensor data, robot state and commands | Quick computations, one-off actions and setting changes |
| Examples | /robot_news, /turtle1/cmd_vel | /add_two_ints, /spawn |
Long-running tasks that need progress feedback or cancellation, such as navigating to a goal, use a third mechanism called actions, which is not covered in this note.
Interface
ROS 2 uses a simplified description language, the interface definition language (IDL), to describe these interfaces. This description makes it easy for ROS tools to automatically generate source code for the interface type in several target languages.
Every topic and service has a type, described with a plain text interface file:
.msg: Fields of a message sent over a topic..srv: Request fields, a---separator, then response fields.
Fields can be of built-in types including bool, byte, char, int8 to int64, uint8 to uint64, float32, float64 and string, as well as arrays like int64[] and other messages like Turtle[]. At build time, Python and C++ classes are generated from these files, which is how nodes written in different languages share the same types.
Before creating custom interfaces, check what already exists with ros2 interface list:
example_interfaces: Generic types (Int64,String,AddTwoInts,SetBool) meant for learning and examples.std_msgs,geometry_msgs(Twist,Pose) andsensor_msgs(Image,LaserScan): Standard types used across the ROS ecosystem.
Custom Interface
Custom interfaces are placed in a dedicated package so any other package can depend on it. The package must be an ament_cmake package even in a Python-only project, as code generation runs through CMake.
# ament_cmake is the default build type
cd ~/ros2_ws/src
ros2 pkg create my_robot_interfaces
# Replace the C++ folders with msg/ and srv/
cd my_robot_interfaces && rm -rf include src && mkdir msg srv
# msg/HardwareStatus.msg
float64 temperature
bool are_motors_ready
string debug_message
# srv/SetLed.srv
int64 led_number
int64 state
---
bool success
File names must be UpperCamelCase (e.g. HardwareStatus.msg), and field names snake_case. The files then need to be registered in the package's build files before running colcon build:
package.xml and CMakeLists.txt additions
<!-- package.xml -->
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
# CMakeLists.txt, before ament_package()
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
"msg/HardwareStatus.msg"
"srv/SetLed.srv"
)
ament_export_dependencies(rosidl_default_runtime)
If a field uses a type from another package (e.g. geometry_msgs/Pose), also add DEPENDENCIES geometry_msgs to rosidl_generate_interfaces and a <depend> to package.xml.
After adding <depend>my_robot_interfaces</depend> to the package.xml of the package using them, custom interfaces are imported like any other:
from my_robot_interfaces.msg import HardwareStatus
class HardwareStatusPublisherNode(Node):
def __init__(self):
super().__init__("hardware_status_publisher")
self.hw_status_pub_ = self.create_publisher(HardwareStatus, "hardware_status", 10)
self.timer_ = self.create_timer(1.0, self.publish_hw_status)
def publish_hw_status(self):
msg = HardwareStatus()
msg.temperature = 43.7
msg.are_motors_ready = True
msg.debug_message = "Nothing special"
self.hw_status_pub_.publish(msg)
# Show the fields of an interface
ros2 interface show my_robot_interfaces/msg/HardwareStatus
Example: battery and LED panel
battery simulates a battery that empties after 4 seconds and recharges in 6 seconds. On each change, it calls /set_led on led_panel, which updates its LED states and publishes them to /led_panel_state (LedStateArray.msg contains a single field int64[] led_states).
# led_panel.py: service server + publisher
from my_robot_interfaces.msg import LedStateArray
from my_robot_interfaces.srv import SetLed
class LEDPanelNode(Node):
def __init__(self):
super().__init__("led_panel")
self.declare_parameter("led_states", [0, 0, 0])
self.led_states_ = self.get_parameter("led_states").value
self.led_states_pub_ = self.create_publisher(LedStateArray, "led_panel_state", 10)
self.led_states_timer_ = self.create_timer(5.0, self.publish_led_states)
self.set_led_service_ = self.create_service(SetLed, "set_led", self.callback_set_led)
def publish_led_states(self):
msg = LedStateArray()
msg.led_states = self.led_states_
self.led_states_pub_.publish(msg)
def callback_set_led(self, request: SetLed.Request, response: SetLed.Response):
# Validate the request and report failure through the response
if not 0 <= request.led_number < len(self.led_states_) or request.state not in [0, 1]:
response.success = False
return response
self.led_states_[request.led_number] = request.state
self.publish_led_states() # publish right away instead of waiting for the timer
response.success = True
return response
# battery.py: timer-driven state machine + service client
from my_robot_interfaces.srv import SetLed
class BatteryNode(Node):
def __init__(self):
super().__init__("battery")
self.battery_state_ = "full"
self.last_change_ = self.now_seconds()
self.set_led_client_ = self.create_client(SetLed, "set_led")
self.battery_timer_ = self.create_timer(0.1, self.check_battery_state)
def now_seconds(self):
return self.get_clock().now().nanoseconds / 1e9
def check_battery_state(self):
elapsed = self.now_seconds() - self.last_change_
if self.battery_state_ == "full" and elapsed > 4.0:
self.battery_state_ = "empty"
self.call_set_led(2, 1) # turn the third LED on while charging
self.last_change_ = self.now_seconds()
elif self.battery_state_ == "empty" and elapsed > 6.0:
self.battery_state_ = "full"
self.call_set_led(2, 0)
self.last_change_ = self.now_seconds()
def call_set_led(self, led_number, state):
while not self.set_led_client_.wait_for_service(1.0):
self.get_logger().warn("Waiting for Set Led service...")
request = SetLed.Request()
request.led_number = led_number
request.state = state
future = self.set_led_client_.call_async(request)
future.add_done_callback(self.callback_call_set_led)
def callback_call_set_led(self, future):
self.get_logger().info(f"LED changed: {future.result().success}")
Parameter
Parameters in ROS 2 are associated with individual nodes. Parameters are used to configure nodes at startup (and during runtime), without changing the code. The lifetime of a parameter is tied to the lifetime of the node (though the node could implement some sort of persistence to reload values after restart).
Parameters allow the same executable to behave differently without changing its code, for instance running five robot_news_station nodes, each with its own robot_name.
from example_interfaces.msg import Int64
class NumberPublisherNode(Node):
def __init__(self):
super().__init__("number_publisher")
self.declare_parameter("number", 2) # name + default value
self.declare_parameter("timer_period", 1.0)
self.number_ = self.get_parameter("number").value
self.timer_period_ = self.get_parameter("timer_period").value
self.number_publisher_ = self.create_publisher(Int64, "number", 10)
self.number_timer_ = self.create_timer(self.timer_period_, self.publish_number)
def publish_number(self):
msg = Int64()
msg.data = self.number_
self.number_publisher_.publish(msg)
Some rules worth knowing:
Declare before use: A parameter must be declared before it can be read, otherwise aParameterNotDeclaredExceptionis raised. Values passed for undeclared parameters are simply ignored.Default value sets the type: Sincenumberdefaults to an integer, starting the node withnumber:=hellofails.Read once: Parameters are usually read once in the constructor. Setting a new value later updates the stored parameter, but the node keeps using its old copy unless it reacts to the change.
# Set parameters when starting the node
ros2 run my_py_pkg number_publisher --ros-args -p number:=3 -p timer_period:=0.5
# Or load them from a YAML file
ros2 run my_py_pkg number_publisher --ros-args --params-file ~/number_params.yaml
# Inspect and change parameters of a running node
ros2 param list
ros2 param get /number_publisher number
ros2 param set /number_publisher number 7
# Print the current values as YAML
ros2 param dump /number_publisher
In a YAML parameter file, top-level keys are node names followed by a ros__parameters key (with two underscores). Use /** as the key to apply values to every node.
/number_publisher:
ros__parameters:
number: 6
timer_period: 1.5
To react to ros2 param set while the node is running, register a callback:
from rclpy.parameter import Parameter
class NumberPublisherNode(Node):
def __init__(self):
...
self.add_post_set_parameters_callback(self.parameters_callback)
def parameters_callback(self, params: list[Parameter]):
for param in params:
if param.name == "number":
self.number_ = param.value
add_post_set_parameters_callback is only available from Iron onward. On Humble, register the callback with add_on_set_parameters_callback instead, which must return SetParametersResult(successful=True) (from rcl_interfaces.msg), otherwise the change is rejected.
Launch File
The launch system in ROS 2 is meant to automate the running of many nodes with a single command. It helps the user describe the configuration of their system and then executes it as described.
With ros2 run, every node needs its own terminal along with its own --ros-args, which gets cumbersome quickly as the application grows. A launch file describes which nodes to start and how to configure them, all started with one command.
By convention, launch and YAML files are placed in a dedicated bringup package, so they aren't tied to any one code package:
cd ~/ros2_ws/src
ros2 pkg create my_robot_bringup
cd my_robot_bringup && rm -rf include src && mkdir launch config
- In
CMakeLists.txt, addinstall(DIRECTORY launch config DESTINATION share/${PROJECT_NAME}/). Bothros2 launchandget_package_share_directory()look for files underinstall/<pkg>/share/<pkg>/, notsrc/. - In
package.xml, add an<exec_depend>for every package whose nodes are launched.
# launch/number_app.launch.py
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
ld = LaunchDescription()
param_config = os.path.join(
get_package_share_directory("my_robot_bringup"), "config", "number_app.yaml")
number_publisher = Node(
package="my_py_pkg",
executable="number_publisher", # name from setup.py, not the file name
name="my_number_publisher", # rename the node
namespace="/abc", # prefix relative names with /abc
remappings=[("number", "my_number")], # rename a topic or service
parameters=[param_config], # or inline: [{"number": 12, "timer_period": 1.3}]
)
number_counter = Node(
package="my_py_pkg",
executable="number_counter",
name="my_number_counter",
namespace="/abc",
remappings=[("number", "my_number")],
)
ld.add_action(number_publisher)
ld.add_action(number_counter)
return ld
# config/number_app.yaml, the key is the full node name including its namespace
/abc/my_number_publisher:
ros__parameters:
number: 6
timer_period: 1.5
colcon build --packages-select my_robot_bringup
source install/setup.bash
ros2 launch my_robot_bringup number_app.launch.py
This results in /abc/my_number_publisher → /abc/my_number → /abc/my_number_counter → /abc/number_count.
Notice how the names are resolved:
Relative name:numberdoesn't start with/, so the namespace and the remapping turn it into/abc/my_number.Absolute name: Names starting with/, such as/turtle1/cmd_velor/spawn, ignore the namespace.
Namespaces make it possible to run several copies of the same set of nodes side by side, e.g. one set per robot.
Since a Python launch file is just Python, loops work as well. For instance, starting five news stations and a smartphone:
def generate_launch_description():
ld = LaunchDescription()
for name in ["Giskard", "BB8", "Daneel", "Jander", "C3PO"]:
ld.add_action(Node(
package="my_py_pkg",
executable="robot_news_station",
name="robot_news_station_" + name.lower(), # node names must be unique
parameters=[{"robot_name": name}],
))
ld.add_action(Node(package="my_py_pkg", executable="smartphone"))
return ld
Launch files can also be written in XML or YAML, which is shorter for simple setups. The concepts stay the same, and launch files of different formats can include each other.
❓ Why are parameters from the YAML file not applied ?
The YAML key must match the full node name including its namespace, otherwise the values are silently skipped and the node keeps its defaults. A node named my_number_publisher under the /abc namespace needs /abc/my_number_publisher as its key, while /**/my_number_publisher matches it under any namespace.
❓ Why can't ros2 launch find my launch file ?
The launch folder is not installed. Make sure CMakeLists.txt contains the install(DIRECTORY launch ...) rule, then rebuild and source the workspace.
Putting It Together
Below example combines all the concepts above: in turtlesim, a master turtle chases and catches turtles spawned at random positions. Before writing any code, the first step is to design the graph, deciding which nodes are needed and which mechanism carries each piece of data.
turtlesim_node is used as is, through the interfaces it already provides:
/turtle1/pose: Topic published by turtlesim with the master turtle's position (turtlesim/msg/Pose)./turtle1/cmd_vel: Topic subscribed by turtlesim to move the master turtle (geometry_msgs/msg/Twist)./spawn: Service to create a turtle at a given position (turtlesim/srv/Spawn)./kill: Service to remove a turtle by its name (turtlesim/srv/Kill).
Two custom nodes, turtle_spawner and turtle_controller, are then added around it:
/alive_turtles /turtle1/cmd_vel
turtle_spawner ─────────────────────→ turtle_controller ────────────────→ turtlesim
│ ↑ │ ↑ │ ↑
│ └──── /catch_turtle (srv) ────┘ └──── /turtle1/pose ──────┘ │
│ │
└──────────────────────────── /spawn, /kill (srv) ─────────────────────────────┘
Driving the master turtle:turtle_controllersubscribes to/turtle1/poseand publishes to/turtle1/cmd_velfrom a timer running at 100 Hz, as both are continuous streams.Spawning turtles:turtle_spawnercalls/spawnfrom a timer, since each spawn is a one-off action with a result.Sharing alive turtles:turtle_spawnerpublishes a customTurtleArraymessage to/alive_turtles, as it is a state that changes over time and any node can listen to it.Catching a turtle:turtle_controllercalls a custom/catch_turtleservice onturtle_spawner, which then calls/killand publishes the updated list.Tuning behavior: Parametersspawn_frequency,turtle_name_prefixandcatch_closest_turtle_firstconfigure the nodes, and a launch file starts all three nodes at once.
# msg/Turtle.msg
string name
float64 x
float64 y
float64 theta
# msg/TurtleArray.msg
Turtle[] turtles
# srv/CatchTurtle.srv
string name
---
bool success
turtle_spawner is the single owner of the alive turtles list. Instead of calling /kill itself, the controller asks the owner through /catch_turtle, so the list and the screen never drift apart.
Control Loop
turtle_controller drives the master turtle with a simple P (proportional) controller: the farther the target, the faster it moves, and the bigger the heading error, the faster it turns.
def control_loop(self): # timer, every 0.01 second
if self.pose_ is None or self.turtle_to_catch_ is None:
return
dist_x = self.turtle_to_catch_.x - self.pose_.x
dist_y = self.turtle_to_catch_.y - self.pose_.y
distance = math.sqrt(dist_x * dist_x + dist_y * dist_y)
cmd = Twist()
if distance > 0.5:
cmd.linear.x = 2 * distance
goal_theta = math.atan2(dist_y, dist_x)
diff = goal_theta - self.pose_.theta
# Keep the error within [-π, π] so the turtle turns the short way
if diff > math.pi:
diff -= 2 * math.pi
elif diff < -math.pi:
diff += 2 * math.pi
cmd.angular.z = 6 * diff
else:
# Target reached: stop (Twist fields default to 0) and report the catch
self.call_catch_turtle_service(self.turtle_to_catch_.name)
self.turtle_to_catch_ = None
self.cmd_vel_publisher_.publish(cmd)
turtle_controller.py
#!/usr/bin/env python3
import math
from functools import partial
import rclpy
from rclpy.node import Node
from turtlesim.msg import Pose
from geometry_msgs.msg import Twist
from my_robot_interfaces.msg import Turtle, TurtleArray
from my_robot_interfaces.srv import CatchTurtle
class TurtleControllerNode(Node):
def __init__(self):
super().__init__("turtle_controller")
self.declare_parameter("catch_closest_turtle_first", True)
self.catch_closest_turtle_first_ = self.get_parameter("catch_closest_turtle_first").value
self.pose_: Pose = None
self.turtle_to_catch_: Turtle = None
self.cmd_vel_publisher_ = self.create_publisher(Twist, "/turtle1/cmd_vel", 10)
self.pose_subscriber_ = self.create_subscription(
Pose, "/turtle1/pose", self.callback_pose, 10)
self.alive_turtles_subscriber_ = self.create_subscription(
TurtleArray, "alive_turtles", self.callback_alive_turtles, 10)
self.catch_turtle_client_ = self.create_client(CatchTurtle, "catch_turtle")
self.control_loop_timer_ = self.create_timer(0.01, self.control_loop)
def callback_pose(self, pose: Pose):
self.pose_ = pose
def callback_alive_turtles(self, msg: TurtleArray):
if len(msg.turtles) == 0 or self.pose_ is None:
return
if self.catch_closest_turtle_first_:
self.turtle_to_catch_ = min(
msg.turtles,
key=lambda t: math.hypot(t.x - self.pose_.x, t.y - self.pose_.y))
else:
self.turtle_to_catch_ = msg.turtles[0]
# control_loop(): see above
def call_catch_turtle_service(self, turtle_name):
while not self.catch_turtle_client_.wait_for_service(1.0):
self.get_logger().warn("Waiting for catch turtle service...")
request = CatchTurtle.Request()
request.name = turtle_name
future = self.catch_turtle_client_.call_async(request)
future.add_done_callback(
partial(self.callback_call_catch_turtle_service, turtle_name=turtle_name))
def callback_call_catch_turtle_service(self, future, turtle_name):
if not future.result().success:
self.get_logger().error(f"Turtle {turtle_name} could not be removed")
def main(args=None):
rclpy.init(args=args)
node = TurtleControllerNode()
rclpy.spin(node)
rclpy.shutdown()
turtle_spawner.py
#!/usr/bin/env python3
import math
import random
from functools import partial
import rclpy
from rclpy.node import Node
from turtlesim.srv import Spawn, Kill
from my_robot_interfaces.msg import Turtle, TurtleArray
from my_robot_interfaces.srv import CatchTurtle
class TurtleSpawnerNode(Node):
def __init__(self):
super().__init__("turtle_spawner")
self.declare_parameter("turtle_name_prefix", "turtle")
self.declare_parameter("spawn_frequency", 1.0)
self.turtle_name_prefix_ = self.get_parameter("turtle_name_prefix").value
self.spawn_frequency_ = self.get_parameter("spawn_frequency").value
self.turtle_counter_ = 0
self.alive_turtles_ = []
self.alive_turtles_publisher_ = self.create_publisher(TurtleArray, "alive_turtles", 10)
self.spawn_client_ = self.create_client(Spawn, "/spawn")
self.kill_client_ = self.create_client(Kill, "/kill")
self.catch_turtle_service_ = self.create_service(
CatchTurtle, "catch_turtle", self.callback_catch_turtle)
self.spawn_turtle_timer_ = self.create_timer(
1.0 / self.spawn_frequency_, self.spawn_new_turtle)
# Spawn: timer → /spawn → add to list → publish
def spawn_new_turtle(self):
self.turtle_counter_ += 1
request = Spawn.Request()
request.name = self.turtle_name_prefix_ + str(self.turtle_counter_)
request.x = random.uniform(0.0, 11.0)
request.y = random.uniform(0.0, 11.0)
request.theta = random.uniform(0.0, 2 * math.pi)
while not self.spawn_client_.wait_for_service(1.0):
self.get_logger().warn("Waiting for spawn service...")
future = self.spawn_client_.call_async(request)
future.add_done_callback(partial(self.callback_call_spawn, request=request))
def callback_call_spawn(self, future, request: Spawn.Request):
response: Spawn.Response = future.result()
if response.name != "":
turtle = Turtle()
turtle.name = response.name
turtle.x = request.x
turtle.y = request.y
turtle.theta = request.theta
self.alive_turtles_.append(turtle)
self.publish_alive_turtles()
# Catch: /catch_turtle → /kill → remove from list → publish
def callback_catch_turtle(self, request: CatchTurtle.Request, response: CatchTurtle.Response):
while not self.kill_client_.wait_for_service(1.0):
self.get_logger().warn("Waiting for kill service...")
kill_request = Kill.Request()
kill_request.name = request.name
future = self.kill_client_.call_async(kill_request)
future.add_done_callback(partial(self.callback_call_kill, turtle_name=request.name))
response.success = True
return response
def callback_call_kill(self, future, turtle_name):
self.alive_turtles_ = [t for t in self.alive_turtles_ if t.name != turtle_name]
self.publish_alive_turtles()
def publish_alive_turtles(self):
msg = TurtleArray()
msg.turtles = self.alive_turtles_
self.alive_turtles_publisher_.publish(msg)
def main(args=None):
rclpy.init(args=args)
node = TurtleSpawnerNode()
rclpy.spin(node)
rclpy.shutdown()
Launch file and YAML
# my_robot_bringup/launch/turtlesim_catch_them_all.launch.py
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
config = os.path.join(get_package_share_directory("my_robot_bringup"),
"config", "catch_them_all_config.yaml")
return LaunchDescription([
Node(package="turtlesim", executable="turtlesim_node"),
Node(package="turtlesim_catch_them_all", executable="controller", parameters=[config]),
Node(package="turtlesim_catch_them_all", executable="spawner", parameters=[config]),
])
# my_robot_bringup/config/catch_them_all_config.yaml
/turtle_controller:
ros__parameters:
catch_closest_turtle_first: true
/turtle_spawner:
ros__parameters:
turtle_name_prefix: "my_turtle"
spawn_frequency: 1.5
Rather than writing everything at once, the application can be built step by step, with each step runnable on its own:
- Controller subscribes to
/turtle1/poseand drives to a hard-coded target. - Spawner spawns turtles from a timer through
/spawn. - Spawner publishes
/alive_turtles, and the controller targets the first turtle in the list. - Spawner provides
/catch_turtle, which kills the turtle and republishes the list. - Controller targets the closest turtle instead of the first one.
- Parameters, a launch file and a YAML file are added.
References
- ROS 2 for Beginners -- Edouard Renard
- Github -- andresalemn/ros2-for-beginners
- ROS 2 Documentation - Basic Concepts
- ROS 2 Documentation - Passing ROS arguments to nodes via the command-line