0

I'm using a ROS node (C++ code) to perform some image processing reading images from different visual sensors living in a simulator. I have a big problem that, so far, is without solution...

let's say that my node is active and is performing some operations on an image acquired from a topic"A"; at a certain point (so at run time) i need to unsubscribe from this topic"A" and subscribe from another topic"B" (the name of this topic"B" is communicated to the node by another subscriber) to read images from another visual sensor: i'd like to do that just changing the topic name (using a string variable for instance) and using the same callback used for topic"A".

the difficulties are the following:

  • i cannot read the all images and choose the one i need: the sensor are too many to handle such a stream of data and, furthermore, this system is not scalable at all.

  • i need to declare this new subscriber in a scope that "lives" sufficiently long for the process of reading from the topic (it is the reason, i think, the subscribers are defined in the main scope, before the while) but, in the same time, in a scope that gives me the possibility to update the topic (so a sort of loop and not in the part before the while that is performed just one time).

please help me...i really don't know how to do that

Matteo
  • 51
  • 1
  • 1
  • 5

2 Answers2

8

Assuming topic A and topic B have messages of the same type this can be done with just one subscriber variable. Simply change the message that the subscriber is subscribed to. From the ROS subscriber tutorial,

subscribe() returns a Subscriber object that you must hold on to until you want to unsubscribe. When all copies of the Subscriber object go out of scope, this callback will automatically be unsubscribed from this topic.

Subscribing to a new topic with the same subscriber variable will cause the old subscriber object to go out of scope and unsubscribe from the old topic. If you want to be explicit, you can call ros::Subscriber::shutdown() to unsubscribe from a topic.

Example:

ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("A", 1, callbackFunc);

// Do something
...

// shutdown the subscriber (this should be unnecessary)
sub.shutdown();


// Now change the subscriber
sub = nh.subscribe("B", 1, callbackFunc);
// You are no longer subscribed to topic A

If you want to be able to change this subscriber in a callback for another ROS message, then you will probably need to define the subscriber and node handler globally.

KLing
  • 195
  • 1
  • 10
2

I was facing a similar problem which was actually due to my lack of understanding of ROS.

ros::topic::waitForMessage() (eventually in a loop) was an interesting alternative.

R.Falque
  • 904
  • 8
  • 29