0
$\begingroup$

Rosanswers logo

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!


Originally posted by Jordan9 on ROS Answers with karma: 113 on 2015-04-03

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

use boost::bind.

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

nh.subscribe("cars/car1", 10, boost::bind(getVelocityCallback, _1, "car1"));

Originally posted by ahendrix with karma: 47576 on 2015-04-03

This answer was ACCEPTED on the original site

Post score: 3


Original comments

Comment by Jordan9 on 2015-04-06:
Awesome, thanks! I ended up following a different strategy (using class methods), but this is a good answer.

Comment by surabhi96 on 2018-09-28:
@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));

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.