ROS系统通过类定义实现数据处理并重新发布在另一话题

 在实际应用中,经常需要在同一个节点内接受数据,在回调函数中将数据进行处理,再将新数据重新发布在另一个新话题上。

实现步骤:

1. 定义一个数据处理类SubscribeAndPublish,设置2个pub成员对象和1个sub成员对象为public。

 2. 在主函数中发布原始消息;

3. 将callback定义为成员函数,并使用新的pub将消息发布出去。

测试程序代码如下:

#include <ros/ros.h>  
#include"std_msgs/String.h"

    class SubscribeAndPublish  
    {  
    public:  
      SubscribeAndPublish()  
      {  
        //Topic you want to publish  
        pub_ = n_.advertise<std_msgs::String>("/published_topic", 1);  
        pub_callback = n_.advertise<std_msgs::String>("/callback_topic", 1);
        //Topic you want to subscribe  
        sub_ = n_.subscribe("/published_topic", 1, &SubscribeAndPublish::callback, this);  //注意这里,和平时使用回调函数不一样了。
      }  
      
      void callback(const std_msgs::String& input)  
      {  
        std_msgs::String output;  
        output.data = input.data;
        output.data.append(" treated!");
        //.... do something with the input and generate the output...  
        ROS_INFO("callbacked and  published on /callback_topic");
        pub_callback.publish(output);  
        // ROS_INFO("callback published");
      }  
      
    public:  
      ros::NodeHandle n_;   
      ros::Publisher pub_;  
      ros::Publisher pub_callback; 
      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;  
      std_msgs::String msg; 
      msg.data = "from main";
      ros::Rate loop_rate(1);
    while (ros::ok())
    {
      SAPObject.pub_.publish(msg);
      ROS_INFO("main published on /published_topic");
      ros::spinOnce();//处理订阅话题的所有回调函数callback(),
      loop_rate.sleep();
    }
      return 0;  
    }  

打印来原始话题的消息和新话题的消息:

rostopic echo /published_topic
rostopic echo /callback_topic

得到原始数据和处理过后的数据的结果。

         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值