什么是插件
一个插件本质上就是一个类对象;
ROS中plugin插件实际上是将C++类通过pluginlib进行封装,编译为动态库(.so文件),使用的时候,再通过pluginlib提供的加载接口在主程序中进行运行时的加载这个插件对象。
也就是插件被包装在库中。
所以说ros中创建插件本质上就是创建动态库。
插件的实现
1,创建插件功能包
ros2 pkg create --build-type ament_cmake 功能包名 --dependencies pluginlib --library-name 插件库的名称
这种方式创建插件功能包,CMakeLists.txt会自动生成用于生成插件库的cmake指令,不需要自己再去添加cmake或者ament_cmake指令。
2,创建接口基类
基类的作用
1,作为生成插件的子类的基类;
2,注册插件的时候需要指定子类的基类;
3,实现插件类
创建功能包的时候指定了库,即插件的文件名,会创建和库同名的源文件和头文件。
在插件类中实现继承于接口基类的函数;
4,注册类为插件
在源文件中,使用PLUGINLIB_EXPORT_CLASS()宏将所有类注册为插件。
#include "test_plugin/test_lib.hpp"
namespace test_plugin
{
TestLib::TestLib()
{
}
TestLib::~TestLib()
{
}
void TestLib::start(){
std::cout<<"Motion start ..."<<std::endl;
}
void TestLib::stop(){
std::cout<<"Motion stop ..."<<std::endl;
}
} // namespace test_plugin
//在源文件最后添加
#include "pluginlib/class_list_macros.hpp"
PLUGINLIB_EXPORT_CLASS(test_plugin::TestLib,test_plugin::TestLibBase)
5,添加插件xml描述文件
在使用插件包中添加插件xml描述文件。
作用:
我们的插件文件最终需要生成库文件--插件库;
我们ros2 run运行节点使用插件的节点时,节点中的节点中的插件加载器会通过扫描这个文件来获取插件库的名称和库中的插件的信息,比如插件类型,基类的类型。
标签含义:
library:在ros2中直接指定为库的名称即可。
<library path="test_lib">
<class type="test_plugin::TestLib" base_class_type="test_plugin::TestLibBase">
<description>...</description>
</class>
</library>
到此为止,就可以通过colcon编译生成插件文件了。
使用插件文件
创建功能包:
ros2 pkg create --build-type ament_cmake 功能包名 --dependencies pluginlib --node-name 节点名
1,使用插件的基类文件实现源文件
#include <rclcpp/rclcpp.hpp>
#include <pluginlib/class_loader.hpp>
//加载基类头文件
#include "test_plugin/test_lib_base.hpp"
int main(int argc,char** argv){
rclcpp::init(argc,argv);
//创建插件加载器
pluginlib::ClassLoader<test_plugin::TestLibBase> controller_loader("test_plugin","test_plugin::TestLibBase");
//选择要加载的插件
std::string controoler_name="test_plugin::TestLib";
//加载插件--创建插件类对象
auto controller=controller_loader.createSharedInstance(controoler_name);
//使用插件类对象
controller->start();
// ......
controller->stop();
rclcpp::shutdown();
return 0;
}
加载器的构造参数:
1,基类所在的包;
2,基类所在的命名空间::基类的名称;
注意:
1,使用插件的节点引用的不是插件所在的头文件,而是基类的头文件;
2,插件加载器指定的模板参数是基类;
3,创建插件加载器之后才是选择创建插件对象;
2,修改cmake
添加:
pluginlib_export_plugin_description_file(polygon_base plugins.xml)