先来说下ros的回调-callback
ROS 共有四种类型的回调,分别绑在不同的对象上:
订阅回调:ros::subscriber
请求回调:ros::servivceserver
行动回调:ros::simpleactionserver
定时器回调:ros::Timer
而callback 一般是在ros框架下,我们来写的,为了实现自己的某种功能的实现。
OS回调机制
ROS默认有维护一个全局回调队列(名为:Global Callback Queue),将已可用的回调插入Callback队列中。再通过Spinner线程获取并执行当前可用的回调。为了说明ROS回调机制,我引入两个ROS节点:一个使用定时器发布多个topic消息;另一个订阅这些topic消息。
发布节点
一个使用ROS定时器超时回调发布多个topic消息。
ros::Timer
来看一个ros::Timer的回调队列,代码如下:
//这段代码主要是实现定时向Topic发布消息
#include "ros/ros.h"
#include <boost/thread.hpp>
#include "my_msg/weather_pub.h"
#include "my_msg/air_quality_pub.h"
#include <sstream>
int main(int argc, char **argv){
ros::init(argc, argv, "multi_publisher");
ros::NodeHandle n;
/*通知ROS master,本node要发布一个名为“Weather”的话题(topic),
消息类型为my_msg::weather_pub,发送队列长度为48*/
ros::Publisher pub_weather =
n.advertise<my_msg::weather_pub>("Weather", 48, true);
/*通知ROS master,本node要发布一个名为“WeatherA”的话题(topic),
消息类型为my_msg::weather_pub,发送队列长度为48*/
ros::Publisher pub_weather_a =
n.advertise<my_msg::weather_pub>("WeatherA", 48, true);
/*通知ROS master,本node要发布一个名为“AirQuality”的话题(topic),
消息类型为my_msg::air_quality_pub,发送队列长度为48*/
ros::Publisher pub_air_quality =
n.advertise<my_msg::air_quality_pub>("AirQuality", 48, true);
int count = 0;
//创建一个ros::Timer每0.2秒进行发布,回调函数采用lamda4方法的格式
ros::Timer timer = n.createTimer(ros::Duration(0.2),
[&](const ros::TimerEvent&) {
my_msg::weather_pub msg;
std::stringstream ss;
ss << "Sunny " << count;
msg.weather= ss.str();
ROS_INFO_STREAM("Thread["<< boost::this_thread::get_id()
<<"],weather:"<< msg.weather.c_str());
pub_weather.publish(msg);
std::stringstream ssa;
ssa << "Sunny " << 20+count;
msg.weather= ssa.str();
ROS_INFO_STREAM("Thread["<< boost::this_thread::get_id()
<<"],weather:"<< msg.weather.c_str());
pub_weather_a.publish(msg);
my_msg::air_quality_pub msg_air;
msg_air.air_quality_index = 128+count;
ROS_INFO_STREAM("Thread["<< boost::this_thread::get_id()
<<"],air quality:"<< msg_air.air_quality_index);

最低0.47元/天 解锁文章
1490

被折叠的 条评论
为什么被折叠?



