Skip to content
Home
Robot Operating System 2: ROS 2 Architecture and Development

Robot Operating System 2: ROS 2 Architecture and Development

Robotics Robotics 8 min read 1502 words Beginner ExcellentWiki Editorial Team

ROS 2 is the second generation of the Robot Operating System, designed for production robotics with real-time support, security, and multi-platform compatibility. It replaces the ROS 1 master-centric architecture with a decentralized Data Distribution Service (DDS) middleware.

ROS 2 Architecture

ROS 2 improves on ROS 1 with real-time support, security, and multi-platform compatibility. Nodes communicate over DDS (Data Distribution Service), a real-time publish-subscribe middleware. The composition model allows multiple nodes to run in a single process, reducing overhead. ROS 2 supports multiple DDS implementations including Fast DDS, Cyclone DDS, and GurumDDS. Launch files in ROS 2 use Python, providing more flexibility than the XML format in ROS 1.

DDS Middleware

DDS provides discovery, serialization, and transport. Unlike ROS 1’s custom TCPROS protocol, DDS is an industry standard (OMG) used in aerospace, defense, and industrial systems. Benefits include:

  • Decentralized discovery — no single master node
  • Quality of Service (QoS) — reliability, durability, deadline, and liveliness policies
  • Real-time support — DDS implementations offer real-time scheduling
  • Security — built-in authentication, encryption, and access control

Nodes and Communication

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)
        self.timer = self.create_timer(1.0, self.timer_callback)
        
    def timer_callback(self):
        msg = String()
        msg.data = 'Hello from ROS 2'
        self.publisher.publish(msg)
        self.get_logger().info(f'Publishing: {msg.data}')

def main(args=None):
    rclpy.init(args=args)
    node = Talker()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

ROS 2 vs ROS 1 Migration

ROS 1 (Noetic) reached end-of-life in May 2025. All new development should use ROS 2. Key migration changes include: Python 3 only, catkin → colcon for builds, custom ROS middleware → DDS, launch XML → Python launch files, and namespaced packages (e.g., std_msgsstd_msgs.msg). Packages from ROS 1’s vast ecosystem are being ported to ROS 2, with most critical ones already available. The ros1_bridge package enables communication between ROS 1 and ROS 2 systems during migration.

Building with Colcon

# Install colcon
pip install colcon-common-extensions

# Build workspace
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build
source install/setup.bash

# Build specific packages
colcon build --packages-select my_package

ROS 2 CLI Tools

Essential command-line tools include ros2 node list to see running nodes, ros2 topic echo /topic_name to inspect messages, ros2 service call /service_name to invoke services, ros2 action send_goal /action_name to execute actions, and ros2 bag record -a to record all topics for later analysis and replay.

# List nodes
ros2 node list

# Echo a topic
ros2 topic echo /odom

# Call a service
ros2 service call /get_pose custom_interfaces/srv/GetPose

# Record bag
ros2 bag record -a -o my_recording

# Play bag
ros2 bag play my_recording

Lifecycle Management

ROS 2 introduces managed nodes with lifecycle states: Unconfigured, Inactive, Active, and Finalized. Lifecycle nodes transition between states on command, enabling controlled startup, shutdown, and error recovery. This is critical for production systems that need deterministic initialization sequences.

from rclpy.lifecycle import LifecycleNode, State, TransitionCallbackReturn

class ManagedNode(LifecycleNode):
    def __init__(self):
        super().__init__('managed_node')
    
    def on_configure(self, state):
        self.get_logger().info('Configuring...')
        # Load parameters, open hardware, allocate resources
        return TransitionCallbackReturn.SUCCESS
    
    def on_activate(self, state):
        self.get_logger().info('Activating...')
        # Start timers, enable publishing
        return TransitionCallbackReturn.SUCCESS
    
    def on_deactivate(self, state):
        self.get_logger().info('Deactivating...')
        # Stop timers, disable publishing
        return TransitionCallbackReturn.SUCCESS

ROS 2 Security

ROS 2 includes built-in security features through DDS’s built-in plugins. SROS 2 provides authentication, access control, and encryption. Use ros2 security commands to generate keystores and configure permissions per node. Enclaves define security boundaries, and access control lists specify which nodes can publish or subscribe to which topics.

# Create keystore
ros2 security create_keystore ~/keystore

# Generate keys for a node
ros2 security create_key ~/keystore /my_node

# Run with security enabled
export ROS_SECURITY_KEYSTORE=~/keystore
export ROS_SECURITY_ENABLE=true
export ROS_SECURITY_STRATEGY=Enforce
ros2 run my_package my_node

ROS 2 Tooling and Ecosystem

The ROS 2 ecosystem includes essential tools beyond the core framework. RViz2 visualizes robot state, sensor data, and maps in 3D. rosbag2 records and plays back ROS topics for offline analysis and testing. ros2doctor diagnoses common configuration issues. robot_state_publisher broadcasts the robot’s kinematic tree using URDF files. nav2 provides production-grade navigation stack with map server, planner, controller, and behavior tree integration. MoveIt 2 handles arm motion planning, kinematics, and collision checking. These tools form a comprehensive development environment for building complex robotic systems.

Summary

