目录
1.编写ROS2的launch文件
- 节点之间一般会存在相互依赖关系
- 一次启动多个节点会比较麻烦
launch文件就诞生了。它允许我们可以同时和配置多个包含ROS2节点的可执行文件,在ROS2中可以使用python来写launch文件。
编写launch文件可以有三种方式,python、yaml、xml这三种方式,但是官方推荐的是使用python格式,因为python是一种编程语言,可以使用python的一些库来进行一些工作
一般的命名方式是xxx.launch.py
1.创建launch文件
在工作区下面建立launch目录(与src并列),并创建xxx.launch.py文件
mkdir launch
cd launch
touch xxx.launch.py
2.编写launch文件
首先在文件开头import两个模块
from launch import LaunchDescription
from launch_ros.actions import Node
然后编写启动描述。launch文件其实就是需要将所有描述放到启动描述(generate_launch_description)中,这个名字必须是这个。ROS2会对其进行识别
def generate_launch_description():
Node_1 = Node(
package='package-name', #节点所在的功能包
namespace='package-namespace', #命名空间。如果存在同名节点,这一选项会有用.使节点名称前增加命名空间前缀,命名空间不同使系统允许两个相同节点名和主题名不冲突。如果没有唯一的命名空间,当topic消息相同时就无法区分是哪个节点的。
executable='execute-name/script-name.py', #表示要运行的可执行文件名或脚本名字.py
parameters=[{'parameter-name': parameter-value}], #参数
arguments=['-xxx', xxx, '-xxx', xxx ], #启动参数
output='screen', #用于将话题信息打印到屏幕
name='node-name' #表示启动后的节点名,可以没有
remappings=[ #重映射,将默认节点属性(如节点名称、主题名称、服务名称等),重映射为其它名称。
('/xxx/xxx-new', '/xxx/xxx-old'),
]
),
Node_2 = Node(
package="Name_2",
executable='',
name=''
)
return LaunchDescription([
Node_1,
Node_2
])
连接路径
使用join
import os
...
#文件
file-name = 'example-file.xxx'
#字符串前加`f`表示可以在字符串里面使用用花括号括起来的变量和表达式,如定义好的`file-name`
file-path = os.path.join(package-path, f'example-folder/{file-name}')
#或者使用逗号隔开
file-path = os.path.join(package-path, 'example-folder', file-name)
#路径
dir-path = os.path.join(package-path, 'example-folder/')
launch文件嵌套
假设已经存在很多的单独的launch文件用于启动不同的功能,如果需要同时启动这些launch文件,可以使用IncludeLaunchDescription
在launch文件中嵌套启动launch文件,这样可以提高复用率。
需要添加以下两个头文件
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
使用IncludeLaunchDescription
嵌套launch文件,其中同样可以使用上文所述的传递参数。
将以下代码放入到generate_launch_description
函数当中,并在return
的时候填入下文件中的another-launch
another-launch = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
os.path.join(launch_file_dir, 'launch-file-name.launch.py')
),
launch_arguments={'arg-name': example-arg}.items()
)
3.运行launch文件
3.1使用python启动launch
在setup.py中编写以下内容
from setuptools import setup
from glob import glob
import os
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
],
},
)
3.2使用C++启动launch
在CmakeList.txt
中添加一句
install(DIRECTORY
launch
DESTINATION share/${PROJECT_NAME}
)
4.启动launch文件
ros2 launch file_name file_name.launch.py