🚀 Understanding the Publish-Subscribe Mechanism in ROS 2
In ROS 2, the Publish-Subscribe (PubSub) mechanism is a fundamental communication pattern that enables nodes to communicate efficiently through topics. This post explores how PubSub works in ROS 2, its key benefits, and provides an example using the rclpy library.
What is the Publish-Subscribe (PubSub) Mechanisum in ROS 2?
The Publish-Subscribe (PubSub) mechanism is a messaging pattern that allows nodes to communicate asynchronously in a distributed system. Publishers send messages to a “topic,” and any node that subscribes to that topic will receive the messages.
Key Points:
- Loose coupling: Publishers and subscribers do not need to know about each other’s existence.
- Asynchronous communication: Subscribers can receive data whenever the publisher sends it.
- Efficiency: The system can scale easily by adding more subscribers to the topic.
How does it work in ROS 2?
In ROS 2, the Publish-Subscribe mechanism can be implemented using the rclpy
library. Here’s a step-by-step breakdown of how to implement a publisher and subscriber works in general:
- Topics: Topics are the fundamental channel of data transfer. A node can subscribe to one or more topics and also publish to one or more topics.
- Publisher: When a node wants to publish a message, it creates a publisher object and uses the
publish
method to send the message to the specified topic. - Subscriber: When a node wants to subscribe to a topic, it creates a subscriber object and uses a
callback
method to connect to the desired topic. - Callback: When a new message is published to a subscribed topic, the subscriber receives a callback function that’s executed with the received message as an argument.
The figure below illustrates this PubSub mechanism where one publisher publishes its information on the topic /chatter and two subscribers subscribe to information on that topic.

Example Code
Here’s some sample code illustrating how PubSub works in ROS 2:
import rclpy
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
from std_msgs.msg import String
class MyPublisher(Node):
def __init__(self):
super().__init__('publisher')
self.publisher = self.create_publisher(String, 'chatter', 10)
self.timer = self.create_timer(1, self.publish)
def publish(self):
msg = String()
msg.data = 'Hello, World!'
self.publisher.publish(msg)
class MySubscriber1(Node):
def __init__(self):
super().__init__('subscriber1')
self.subscription = self.create_subscription(
String,
'chatter',
self.listener_callback,
10)
def listener_callback(self, msg):
self.get_logger().info(f'Received: {msg.data}')
class MySubscriber2(Node):
def __init__(self):
super().__init__('subscriber2')
self.subscription = self.create_subscription(
String,
'chatter',
self.listener_callback,
10)
def listener_callback(self, msg):
self.get_logger().info(f'Received: {msg.data}')
def main(args=None):
rclpy.init(args=args)
publisher = MyPublisher()
subscriber1 = MySubscriber1()
subscriber2 = MySubscriber2()
executor = SingleThreadedExecutor()
executor.add_node(publisher)
executor.add_node(subscriber1)
executor.add_node(subscriber2)
executor.spin()
if __name__ == '__main__':
main()
In this example, we have three nodes: publisher and subscriber1 and subscriber2. The publisher node publishes a message to the chatter topic, while the subscriber node subscribe to that same topic. When the subscribers receive a new message, they log it to the console.
Let’s discuss the most important parts of the code:
- self.publisher = self.create_publisher(String, ‘chatter’, 10)
:
Here the inherited method create_publisher is used to create the publisher object. It publishes messages of type std_msgs.msg.String() on the chatter topic with a queue size of 10. - self.publisher.publish(msg): The publish method of the created publisher object is utilized to send messages via the chatter topic.
- self.subscription = self.create_subscription(String, ‘chatter’, self.listener_callback, 10): Here the inherited method create_subscription is used to subscribe (listen) on messages on the chatter topic. Incoming messages are then processed in the listener_callback method.
Benefits of PubSub
The Publish-Subscribe mechanism offers several advantages, making it a popular choice in robotics systems:
- Loose Coupling: Publishers and subscribers do not need to know about each other, which reduces interdependencies and enhances modularity.
- Scalability: Multiple subscribers can listen to the same topic, allowing for easy expansion as more components are added.
- Flexibility: Subscribers can filter and choose which topics to subscribe to, controlling the data they receive.
- Asynchronous Communication: Messages are delivered asynchronously, allowing for non-blocking, efficient communication between nodes.
Practical Applications in Robotics
The Publish-Subscribe mechanism is widely used in ROS 2 robotics for tasks like:
- Sensor Data Collection: Nodes can publish sensor readings to topics for other nodes to process or log.
- Control Systems: Controllers can subscribe to commands or data published by other components of the robot.
- Inter-robot Communication: Different robots can communicate through topics, enabling collaborative tasks.
Conclusion
The Publish-Subscribe mechanism in ROS 2, powered by rclpy
, is essential for building scalable and modular robotic systems. It allows nodes to communicate asynchronously, with benefits like loose coupling, flexibility, and scalability. Whether you’re handling sensor data, controlling robotic components, or enabling inter-robot communication, PubSub offers an efficient and organized way to manage message exchanges.
Explore more ROS 2 PubSub examples and download the full source code from our GitHub repository.
Frequently Asked Questions (FAQs)
- What is the difference between ROS 1 and ROS 2 PubSub mechanisms?
ROS 1 uses a global master for node registration, whereas ROS 2 implements a decentralized architecture that allows for more flexibility and scalability, particularly in multi-robot systems. - Can I use the PubSub mechanism for inter-process communication?
Yes, ROS 2’s PubSub pattern allows for inter-process as well as inter-machine communication, making it highly versatile. - What message types can I publish in ROS 2?
ROS 2 supports various message types, including standard types likeString
,Int32
, over sensor data likePointCloud2
and custom messages defined in.msg
files. - How do I handle large data in ROS 2 PubSub?
For large data, consider increasing the message queue size or using more efficient data serialization methods to avoid delays or data loss and setting the correct Quality of Service (QoS) settings. - What is the role of
rclpy
in ROS 2?rclpy
is the Python client library in ROS 2, enabling the development of nodes in Python. It simplifies interaction with the ROS 2 core, including PubSub operations. - Can I run PubSub across multiple machines in ROS 2?
Yes, ROS 2 supports distributed systems, so PubSub can work across different machines in a network using Data Distribution Service (DDS).