目标:了解 ROS 2 启动文件中的替代项。
教程级别:中级
时间:15 分钟
目录
背景
先决条件
使用替代品
1. 创建并设置包
2. 父启动文件
3 替代示例启动文件
4. 构建包
启动示例
修改启动参数
文档
摘要
背景
启动文件用于启动节点、服务和执行进程。这组动作可能有参数,这些参数会影响它们的行为。在参数中可以使用替代来提供在描述可重用启动文件时更多的灵活性。替代是一种变量,只有在执行启动描述时才会评估,可用于获取特定信息,如启动配置、环境变量,或评估任意 Python 表达式。
本教程展示了 ROS 2 启动文件中替代用法的示例。
先决条件
本教程使用 turtlesim 包。本教程还假设您熟悉创建包。
始终不要忘记在您打开的每个新终端中获取 ROS 2 的源。
使用替代品
1. 创建并设置包
首先,创建一个名为 launch_tutorial
的新包:
Python包: 创建一个新的 build_type ament_python
包:
ros2 pkg create --build-type ament_python --license Apache-2.0 launch_tutorial
C++包: 创建一个新的 build_type ament_cmake
包:
ros2 pkg create --build-type ament_cmake --license Apache-2.0 launch_tutoria
在那个包内部,创建一个名为 launch
的目录:
mkdir launch_tutorial/launch
最后,请确保安装启动文件:
Python包:将以下更改添加到包裹的 setup.py
中:
import os
from glob import glob
from setuptools import find_packages, setup
package_name = 'launch_tutorial'
setup(
# Other parameters ...
data_files=[
# ... Other data files
# Include all launch files.
(os.path.join('share', package_name, 'launch'), glob(os.path.join('launch', '*launch.[pxy][yma]*')))
]
)
C++包:将以下代码添加到 CMakeLists.txt
中,就在 ament_package()
之前:
install(DIRECTORY
launch
DESTINATION share/${PROJECT_NAME}/
)
2 父级启动文件
让我们创建一个启动文件,它将调用另一个启动文件并传递参数。这个启动文件可以是 Python 格式的,也可以是 YAML 格式的。
为此,在 launch_tutorial
包的 launch
文件夹中创建以下文件。
Python:将完整代码复制并粘贴到 launch/example_main_launch.py
文件中:
# 导入FindPackageShare类,用于查找ROS包的路径
from launch_ros.substitutions import FindPackageShare
# 导入LaunchDescription类,用于描述要启动的节点
from launch import LaunchDescription
# 导入IncludeLaunchDescription类,用于包含其他的启动描述
from launch.actions import IncludeLaunchDescription
# 导入PythonLaunchDescriptionSource类,用于指定Python文件作为启动源
from launch.launch_description_sources import PythonLaunchDescriptionSource
# 导入PathJoinSubstitution和TextSubstitution类,用于路径和文本的替换
from launch.substitutions import PathJoinSubstitution, TextSubstitution
# 定义generate_launch_description函数,用于生成启动描述
def generate_launch_description():
# 定义一个字典,存储颜色配置
colors = {
'background_r': '200' # 背景颜色红色分量的值
}
# 返回一个启动描述对象
return LaunchDescription([
# 包含另一个启动描述
IncludeLaunchDescription(
# 指定Python文件作为启动源
PythonLaunchDescriptionSource([
# 使用路径拼接替换,找到'launch_tutorial'包的路径,再拼接后续的路径
PathJoinSubstitution([
FindPackageShare('launch_tutorial'), # 查找'launch_tutorial'包的路径
'launch', # launch文件夹
'example_substitutions_launch.py' # 启动文件名
])
]),
# 设置启动参数
laun