ROS 2 provides a production-ready robotics framework with DDS middleware, real-time support, security, and lifecycle management. Use colcon for building, Python launch files for starting systems, and SROS 2 for security. All new development should target ROS 2 — ROS 1 is end-of-life.

ROS 2 Namespace and Multi-Robot Systems

ROS 2 uses namespaces to isolate multiple robots on the same network. Launch each robot’s nodes under a unique namespace: ros2 launch my_bot bringup.launch.py namespace:=robot1. Topics and services are remapped to include the namespace, so /robot1/odom and /robot2/odom coexist without conflict. Use PushRosNamespace in launch files to apply namespace automatically to all nodes in a group. For multi-robot coordination, use a centralized supervisor node or distributed consensus protocols. TF (transform) frames also use namespacing with robot1/base_link and robot2/base_link to distinguish coordinate frames.

FAQ

Should I use ROS 2 or ROS 1 for a new project?

Use ROS 2 for all new projects. ROS 1 (Noetic) reached end-of-life in May 2025 with no further updates. ROS 2 provides real-time support, security, multi-platform support (Windows, macOS, Linux), and is actively developed by the Open Robotics community.

What DDS implementation should I choose?

Fast DDS (eProsima) is the default and most widely tested. Cyclone DDS (Eclipse) offers better performance in large systems and is the default in newer ROS 2 distributions. GurumDDS is optimized for embedded systems. For most users, the default (Fast DDS or Cyclone DDS depending on distro) is sufficient.

How do I achieve real-time performance with ROS 2?

Use the real-time Linux kernel (PREEMPT_RT). Set CPU affinity for critical nodes using taskset. Isolate CPUs from the kernel scheduler using isolcpus boot parameter. Use the ROS 2 real-time executor (rclcpp::executors::StaticSingleThreadedExecutor) for predictable callback execution. Avoid dynamic memory allocation in real-time callbacks.

ROS 2 Security Features

ROS 2 integrates the DDS security protocol (DDS-Security) for authentication, access control, and encryption. The Security enclave model creates a root of trust with certificates, permissions, and governance files. Enable security by setting RMW_IMPLEMENTATION to rmw_fastrtps_cpp and configuring the SROS2 keystore. Use ros2 security create_keystore, ros2 security create_enclave, and ros2 security create_permission to set up authenticated groups. Nodes without proper credentials cannot publish or subscribe to protected topics. This security model is critical for deployment in industrial and medical environments.

Monitoring and Visualization

RViz2 provides 3D visualization for robot state, sensor data, and navigation maps. Configure displays for robot model (TF + URDF), laser scans, camera images, point clouds, and planned paths. Use ros2 run rviz2 rviz2 with a saved configuration file for consistent startup. For web-based monitoring, rosbridge_server exposes ROS 2 topics over WebSocket for browser-based dashboards built with roslibjs. The ros2 topic hz command monitors message frequency to detect publisher failures. Log analysis with ros2 bag play and rqt_console helps diagnose runtime issues.

Data Recording and Playback

ROS 2’s rosbag2 tool records topic data for offline analysis. Record all topics: ros2 bag record -a. Record specific topics: ros2 bag record /camera/image /scan /odom. Play back: ros2 bag play my_bag. Split recordings by duration or file size with --max-cache-size and --max-splits. Use ros2 bag info to inspect bag contents. For deterministic testing, play bags at different rates: --rate 0.5 for slow-motion analysis. Bag files are essential for debugging intermittent issues, benchmarking algorithms, and creating regression test datasets.

ROS 2 on Embedded Systems

Deploy ROS 2 on resource-constrained hardware using micro-ROS — a ROS 2 framework for microcontrollers. micro-ROS runs on FreeRTOS, Zephyr, and bare-metal systems with as little as 32 KB RAM. It supports publishers, subscribers, services, and parameters over DDS (using Micro XRCE-DDS). Connect micro-ROS nodes to a ROS 2 system through a client agent running on a companion computer. This enables sensor nodes, motor controllers, and actuator drivers to participate in the ROS 2 ecosystem directly from microcontrollers without a full Linux stack. micro-ROS is production-ready for embedded robotics, industrial sensors, and smart actuators.

ROS 2 Community and Resources

The ROS 2 community provides extensive resources: ROS Discourse for Q&A, ROS Answers for technical questions, ROSCon conference proceedings for latest developments, and the ROS 2 design documents on GitHub for architectural decisions. The ros-tutorials package provides hands-on examples. Index.ros.org catalogs over 3,000 ROS 2 packages. The ROS 2 Technical Steering Committee oversees development. Active contribution is encouraged — many core packages accept pull requests from the community. The ecosystem continues to grow rapidly as ROS 1 users complete their migration. New users should start with the official ROS 2 tutorials and join the ROS Discourse for community support.

Can ROS 2 communicate with ROS 1 systems?

Yes — the ros1_bridge package provides bidirectional communication between ROS 1 and ROS 2 systems. Run ros1_bridge on a machine that has both ROS 1 and ROS 2 installed. Topics are bridged dynamically based on message type matching. Use this during migration from ROS 1 to ROS 2.

For a comprehensive overview, read our article on Ai Robotics.

For a comprehensive overview, read our article on Autonomous Mobile Robots.

Section: Robotics 1502 words 8 min read Beginner 756 articles in section Report inaccuracy Back to top