Launch 系统
目标: 向 ROS 2 包中添加 launch 文件
教程级别: 中级
时间: 10 分钟
你应该已经学习了如何创建 ROS 2 包的教程。
一如既往,不要忘记在你打开的每个新终端中 source ROS 2。
在上一篇教程中,我们学习了如何编写独立的 launch 文件。本教程将展示如何将 launch 文件添加到现有的包中,并介绍一些常用的约定。
为包创建一个工作空间:
Linux / macOS:
mkdir -p launch_ws/srccd launch_ws/srcWindows:
md launch_ws\srccd launch_ws\srcPython 包:
ros2 pkg create --build-type ament_python --license Apache-2.0 py_launch_exampleC++ 包:
ros2 pkg create --build-type ament_cmake --license Apache-2.0 cpp_launch_example2 创建存放 launch 文件的目录结构
Section titled “2 创建存放 launch 文件的目录结构”按照约定,一个包的所有 launch 文件都存放在该包根目录下的 launch 目录中。请确保在前面创建的包的顶层目录中创建一个 launch 文件夹。
Python 包:
对于 Python 包,包含你的包的目录结构应如下所示:
src/ py_launch_example/ launch/ package.xml py_launch_example/ resource/ setup.cfg setup.py test/为了让 colcon 能够找到并使用这些 launch 文件,我们需要通过 Python 的 setup 工具告知它们的存在。具体做法是:打开 setup.py,在顶部添加必要的 import 语句,然后将 launch 文件添加到 setup 的 data_files 参数中:
import osfrom glob import glob# Other imports ...
package_name = 'py_launch_example'
setup( # Other parameters ... data_files=[ # ... Other data files # Include all launch files. (os.path.join('share', package_name, 'launch'), glob('launch/*')) ])C++ 包:
对于 C++ 包,我们只需在 CMakeLists.txt 文件末尾(但在 ament_package() 之前)添加以下内容:
# Install launch files.install(DIRECTORY launch DESTINATION share/${PROJECT_NAME}/)3 编写 launch 文件
Section titled “3 编写 launch 文件”XML launch 文件:
在 launch 目录中创建一个名为 my_script_launch.xml 的新 launch 文件。建议以 _launch.xml 作为 XML launch 文件的后缀(非强制要求)。
<?xml version="1.0" encoding="UTF-8"?><launch> <node pkg="demo_nodes_cpp" exec="talker" name="talker"/></launch>YAML launch 文件:
在 launch 目录中创建一个名为 my_script_launch.yaml 的新 launch 文件。建议以 _launch.yaml 作为 YAML launch 文件的后缀(非强制要求)。
%YAML 1.2---launch: - node: pkg: "demo_nodes_cpp" exec: "talker" name: "talker"Python launch 文件:
在你的 launch 目录中创建一个名为 my_script_launch.py 的新 launch 文件。建议以 _launch.py 作为 Python launch 文件的后缀(非强制要求)。但需要注意的是,launch 文件名必须以 launch.py 结尾,才能被 ros2 launch 正确识别和自动补全。
你的 launch 文件应定义 generate_launch_description() 函数,该函数返回一个供 ros2 launch 命令使用的 launch.LaunchDescription()。
import launchimport launch_ros.actions
def generate_launch_description(): return launch.LaunchDescription([ launch_ros.actions.Node( package='demo_nodes_cpp', executable='talker', name='talker'), ])4 构建并运行 launch 文件
Section titled “4 构建并运行 launch 文件”返回到工作空间的根目录,然后执行构建:
colcon build在 colcon build 成功完成并 source 了工作空间之后,你就可以用以下命令运行 launch 文件了:
Python 包:
ros2 launch py_launch_example my_script_launch.xmlros2 launch py_launch_example my_script_launch.yamlros2 launch py_launch_example my_script_launch.pyC++ 包:
ros2 launch cpp_launch_example my_script_launch.xmlros2 launch cpp_launch_example my_script_launch.yamlros2 launch cpp_launch_example my_script_launch.pylaunch 文档提供了关于 launch_ros 中同样用到的概念的更多细节。
关于 launch 功能的更多文档和示例即将推出。在此之前,请查阅源代码:https://github.com/ros2/launch 和 https://github.com/ros2/launch_ros。