背景
在上一篇文档中,介绍了如何编写独立的launch文件。本节将介绍如何将launch文件添加到现有包中,以及通常使用的设定。
任务
1 创建包
为包创建一个工作空间:
mkdir -p launch_ws/src
cd launch_ws/src
ros2 pkg create --build-type ament_cmake --license Apache-2.0 cpp_launch_example
2 创建launch文件的结构
通常一个包的所有启动文件都存储在包内的启动目录中。确保在上面创建的包的顶层创建一个launch目录。
对于c++包,我们通过添加以下内容来调整CMakeLists.txt文件(到文件的末尾,但在ament_package()之前):
# Install launch files.
install(DIRECTORY
launch
DESTINATION share/${PROJECT_NAME}/
)
3 编写launch文件
3.1 python launch文件
在launch目录中,创建一个名为my_script_launch.py的新启动文件。建议使用_launch.py作为Python launch文件的文件后缀,以便ros2 launch命令能够识别并自动完成导入。
import launch
import launch_ros.actions
def generate_launch_description():
return launch.LaunchDescription([
launch_ros.actions.Node(
package='demo_nodes_cpp',
executable='talker',
name='talker'),
])
3.2 xml launch 文件
在launch目录中,创建一个名为my_script_launch.xml的新launch文件,建议使用_launch.xml作为XML launch文件的后缀。
<launch>
<node pkg="demo_nodes_cpp" exec="talker" name="talker"/>
</launch>
3.3 yaml launch文件
在launch目录中,创建一个名为my_script_launch.yaml的新launch文件,建议使用yaml作为yaml launch文件的文件后缀。
launch:
- node:
pkg: "demo_nodes_cpp"
exec: "talker"
name: "talker"
4 编译并运行launch文件
转到工作区的顶层,并编译:
colcon build
在colcon编译成功之后,source一下工作区,运行launch文件:
ros2 launch cpp_launch_example my_script_launch.py (python格式)
ros2 launch cpp_launch_example my_script_launch.xml (xml格式)
ros2 launch cpp_launch_example my_script_launch.yaml (yaml格式)
参考资料:
https://github.com/ros2/launch/blob/humble/launch/doc/source/architecture.rst