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

Revision history [back]

click to hide/show revision 1
initial version

You're making the subscriber much more complicated than it needs to be.

  • ROS will handle subscribing to a new publisher automatically - no need to call subscribe on every iteration
  • ros::spin() doesn't return until your program is done - probably not what you want

The pseudocode for a watchdog should look more like:

class Watchdog {
  private:
    // timer or last update time member variables
  public:
    void callback(your_message & msg); // update/reset timer
    bool check(); // check timer for timeout
}

int main() {
   // ros node and nodehandle setup
   Watchdog watchdog;
   ros::Subscriber sub = nh.subscribe("topic", 10, &watchdog, &Watchdog::callback);

   ros::Rate rate(100);

   while(ros::ok()) {
      if(!watchdog.check()) {
        // scream loudly and/or throw things
      }
      // check subscriber for correct number of publishers
      ros::spinOnce();
   }

   return 0;
}

Most of the implementation details are left to the reader.

Note that there are two different checks being done here:

  • Check that a message was received recently (the publisher is still publishing)
  • Check that there are still publishers connected

Note also that you could move the ros::Subscriber object to be a member of the Watchdog class, and do the subscriber setup in the Watchdog constructor.