Ask Your Question
0

Unsubsribe from a topic and define a new one runtime(C++)

asked 2013-06-11 06:00:41 -0500

mateo_7_7 gravatar image

updated 2014-01-28 17:16:50 -0500

ngrennan gravatar image

i'd like to change the name of the topic which I read data from during runtime. ..that seems not to be feasible. my idea now is the following: if a certain condition is satisfied I unsubscribe from a topic and define a new subscriber (with a new topic) that uses the same callback used by the old subscriber. Is this feasible? how can i unsubscribe from a topic?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2013-06-11 14:22:26 -0500

joq gravatar image

updated 2013-06-12 04:31:22 -0500

If you subscribe to a new topic using the same callback and store the result in the same Subscriber object, storing that new value in the original variable should unsubscribe the other topic.

EXAMPLE: untested, probably buggy

class Reader
{
public:
  Reader(ros::NodeHandle node)
  {
    node_ = node;
    // subscribe to original topic
    topic_ = node.subscribe("first_topic", 10,
                            &Reader::callback, (Reader *) this);
  }

private:
  void callback(const std_msgs::String::ConstPtr &msg)
  {
    if (msg->data == "switch")
      {
        // subscribe to other topic
        topic_ = node_.subscribe("next_topic", 10,
                                 &Reader::callback, (Reader *) this);
      }
    else
      {
        // log message from current topic
        ROS_INFO_STREAM(msg->data);
      }
  }

  // class variables
  ros::NodeHandle node_;
  ros::Subscriber topic_;           // current topic subscription
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "your_node");
  ros::NodeHandle node;
  Reader read(node);
  ros::spin();
  return 0;
}
edit flag offensive delete link more

Comments

so changing the topic name (changing the string) runtime should be sufficient to unsubscribe from a topic and start subscribing from another...but, as i understood, it's not allowed in ROS actually.

mateo_7_7 gravatar image mateo_7_7  ( 2013-06-11 22:22:18 -0500 )edit

Just make a new subscription in the same we you did the original one.

dornhege gravatar image dornhege  ( 2013-06-12 00:49:36 -0500 )edit

..can you post an example please?

mateo_7_7 gravatar image mateo_7_7  ( 2013-06-12 00:52:49 -0500 )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

Stats

Asked: 2013-06-11 06:00:41 -0500

Seen: 596 times

Last updated: Jun 12 '13