Python rclpy.create_node() Examples

The following are 30 code examples of rclpy.create_node(). 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: 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 #2
Source File: client.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_client')
    cli = node.create_client(AddTwoInts, 'add_two_ints')

    req = AddTwoInts.Request()
    req.a = 41
    req.b = 1
    while not cli.wait_for_service(timeout_sec=1.0):
        node.get_logger().info('service not available, waiting again...')

    future = cli.call_async(req)
    rclpy.spin_until_future_complete(node, future)

    try:
        result = future.result()
    except Exception as e:
        node.get_logger().info('Service call failed %r' % (e,))
    else:
        node.get_logger().info(
            'Result of add_two_ints: for %d + %d = %d' %
            (req.a, req.b, result.sum))

    node.destroy_node()
    rclpy.shutdown() 
Example #3
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 #4
Source File: test_handle.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_handle_destroyed_when_not_used():
    context = rclpy.context.Context()
    rclpy.init(context=context)

    try:
        node = rclpy.create_node('test_handle_destroyed_when_not_used', context=context)
        with node.handle:
            node.handle.destroy()
            with node.handle:
                pass

        with pytest.raises(InvalidHandle):
            with node.handle:
                pass
    finally:
        rclpy.shutdown(context=context) 
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_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 #7
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 #8
Source File: test_node.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_use_sim_time(self):
        self.assertTrue(self.node.has_parameter(USE_SIM_TIME_NAME))
        self.assertFalse(self.node.get_parameter(USE_SIM_TIME_NAME).value)

        temp_node = rclpy.create_node(
            TEST_NODE + '2',
            namespace=TEST_NAMESPACE,
            context=self.context,
            parameter_overrides=[
                Parameter(USE_SIM_TIME_NAME, value=True),
            ],
            automatically_declare_parameters_from_overrides=False
        )
        # use_sim_time is declared automatically anyways; in this case using override value.
        self.assertTrue(temp_node.has_parameter(USE_SIM_TIME_NAME))
        self.assertTrue(temp_node.get_parameter(USE_SIM_TIME_NAME).value)
        temp_node.destroy_node() 
Example #9
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 #10
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 #11
Source File: test_node.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.context = rclpy.context.Context()
        rclpy.init(context=self.context)
        self.node = rclpy.create_node(
            TEST_NODE,
            namespace=TEST_NAMESPACE,
            context=self.context,
            parameter_overrides=[
                Parameter('initial_foo', Parameter.Type.INTEGER, 4321),
                Parameter('initial_bar', Parameter.Type.STRING, 'init_param'),
                Parameter('initial_baz', Parameter.Type.DOUBLE, 3.14)
            ],
            cli_args=[
                '--ros-args', '-p', 'initial_fizz:=buzz',
                '--params-file', str(TEST_RESOURCES_DIR / 'test_parameters.yaml'),
                '-p', 'initial_buzz:=1.'
            ],
            automatically_declare_parameters_from_overrides=False
        ) 
Example #12
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 #13
Source File: talker.py    From ROS-Robotics-Projects-SecondEdition with MIT License 5 votes vote down vote up
def talker_main():
	rclpy.init(args=None)
	node = rclpy.create_node('ros2_talker_node')
	pub = node.create_publisher(String, '/chatter')
	msg = String()
	i = 0
	while rclpy.ok():
		msg.data = 'Hello World: %d' % i
		i += 1
		node.get_logger().info('Publishing: "%s"' % msg.data)
		pub.publish(msg)
		sleep(0.5) 
Example #14
Source File: test_create_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_create_node_invalid_relative_namespace(self):
        node_name = 'create_node_test_invalid_namespace'
        namespace = 'invalid_namespace?'
        with self.assertRaisesRegex(InvalidNamespaceException, 'must not contain characters'):
            rclpy.create_node(node_name, namespace=namespace, context=self.context) 
Example #15
Source File: test_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.node = rclpy.create_node('TestClient', context=cls.context) 
Example #16
Source File: test_init_shutdown.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_create_node_without_init():
    context = rclpy.context.Context()
    with pytest.raises(NotInitializedException):
        rclpy.create_node('foo', context=context) 
