Python rclpy.shutdown() Examples

The following are 30 code examples of rclpy.shutdown(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rclpy , or try the search function .
Example #1
Source File: echo_server.py    From ros2cli with Apache License 2.0 8 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = EchoServer()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('server stopped cleanly')
    except BaseException:
        print('exception in server:', file=sys.stderr)
        raise
    finally:
        # Destroy the node explicitly
        # (optional - Done automatically when node is garbage collected)
        node.destroy_node()
        rclpy.shutdown() 
Example #2
Source File: publisher_old_school.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = rclpy.create_node('minimal_publisher')

    publisher = node.create_publisher(String, 'topic', 10)

    msg = String()

    i = 0
    while rclpy.ok():
        msg.data = 'Hello World: %d' % i
        i += 1
        node.get_logger().info('Publishing: "%s"' % msg.data)
        publisher.publish(msg)
        sleep(0.5)  # seconds

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    node.destroy_node()
    rclpy.shutdown() 
Example #3
Source File: bw.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def _rostopic_bw(node, topic, window_size=DEFAULT_WINDOW_SIZE):
    """Periodically print the received bandwidth of a topic to console until shutdown."""
    # pause bw until topic is published
    msg_class = get_msg_class(node, topic, blocking=True, include_hidden_topics=True)
    if msg_class is None:
        node.destroy_node()
        return

    rt = ROSTopicBandwidth(node, window_size)
    node.create_subscription(
        msg_class,
        topic,
        rt.callback,
        qos_profile_sensor_data,
        raw=True
    )

    print(f'Subscribed to [{topic}]')
    timer = node.create_timer(1, rt.print_bw)
    while rclpy.ok():
        rclpy.spin_once(node)

    node.destroy_timer(timer)
    node.destroy_node()
    rclpy.shutdown() 
Example #4
Source File: repeater_node.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    parsed_args = parse_arguments(args=args)

    rclpy.init(args=args)

    node = RepeaterNode(message_type=parsed_args.message_type)

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('repeater stopped cleanly')
    except BaseException:
        print('exception in repeater:', file=sys.stderr)
        raise
    finally:
        node.destroy_node()
        rclpy.shutdown() 
Example #5
Source File: test_daemon.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def daemon_node():
    if is_daemon_running(args=[]):
        with DaemonNode(args=[]) as node:
            node.system.shutdown()
    assert spawn_daemon(args=[], wait_until_spawned=5.0)
    with DaemonNode(args=[]) as node:
        attempts = 3
        delay_between_attempts = 2  # seconds
        for _ in range(attempts):
            node_names_and_namespaces = node.get_node_names_and_namespaces()
            if [TEST_NODE_NAME, TEST_NODE_NAMESPACE] in node_names_and_namespaces:
                break
            time.sleep(delay_between_attempts)
        else:
            pytest.fail(
                f'daemon failed to discover {TEST_NODE_NAMESPACE}/{TEST_NODE_NAME}'
            )
        yield node
        node.system.shutdown() 
Example #6
Source File: callback_group.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)
    try:
        talker = DoubleTalker()
        listener = Listener()
        # MultiThreadedExecutor executes callbacks with a thread pool. If num_threads is not
        # specified then num_threads will be multiprocessing.cpu_count() if it is implemented.
        # Otherwise it will use a single thread. This executor will allow callbacks to happen in
        # parallel, however the MutuallyExclusiveCallbackGroup in DoubleTalker will only allow its
        # callbacks to be executed one at a time. The callbacks in Listener are free to execute in
        # parallel to the ones in DoubleTalker however.
        executor = MultiThreadedExecutor(num_threads=4)
        executor.add_node(talker)
        executor.add_node(listener)

        try:
            executor.spin()
        finally:
            executor.shutdown()
            listener.destroy_node()
            talker.destroy_node()
    finally:
        rclpy.shutdown() 
Example #7
Source File: interface.py    From HRIM with Apache License 2.0 6 votes vote down vote up
def closeEvent(self, event=None):
        try:

            # Signal worker threads should stop
            self.keepThreads = False

            # Give time to threads to stop
            time.sleep(0.1)

            if os.path.exists(os.path.join(os.getcwd(),"tmp")):
                shutil.rmtree(os.path.join(os.getcwd(),"tmp"))

            # ROS2 cleanup
            self.executor.shutdown()
            self.node.destroy_node()
            rclpy.shutdown(context=self.context)

            sys.exit(0)
        except:
            raise

    #########################################################
    # UI interaction handlers                               #
    ######################################################### 
Example #8
Source File: subscriber_lambda.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = rclpy.create_node('minimal_subscriber')

    subscription = node.create_subscription(
        String, 'topic', lambda msg: node.get_logger().info('I heard: "%s"' % msg.data), 10)
    subscription  # prevent unused variable warning

    rclpy.spin(node)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    node.destroy_node()
    rclpy.shutdown() 
