Skip to main content

rclpy: Connecting Python Agents to ROS Controllers

Python has become one of the primary languages for AI and robotics development, and ROS 2's Python client library (rclpy) provides the interface for connecting AI algorithms to physical robot controllers. This section covers how to develop Python-based agents that can control robots through ROS 2.

Introduction to rclpy​

rclpy is the Python client library for ROS 2. It provides a Pythonic interface to ROS 2's functionality, allowing you to create nodes, publish/subscribe to topics, provide/call services, and work with actions from Python code.

Why Python for AI Agents?​

Python has become the dominant language for AI development due to:

  • Rich ecosystem of machine learning libraries (TensorFlow, PyTorch, scikit-learn)
  • Interactive development environment (Jupyter, IPython)
  • Large community and extensive documentation
  • Easy prototyping and experimentation
  • Integration with scientific computing tools (NumPy, Pandas, Matplotlib)

Key rclpy Concepts​

import rclpy
from rclpy.node import Node

class PythonAIAgent(Node):
def __init__(self):
super().__init__('python_ai_agent')

# Create publishers for sending commands to robot
self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)

# Create subscribers for receiving sensor data
self.sensor_sub = self.create_subscription(
LaserScan,
'/scan',
self.scan_callback,
10
)

# Create service clients for calling robot services
self.nav_client = self.create_client(NavigateToPose, '/navigate_to_pose')

# Create action clients for long-running tasks
self.follow_path_client = ActionClient(
self,
FollowPath,
'/follow_path'
)

# Timer for periodic AI processing
self.ai_timer = self.create_timer(0.1, self.ai_processing_callback)

# Internal state for the AI agent
self.laser_data = None
self.robot_pose = None

Building AI Controllers with rclpy​

Reactive Controllers​

Reactive controllers respond directly to sensor inputs without maintaining complex internal states:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
import numpy as np

class ReactiveObstacleAvoider(Node):
def __init__(self):
super().__init__('reactive_obstacle_avoider')

self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)
self.scan_sub = self.create_subscription(
LaserScan,
'/scan',
self.scan_callback,
10
)

# Robot parameters
self.min_distance = 0.5 # meters
self.linear_speed = 0.2 # m/s
self.angular_speed = 0.5 # rad/s

def scan_callback(self, msg):
# Process laser scan to detect obstacles
ranges = np.array(msg.ranges)
ranges = ranges[~np.isnan(ranges)] # Remove invalid readings

if len(ranges) == 0:
return # All measurements are invalid

min_range = np.min(ranges)

# Create command message
cmd = Twist()

if min_range < self.min_distance:
# Obstacle detected, turn
cmd.angular.z = self.angular_speed
else:
# Clear path, move forward
cmd.linear.x = self.linear_speed

self.cmd_pub.publish(cmd)

State-Based Controllers​

More complex agents maintain internal states and make decisions based on both sensor data and internal state:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
from enum import Enum
import numpy as np

class NavigationState(Enum):
EXPLORING = 1
AVOIDING = 2
TURNING = 3
GOAL_REACHED = 4

class StateBasedExplorer(Node):
def __init__(self):
super().__init__('state_based_explorer')

self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)
self.scan_sub = self.create_subscription(
LaserScan,
'/scan',
self.scan_callback,
10
)

# State management
self.state = NavigationState.EXPLORING
self.state_timer = self.create_timer(0.1, self.state_machine_callback)
self.state_start_time = self.get_clock().now()

# Robot parameters
self.min_distance = 0.5
self.linear_speed = 0.2
self.angular_speed = 0.5
self.turn_duration = 2.0 # seconds to turn when stuck

def scan_callback(self, msg):
self.laser_ranges = np.array(msg.ranges)
self.laser_ranges = self.laser_ranges[~np.isnan(self.laser_ranges)]

def state_machine_callback(self):
cmd = Twist()

