ROS两节点通信 可同时订阅与发布消息

在处理ROS节点通信时,节点a发布消息,节点b进行订阅。这时常常会有需要将节点b接收到的消息进行处理之后,重新发布,a进行订阅。

本人是新手,简单代码如下:

node_a:

#include 
#include "std_msgs/String.h"
#include 
#include 
 
void Callback(const std_msgs::String& sub_msg)
{
  
    ROS_INFO("I heard %s", sub_msg.data.c_str());

}
 
int main(int argc, char* argv[])
{
  ros::init(argc, argv, "node_a");
  ros::NodeHandle n;
  ros::Publisher pub = n.advertise("chatter_a", 100);
  ros::Subscriber sub = n.subscribe("chatter_b",100,Callback);
 
  ros::Rate loop_rate(1);
  while (n.ok()) {
    std_msgs::String pub_msg;
    std::stringstream ss;
    ss << "hello world" ;
    pub_msg.data = ss.str();
    ROS_INFO("%s", pub_msg.data.c_str());
    pub.publish(pub_msg);
    ros::spinOnce();
    loop_rate.sleep();
  }
}

node_b:

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

using namespace std;
      
class ListenerCall  
{           
public:  
  ListenerCall()
  {
  pub = nh.advertise("chatter_b", 100); 
  sub = nh.subscribe("chatter_a", 100, &ListenerCall::Callback, this);    
  }
  void Callback(const std_msgs::String& sub_msg)  
  {  
    std_msgs::String pub_msgs; 
    stringstream ss;
    ss << "I heard node_a ";
    pub_msgs.data = ss.str();
    pub_msgs.data += sub_msg.data;
    cout << pub_msgs.data << endl;
    //ROS_INFO("%s", pub_msgs);
    pub.publish(pub_msgs);   
  }  
private:
  ros::NodeHandle nh;  
  ros::Subscriber sub;  
  ros::Publisher pub; 
      
};  
      
      
int main(int argc, char *argv[])  
{  
  ros::init(argc, argv, "node_b");  
  ListenerCall lc;  
  ros::spin();  
          
  return 0;  
}
 

可以用RoboWare Studio,非常方便,CMakeLists.txt和package.xml就不贴了,望指教。

你可能感兴趣的:(实战所得,ROS,节点,通信)