Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท ROS and Software Architecture

ROS 2 in Code: Publishers, Subscribers and Services

Write ROS 2 nodes in Python with rclpy: publisher, subscriber, timer, service, parameters and a launch file. Includes a runnable mini-ROS stand-in for practice.

The previous lesson explained the ideas. Now we write the code. ROS 2 supports C++ (rclcpp) and Python (rclpy); Python is shorter, so we use it here.

The real ROS 2 code in this lesson is read-only: it needs a ROS 2 installation on Linux. To let you practice the structure anyway, each section also has a runnable stand-in: a 40-line "mini ROS" written in plain Python with the same method names (create_publisher, create_subscription, create_timer, create_service). It runs on a fake clock, so you can read the output immediately. It is a teaching tool, not ROS: no processes, no network, no DDS.

Anatomy of a node

Every ROS 2 Python program follows the same recipe:

  1. rclpy.init() starts the client library.
  2. You subclass Node, give it a name, and create publishers, subscribers, timers, services in __init__.
  3. rclpy.spin(node) runs the callbacks until you press Ctrl+C.
  4. destroy_node() and rclpy.shutdown() clean up.

A publisher (the real code)

Python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String


class Talker(Node):
    def __init__(self):
        super().__init__('talker')
        self.publisher = self.create_publisher(String, 'chatter', 10)  # topic, queue depth
        self.timer = self.create_timer(0.5, self.on_timer)             # every 0.5 s
        self.count = 0

    def on_timer(self):
        msg = String()
        msg.data = f'hello {self.count}'
        self.publisher.publish(msg)
        self.get_logger().info(f'published: {msg.data}')
        self.count += 1


def main():
    rclpy.init()
    node = Talker()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

The 10 is the QoS history depth. Messages are typed objects: String has one field, data. Standard types live in std_msgs, geometry_msgs (Twist, Pose), sensor_msgs (LaserScan, Image), nav_msgs (Odometry, Path).

A subscriber (the real code)

Python
class Listener(Node):
    def __init__(self):
        super().__init__('listener')
        self.subscription = self.create_subscription(
            String, 'chatter', self.on_message, 10)

    def on_message(self, msg):
        self.get_logger().info(f'heard: {msg.data}')

Callbacks should be fast. A slow callback blocks other callbacks in the same executor, so heavy work (image processing, planning) goes into separate threads, a multi-threaded executor, or its own node.

Runnable stand-in: talker and listener

The next block defines the mini framework, then the two nodes exactly as you would write them. Notice how little of the node code mentions the framework.

Python Stand-in mini-ROS: talker and listener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Services (the real code)

A service needs an interface with a request and a response. example_interfaces/srv/AddTwoInts is the classic: request a, b; response sum.

Python
from example_interfaces.srv import AddTwoInts

class AdderServer(Node):
    def __init__(self):
        super().__init__('adder_server')
        self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.handle)

    def handle(self, request, response):
        response.sum = request.a + request.b
        self.get_logger().info(f'{request.a} + {request.b} = {response.sum}')
        return response


class AdderClient(Node):
    def __init__(self):
        super().__init__('adder_client')
        self.client = self.create_client(AddTwoInts, 'add_two_ints')
        while not self.client.wait_for_service(timeout_sec=1.0):
            self.get_logger().info('waiting for the service...')

    def ask(self, a, b):
        request = AddTwoInts.Request()
        request.a, request.b = a, b
        return self.client.call_async(request)     # returns a future

Always use call_async and wait for the future (with rclpy.spin_until_future_complete), never a blocking call inside a callback: that can deadlock the executor.

Runnable stand-in: a reactive obstacle-avoider

A realistic node reads a sensor topic and publishes a command topic. Below, a simulated robot drives toward a wall; a Avoider node subscribes to /scan (distance ahead) and publishes /cmd_vel (forward speed). A Simulator node owns the "physics", just as Gazebo would in a real setup.

Python Stand-in mini-ROS: scan in, cmd_vel out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The simulated robot jumps to full speed (a shortcut: there is no acceleration limit), cruises, slows as the wall nears, and creeps to a stop about a meter away. In real ROS 2 you would test the same Avoider against a Gazebo world, then swap the simulator for the real robot driver without changing the Avoider.

Parameters

Hard-coded numbers make nodes inflexible. Declare parameters with defaults, and set them from YAML or the command line.

Python
class Avoider(Node):
    def __init__(self):
        super().__init__('avoider')
        self.declare_parameter('stop_distance', 1.0)
        self.declare_parameter('max_speed', 2.0)
        self.stop_at = self.get_parameter('stop_distance').value
Terminal
ros2 run my_robot avoider --ros-args -p stop_distance:=0.6

Packages and launch files

Code lives in a package: a folder with package.xml (name, version, dependencies) and setup.py (Python) or CMakeLists.txt (C++). Entry points expose your main functions to ros2 run:

Python
# setup.py (excerpt)
entry_points={
    'console_scripts': [
        'talker = my_robot.talker:main',
        'listener = my_robot.listener:main',
    ],
},

A launch file starts several nodes at once:

Python
from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    return LaunchDescription([
        Node(package='my_robot', executable='talker', name='talker'),
        Node(package='my_robot', executable='listener', name='listener',
             remappings=[('chatter', '/robot/chatter')]),
        Node(package='my_robot', executable='avoider',
             parameters=[{'stop_distance': 0.6}]),
    ])

Build and run with colcon build, source install/setup.bash, then ros2 launch my_robot bringup.launch.py.

The most common beginner mistakes: forgetting source install/setup.bash in a new terminal, mismatched message types or topic names (check with ros2 topic info), blocking inside a callback, QoS incompatibility, and sending messages with timestamps from different clocks (use simulated time with use_sim_time:=true consistently).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does rclpy.spin(node) do?

    Spin runs the executor so timers, subscriptions and services get their callbacks called.
  2. 2. A subscription callback takes two seconds to run. What is the risk?

    Callbacks share an executor thread by default; long ones delay everything else. Move heavy work elsewhere.
  3. 3. Which is the right way to call a service from inside a node's callback?

    Blocking inside a callback can deadlock the executor. Use call_async and react to the future.
  4. 4. What does the remappings entry in a launch file do?

    Remapping connects a node's default topic name to a different actual topic.

Summary

  • A Python ROS 2 node: rclpy.init, subclass Node, create publishers/subscribers/timers/services, spin, shut down.
  • Messages are typed; services have a request and response; use call_async for clients.
  • Keep callbacks short and move heavy work out of them.
  • Parameters make nodes configurable; packages and launch files organize and start whole systems.
  • The mini-ROS stand-ins here show the structure but are not ROS: install ROS 2 to run the real code.

Next: Robot Software Architecture