Skip to main content

Nodes, Topics, Services, and Actions

In ROS 2, communication between different parts of a robot system happens through several patterns: topics for asynchronous data streams, services for request-response interactions, and actions for long-running, cancellable tasks. Understanding these patterns is crucial for designing effective robotic systems.

Nodes: The Basic Computational Units​

Definition and Purpose​

A node is an executable process that performs computation in a ROS 2 system. Nodes contain the algorithmic logic of your robot, such as sensor processing, control algorithms, planning, or user interfaces. Each node typically serves one primary purpose, following the Unix philosophy of doing one thing well.

Node Implementation​

Here's a more detailed example of a node implementation:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

class RobotController(Node):
def __init__(self):
super().__init__('robot_controller')

# Create publishers
self.cmd_vel_pub = self.create_publisher(Twist, 'cmd_vel', 10)

# Create subscribers
self.laser_sub = self.create_subscription(
LaserScan,
'scan',
self.laser_callback,
10)

# Create timers for periodic tasks
self.timer = self.create_timer(0.1, self.control_loop)

# Internal state
self.obstacle_distance = float('inf')

def laser_callback(self, msg):
# Process laser scan to detect obstacles
self.obstacle_distance = min(msg.ranges)

def control_loop(self):
# Simple obstacle avoidance algorithm
cmd = Twist()
if self.obstacle_distance > 1.0:
cmd.linear.x = 0.2 # Move forward
else:
cmd.angular.z = 0.5 # Turn
self.cmd_vel_pub.publish(cmd)

Node Design Principles​

  • Single Responsibility: Each node should have one well-defined purpose
  • Modularity: Nodes should be reusable and replaceable
  • Isolation: Failure in one node shouldn't crash others
  • Communication: Nodes communicate only through ROS interfaces (topics, services, actions)

Topics: Publish-Subscribe Communication​

Concept​

Topics enable asynchronous, many-to-many communication in ROS 2. A node can publish data to a topic, and multiple nodes can subscribe to the same topic. This decouples publishers from subscribers in time, space, and implementation.

Publisher-Subscriber Pattern​

# Publisher example
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)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)

def timer_callback(self):
msg = String()
msg.data = 'Hello World: %d' % self.get_clock().now().nanoseconds
self.publisher.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)

# Subscriber example
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class Listener(Node):
def __init__(self):
super().__init__('listener')
self.subscription = self.create_subscription(
String,
'chatter',
self.listener_callback,
10)
self.subscription # prevent unused variable warning

def listener_callback(self, msg):
self.get_logger().info('I heard: "%s"' % msg.data)

Topic Characteristics​

  • Asynchronous: Publishers and subscribers don't block each other
  • Unidirectional: Data flows from publisher to subscriber
  • Many-to-many: Multiple publishers can send to a topic, multiple subscribers can receive
  • Type-safe: All messages on a topic are of the same type

Quality of Service (QoS) Settings​

For physical AI systems, QoS settings are crucial:

from rclpy.qos import QoSProfile, QoSHistoryPolicy, QoSReliabilityPolicy

# For critical sensor data
sensor_qos = QoSProfile(
history=QoSHistoryPolicy.KEEP_LAST,
depth=1,
reliability=QoSReliabilityPolicy.RELIABLE,
durability=rclpy.qos.QoSDurabilityPolicy.VOLATILE
)

# For less critical visualization data
viz_qos = QoSProfile(
history=QoSHistoryPolicy.KEEP_LAST,
depth=1,
reliability=QoSReliabilityPolicy.BEST_EFFORT,
durability=rclpy.qos.QoSDurabilityPolicy.VOLATILE
)

# Create subscriber with specific QoS
self.subscriber = self.create_subscription(
LaserScan,
'scan',
self.scan_callback,
sensor_qos
)

Services: Request-Response Communication​

Concept​

Services provide synchronous, request-response communication. A client sends a request and waits for a response. This is useful for operations that have a clear beginning and end, like setting parameters or performing calculations.

Service Implementation​

First, define the service interface in .srv files:

# AddTwoInts.srv
int64 a
int64 b
---
int64 sum

Then implement the server:

import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts

class MinimalService(Node):
def __init__(self):
super().__init__('minimal_service')
self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_two_ints_callback)

def add_two_ints_callback(self, request, response):
response.sum = request.a + request.b
self.get_logger().info('Incoming request\na: %d b: %d' % (request.a, request.b))
return response

And the client:

import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts

class MinimalClient(Node):
def __init__(self):
super().__init__('minimal_client')
self.cli = self.create_client(AddTwoInts, 'add_two_ints')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger().info('Service not available, waiting again...')
self.req = AddTwoInts.Request()

def send_request(self, a, b):
self.req.a = a
self.req.b = b
self.future = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.future)
return self.future.result()

