ROS 2: How to quit a node from within a callback?
I have a node with a callback. Now I want this callback to be able to shut down my node. I could do this in ROS 1 simply by calling rospy.signal_shutdown(). In ROS 2, I tried calling rclpy.shutdown(), but this just hangs the node. Any thoughts?
Below is a modification of the publisher tutorial where I inserted a call to shutdown in the callback that just causes it to hang. How can the callback cause the node to quit properly?
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
timer_period = 0.5 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = 'Hello World: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
if self.i==10: # I could put other non hard-coded tests here
msg.data = 'Done'
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
rclpy.shutdown() # <-- Here is where I want to the node to quit
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()