How can I publish the subscribed and processed msgs in a single node?
Hi guys, I'm quite new to ROS and I also just start learning C++ in ROS.
I have followed the tutorial ROS/Tutorials/WritingPublisherSubscriber(c++) and already known how to write a publisher and a subscriber separately.
But I wonder can I put a publisher and subscriber in the same node. I searched and found this answer how to put subscriber and publisher in one cpp file ?. Yes, it does put them together, but they just work separately.
What I want to do is Node A published "hello world" to Node B, and Node B can process the messages and then publish the edited resultes to Node C.
I tried a simple node and this is my code based on the sample codes.
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
if("%s" == "hello world ", msg->data.c_str())
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter2", 1000);
std_msgs::String msg;
std::stringstream ss;
ss << "long time no see";
msg.data = ss.str();
chatter_pub.publish(msg);
ros::spinOnce();
}
else
{
ROS_INFO("I didn't hear: [%s]", msg->data.c_str());
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "trans");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter1", 1000, chatterCallback);
ros::spin();
return 0;
}
But only the communication between talker and trans works, there is no message on topic chatter2.
Can anyone help me find where is wrong or give me a sample code to study?