Ask Your Question
0

Close a node from inside Node class

asked 2019-07-31 04:03:29 -0500

hect1995 gravatar image

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-07-31 06:19:48 -0500

alsora gravatar image

updated 2019-07-31 06:22:15 -0500

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

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2019-07-31 04:03:29 -0500

Seen: 42 times

Last updated: Jul 31