之前4.3节例子中,需要分别启动turtle_control、patrol_client、turtlesim_node三个节点,每个节点都需要单独的终端和命令。比较麻烦,ros2 提供了简化启动过程的方法。
4.6.1 使用launch启动多个节点
ros2 支持使用python、xml、YAML 三种格式编写launch脚本。小鱼老师推荐python.
在src/demo_cpp_service下新建文件夹launch,新建文件demo.launch.py,代码如下
import launch
import launch_ros
def generate_launch_description():
action_node_turtle_control = launch_ros.actions.Node(
package='demo_cpp_service',
executable="turtle_control",
output='screen',
)
action_node_patrol_client = launch_ros.actions.Node(
package='demo_cpp_service',
executable="patrol_client",
output='log',
)
action_node_turtlesim_node = launch_ros.actions.Node(
package='turtlesim',
executable='turtlesim_node',
output='both',
)
# 合成启动描述并返回
return launch.LaunchDescription([
action_node_turtlesim_node,
action_node_patrol_client,
action_node_turtle_control,
])
导入依赖库launch、launch_ros。函数generate_launch_description中创建3个launch_ros.actions.Node对象,里面指定package功能包、executable可执行文件、output 指定日志输出位置。最后将三个节点合成数组,调用launch.LaunchDescription启动描述并返回。
修改 编译文件CMakeLists.txt增加install,用于吧launch目录复制到install对于功能包share目录下
cmake_minimum_required(VERSION 3.8)
project(demo_cpp_service)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
find_package(chapt4_interfaces REQUIRED)
find_package(rclcpp REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(turtlesim REQUIRED)
add_executable(turtle_control src/turtle_control.cpp)
ament_target_dependencies(turtle_control rclcpp geometry_msgs turtlesim chapt4_interfaces)
add_executable(patrol_client src/patrol_client.cpp)
ament_target_dependencies(patrol_client rclcpp chapt4_interfaces)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added