Example #9
Source File: client_async_member_function.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    minimal_client = MinimalClientAsync()
    minimal_client.send_request()

    while rclpy.ok():
        rclpy.spin_once(minimal_client)
        if minimal_client.future.done():
            try:
                response = minimal_client.future.result()
            except Exception as e:
                minimal_client.get_logger().info(
                    'Service call failed %r' % (e,))
            else:
                minimal_client.get_logger().info(
                    'Result of add_two_ints: for %d + %d = %d' %
                    (minimal_client.req.a, minimal_client.req.b, response.sum))
            break

    minimal_client.destroy_node()
    rclpy.shutdown() 
Example #10
Source File: listener.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    """
    Run a Listener node standalone.

    This function is called directly when using an entrypoint. Entrypoints are configured in
    setup.py. This along with the script installation in setup.cfg allows a listener node to be run
    with the command `ros2 run examples_rclpy_executors listener`.

    :param args: Arguments passed in from the command line.
    """
    rclpy.init(args=args)
    try:
        listener = Listener()
        rclpy.spin(listener)
    finally:
        listener.destroy_node()
        rclpy.shutdown() 
Example #11
Source File: talker.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    """
    Run a Talker node standalone.

    This function is called directly when using an entrypoint. Entrypoints are configured in
    setup.py. This along with the script installation in setup.cfg allows a talker node to be run
    with the command `ros2 run examples_rclpy_executors talker`.

    :param args: Arguments passed in from the command line.
    """
    # Run standalone
    rclpy.init(args=args)
    try:
        talker = Talker()
        rclpy.spin(talker)
    finally:
        talker.destroy_node()
        rclpy.shutdown() 
Example #12
Source File: custom_executor.py    From examples with Apache License 2.0 6 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)
    try:
        listener = Listener()
        talker = Talker()
        estopper = Estopper()

        executor = PriorityExecutor()
        executor.add_high_priority_node(estopper)
        executor.add_node(listener)
        executor.add_node(talker)
        try:
            executor.spin()
        finally:
            executor.shutdown()
            estopper.destroy_node()
            talker.destroy_node()
            listener.destroy_node()
    finally:
        rclpy.shutdown() 
Example #13
Source File: test_node.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_create_raw_subscription(self):
        executor = SingleThreadedExecutor(context=self.context)
        executor.add_node(self.node)
        basic_types_pub = self.node.create_publisher(BasicTypes, 'raw_subscription_test', 1)
        self.raw_subscription_msg = None  # None=No result yet
        self.node.create_subscription(
            BasicTypes,
            'raw_subscription_test',
            self.raw_subscription_callback,
            1,
            raw=True
        )
        basic_types_msg = BasicTypes()
        cycle_count = 0
        while cycle_count < 5 and self.raw_subscription_msg is None:
            basic_types_pub.publish(basic_types_msg)
            cycle_count += 1
            executor.spin_once(timeout_sec=1)
        self.assertIsNotNone(self.raw_subscription_msg, 'raw subscribe timed out')
        self.assertIs(type(self.raw_subscription_msg), bytes, 'raw subscribe did not return bytes')
        # The length might be implementation dependant, but shouldn't be zero
        # There may be a canonical serialization in the future at which point this can be updated
        self.assertNotEqual(len(self.raw_subscription_msg), 0, 'raw subscribe invalid length')

        executor.shutdown() 
Example #14
Source File: test_node.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_use_global_arguments(self):
        context = rclpy.context.Context()
        rclpy.init(
            args=['process_name', '--ros-args', '-r', '__node:=global_node_name'],
            context=context
        )
        try:
            node1 = rclpy.create_node(
                'my_node', namespace='/my_ns', use_global_arguments=True, context=context)
            node2 = rclpy.create_node(
                'my_node', namespace='/my_ns', use_global_arguments=False, context=context)
            self.assertEqual('global_node_name', node1.get_name())
            self.assertEqual('my_node', node2.get_name())
            node1.destroy_node()
            node2.destroy_node()
        finally:
            rclpy.shutdown(context=context) 
Example #15
Source File: test_node.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_bad_node_arguments(self):
        context = rclpy.context.Context()
        rclpy.init(context=context)

        from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy

        invalid_ros_args_error_pattern = r'Failed to parse ROS arguments:.*not-a-remap.*'
        with self.assertRaisesRegex(_rclpy.RCLInvalidROSArgsError, invalid_ros_args_error_pattern):
            rclpy.create_node(
                'my_node',
                namespace='/my_ns',
                cli_args=['--ros-args', '-r', 'not-a-remap'],
                context=context)

        unknown_ros_args_error_pattern = r'Found unknown ROS arguments:.*\[\'--my-custom-flag\'\]'
        with self.assertRaisesRegex(_rclpy.UnknownROSArgsError, unknown_ros_args_error_pattern):
            rclpy.create_node(
                'my_node',
                namespace='/my_ns',
                cli_args=['--ros-args', '--my-custom-flag'],
                context=context)

        rclpy.shutdown(context=context) 