Service Characteristics​

  • Synchronous: Client waits for response
  • Reliable: Request is guaranteed to reach the server
  • One-to-one: One server serves many clients
  • Stateless: Each request is independent

Actions: Goal-Fedback-Result Communication​

Concept​

Actions are designed for long-running tasks that might take seconds, minutes, or longer. They provide feedback during execution and can be canceled. Examples include navigation to a goal, manipulation tasks, or calibration procedures.

Action Implementation​

Define the action interface in .action files:

# Fibonacci.action
int32 order
---
int32[] sequence
---
int32[] partial_sequence

Server implementation:

import rclpy
from rclpy.action import ActionServer
from rclpy.node import Node
from example_interfaces.action import Fibonacci

class FibonacciActionServer(Node):
def __init__(self):
super().__init__('fibonacci_action_server')
self._action_server = ActionServer(
self,
Fibonacci,
'fibonacci',
self.execute_callback)

def execute_callback(self, goal_handle):
self.get_logger().info('Executing goal...')

feedback_msg = Fibonacci.Feedback()
feedback_msg.partial_sequence = [0, 1]

for i in range(1, goal_handle.request.order):
if goal_handle.is_cancel_requested:
goal_handle.canceled()
self.get_logger().info('Goal canceled')
return Fibonacci.Result()

feedback_msg.partial_sequence.append(
feedback_msg.partial_sequence[i] + feedback_msg.partial_sequence[i-1])

goal_handle.publish_feedback(feedback_msg)
time.sleep(1) # Simulate work

goal_handle.succeed()
result = Fibonacci.Result()
result.sequence = feedback_msg.partial_sequence
self.get_logger().info('Returning result: {0}'.format(result.sequence))

return result

Client implementation:

import rclpy
from rclpy.action import ActionClient
from rclpy.node import Node
from example_interfaces.action import Fibonacci

class FibonacciActionClient(Node):
def __init__(self):
super().__init__('fibonacci_action_client')
self._action_client = ActionClient(
self,
Fibonacci,
'fibonacci')

def send_goal(self, order):
goal_msg = Fibonacci.Goal()
goal_msg.order = order

self._action_client.wait_for_server()

self._send_goal_future = self._action_client.send_goal_async(
goal_msg,
feedback_callback=self.feedback_callback)

self._send_goal_future.add_done_callback(self.goal_response_callback)

def goal_response_callback(self, future):
goal_handle = future.result()
if not goal_handle.accepted:
self.get_logger().info('Goal rejected :(')
return

self.get_logger().info('Goal accepted :)')
self._get_result_future = goal_handle.get_result_async()
self._get_result_future.add_done_callback(self.get_result_callback)

def feedback_callback(self, feedback_msg):
feedback = feedback_msg.feedback
self.get_logger().info('Received feedback: {0}'.format(feedback.partial_sequence))

def get_result_callback(self, future):
result = future.result().result
self.get_logger().info('Result: {0}'.format(result.sequence))

Action Characteristics​

  • Long-running: Designed for tasks that take significant time
  • Feedback: Provides intermediate status during execution
  • Cancelability: Can be canceled during execution
  • Goal-oriented: Clear start and end conditions

Physical AI Communication Patterns​

Sensor Integration​

  • Sensors publish data on topics (image, laser, IMU)
  • Multiple algorithms can consume the same sensor data
  • QoS settings ensure timely delivery of critical sensor data

Control Systems​

  • High-frequency control loops use topics for real-time commands
  • Low-frequency planning uses services or actions
  • Safety monitors subscribe to all critical topics

Human-Robot Interaction​

  • Natural language interfaces use services for turn-based interactions
  • Continuous feedback uses topics for real-time updates
  • Complex tasks use actions with progress feedback

Best Practices for Physical AI​

Topic Design​

  • Use appropriate QoS settings based on real-time requirements
  • Design message types that include timestamps for synchronization
  • Use standard message types when possible for interoperability

Service Design​

  • Keep request-response times short to avoid blocking
  • Use services for configuration, calibration, and discrete actions
  • Implement proper error handling and reporting

Action Design​

  • Use for tasks that take more than 100ms to complete
  • Provide meaningful feedback messages during execution
  • Implement proper cancellation handling

Learning Objectives​

After completing this module, you will be able to:

  • Differentiate between topics, services, and actions
  • Implement each communication pattern in ROS 2
  • Choose the appropriate communication pattern for specific use cases
  • Configure Quality of Service settings for physical AI applications

Hands-On Exercise​

Create a navigation system using all three communication patterns:

  1. Use topics for sensor data (laser scans, odometry)
  2. Use a service to set navigation parameters
  3. Use an action for the navigation task itself with feedback Test the system with simulated obstacles and verify proper communication flow.

Next Steps​

In the next section, we'll explore how to connect Python agents to ROS controllers, bridging the gap between AI algorithms and physical robot control.