0
0

【ROS2 launch.py Tips】launch.pyファイル内で、実行時引数(DeclareLaunchArgument)の値を取得する方法

Last updated at Posted at 2024-07-23

はじめに

 ROS2のlaunch.pyで、ファイル内で実行時に引数で指定した値を使う方法を紹介する。テストコードで挙動を変えたりURDFの読み込み先を引数によって変更したい場合などに有効。

動作確認環境

  • ROS2 Foxy

方法

launch.acitons.OpaqueFunctionを使う。

  • ポイント
    • DeclareLaunchArgumentで設定したcontextを受け取れるaction
    • OpaqueFunctionの引数で設定した関数内で、上記のcontextを利用してLaunchConfigurationに設定されたパラメータを取得する

サンプルコード

グローバルに宣言している

  • bool_param
  • int_param
  • float_param
from distutils.util import strtobool
from ament_index_python.packages import get_package_share_directory, get_package_prefix
import launch
from launch.actions import DeclareLaunchArgument, OpaqueFunction
from launch_ros.actions import Node
from launch.substitutions import (EnvironmentVariable, FindExecutable,
                                LaunchConfiguration, LocalSubstitution,
                                PythonExpression)
from launch.launch_context import LaunchContext
import launch_testing.actions
import launch_testing_ros

bool_param = False
int_param = 1
float_param = 0.0

def launch_setup(context: LaunchContext, *args, **kwargs):
    bool_param_config = LaunchConfiguration('bool_param')
    int_param_config = LaunchConfiguration('int_param')
    float_param_config = LaunchConfiguration('float_param')

    # globalパラメータとして宣言することで、launch_setup関数外でも利用可能にする
    global bool_param
    global init_param
    global float_param
    
    # context.perform_substitution関数を用いて、
    # 実行時、DeclareLaunchArgumentで指定した引数の値をLaunchConfiguration経由で取得
    # Text(str)型なので、型変換が必要
    bool_param = bool(strtobool(context.perform_substitution(bool_param_config)))
    int_param = int(context.perform_substitution(int_param_config))
    float_param = float(context.perform_substitution(float_param_config))
    
    # 通常通り、ノードのパラメータはLaunchConfigurationで渡す
    some_node = Node(
        package='some_node_package',
        executable='some_node',
        output='screen',
        parameters=[{
            'bool_param': bool_param,
            'int_param': int_param,
            'float_param': float_param
        }],
    )
    return [some_node]

def generate_launch_description():    
    return (
        launch.LaunchDescription([
            DeclareLaunchArgument(
                'bool_param', default_value='false', description='bool param'
            ),
            DeclareLaunchArgument(
                'int_param', default_value='10', description='int param'
            ),
            DeclareLaunchArgument(
                'float_param', default_value='0.1', description='float param'),
            OpaqueFunction(function=launch_setup)
        ])

まとめ

 ROS2のlaunch.pyで、ファイル内で実行時に引数で指定した値を使う方法を紹介した。URDFの動的な読み込みやテストコードで挙動を変えたいときに役立つ。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0