Close a node from inside Node class
I want to shutdown a node inside the own node class in case a certain condition is fullfilled (like receive a message or a certain variable gets a certain value).
import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32MultiArray
class ProcessNode(Node):
def __init__(self, number_spot=0):
super().__init__('process_node')
self._cur_loc_subscriber = self.create_subscription(String, 'request_user_ip', self.listener_callback)
def listener_callback(self):
self.destroy_node()
rclpy.shutdown()
def main(args=None):
rclpy.init(args=args)
minimal_action_server = ProcessNode()
rclpy.spin(minimal_action_server)
minimal_action_server.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
If I run this code I get the error:
RuntimeError: Failed to shutdown: rcl_shutdown already called on the given context, at /tmp/binarydeb/ros-crystal-rcl-0.6.5/src/rcl/init.c:164
How can I close a node from inside the class while keeping rclpy.shutdown()
in the main in case I want to terminate from terminal?
Asked by hect1995 on 2019-07-31 04:03:29 UTC
Answers
Your callback should only look like this:
def listener_callback(self):
self.destroy_node()
I tested this with the examples_rclpy_minimal_publisher/publisher_member_function
.
Here for example you can call self.destroy_node()
in the timer callback after N messages have been published.
def timer_callback(self):
if self.i > 5:
self.destroy_node()
return
msg = String()
msg.data = 'Hello World: %d' % self.i
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
self.i += 1
You can check that the node has been killed through command line: ros2 node list
Note that the rclpy.spin(minimal_action_server)
will not terminate even if you kill the node
Asked by alsora on 2019-07-31 06:19:48 UTC
Comments