Example #17
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 #18
Source File: test_handle.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_handle_destroyed_immediately():
    context = rclpy.context.Context()
    rclpy.init(context=context)

    try:
        node = rclpy.create_node('test_handle_destroyed_immediately', context=context)
        node.handle.destroy()
        with pytest.raises(InvalidHandle):
            with node.handle:
                pass
    finally:
        rclpy.shutdown(context=context) 
Example #19
Source File: test_executor.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.context = rclpy.context.Context()
        rclpy.init(context=self.context)
        self.node = rclpy.create_node('TestExecutor', namespace='/rclpy', 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_client_asap():
    context = rclpy.context.Context()
    rclpy.init(context=context)

    try:
        node = rclpy.create_node('test_destroy_client_asap', context=context)
        try:
            client = node.create_client(BasicTypesSrv, 'cli_service')

            # handle valid
            with client.handle:
                pass

            with client.handle:
                node.destroy_client(client)
                # handle valid because it's still being used
                with client.handle:
                    pass

            with pytest.raises(InvalidHandle):
                # handle invalid because it was destroyed when no one was using it
                with client.handle:
                    pass
        finally:
            node.destroy_node()
    finally:
        rclpy.shutdown(context=context) 
Example #21
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 #22
Source File: test_time_source.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_time_source_using_sim_time(self):
        time_source = TimeSource(node=self.node)
        clock = ROSClock()
        time_source.attach_clock(clock)

        # Setting ROS time active on a time source should also cause attached clocks' use of ROS
        # time to be set to active.
        self.assertFalse(time_source.ros_time_is_active)
        self.assertFalse(clock.ros_time_is_active)
        assert self.set_use_sim_time_parameter(True)
        self.assertTrue(time_source.ros_time_is_active)
        self.assertTrue(clock.ros_time_is_active)

        # A subscriber should have been created
        assert time_source._clock_sub is not None

        # Before any messages have been received on the /clock topic, now() should return 0
        assert clock.now() == Time(seconds=0, clock_type=ClockType.ROS_TIME)

        # When using sim time, ROS time should look like the messages received on /clock
        self.publish_clock_messages()
        assert clock.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME)
        assert clock.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME)

        # Check that attached clocks get the cached message
        clock2 = Clock(clock_type=ClockType.ROS_TIME)
        time_source.attach_clock(clock2)
        assert clock2.now() > Time(seconds=0, clock_type=ClockType.ROS_TIME)
        assert clock2.now() <= Time(seconds=5, clock_type=ClockType.ROS_TIME)

        # Check detaching the node
        time_source.detach_node()
        node2 = rclpy.create_node('TestTimeSource2', namespace='/rclpy', context=self.context)
        time_source.attach_node(node2)
        node2.destroy_node()
        assert time_source._get_node() == node2
        assert time_source._clock_sub is None 
Example #23
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 #24
Source File: test_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_set_executor_clear_executor(self):
        node = rclpy.create_node('my_node', context=self.context)
        executor = Mock()
        executor.add_node.return_value = True
        try:
            node.executor = executor
            assert id(executor) == id(node.executor)
            node.executor = None
            assert node.executor is None
        finally:
            node.destroy_node() 
Example #25
Source File: test_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_set_executor_removes_node_from_old_executor(self):
        node = rclpy.create_node('my_node', context=self.context)
        old_executor = Mock()
        old_executor.add_node.return_value = True
        new_executor = Mock()
        new_executor.add_node.return_value = True
        try:
            node.executor = old_executor
            assert id(old_executor) == id(node.executor)
            node.executor = new_executor
            assert id(new_executor) == id(node.executor)
        finally:
            node.destroy_node()
        old_executor.remove_node.assert_called_once_with(node)
        new_executor.remove_node.assert_not_called() 
Example #26
Source File: test_node.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_initially_no_executor(self):
        node = rclpy.create_node('my_node', context=self.context)
        try:
            assert node.executor is None
        finally:
            node.destroy_node() 
Example #27
Source File: test_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)
        cls.node = rclpy.create_node(
            TEST_NODE, namespace=TEST_NAMESPACE, context=cls.context,
            allow_undeclared_parameters=True) 
Example #28
Source File: test_parameters_callback.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.node = rclpy.create_node(
            'parameters_callback_node', context=self.context, allow_undeclared_parameters=True) 
Example #29
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 #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)