Example #16
Source File: test_destruction.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_destroy_timers():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_node3', context=context)
        try:
            timer1 = node.create_timer(0.1, None)
            timer2 = node.create_timer(1, None)
            timer2  # noqa

            assert 2 == len(tuple(node.timers))
            assert node.destroy_timer(timer1)

            assert 1 == len(tuple(node.timers))
        finally:
            node.destroy_node()
        assert 0 == len(tuple(node.timers))
    finally:
        rclpy.shutdown(context=context) 
Example #17
Source File: test_destruction.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_destroy_node_asap():
    context = rclpy.context.Context()
    rclpy.init(context=context)

    try:
        node = rclpy.create_node('test_destroy_subscription_asap', context=context)
        with node.handle:
            node.destroy_node()
            # handle valid because it's still being used
            with node.handle:
                pass

        with pytest.raises(InvalidHandle):
            # handle invalid because it was destroyed when no one was using it
            with node.handle:
                pass
    finally:
        rclpy.shutdown(context=context) 
Example #18
Source File: test_executor.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_remove_node(self):
        self.assertIsNotNone(self.node.handle)
        executor = SingleThreadedExecutor(context=self.context)

        got_callback = False

        def timer_callback():
            nonlocal got_callback
            got_callback = True

        try:
            tmr = self.node.create_timer(0.1, timer_callback)
            try:
                executor.add_node(self.node)
                executor.remove_node(self.node)
                executor.spin_once(timeout_sec=0.2)
            finally:
                self.node.destroy_timer(tmr)
        finally:
            executor.shutdown()

        assert not got_callback 
Example #19
Source File: test_action_server.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        self.node.destroy_node()
        self.executor.shutdown()
        rclpy.shutdown(context=self.context) 
Example #20
Source File: test_destruction.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_destroy_entities():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_node4', context=context)
        try:
            timer = node.create_timer(0.1, None)
            timer  # noqa
            assert 1 == len(tuple(node.timers))
            pub1 = node.create_publisher(BasicTypes, 'pub1_topic', 1)
            assert 2 == len(tuple(node.publishers))
            pub2 = node.create_publisher(BasicTypes, 'pub2_topic', 1)
            pub2  # noqa
            assert 3 == len(tuple(node.publishers))
            sub1 = node.create_subscription(
                BasicTypes, 'sub1_topic', lambda msg: ..., 1)
            assert 1 == len(tuple(node.subscriptions))
            sub2 = node.create_subscription(
                BasicTypes, 'sub2_topic', lambda msg: ..., 1)
            sub2  # noqa
            assert 2 == len(tuple(node.subscriptions))

            assert node.destroy_publisher(pub1)
            assert 2 == len(tuple(node.publishers))

            assert node.destroy_subscription(sub1)
            assert 1 == len(tuple(node.subscriptions))
        finally:
            node.destroy_node()
        assert 0 == len(tuple(node.timers))
        assert 0 == len(tuple(node.publishers))
        assert 0 == len(tuple(node.subscriptions))
    finally:
        rclpy.shutdown(context=context) 
Example #21
Source File: test_action_client.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        cls.node.destroy_node()
        rclpy.shutdown(context=cls.context) 
Example #22
Source File: test_publisher.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDown(cls):
        cls.node.destroy_node()
        cls.node_with_ns.destroy_node()
        rclpy.shutdown(context=cls.context) 
Example #23
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        cls.executor.shutdown()
        cls.node.destroy_node()
        rclpy.shutdown(context=cls.context) 
Example #24
Source File: test_create_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        rclpy.shutdown(context=cls.context) 
Example #25
Source File: test_rate.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_shutdown_wakes_rate():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    node = rclpy.create_node('test_rate_shutdown', context=context)
    executor = SingleThreadedExecutor(context=context)
    executor.add_node(node)

    rate = node.create_rate(0.0000001)

    _thread = threading.Thread(target=rate.sleep, daemon=True)
    _thread.start()
    executor.shutdown()
    node.destroy_node()
    rclpy.shutdown(context=context)
    _thread.join() 
Example #26
Source File: test_parameters_callback.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDownClass(cls):
        rclpy.shutdown(context=cls.context) 
Example #27
Source File: test_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        self.node.destroy_node()
        rclpy.shutdown(context=self.context) 
Example #28
Source File: test_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_node_arguments(self):
        context = rclpy.context.Context()
        rclpy.init(context=context)
        try:
            node = rclpy.create_node(
                'my_node',
                namespace='/my_ns',
                cli_args=['--ros-args', '-r', '__ns:=/foo/bar'],
                context=context
            )
            self.assertEqual('/foo/bar', node.get_namespace())
            node.destroy_node()
        finally:
            rclpy.shutdown(context=context) 
Example #29
Source File: test_destruction.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_destroy_node_twice():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_node2', context=context)
        node.destroy_node()
        with pytest.raises(InvalidHandle):
            node.destroy_node()
    finally:
        rclpy.shutdown(context=context) 
Example #30
Source File: test_rate.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def teardown_method(self):
        self.executor.shutdown()
        self.node.destroy_node()
        rclpy.shutdown(context=self.context)