ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How can I publish the subscribed and processed msgs in a single node?

asked 2014-05-06 23:07:38 -0500

shinnqy gravatar image

updated 2014-05-07 04:01:31 -0500

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2014-05-06 23:31:36 -0500

dornhege gravatar image

You should create all publishers and subscribers once at node startup. They need to build up a connection to other nodes, which just isn't there yet between two C++ lines.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2014-05-06 23:07:38 -0500

Seen: 275 times

Last updated: May 07 '14