ros2版本自定义插件的实现与热插拔
文章目录
- 一、自定义插件抽象类
- 二、编写第一个插件
- 1. 插件定义
- 2. 插件实现
- 3. 插件描述文件
- 4. 编辑 CMakeList.txt
- 5. 编写自定义测试程序
- 三、不同插件间热插拔
在 创建基于Move_Base的自定义局部规划器框架 博客里 自己整理了 ROS1 版本的自定义局部规划器的框架,今天整理ROS2的自定义插件实现热插拔。
一、自定义插件抽象类
首先,确保已安装pluginlib插件库:
sudo apt install -y ros-$ROS_DISTRO-pluginlib
接着,创建测试工作空间、自定义插件功能包及自定义插件抽象类:
# 创建 plugins_test工作空间
mkdir -p plugins_test/src && cd plugins_test/src/# 创建 motion_control_plugins功能包
ros2 pkg create motion_control_plugins --dependencies pluginlib rclcpp --build-type ament_cmake --license Apache-2.0
在 plugins_test/src/motion_control_plugins/include/motion_control_plugins
路径下新建motion_control_interface.hpp
做为抽象类:
#ifndef MOTION_CONTROL_INTERFACE_HPP
#define MOTION_CONTROL_INTERFACE_HPPnamespace motion_control_plugins {class MotionController {
public:virtual void start() = 0;virtual void stop() = 0;virtual ~MotionController() {}
};} // namespace motion_control_plugins#endif // MOTION_CONTROL_INTERFACE_HPP
说明:
- virtual : 关键字用于声明虚函数;
- = 0:用于声明纯虚函数(包含至少一个纯虚函数的类被称为抽象类);
二、编写第一个插件
1. 插件定义
在plugins_test/src/motion_control_plugins/include/motion_control_plugins
路径下新建linear_motion_controller.hpp
表示线性运动的插件:
#ifndef LINEAR_MOTION_CONTROLLER_HPP
#define LINEAR_MOTION_CONTROLLER_HPP#include "motion_control_plugins/motion_control_interface.hpp"namespace motion_control_plugins
{class LinearMotionController : public MotionController{public:void start() override;void stop() override;};} // namespace motion_control_plugins#endif // LINEAR_MOTION_CONTROLLER_HPP
说明:
在 motion_control_plugins 命名空间下定义 类LinearMotionController ,继承抽象 类MotionController,声明 start() 、stop()成员方法,使用 override关键字表示派生类的成员函数覆盖基类的虚函数。
2. 插件实现
接着在plugins_test/src/motion_control_plugins/src/
路径下新建 linear_motion_controller.cpp
文件:
#include <iostream>
#include "motion_control_plugins/linear_motion_controller.hpp"
namespace motion_control_plugins
{void LinearMotionController::start(){// 实现线性运动控制逻辑std::cout << "LinearMotionController::start" << std::endl;<