Ask Your Question
0

Same Callback with Multiple Topics

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

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 -0600

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 imageJordan9 ( 2015-04-06 10:14:13 -0600 )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 imagesurabhi96 ( 2018-09-28 04:46:25 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

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

Seen: 1,553 times

Last updated: Apr 03 '15