During the early design phase of a robotics software stack, one architectural question comes up repeatedly: “Should we pass this data over a Topic, wrap it in a Service, or build an Action server?” When Parameters, TF2 coordinate frames, Executors, and Launch files enter the picture at the same time, it is tempting to fall back on familiar Publisher and Subscriber topics for every single interaction.
However, just as our analysis of 2WD mobile robot hardware layers and five core components partitioned electronics by execution cycle time, and our deep dive into ROS 2 Jazzy DDS architecture and the RMW layer showed how discovery and QoS contracts govern transport, ROS 2 communication primitives partition software along two strict engineering axes: inter-node coupling and task duration. Once a team decides when to adopt ROS 2 in a Physical AI project, mastering these interface boundaries is the fastest way to prevent deadlocks and silent packet drops. Using the myros_sketch differential-drive robot as a concrete example, this tutorial walks through Nodes, Topics, Services, Actions, production QoS profiles in rclpy, Parameters, TF2 trees, and Launch files with step-by-step CLI verification.
1. Nodes: Modular Execution Units Defined by Single Responsibility and Replaceability
A Node is the fundamental unit of computation in a ROS 2 graph, responsible for one well-scoped task. In ROS 2 Jazzy, a node does not have to map 1:1 to an operating system process; multiple nodes can be composed into a single process as Composable Nodes to exchange messages via zero-copy shared memory pointers.
The practical litmus test for a well-designed node boundary is replaceability. If you swap the 2D LiDAR on myros_sketch from one manufacturer’s unit to another, or switch from a real robot to Gazebo simulation, the SLAM and navigation nodes should require zero source code edits. To achieve that isolation, myros_sketch divides responsibilities across focused nodes:
lidar_driver: Reads raw serial packets from the laser scanner and publishes only/scan(sensor_msgs/msg/LaserScan).camera_driver: Captures USB frames and publishes/camera/image_rawalongside calibration metadata on/camera/camera_info.esp32_bridge(via micro-ROS Agent): Subscribes to/cmd_velto drive the 200 Hz motor loop on the ESP32-S3, while publishing wheel odometry (/odom) and inertial data (/imu/data).robot_state_publisher: Parses the robot’s URDF description and broadcasts fixed and movable link transforms onto/tf_staticand/tf.
# Run a standard C++ demo node and inspect its full interface contract (publishers, subscribers, services)
ros2 run demo_nodes_cpp talker
ros2 node list
ros2 node info /talker
The output of ros2 node info <node_name> acts as the node’s public API specification, listing every topic, service, and action endpoint it exposes to the DDS domain.
2. Topics, Services, and Actions: Selecting Communication Patterns by Coupling and Duration
As outlined in the official ROS 2 Jazzy core concepts documentation, Topics, Services, and Actions solve three distinct synchronization problems.
Topics: Continuous State and Sensor Streams (Many-to-Many · Unidirectional · Asynchronous)
A Topic is an asynchronous, many-to-many (N:M) publish-subscribe data stream. The publisher pushes samples onto the bus without knowing—or caring—whether zero, one, or ten subscribers are listening. This loose coupling is what makes ROS 2 extensible: you can attach rviz2 for 3D visualization or ros2 bag record for data logging while the robot is driving, without touching the navigation nodes.
myros_sketch Topic Name | Message Type | Target Rate | Why a Topic Is the Correct Primitive |
|---|---|---|---|
/scan | sensor_msgs/msg/LaserScan | 10 Hz | Continuously refreshed planar range array; stale scans are obsolete |
/imu/data | sensor_msgs/msg/Imu | 100 Hz | High-frequency inertial stream consumed by odometry fusion filters |
/odom | nav_msgs/msg/Odometry | 50 Hz | Continuously integrated pose and twist estimate from wheel encoders |
/cmd_vel | geometry_msgs/msg/Twist | 20 Hz | Streamed velocity setpoints feeding the MCU watchdog loop |
/tf | tf2_msgs/msg/TFMessage | 50–100 Hz | Dynamic coordinate frame transforms broadcast to all perception nodes |
The limitation of a topic is that it is fire-and-forget: publishing a message on /cmd_vel gives the caller no confirmation that the robot actually reached a target distance or executed a state transition.
Services: Sub-Second Synchronous Transactions (One-to-One · Bidirectional · Request/Response)
A Service implements a synchronous request-response remote procedure call (RPC). A client sends a request payload and waits for the server to return a single response payload. Services are designed for short, discrete operations whose outcome is determined immediately (within a few milliseconds to a few hundred milliseconds):
/reset_odometry(std_srvs/srv/Trigger): Zeroes out integrated wheel odometry coordinates./set_motor_enable(std_srvs/srv/SetBool): Enables or disables H-bridge motor torque./get_parametersand/set_parameters: Queries or modifies node configuration at runtime.
A strict architectural rule applies to services: never perform long blocking loops or multi-second physical motion inside a service callback. While a service callback is executing, a default single-threaded executor cannot process incoming sensor topics or watchdog timers.
Actions: Long-Running, Preemptible Goals with Continuous Feedback
An Action is built for tasks that span several seconds to several minutes—such as driving across a building (nav2_msgs/action/NavigateToPose), docking onto a charging station, or executing a multi-waypoint arm trajectory. Under the hood, an action combines two services (Goal submission and Cancel request) with two topics (periodic Feedback stream and final Result notification) into a state machine.
| Decision Criterion | Topic | Service | Action |
|---|---|---|---|
| Communication Pattern | Publish-Subscribe (unidirectional stream) | Request-Response (single round-trip RPC) | Goal-Feedback-Result (stateful machine) |
| Inter-Node Coupling | Low (publisher is anonymous to subscribers) | High (client depends on server response) | Moderate (asynchronous goal handle + stream) |
| Typical Time Horizon | Continuous / unbounded stream | Milliseconds to ~200 ms | Several seconds to several minutes |
| Progress Feedback | None | None (returns only upon completion) | Built-in periodic feedback stream (1–10 Hz) |
| Preemption / Cancel | Not applicable | Cannot be cancelled once sent | Client or server can cancel mid-execution |
| Multiple Listeners | Yes (N:M) | 1:1 per request transaction | Feedback and status can be monitored by many |
myros_sketch Examples | /scan, /imu/data, /cmd_vel, /odom | Reset odometry, toggle motor enable, save map | NavigateToPose, autonomous charger docking |
Four-Step Workflow to Select and Verify Communication Interfaces
Follow this four-step procedure whenever you add a new capability to a robot package or debug an existing node graph:
- Classify by Duration and Coupling: If the data is a continuously updated measurement or setpoint, choose a Topic. If it is a discrete configuration trigger completing in under 200 ms, choose a Service. If it involves physical travel or computation lasting more than a second and requires cancellation or progress reporting, choose an Action.
- Search Standard ROS 2 Interfaces First: Before creating a custom interface package, inspect built-in definitions in
sensor_msgs,geometry_msgs,nav_msgs,std_srvs, andnav2_msgsusingros2 interface listandros2 interface show. - Verify Endpoint Types and Rates via CLI: Launch the node and confirm that topic frequencies (
ros2 topic hz), service signatures (ros2 service list -t), and action servers (ros2 action list -t) match your design table. - Audit QoS Compatibility on Silent Links: Whenever a subscriber callback fails to fire even though the topic appears in
ros2 topic list, runros2 topic info <topic_name> -vto compare the publisher’s offered QoS against the subscriber’s requested QoS.
# Inspect and exercise Topics, Services, and Actions directly from the terminal
ros2 topic list -t
ros2 topic echo /scan --once
ros2 service list -t
ros2 service call /reset_odometry std_srvs/srv/Trigger "{}"
ros2 action list -t
ros2 interface show nav2_msgs/action/NavigateToPose
3. Production QoS Profiles and rclpy Implementation for Sensors, Commands, and Maps
As established in our DDS architecture analysis, QoS policies are explicit delivery contracts enforced by the middleware. When translating the official ROS 2 Jazzy Quality of Service settings guide into Python or C++ node code, the five baseline profiles below prevent the vast majority of wireless bottlenecks and matching failures.
Data Category (myros_sketch) | Reliability | Durability | History (Depth) | Engineering Rationale for This Profile |
|---|---|---|---|---|
Sensors (/scan, /imu/data, /camera) | BEST_EFFORT | VOLATILE | KEEP_LAST (5) | Prioritizes low-latency arrival of the newest physical sample over retransmission |
Velocity Commands (/cmd_vel) | RELIABLE | VOLATILE | KEEP_LAST (10) | Dropped stop commands are hazardous, but late-joining nodes must not replay old twists |
Dynamic Transforms (/tf) | RELIABLE | VOLATILE | KEEP_LAST (100) | High-rate bursts from multiple links require a deeper queue to prevent dropped frames |
Static Transforms (/tf_static) | RELIABLE | TRANSIENT_LOCAL | KEEP_LAST (1) | Published once at boot; late-joining nodes must receive the latched static offsets |
Static Map (/map) & /robot_description | RELIABLE | TRANSIENT_LOCAL | KEEP_LAST (1) | Ensures RViz2 or planners started minutes later still receive the map and URDF string |
The complete rclpy node below demonstrates how to combine an explicit BEST_EFFORT sensor Topic subscription and publication with runtime Parameters and a synchronous reset Service in a single well-structured class:
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy, HistoryPolicy
from sensor_msgs.msg import LaserScan
from std_srvs.srv import Trigger
class ScanRelayNode(Node):
def __init__(self):
super().__init__('scan_relay_node')
# 1. Declare runtime parameters (change frame IDs or range limits without recompiling)
self.declare_parameter('target_frame_id', 'laser_frame')
self.declare_parameter('max_valid_range', 12.0)
# 2. Define explicit sensor QoS (BEST_EFFORT + VOLATILE + Depth 5)
sensor_qos = QoSProfile(
reliability=ReliabilityPolicy.BEST_EFFORT,
durability=DurabilityPolicy.VOLATILE,
history=HistoryPolicy.KEEP_LAST,
depth=5,
)
self.scan_count = 0
self.pub = self.create_publisher(LaserScan, '/scan_filtered', sensor_qos)
self.sub = self.create_subscription(
LaserScan, '/scan', self.on_scan_received, sensor_qos
)
# 3. Register a synchronous Service server to reset the processed scan counter
self.srv = self.create_service(
Trigger, '/reset_scan_count', self.on_reset_count
)
self.get_logger().info('scan_relay_node ready with BEST_EFFORT sensor QoS')
def on_scan_received(self, msg: LaserScan):
frame_id = self.get_parameter('target_frame_id').get_parameter_value().string_value
max_range = self.get_parameter('max_valid_range').get_parameter_value().double_value
msg.header.frame_id = frame_id
msg.range_max = float(max_range)
self.scan_count += 1
self.pub.publish(msg)
def on_reset_count(self, request: Trigger.Request, response: Trigger.Response):
prev = self.scan_count
self.scan_count = 0
response.success = True
response.message = f'Reset scan_count from {prev} to 0'
return response
def main(args=None):
rclpy.init(args=args)
node = ScanRelayNode()
try:
rclpy.spin(node)
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
A classic beginner bug is passing an integer queue depth like 10 as the fourth argument to create_subscription(LaserScan, '/scan', self.on_scan_received, 10). Passing an integer defaults to RELIABLE reliability. When the hardware LiDAR driver offers BEST_EFFORT, DDS rejects the match silently and on_scan_received is never invoked. Explicitly passing a QoSProfile with ReliabilityPolicy.BEST_EFFORT eliminates that mismatch.
4. Parameters, TF2, Launch Files, and Executors: The Four Supporting Pillars
While Nodes, Topics, Services, and Actions move payloads across the graph, four supporting subsystems turn individual scripts into a coherent robot software stack: Parameters, TF2 coordinate transforms, Packages and Launch files, and Executors.
Parameters: Runtime Tuning Knobs Without Rebuilding Code
Hardcoding physical constants such as wheel_radius = 0.0325, max_linear_speed = 0.5, target_frame_id = 'laser_frame', or use_sim_time = True inside C++ or Python source files forces a rebuild for every minor calibration tweak. Declaring them as node parameters allows you to inject different YAML files for simulation versus physical hardware or adjust gains live from the CLI:
# List, query, and update node parameters dynamically at runtime
ros2 param list /scan_relay_node
ros2 param get /scan_relay_node max_valid_range
ros2 param set /scan_relay_node max_valid_range 8.0
TF2: Tracking 3D Coordinate Transforms Across Space and Time
When the 2D LiDAR detects an obstacle 0.8 m directly ahead in laser_frame, the navigation controller needs to know where that point lies relative to the drive axle (base_link) and the global room map (map). As taught in the ROS 2 Jazzy TF2 tutorials, TF2 buffers time-stamped 3D translation $(x, y, z)$ and quaternion rotation $(q_x, q_y, q_z, q_w)$ transforms across a directed tree of coordinate frames, allowing any node to query the exact transform between two frames at the timestamp when a sensor scan was captured.
The canonical TF2 hierarchy for myros_sketch follows the standard mobile robotics convention:
map (Global world frame: SLAM / AMCL publishes map -> odom to correct drift)
└── odom (Continuous odometry frame: esp32_bridge publishes odom -> base_footprint)
└── base_footprint (Ground-plane projection directly below the drive axle)
└── base_link (Drive axle midpoint: root link of the URDF model)
├── left_wheel_link / right_wheel_link (Continuous wheel joints: dynamic TF)
└── chassis (3D-printed body plate: static TF)
├── caster_wheel_link (Front passive ball caster)
├── imu_link (6-axis IMU sensor origin)
├── lidar_base_frame ──> laser_frame (2D LiDAR scan plane at z ≈ 117 mm)
└── camera_link ──> camera_link_optical (Camera optical axis: +Z forward)
Two rules keep this tree healthy: never break the chain, and never duplicate a parent-child publisher. Every static offset below base_link comes directly from the URDF model via robot_state_publisher on /tf_static, while esp32_bridge (or an EKF fusion node) publishes the dynamic odom → base_footprint transform on /tf.
# Export the active TF2 tree to a PDF diagram and stream live transforms between two frames
ros2 run tf2_tools view_frames
ros2 run tf2_ros tf2_echo base_link laser_frame
Launch Files and Executors: Orchestrating Multi-Node Startup and Callback Concurrency
Rather than opening six terminal tabs and running ros2 run manually every time the robot boots, engineers bundle nodes, URDF descriptions, and parameter YAML files into a Package and start them declaratively with a Python Launch file:
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[{'use_sim_time': False}],
),
Node(
package='myros_sketch',
executable='scan_relay_node',
name='scan_relay_node',
parameters=[{'target_frame_id': 'laser_frame', 'max_valid_range': 10.0}],
),
])
Finally, as your nodes grow to handle multiple subscriptions, timers, and services simultaneously, you must account for how the ROS 2 Executor and callback groups schedule work. By default, rclpy.spin(node) uses a SingleThreadedExecutor that runs callbacks sequentially one at a time. If an image processing callback blocks for 40 ms, incoming /cmd_vel or /imu/data callbacks sit waiting in the queue. When high-frequency and heavy-compute callbacks must live inside the same node, assign them to separate MutuallyExclusiveCallbackGroup instances and spin the node with a MultiThreadedExecutor—or split the heavy processing into its own dedicated node.
Why Fixing Communication Interfaces First Keeps the Node Graph Stable
Topic names, message types, QoS profiles, and TF2 frame_id strings are the hardest design decisions to change once a robotics project matures. As you add SLAM, Nav2, and perception packages, those interface signatures become the structural contract binding the entire system together.
In fact, building a URDF robot model is ultimately an interface definition task: the <link> and <joint> names you write in URDF (base_link, laser_frame, imu_link, camera_link_optical) flow directly into the /tf and /tf_static topics expected by every downstream algorithm. With the hardware layers, DDS discovery architecture, and communication primitives now established, the next tutorial—Installing ROS 2 Jazzy on Ubuntu 24.04 and Locking Your .bashrc Workspace Environment—shows how to set up a reproducible Linux and container development environment so every command and launch file runs reliably without environment variable collisions.