# Can 1 node subsrcibe MSG from a topic and publish MSG to other topic at the same time?

Hi all, I downloaded the face_recognition demo and pi_tracker demo, and I want to combine the two which means that I want the turtlebot recognized me at first and move as I wish. However, it means that I must publish MSG to contract with pi_tracker after being recognized, so in the face_rec_client.cpp, I added the code:

if(strcmp(feedback->names[0].c_str(),"David")==0)
{
ros::NodeHandle n1;
std_msgs::String msg;
std::stringstream ss;
ss << "You are Master!";'t
msg.data = ss.str();
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
}


which means that if the turtlebot recognized me(David), it should publish a msg on topic "chatter1" as well as ROS_INFO the msg. NOW, THE QUESTION IS: it does print "You are Master" on screen, but I can't get it on topic "chatter1". so I think maybe I didn't publish the msg in the right way. anybody could help me? Thanks?

edit retag close merge delete

Sort by » oldest newest most voted

My guess is that the problem is caused by chatter_pub going out of scope immediately after the publish call. You're creating chatter_pub fresh every time you use it in the body of the if statement, which is probably not a good idea. Move the declaration of chatter_pub out to a more global scope (outside of the if block) and see if this solves things. As it stands, I think that you're (automatically) destroying the publisher before it has a chance to do its work.

more

After a node advertises a topic, it sometimes takes a small amount of time for other subscribers to connect to the newly-advertised publisher. Any messages that are published before the subscribers are fully connected are "lost". See this thread for more discussion on this issue.

I recommend that you put the n1.advertise call somewhere near the start of your node. That way, subscribers are connected when the node first starts up. They should be connected by the time you need to actually publish your message. Alternatively, you can add a sleep/delay after the advertise call, to give subscribers a chance to connect before you publish your first message.

more