Python rclpy.init() Examples

The following are 30 code examples of rclpy.init(). 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: test_action_graph.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node0 = rclpy.create_node(TEST_NODE0, namespace=TEST_NAMESPACE0, context=cls.context)
        cls.node1 = rclpy.create_node(TEST_NODE1, namespace=TEST_NAMESPACE1, context=cls.context)
        cls.node2 = rclpy.create_node(TEST_NODE2, namespace=TEST_NAMESPACE2, context=cls.context)

        cls.action_client10 = ActionClient(cls.node1, Fibonacci, TEST_ACTION0)
        cls.action_server10 = ActionServer(cls.node1, Fibonacci, TEST_ACTION0, lambda: None)
        cls.action_client20 = ActionClient(cls.node2, Fibonacci, TEST_ACTION0)
        cls.action_client21 = ActionClient(cls.node2, Fibonacci, TEST_ACTION1)
        cls.action_server20 = ActionServer(cls.node2, Fibonacci, TEST_ACTION0, lambda: None)
        cls.action_server21 = ActionServer(cls.node2, Fibonacci, TEST_ACTION1, lambda: None)

        assert cls.wait_for_node(node=cls.node1, remote_node=cls.node0, timeout=2)
        assert cls.wait_for_node(node=cls.node1, remote_node=cls.node2, timeout=2)
        assert cls.wait_for_node(node=cls.node2, remote_node=cls.node0, timeout=2)
        assert cls.wait_for_node(node=cls.node2, remote_node=cls.node1, timeout=2) 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #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: 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 #10
Source File: test_publisher.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def setUp(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node = rclpy.create_node(
            'node',
            context=cls.context,
            cli_args=[
                '--ros-args', '-r', '{}:={}'.format(TEST_TOPIC_FROM, TEST_TOPIC_TO),
                '--ros-args', '-r', '{}:={}'.format(TEST_FQN_TOPIC_FROM, TEST_FQN_TOPIC_TO)
            ],
        )
        cls.node_with_ns = rclpy.create_node(
            'node_withns',
            context=cls.context,
            namespace=TEST_NODE_NAMESPACE,
        ) 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: test_destruction.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_destroy_node():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_node1', context=context)
        node.destroy_node()
    finally:
        rclpy.shutdown(context=context) 
Example #16
Source File: test_create_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context) 
Example #17
Source File: test_action_client.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.executor = SingleThreadedExecutor(context=cls.context)
        cls.node = rclpy.create_node('TestActionClient', context=cls.context)
        cls.mock_action_server = MockActionServer(cls.node) 
Example #18
Source File: test_callback_group.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node = rclpy.create_node('TestCallbackGroup', namespace='/rclpy', context=cls.context) 
Example #19
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node = rclpy.create_node(
            'TestWaitable', namespace='/rclpy/test', context=cls.context,
            allow_undeclared_parameters=True)
        cls.executor = SingleThreadedExecutor(context=cls.context)
        cls.executor.add_node(cls.node) 
Example #20
Source File: test_create_while_spinning.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        rclpy.init()
        self.node = rclpy.create_node('TestCreateWhileSpinning', namespace='/rclpy')
        self.executor = SingleThreadedExecutor()
        self.executor.add_node(self.node)
        self.exec_thread = threading.Thread(target=self.executor.spin)
        self.exec_thread.start()
        # Make sure executor is blocked by rcl_wait
        time.sleep(TIMEOUT) 
Example #21
Source File: test_subscription.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setup_ros():
    rclpy.init() 
Example #22
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 #23
Source File: test_timer.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_number_callbacks(period):
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_timer_number_callbacks', context=context)
        try:
            executor = SingleThreadedExecutor(context=context)
            try:
                executor.add_node(node)
                # The first spin_once() takes  long enough for 1ms timer tests to fail
                executor.spin_once(timeout_sec=0)

                callbacks = []
                timer = node.create_timer(period, lambda: callbacks.append(len(callbacks)))
                try:
                    begin_time = time.time()

                    while rclpy.ok(context=context) and time.time() - begin_time < 4.5 * period:
                        executor.spin_once(timeout_sec=period / 10)

                    assert len(callbacks) == 4
                finally:
                    node.destroy_timer(timer)
            finally:
                executor.shutdown()
        finally:
            node.destroy_node()
    finally:
        rclpy.shutdown(context=context) 
Example #24
Source File: test_timer.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_zero_callback(period):
    context = rclpy.context.Context()
    rclpy.init(context=context)
    try:
        node = rclpy.create_node('test_timer_no_callback', context=context)
        try:
            executor = SingleThreadedExecutor(context=context)
            try:
                executor.add_node(node)
                # The first spin_once() takes  long enough for 1ms timer tests to fail
                executor.spin_once(timeout_sec=0)

                callbacks = []
                timer = node.create_timer(period, lambda: callbacks.append(len(callbacks)))
                try:
                    executor.spin_once(timeout_sec=(period / 2))

                    assert len(callbacks) == 0
                finally:
                    node.destroy_timer(timer)
            finally:
                executor.shutdown()
        finally:
            node.destroy_node()
    finally:
        rclpy.shutdown(context=context) 
Example #25
Source File: test_guard_condition.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node = rclpy.create_node(
            'TestGuardCondition', namespace='/rclpy/test', context=cls.context)
        cls.executor = SingleThreadedExecutor(context=cls.context)
        cls.executor.add_node(cls.node) 
Example #26
Source File: test_messages.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.context = rclpy.context.Context()
        rclpy.init(context=cls.context)
        cls.node = rclpy.create_node(
            TestMessages.NODE_NAME,
            namespace=TestMessages.NAMESPACE,
            context=cls.context
        ) 
Example #27
Source File: test_init_shutdown.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_init():
    context = rclpy.context.Context()
    rclpy.init(context=context)
    rclpy.shutdown(context=context) 
Example #28
Source File: test_init_shutdown.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_init_with_unknown_ros_args():
    from rclpy.impl.implementation_singleton import rclpy_implementation as _rclpy

    context = rclpy.context.Context()
    unknown_ros_args_error_pattern = r'Found unknown ROS arguments:.*\[\'unknown\'\]'
    with pytest.raises(_rclpy.UnknownROSArgsError, match=unknown_ros_args_error_pattern):
        rclpy.init(context=context, args=['--ros-args', 'unknown']) 
Example #29
Source File: test_init_shutdown.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_init_with_non_utf8_arguments():
    context = rclpy.context.Context()
    # Embed non decodable characters e.g. due to
    # wrong locale settings.
    # See PEP-383 for further reference.
    args = ['my-node.py', 'Ragnar\udcc3\udcb6k']
    with pytest.raises(UnicodeEncodeError):
        rclpy.init(context=context, args=args) 
Example #30
Source File: test_rate.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setup_method(self):
        self.context = rclpy.context.Context()
        rclpy.init(context=self.context)
        self.node = rclpy.create_node('test_rate', context=self.context)
        self.executor = SingleThreadedExecutor(context=self.context)
        self.executor.add_node(self.node)