ROS 环境下 单一节点内包含订阅者与发布者 订阅者回调函数含有多形参
参考链接
同一节点内包含订阅者与发布者
多形参回调函数
两者结合
注意点
- 采用boost::bind对回调函数进行绑定时,请注意在创建订阅者时候指定订阅节点的消息类型:
#include "ros/ros.h"
#include <std_msgs/String.h>
#include <boost/bind.hpp>
void Callback(const std_msgs::String::ConstPtr & msg, int* k)
{
//doing stuff
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mapper");
ros::NodeHandle n;
int test;
ros::Subscriber sub=n.subscribe<std_msgs::String>("xxxx",10, boost::bind(&Callback, _1, &test));
while (ros::ok())
{
ros::spinOnce();
sleep(2);
}
return 0;
}
即该行代码
ros::Subscriber sub=n.subscribe<std_msgs::String>("xxxx",10, boost::bind(&Callback, _1, &test));
简单的订阅者是没有<>内的内容的。
另外回调函数中消息需要采用const xxx_msgs::xxxxx::ConstPtr &msg
的形式。
最后如果回调函数中多余的形参如果是引用,请在boost::bind中对该参数采用boost::ref(arg_name)
的方式传入参数。
2. 参考链接1中将发布者与订阅者同时塞进一个类中的做法优雅值得学习
下面直接贴出源码
#include <ros/ros.h>
class SubscribeAndPublish
{
public:
SubscribeAndPublish()
{
//Topic you want to publish
pub_ = n_.advertise<PUBLISHED_MESSAGE_TYPE>("/published_topic", 1);
//Topic you want to subscribe
sub_ = n_.subscribe("/subscribed_topic", 1, &SubscribeAndPublish::callback, this);
}
void callback(const SUBSCRIBED_MESSAGE_TYPE& input)
{
PUBLISHED_MESSAGE_TYPE output;
//.... do something with the input and generate the output...
pub_.publish(output);
}
private:
ros::NodeHandle n_;
ros::Publisher pub_;
ros::Subscriber sub_;
}//End of class SubscribeAndPublish
int main(int argc, char **argv)
{
//Initiate ROS
ros::init(argc, argv, "subscribe_and_publish");
//Create an object of class SubscribeAndPublish that will take care of everything
SubscribeAndPublish SAPObject;
ros::spin();
return 0;
}