← Quay lại Blog
otherroboticsros2

Giới thiệu ROS 2: Nền tảng lập trình robot thế hệ mới

ROS 2 mang đến kiến trúc phân tán mạnh mẽ, hỗ trợ real-time và bảo mật — lý tưởng cho robot công nghiệp và tự hành.

Nguyễn Anh Tuấn15 tháng 6, 20256 phút đọc
Giới thiệu ROS 2: Nền tảng lập trình robot thế hệ mới

ROS 2 là gì?

ROS 2 (Robot Operating System 2) là framework mã nguồn mở được thiết kế lại hoàn toàn từ ROS 1, nhắm đến việc hỗ trợ các ứng dụng robot thương mại và công nghiệp. Không giống như ROS 1 phụ thuộc vào một master node trung tâm (roscore), ROS 2 sử dụng DDS (Data Distribution Service) làm middleware giao tiếp, cho phép kiến trúc phân tán thực sự.

Hiểu đơn giản: nếu ROS 1 như một hệ thống điện thoại cần tổng đài trung tâm, thì ROS 2 như mạng internet — mỗi node có thể giao tiếp trực tiếp với nhau mà không cần "tổng đài".

Kiến trúc phân tán ROS 2 với DDS middleware

Tại sao nên chuyển sang ROS 2?

1. Hỗ trợ Real-time

ROS 2 được xây dựng trên nền tảng DDS với khả năng QoS (Quality of Service) linh hoạt. Điều này cho phép bạn cấu hình độ tin cậy, độ trễ và băng thông cho từng topic riêng biệt — yếu tố quan trọng trong điều khiển robot công nghiệp.

Ví dụ thực tế: Khi điều khiển cánh tay robot hàn, bạn cần dữ liệu encoder đến trong vòng 1ms. Với ROS 2, bạn set QoS profile RELIABLE + KEEP_LAST(1) cho topic /joint_states để đảm bảo điều này. Trong khi đó, topic camera có thể dùng BEST_EFFORT vì mất vài frame không ảnh hưởng.

2. Bảo mật tích hợp

ROS 2 tích hợp SROS2 (Secure ROS 2) với mã hóa TLS/DTLS cho giao tiếp giữa các node. Trong môi trường nhà máy, đây là yêu cầu bắt buộc khi robot kết nối qua mạng nội bộ.

Thiết lập bảo mật cơ bản:

# Tạo keystore và certificates cho các node
ros2 security create_keystore ~/sros2_keystore
ros2 security create_enclave ~/sros2_keystore /my_robot/camera_node
ros2 security create_enclave ~/sros2_keystore /my_robot/motor_node

# Kích hoạt bảo mật khi chạy
export ROS_SECURITY_KEYSTORE=~/sros2_keystore
export ROS_SECURITY_ENABLE=true
export ROS_SECURITY_STRATEGY=Enforce

3. Đa nền tảng

ROS 2 hỗ trợ chính thức Ubuntu, Windows và macOS. Bạn có thể phát triển trên laptop Windows và deploy lên robot chạy Ubuntu ARM64 mà không cần thay đổi code. Đây là lợi thế lớn so với ROS 1 chỉ hỗ trợ tốt trên Ubuntu.

4. Lifecycle Node Management

ROS 2 giới thiệu Lifecycle Nodes — cho phép quản lý trạng thái của node (Unconfigured → Inactive → Active → Finalized). Điều này rất quan trọng trong sản xuất: bạn có thể cấu hình tất cả node trước, rồi activate đồng loạt khi robot sẵn sàng.

from rclpy.lifecycle import Node as LifecycleNode

class CameraNode(LifecycleNode):
    def __init__(self):
        super().__init__('camera_node')

    def on_configure(self, state):
        # Khởi tạo camera driver, load calibration
        self.camera = cv2.VideoCapture(0)
        self.get_logger().info('Camera configured')
        return TransitionCallbackReturn.SUCCESS

    def on_activate(self, state):
        # Bắt đầu publish frames
        self.timer = self.create_timer(0.033, self.publish_frame)
        return TransitionCallbackReturn.SUCCESS

    def on_deactivate(self, state):
        # Dừng publish, giữ camera mở
        self.destroy_timer(self.timer)
        return TransitionCallbackReturn.SUCCESS

Kiến trúc cơ bản

Một hệ thống ROS 2 điển hình bao gồm 4 primitives giao tiếp:

