Launch Files, Parameters & Robot Communication
In ROS 2, launch files and parameters are essential for configuring and starting robot systems. They allow you to define complex robot behaviors, manage system configurations, and control how different components communicate. This section covers how to use these tools effectively in Physical AI systems.
Understanding Launch Files
Launch files are Python scripts that define how to start ROS 2 processes and configure them. They replace the older XML-based launch system from ROS 1 with a more flexible Python-based approach.
Basic Launch File Structure
A simple launch file:
# launch/simple_robot.launch.py
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
return LaunchDescription([
Node(
package='simple_robot',
executable='robot_controller',
name='robot_controller',
parameters=[
{'wheel_radius': 0.05},
{'wheel_separation': 0.3},
],
remappings=[
('/cmd_vel', '/robot/cmd_vel'),
('/odom', '/robot/odom'),
]
),
Node(
package='simple_robot',
executable='sensor_processor',
name='sensor_processor'
)
])
Launch File Components
The main components of launch files include:
- LaunchDescription: Container for all launch actions
- Node: Defines a ROS 2 node to launch
- Parameters: Configuration values passed to nodes
- Remappings: Redirect topic/service names
- Conditions: Conditional launch of components
- Events: React to system events
Advanced Launch Features
Conditional Launch
Launch components based on conditions:
from launch import LaunchDescription, conditions
from launch.substitutions import LaunchConfiguration
from launch.actions import DeclareLaunchArgument
from launch_ros.actions import Node
def generate_launch_description():
# Declare launch arguments
use_sim_time = LaunchConfiguration('use_sim_time')
use_sim_time_arg = DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use simulation time if true'
)
# Conditional node launch
controller_node = Node(
package='simple_robot',
executable='robot_controller',
name='robot_controller',
parameters=[
{'use_sim_time': use_sim_time}
],
condition=conditions.IfCondition(use_sim_time)
)
return LaunchDescription([
use_sim_time_arg,
controller_node
])
Launch Substitutions
Use substitutions to make launch files more flexible:
from launch import LaunchDescription
from launch.substitutions import TextSubstitution, PathJoinSubstitution
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
def generate_launch_description():
# Use parameter substitution
robot_name = LaunchConfiguration('robot_name', default='simple_robot')
# Use path substitution for configuration files
config_file_path = PathJoinSubstitution([
get_package_share_directory('simple_robot'),
'config',
[robot_name, '.yaml']
])
return LaunchDescription([
Node(
package='simple_robot',
executable='robot_controller',
name=[robot_name, '_controller'],
parameters=[config_file_path]
)
])
Parameter Management
Parameters provide a way to configure ROS 2 nodes dynamically, which is crucial for Physical AI systems that need to adapt to different environments and tasks.
Parameter Declaration in Nodes
import rclpy
from rclpy.node import Node
class RobotController(Node):
def __init__(self):
super().__init__('robot_controller')
# Declare parameters with default values
self.declare_parameter('robot_name', 'simple_robot')
self.declare_parameter('control_frequency', 50.0)
self.declare_parameter('max_linear_speed', 0.5)
self.declare_parameter('max_angular_speed', 1.0)
self.declare_parameter('safety_distance', 0.3)
# Get parameter values
self.robot_name = self.get_parameter('robot_name').value
self.control_freq = self.get_parameter('control_frequency').value
self.max_linear = self.get_parameter('max_linear_speed').value
self.max_angular = self.get_parameter('max_angular_speed').value
self.safety_distance = self.get_parameter('safety_distance').value
# Create timer based on parameter
self.control_timer = self.create_timer(
1.0 / self.control_freq,
self.control_loop
)
# Setup parameter callback for dynamic reconfiguration
self.add_on_set_parameters_callback(self.parameter_callback)
def parameter_callback(self, params):
"""Callback for parameter changes"""
for param in params:
if param.name == 'max_linear_speed' and param.type_ == Parameter.Type.DOUBLE:
self.max_linear = param.value
self.get_logger().info(f'Updated max_linear_speed to {self.max_linear}')
elif param.name == 'max_angular_speed' and param.type_ == Parameter.Type.DOUBLE:
self.max_angular = param.value
self.get_logger().info(f'Updated max_angular_speed to {self.max_angular}')
return SetParametersResult(successful=True)
YAML Parameter Files
Organize parameters in YAML files for better management:
# config/simple_robot.yaml
/**:
ros__parameters:
robot_name: "simple_robot"
control_frequency: 50.0
max_linear_speed: 0.5
max_angular_speed: 1.0
safety_distance: 0.3
wheel_radius: 0.05
wheel_separation: 0.3
# Controller parameters
controller:
k_p: 1.0
k_i: 0.1
k_d: 0.05
max_integral: 1.0
Load parameters in launch file:
from launch import LaunchDescription
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
config = os.path.join(
get_package_share_directory('simple_robot'),
'config',
'simple_robot.yaml'
)
return LaunchDescription([
Node(
package='simple_robot',
executable='robot_controller',
name='robot_controller',
parameters=[config],
output='screen'
)
])
Robot Communication Patterns
Robot State Publisher
The robot_state_publisher node publishes transforms for your robot's URDF model:
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import os
def generate_launch_description():
# Get URDF file path
urdf_file = os.path.join(
get_package_share_directory('simple_robot_description'),
'urdf',
'simple_robot.urdf'
)
# Launch robot state publisher
robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[
{'robot_description': open(urdf_file).read()},
{'use_sim_time': LaunchConfiguration('use_sim_time', default='false')}
]
)
return LaunchDescription([
robot_state_publisher
])
Joint State Publisher
Publishes joint positions for visualization:
# For simulation (with Gazebo)
joint_state_publisher = Node(
package='joint_state_publisher',
executable='joint_state_publisher',
name='joint_state_publisher'
)
# For real robots, use joint state publisher GUI or robot hardware interface
joint_state_publisher_gui = Node(
package='joint_state_publisher_gui',
executable='joint_state_publisher_gui',
name='joint_state_publisher_gui'
)
TF (Transform) Communication
TF trees provide spatial relationships between robot parts:
import rclpy
from rclpy.node import Node
from tf2_ros import TransformBroadcaster
from geometry_msgs.msg import TransformStamped
class RobotTfPublisher(Node):
def __init__(self):
super().__init__('robot_tf_publisher')
# Initialize transform broadcaster
self.tf_broadcaster = TransformBroadcaster(self)
# Publish transforms at 50 Hz
self.timer = self.create_timer(0.02, self.publish_transforms)
def publish_transforms(self):
"""Publish transforms for robot components"""
# Example: Publish transform between base_link and laser_frame
t = TransformStamped()
# Header
t.header.stamp = self.get_clock().now().to_msg()
t.header.frame_id = 'base_link'
t.child_frame_id = 'laser_frame'
# Transform
t.transform.translation.x = 0.1
t.transform.translation.y = 0.0
t.transform.translation.z = 0.2
t.transform.rotation.x = 0.0
t.transform.rotation.y = 0.0
t.transform.rotation.z = 0.0
t.transform.rotation.w = 1.0
# Send transform
self.tf_broadcaster.sendTransform(t)
Complex Robot System Launch
For complete robot systems, launch files coordinate multiple components:
# launch/physical_ai_robot.launch.py
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node, ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
from ament_index_python.packages import get_package_share_directory
def generate_launch_description():
# Declare launch arguments
use_sim_time = DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use simulation time if true'
)
robot_name = DeclareLaunchArgument(
'robot_name',
default_value='physical_ai_robot',
description='Name of the robot'
)
# Robot description
robot_description_path = PathJoinSubstitution([
get_package_share_directory('physical_ai_robot_description'),
'urdf',
'physical_ai_robot.urdf.xacro'
])
# Include navigation launch file if needed
nav_launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource([
get_package_share_directory('nav2_bringup'),
'/launch/navigation_launch.py'
]),
launch_arguments={
'use_sim_time': LaunchConfiguration('use_sim_time')
}.items()
)
# Robot state publisher
robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[
{'robot_description': open(robot_description_path.perform(context=None)).read()},
{'use_sim_time': LaunchConfiguration('use_sim_time')}
],
remappings=[
('/tf', 'tf'),
('/tf_static', 'tf_static')
]
)
# Robot controller
robot_controller = Node(
package='physical_ai_robot_controller',
executable='robot_controller',
name='robot_controller',
parameters=[
PathJoinSubstitution([
get_package_share_directory('physical_ai_robot_controller'),
'config',
'controller.yaml'
]),
{'use_sim_time': LaunchConfiguration('use_sim_time')}
],
output='screen'
)
# Perception pipeline (using composition for efficiency)
perception_container = ComposableNodeContainer(
name='perception_container',
namespace='',
package='rclcpp_components',
executable='component_container_mt',
composable_node_descriptions=[
ComposableNode(
package='physical_ai_robot_perception',
plugin='LaserFilterNode',
name='laser_filter'
),
ComposableNode(
package='physical_ai_robot_perception',
plugin='ObstacleDetectorNode',
name='obstacle_detector'
)
],
output='screen'
)
# Return launch description
return LaunchDescription([
use_sim_time,
robot_name,
robot_state_publisher,
robot_controller,
perception_container,
# nav_launch # Uncomment if navigation is needed
])
Physical AI Communication Requirements
Real-time Communication
Physical AI systems have strict timing requirements:
# High-frequency control loop
self.control_timer = self.create_timer(
0.01, # 100 Hz for reactive control
self.high_freq_control_loop,
clock=self.get_clock()
)
# Medium-frequency processing
self.processing_timer = self.create_timer(
0.1, # 10 Hz for AI processing
self.ai_processing_loop,
clock=self.get_clock()
)
Parameter Tuning for Performance
For Physical AI systems, parameters often need real-time adjustment:
class AdaptiveController(Node):
def __init__(self):
super().__init__('adaptive_controller')
# Runtime-tunable parameters
self.declare_parameter('kp_linear', 1.0)
self.declare_parameter('kp_angular', 1.0)
self.declare_parameter('adaptive_gain', 0.5)
# Setup parameter callback
self.add_on_set_parameters_callback(self.update_parameters)
def update_parameters(self, params):
"""Update parameters at runtime"""
for param in params:
if param.name == 'kp_linear':
self.kp_linear = param.value
elif param.name == 'kp_angular':
self.kp_angular = param.value
elif param.name == 'adaptive_gain':
self.adaptive_gain = param.value
return SetParametersResult(successful=True)
Best Practices for Physical AI Systems
Modular Launch Files
Create modular launch files that can be combined:
# Separate launch files for different components
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from ament_index_python.packages import get_package_share_directory
def generate_launch_description():
return LaunchDescription([
# Include base robot launch
IncludeLaunchDescription(
PythonLaunchDescriptionSource([
get_package_share_directory('simple_robot_bringup'),
'/launch/robot.launch.py'
])
),
# Include perception stack
IncludeLaunchDescription(
PythonLaunchDescriptionSource([
get_package_share_directory('simple_robot_perception'),
'/launch/perception.launch.py'
])
),
# Include AI controller
IncludeLaunchDescription(
PythonLaunchDescriptionSource([
get_package_share_directory('simple_robot_ai'),
'/launch/ai_controller.launch.py'
])
)
])
Error Handling and Monitoring
Implement robust error handling:
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSDurabilityPolicy, QoSProfile
class RobustController(Node):
def __init__(self):
super().__init__('robust_controller')
# Configure QoS for reliable communication
qos_profile = QoSProfile(
depth=10,
durability=QoSDurabilityPolicy.VOLATILE
)
# Create subscribers with error handling
try:
self.cmd_vel_sub = self.create_subscription(
Twist,
'cmd_vel',
self.cmd_vel_callback,
qos_profile
)
except Exception as e:
self.get_logger().error(f'Failed to create subscriber: {e}')
return
def cmd_vel_callback(self, msg):
try:
# Process command safely
if not self.validate_command(msg):
return
self.execute_command(msg)
except Exception as e:
self.get_logger().error(f'Error processing command: {e}')
# Implement safe behavior when errors occur
self.emergency_stop()
def validate_command(self, cmd):
"""Validate incoming commands"""
return (
abs(cmd.linear.x) <= 2.0 and
abs(cmd.angular.z) <= 2.0
)
Learning Objectives
After completing this module, you will be able to:
- Create and use launch files to configure robot systems
- Manage parameters for dynamic reconfiguration
- Set up robot communication patterns (TF, state publishing)
- Design launch files for complex Physical AI systems
- Implement parameter validation and error handling
Hands-On Exercise
Create a launch file system for a humanoid robot that:
- Loads robot description from URDF
- Launches state publisher and joint state publisher
- Starts a controller node with parameter configuration
- Includes a perception pipeline with proper QoS settings
- Has launch arguments to switch between simulation and real robot modes
Next Steps
In the next section, we'll implement a mini-project that brings together everything learned in Module 1 by building a complete ROS 2 control pipeline for a humanoid robot.