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

Automatic node shutdown if topic is no longer receiving messages

asked 2022-01-03 15:17:45 -0600

ashwath1993 gravatar image

Hi,

I have a node that receives camera messages. I want the node to shutdown when the rosbag is done playing. I know I can do this with roslaunch. But I wanted to know if I could do this with code.

I noticed that my code works for some recordings and fails for others.

void callback(const sensor_msgs::ImageConstPtr& msg)
{
if(sub.getNumPublishers() == 0)
{
 // run main algo and write results
 ros::shutdown();
}
else
{
   // process message
}

}

Is there a way to shutdown the node outside the callback? My subscriber is part of a class and the subscriber is initialized with the constructor.

MyClass(ros::NodeHandle& n)
{
  sub = n.subscribe<sensor_msgs::Image>("/camera/image_color", 100, &MyClass::callback, this);
}

My node is defined as follows

int main(int argc, char * argv[])
{
ros::init(argc, argv, "calib_node");

ros::NodeHandle n;
MyClass obj(n);
ros::spin();

return 0;
}
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-04 14:06:06 -0600

Mike Scheutzow gravatar image

In your main(), you can replace the ros::spin() with a while loop that does whatever you want it to. In this example, check_for_done() is a function that you provide. If you use this approach, be sure you sleep() on every iteration of the while loop.

ros::Duration d(0.100);
while(ros::ok) {
    if (check_for_done()) {
        ros::shutdown();
    }
    d.sleep();
}
edit flag offensive delete link more

Comments

This was sufficient for what I wanted to achieve. Thanks!

ashwath1993 gravatar image ashwath1993  ( 2022-02-06 09:10:36 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2022-01-03 15:17:45 -0600

Seen: 325 times

Last updated: Jan 04 '22