2025年9月23日 星期二

ROS2 load URDF to ros_gz_sim

 在 ros_gz_sim 中載入 URDF 檔案的方式與舊版 Gazebo 不同,

它依賴於 ROS 2 的啟動檔案(launch file)來處理 URDF 到 Gazebo 模型的轉換和載入。

直接使用 spawn_entity.py 腳本通常不適用於複雜的 .xacro 模型。


載入 URDF 到 ros_gz_sim 的正確方法

為了將您的 twowheel.urdf 載入到 ros_gz_sim 中,您需要使用一個 ROS 2 啟動檔案。這個啟動檔案會自動執行以下步驟:

  1. 啟動 Gazebo Sim:運行 gzservergzclient

  2. 發布機器人描述:使用 robot_state_publisher 節點來讀取您的 twowheel.urdf 檔案,並將其發布到 ROS 2 的 robot_description 主題上。

  3. 生成實體:使用 gazebo_ros 套件中的 spawn_entity.py 工具,從 robot_description 主題讀取 URDF 內容,並將機器人實體化到 Gazebo 模擬中。


啟動檔案範例

請在您的套件中創建一個 launch 資料夾,並將以下內容保存為 twowheel_sim.launch.py。這個檔案將會自動完成所有必要的步驟。

twowheel_sim.launch.py

>import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, SetEnvironmentVariable
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node

def generate_launch_description():

    # 獲取您的套件共享目錄
    pkg_share_path = get_package_share_directory('twowheel_bot')

    # 獲取 Gazebo world 檔案路徑
    world_path = os.path.join(pkg_share_path, 'worlds', 'empty.world')

    # 獲取 URDF 檔案路徑
    urdf_path = os.path.join(pkg_share_path, 'urdf', 'twowheel.urdf')

    # 使用一個 launch argument 來傳遞 URDF 到 robot_state_publisher
    robot_description_content = f"""
    <robot name="twowheel_bot">
      <xacro:include filename="{urdf_path}" />
    </robot>
    """

    return LaunchDescription([
        # 設置 Gazebo 模型路徑環境變數
        SetEnvironmentVariable('GAZEBO_MODEL_PATH', os.path.join(pkg_share_path, 'models')),

        # 啟動 Gazebo 伺服器和客戶端
        IncludeLaunchDescription(
            PythonLaunchDescriptionSource(
                os.path.join(
                    get_package_share_directory('ros_gz_sim'),
                    'launch',
                    'gz_sim.launch.py'
                )
            ),
            launch_arguments={'gz_args': world_path}.items()
        ),

        # 發布機器人描述
        Node(
            package='robot_state_publisher',
            executable='robot_state_publisher',
            name='robot_state_publisher',
            output='screen',
            parameters=[{'robot_description': robot_description_content}],
        ),

        # 將機器人生成到 Gazebo
        Node(
            package='ros_gz_sim',
            executable='create',
            arguments=['-name', 'twowheel_amr', '-topic', 'robot_description'],
            output='screen'
        ),
    ])
```
eof

### 如何使用

1.  **保存檔案**:將上述內容保存為 `twowheel_sim.launch.py`,並放在您的 ROS 2 套件(`twowheel_bot`)的 `launch` 資料夾中。
2.  **編譯**:確保您的套件已經被編譯:`colcon build`。
3.  **運行**:使用 `ros2 launch` 指令啟動模擬。
    ```

bash
 ros2 launch twowheel_bot twowheel_sim.launch.py
    

這個啟動檔案將會自動處理所有 URDF 載入和模型生成的問題,

讓您能夠輕鬆地在 ros_gz_sim 中進行模擬。

沒有留言:

張貼留言