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

Same Callback with Multiple Topics

asked 2015-04-03 11:19:16 -0500

Jordan9 gravatar image

I'm working with a package that publishes the same message type on multiple different topics, one topic for each of a set of objects it relates to. e.g. say we have 5 cars, car1 through car5, this package will publish a "velocity" custom msg on the topic /cars/CARNAME. So, I will have "velocity" msgs on /cars/car1, /cars/car2, etc. topics.

In the package I am building to subscribe to these messages (in C++), I would like to use the same callback function for each of the above topics (one topic for each car). However, since the message that is sent on each topic only contains a velocity and no information about which car it's for, then when the callback runs with a received message I have no idea what car that message is for.

My question is, is there some way with the NodeHandle.subscribe() function to pass a static argument to the callback every time it is called? Something like:

nh.subscribe("cars/car1", 1000, getVelocityCallback, "car1")
nh.subscribe("cars/car2", 1000, getVelocityCallback, "car2")
nh.subscribe("cars/car3", 1000, getVelocityCallback, "car3")

where the last argument is a string that would be available in the callback function, like so:

void getVelocityCallback(const carspack::Velocity::ConstPtr& msg, std::string carname)
{
   // process this message, knowing that it relates to "carname"
}

Thanks!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2015-04-03 12:51:38 -0500

ahendrix gravatar image

use boost::bind.

If I remember correctly, the syntax should be something like:

nh.subscribe("cars/car1", 10, boost::bind(getVelocityCallback, _1, "car1"));
edit flag offensive delete link more

Comments

Awesome, thanks! I ended up following a different strategy (using class methods), but this is a good answer.

Jordan9 gravatar image Jordan9  ( 2015-04-06 10:14:13 -0500 )edit

@ahendrix How can I do the same thing if the callback is a class method? I tried this but it did not work. A1_subscriber = it_->subscribe("image_color", 1, boost::bind(&nodelet_class::ReceiveA1, this, "A1", _1));

surabhi96 gravatar image surabhi96  ( 2018-09-28 04:46:25 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2015-04-03 11:19:16 -0500

Seen: 2,683 times

Last updated: Apr 03 '15