Publisher and Subscriber Nodes¶
Concept¶
A publisher sends messages on a named topic. A subscriber listens on a topic and receives those messages. Nodes communicate via topics without needing direct knowledge of each other — only the topic name and message type must match.
File Locations¶
Both Python files go inside:
~/ROBOT/src/robot_pkg/robot_pkg/publisher.py¶
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
def main():
rclpy.init()
node = Node('publisher_node')
pub = node.create_publisher(String, 'chat', 10)
def timer_callback():
msg = String()
msg.data = 'Hello from Publisher!'
pub.publish(msg)
node.get_logger().info('Sent: ' + msg.data)
node.create_timer(1.0, timer_callback) # publish every 1 second
rclpy.spin(node)
rclpy.shutdown()
main()subscriber.py¶
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
def main():
rclpy.init()
node = Node('subscriber_node')
def callback(msg):
node.get_logger().info('Received: ' + msg.data)
node.create_subscription(String, 'chat', callback, 10)
rclpy.spin(node)
rclpy.shutdown()
main()Register in setup.py¶
Open ~/ROBOT/src/robot_pkg/setup.py and update entry_points:
entry_points={
'console_scripts': [
'publisher = robot_pkg.publisher:main',
'subscriber = robot_pkg.subscriber:main',
],
},Build and Run¶
Terminal 1 — Build
cd ~/ROBOT && colcon build && source install/setup.bashTerminal 2 — Publisher
source ~/ROBOT/install/setup.bash
ros2 run robot_pkg publisherTerminal 3 — Subscriber
source ~/ROBOT/install/setup.bash
ros2 run robot_pkg subscriberTerminal 4 — Verify the topic
ros2 topic echo /chatExpected Output¶
Subscriber terminal:
[INFO] [subscriber_node]: Received: Hello from Publisher!
[INFO] [subscriber_node]: Received: Hello from Publisher!
...