将启动文件集成到ROS 2包中 [5439]
**目标:**将一个启动文件添加到ROS 2包中 [5440]
教程级别: 中级 [16770]
时间: 10分钟 [16421]
内容 [16422]
先决条件 [16411]
您应该已经完成了教程,学习如何 创建一个ROS 2包。 [5441]
如往常一样,在每次打开新的终端时不要忘记在 :doc`每个新终端中启用ROS 2环境 <../../Beginner-CLI-Tools/Configuring-ROS2-Environment>`。 [5392]
任务 [16427]
1 创建一个包 [3283]
为包创建一个工作空间: [5443]
mkdir -p launch_ws/src
cd launch_ws/src
mkdir -p launch_ws/src
cd launch_ws/src
md launch_ws\src
cd launch_ws\src
ros2 pkg create py_launch_example --build-type ament_python
ros2 pkg create cpp_launch_example --build-type ament_cmake
2 创建用于存放启动文件的结构 [5446]
按照惯例,包中的所有启动文件都存储在包内的“launch”目录中。请确保在上面创建的包的顶级目录下创建一个“launch”目录。 [5447]
对于 Python 包,包含包的目录应该像这样: [5448]
src/
py_launch_example/
launch/
package.xml
py_launch_example/
resource/
setup.cfg
setup.py
test/
为了让colcon能够找到启动文件,我们需要使用``setup``的``data_files``参数,向Python的设置工具提供我们的启动文件信息。 [5449]
在我们的``setup.py``文件中: [5450]
import os
from glob import glob
from setuptools import setup
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(os.path.join('launch', '*launch.[pxy][yma]*')))
]
)
3 编写启动文件 [5453]
在你的``launch``目录中,创建一个名为``my_script_launch.py``的新启动文件。推荐使用``_launch.py``作为Python启动文件的文件后缀,但不是必需的。但是,启动文件的名称必须以``launch.py``结尾,以便被``ros2 launch``识别并自动完成。 [5455]
你的启动文件应该定义``generate_launch_description()``函数,该函数返回一个``launch.LaunchDescription()``对象,供``ros2 launch``命令使用。 [5456]
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'),
])
在你的``launch``目录中,创建一个名为``my_script_launch.xml``的新启动文件。推荐使用``_launch.xml``作为XML启动文件的文件后缀,但不是必需的。 [5458]
<launch>
<node pkg="demo_nodes_cpp" exec="talker" name="talker"/>
</launch>
在你的``launch``目录中,创建一个名为``my_script_launch.yaml``的新启动文件。推荐使用``_launch.yaml``作为YAML启动文件的文件后缀,但不是必需的。 [5460]
launch:
- node:
pkg: "demo_nodes_cpp"
exec: "talker"
name: "talker"
4 构建和运行启动文件 [5461]
进入工作空间的顶层,并进行构建: [5462]
colcon build
在 colcon build
成功并且你已经载入了工作空间之后,你应该能够按照以下方式运行启动文件: [5463]
ros2 launch py_launch_example my_script_launch.py
ros2 launch py_launch_example my_script_launch.xml
ros2 launch py_launch_example my_script_launch.yaml
ros2 launch cpp_launch_example my_script_launch.py
ros2 launch cpp_launch_example my_script_launch.xml
ros2 launch cpp_launch_example my_script_launch.yaml
文档 [5464]
启动文档 提供了关于 launch_ros
中也使用的概念的更多细节。 [5465]
其他启动功能的文档/示例即将推出。在此期间,请参考源代码 (https://github.com/ros2/launch 和 https://github.com/ros2/launch_ros)。 [5466]