Primitive Mô tả Use case
Topic Pub/Sub bất đồng bộ Sensor data, robot state
Service Request/Response đồng bộ Get parameter, trigger action
Action Goal + Feedback + Result Navigation, arm movement
Parameter Key-value runtime config Tuning PID, thay đổi speed

Graph concept

Mỗi node ROS 2 là một process độc lập. Chúng giao tiếp qua DDS network mà không cần biết nhau ở đâu — cùng máy hay khác máy đều hoạt động như nhau. Đây gọi là location transparency.

# Xem toàn bộ graph hiện tại
ros2 node list
ros2 topic list
ros2 topic echo /scan  # Xem dữ liệu LiDAR real-time

ROS 2 computation graph với nodes, topics và services

Bắt đầu với ROS 2 Humble

ROS 2 Humble Hawksbill là phiên bản LTS (hỗ trợ đến 2027), phù hợp cho dự án production. Cài đặt trên Ubuntu 22.04:

# Thêm ROS 2 repository
sudo apt update && sudo apt install -y software-properties-common
sudo add-apt-repository universe
sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu $(. /etc/os-release && echo $UBUNTU_CODENAME) main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null

# Cài đặt
sudo apt update
sudo apt install ros-humble-desktop

# Source environment
echo "source /opt/ros/humble/setup.bash" >> ~/.bashrc
source ~/.bashrc

Tạo workspace và package đầu tiên

# Tạo workspace
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src

# Tạo Python package
ros2 pkg create --build-type ament_python my_robot_pkg --dependencies rclpy std_msgs

# Build
cd ~/ros2_ws
colcon build --symlink-install

# Source workspace
source install/setup.bash

Publisher node đơn giản

# my_robot_pkg/my_robot_pkg/sensor_publisher.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32

class SensorPublisher(Node):
    def __init__(self):
        super().__init__('sensor_publisher')
        self.publisher = self.create_publisher(Float32, '/temperature', 10)
        self.timer = self.create_timer(1.0, self.timer_callback)
        self.get_logger().info('Sensor publisher started')

    def timer_callback(self):
        msg = Float32()
        msg.data = self.read_temperature()
        self.publisher.publish(msg)

    def read_temperature(self):
        # Đọc từ sensor thực tế hoặc giả lập
        return 25.5

def main():
    rclpy.init()
    node = SensorPublisher()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

Hệ sinh thái ROS 2

Sức mạnh thật sự của ROS 2 nằm ở hệ sinh thái packages:

So sánh ROS 1 vs ROS 2

Tiêu chí ROS 1 ROS 2
Middleware Custom (TCPROS) DDS (chuẩn công nghiệp)
Master node Bắt buộc (roscore) Không cần
Real-time Không hỗ trợ QoS profiles
Bảo mật Không có SROS2 (TLS/DTLS)
Multi-robot Khó (namespace) Dễ (DDS domain)
OS Ubuntu only Ubuntu, Windows, macOS
Lifecycle Không có Lifecycle nodes

Kết luận

ROS 2 đã trưởng thành đủ để sử dụng trong sản xuất. Với hệ sinh thái phong phú (Navigation2, MoveIt2, ros2_control), đây là lựa chọn hàng đầu cho bất kỳ dự án robot nào từ nghiên cứu đến thương mại.

Bước tiếp theo:

Bài viết liên quan

Bài viết liên quan

Deep DiveDigital Twins và ROS 2: Simulation trong sản xuất
simulationros2digital-twinPhần 6

Digital Twins và ROS 2: Simulation trong sản xuất

Ứng dụng simulation trong công nghiệp — digital twins, ROS 2 + Gazebo/Isaac integration cho nhà máy thông minh.

3/4/202611 phút đọc
IROS 2026: Papers navigation và manipulation đáng theo dõi
researchconferencerobotics

IROS 2026: Papers navigation và manipulation đáng theo dõi

Phân tích papers nổi bật về autonomous navigation và manipulation — chuẩn bị cho IROS 2026 Pittsburgh.

2/4/20267 phút đọc
Sim-to-Real Transfer: Train simulation, chạy thực tế
ai-perceptionresearchrobotics

Sim-to-Real Transfer: Train simulation, chạy thực tế

Kỹ thuật chuyển đổi mô hình từ simulation sang robot thật — domain randomization, system identification và best practices.

1/4/202612 phút đọc