if self.state == NavigationState.EXPLORING:
if self.laser_ranges is not None and np.min(self.laser_ranges) < self.min_distance:
self.state = NavigationState.AVOIDING
self.state_start_time = self.get_clock().now()
else:
cmd.linear.x = self.linear_speed

elif self.state == NavigationState.AVOIDING:
if self.laser_ranges is not None and np.min(self.laser_ranges) < self.min_distance:
# Continue turning to avoid obstacle
cmd.angular.z = self.angular_speed
else:
# Obstacle avoided, go back to exploring
self.state = NavigationState.EXPLORING

self.cmd_pub.publish(cmd)

Machine Learning Integration​

Real-Time Inference​

Python's rich ML ecosystem can be integrated directly with rclpy:

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from geometry_msgs.msg import Twist
import cv2
from cv_bridge import CvBridge
import torch
import torchvision.transforms as transforms

class MLController(Node):
def __init__(self):
super().__init__('ml_controller')

self.image_sub = self.create_subscription(Image, '/camera/image_raw', self.image_callback, 10)
self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)

self.bridge = CvBridge()

# Load pre-trained model
self.model = torch.load('path_to_model.pth')
self.model.eval()

# Image transformation
self.transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])

def image_callback(self, msg):
try:
# Convert ROS Image to OpenCV image
cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")

# Preprocess image
input_tensor = self.transform(cv_image).unsqueeze(0)

# Run inference
with torch.no_grad():
output = self.model(input_tensor)
# Assume output is steering angle and speed
steering_angle = output[0][0].item()
speed = output[0][1].item()

# Send command to robot
cmd = Twist()
cmd.linear.x = max(0.0, min(1.0, speed))
cmd.angular.z = max(-1.0, min(1.0, steering_angle))

self.cmd_pub.publish(cmd)

except Exception as e:
self.get_logger().error(f'Error processing image: {e}')

Reinforcement Learning Integration​

RL agents can be implemented with rclpy for robot learning:

import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
import numpy as np
import torch
import torch.nn as nn

class DQNAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.model = self._build_model()

def _build_model(self):
# Simple neural network for DQN
model = nn.Sequential(
nn.Linear(self.state_size, 24),
nn.ReLU(),
nn.Linear(24, 24),
nn.ReLU(),
nn.Linear(24, self.action_size)
)
return model

def act(self, state):
# Epsilon-greedy action selection
# Implementation details omitted for brevity
pass

class RLController(Node):
def __init__(self):
super().__init__('rl_controller')

self.scan_sub = self.create_subscription(LaserScan, '/scan', self.scan_callback, 10)
self.odom_sub = self.create_subscription(Odometry, '/odom', self.odom_callback, 10)
self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)

# RL agent
self.agent = DQNAgent(state_size=360, action_size=5) # 360 laser readings, 5 actions

# Robot state
self.scan_data = None
self.odom_data = None

def scan_callback(self, msg):
self.scan_data = np.array(msg.ranges)

def odom_callback(self, msg):
self.odom_data = msg

def process_rl_step(self):
if self.scan_data is not None and self.odom_data is not None:
# Create state vector from sensor data
state = self.scan_data

# Get action from RL agent
action = self.agent.act(state)

# Convert action to robot command
cmd = Twist()
# Map action to linear and angular velocities
cmd.linear.x = 0.2 if action == 0 else 0.1 # Forward speeds
cmd.angular.z = [-0.5, -0.2, 0.0, 0.2, 0.5][action] # Turn rates

self.cmd_pub.publish(cmd)

Advanced rclpy Features​

Async/Await Support​

For more complex agents, rclpy supports asyncio:

import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile
from rclpy.action import ActionClient
from example_interfaces.action import Fibonacci
import asyncio

class AsyncAIAgent(Node):
def __init__(self):
super().__init__('async_ai_agent')
self.action_client = ActionClient(
self,
Fibonacci,
'fibonacci'
)

async def execute_fibonacci_goal(self, order):
# Wait for action server
while not self.action_client.wait_for_server(timeout_sec=1.0):
self.get_logger().info('Action server not available, waiting...')

# Create goal
goal_msg = Fibonacci.Goal()
goal_msg.order = order

# Send goal and await result
self.get_logger().info(f'Sending Fibonacci goal with order {order}')
goal_handle = await self.action_client.send_goal_async(goal_msg)

if not goal_handle.accepted:
self.get_logger().info('Goal was rejected')
return None

self.get_logger().info('Goal accepted, waiting for result...')
result = await goal_handle.get_result_async()

self.get_logger().info(f'Goal completed with result: {result.result.sequence}')
return result.result.sequence

Lifecycle Nodes​

For more robust systems, consider using lifecycle nodes:

from rclpy.lifecycle import LifecycleNode
from rclpy.lifecycle import TransitionCallbackReturn

class LifecycleAIAgent(LifecycleNode):
def __init__(self):
super().__init__('lifecycle_ai_agent')

def on_configure(self, state):
self.get_logger().info('Configuring')
# Create publishers/subscribers here
self.cmd_pub = self.create_publisher(Twist, '/cmd_vel', 10)
return TransitionCallbackReturn.SUCCESS

def on_activate(self, state):
self.get_logger().info('Activating')
# Enable publishers/subscribers
self.cmd_pub.on_activate()
return TransitionCallbackReturn.SUCCESS

def on_deactivate(self, state):
self.get_logger().info('Deactivating')
self.cmd_pub.on_deactivate()
return TransitionCallbackReturn.SUCCESS

def on_cleanup(self, state):
self.get_logger().info('Cleaning up')
# Destroy publishers/subscribers
self.destroy_publisher(self.cmd_pub)
return TransitionCallbackReturn.SUCCESS

Performance Considerations​

Timing and Real-Time Requirements​

AI agents must consider timing constraints in physical systems:

import rclpy
from rclpy.node import Node

class TimedAIAgent(Node):
def __init__(self):
super().__init__('timed_ai_agent')

# Process sensor data at specific rate
self.process_timer = self.create_timer(
0.05, # 20 Hz for reactive control
self.process_sensor_data
)

# AI decision making at lower rate
self.decision_timer = self.create_timer(
0.5, # 2 Hz for high-level decisions
self.make_high_level_decision
)

def process_sensor_data(self):
# Fast processing for reactive behaviors
pass

def make_high_level_decision(self):
# Slower processing for planning and learning
pass

Memory Management​

For continuous operation, consider memory usage:

from collections import deque

class MemoryEfficientAgent(Node):
def __init__(self):
super().__init__('memory_efficient_agent')

# Use deques instead of lists for time series data
self.sensor_history = deque(maxlen=1000)

# Regular cleanup of old data
self.cleanup_timer = self.create_timer(10.0, self.cleanup_old_data)

def cleanup_old_data(self):
# Remove old data that's no longer needed
pass

Learning Objectives​

After completing this module, you will be able to:

  • Implement Python-based AI agents using rclpy
  • Connect machine learning models to robot control
  • Design state-based controllers for complex behaviors
  • Apply async/await patterns for advanced robotics applications
  • Optimize AI agents for real-time robotics requirements

Hands-On Exercise​

Create a Python-based obstacle avoidance agent that:

  1. Subscribes to laser scan data
  2. Runs a simple machine learning model to classify obstacles
  3. Publishes velocity commands to avoid obstacles
  4. Uses appropriate QoS settings and timing constraints
  5. Maintains internal state for improved navigation decisions

Next Steps​

In the next section, we'll explore URDF (Unified Robot Description Format), which is used to describe robot models in ROS 2, enabling simulation and visualization of your robot designs.

💬
🤖
ROBO-ASSISTANT
Hello! I'm your AI assistant for Physical AI & Humanoid Robotics. How can I help you today?