Python rclpy.node() Examples

The following are 30 code examples of rclpy.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: 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: 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 #3
Source File: custom_executor.py    From examples with Apache License 2.0 6 votes vote down vote up
def spin_once(self, timeout_sec=None):
        """
        Execute a single callback, then return.

        This is the only function which must be overridden by a custom executor. Its job is to
        start executing one callback, then return. It uses the method `wait_for_ready_callbacks`
        to get work to execute.

        :param timeout_sec: Seconds to wait. Block forever if None. Don't wait if <= 0
        :type timeout_sec: float or None
        """
        # wait_for_ready_callbacks yields callbacks that are ready to be executed
        try:
            handler, group, node = self.wait_for_ready_callbacks(timeout_sec=timeout_sec)
        except StopIteration:
            pass
        else:
            if node in self.high_priority_nodes:
                self.hp_executor.submit(handler)
            else:
                self.lp_executor.submit(handler) 
Example #4
Source File: echo.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def main(args):
    if not args.csv:
        truncate_length = args.truncate_length if not args.full_length else None
        callback = subscriber_cb(truncate_length, args.no_arr, args.no_str)
    else:
        truncate_length = args.truncate_length if not args.full_length else None
        callback = subscriber_cb_csv(truncate_length, args.no_arr, args.no_str)
    qos_profile = qos_profile_from_short_keys(
        args.qos_profile, reliability=args.qos_reliability, durability=args.qos_durability,
        depth=args.qos_depth, history=args.qos_history)
    with NodeStrategy(args) as node:
        if args.message_type is None:
            message_type = get_msg_class(node, args.topic_name, include_hidden_topics=True)
        else:
            message_type = get_message(args.message_type)

        if message_type is None:
            raise RuntimeError('Could not determine the type for the passed topic')

        subscriber(
            node, args.topic_name, message_type, callback, qos_profile, args.lost_messages) 
Example #5
Source File: echo.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def subscriber(
    node: Node,
    topic_name: str,
    message_type: MsgType,
    callback: Callable[[MsgType], Any],
    qos_profile: QoSProfile,
    report_lost_messages: bool
) -> Optional[str]:
    """Initialize a node with a single subscription and spin."""
    event_callbacks = None
    if report_lost_messages:
        event_callbacks = SubscriptionEventCallbacks(message_lost=message_lost_event_callback)
    try:
        node.create_subscription(
            message_type, topic_name, callback, qos_profile, event_callbacks=event_callbacks)
    except UnsupportedEventTypeError:
        assert report_lost_messages
        print(
            f"The rmw implementation '{get_rmw_implementation_identifier()}'"
            ' does not support reporting lost messages'
        )
    rclpy.spin(node) 
Example #6
Source File: pub.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def main(args):
    qos_profile = qos_profile_from_short_keys(
        args.qos_profile, reliability=args.qos_reliability, durability=args.qos_durability,
        depth=args.qos_depth, history=args.qos_history)
    times = args.times
    if args.once:
        times = 1
    with DirectNode(args, node_name=args.node_name) as node:
        return publisher(
            node.node,
            args.message_type,
            args.topic_name,
            args.values,
            1. / args.rate,
            args.print,
            times,
            qos_profile,
            args.keep_alive) 
Example #7
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 #8
Source File: test_waitable.py    From rclpy with Apache License 2.0 6 votes vote down vote up
def test_waitable_with_client(self):
        self.waitable = ClientWaitable(self.node)
        self.node.add_waitable(self.waitable)

        server = self.node.create_service(EmptySrv, 'test_client', lambda req, resp: resp)

        while not _rclpy.rclpy_service_server_is_available(self.waitable.client):
            time.sleep(0.1)

        thr = self.start_spin_thread(self.waitable)
        _rclpy.rclpy_send_request(self.waitable.client, EmptySrv.Request())
        thr.join()

        assert self.waitable.future.done()
        assert isinstance(self.waitable.future.result()['client'], EmptySrv.Response)
        self.node.destroy_service(server) 
Example #9
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_waitable_with_server(self):
        self.waitable = ServerWaitable(self.node)
        self.node.add_waitable(self.waitable)
        client = self.node.create_client(EmptySrv, 'test_server')

        thr = self.start_spin_thread(self.waitable)
        client.call_async(EmptySrv.Request())
        thr.join()

        assert self.waitable.future.done()
        assert isinstance(self.waitable.future.result()['server'], EmptySrv.Request)
        self.node.destroy_client(client) 
Example #10
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def __init__(self, node):
        super().__init__(ReentrantCallbackGroup())

        self._clock = Clock(clock_type=ClockType.STEADY_TIME)
        period_nanoseconds = 10000
        with self._clock.handle as clock_capsule, node.context.handle as context_capsule:
            self.timer = _rclpy.rclpy_create_timer(
                clock_capsule, context_capsule, period_nanoseconds)
        self.timer_index = None
        self.timer_is_ready = False

        self.node = node
        self.future = None 
Example #11
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def __init__(self, node):
        super().__init__(ReentrantCallbackGroup())

        with node.handle as node_capsule:
            self.subscription = _rclpy.rclpy_create_subscription(
                node_capsule, EmptyMsg, 'test_topic', QoSProfile(depth=10).get_c_qos_profile())
        self.subscription_index = None
        self.subscription_is_ready = False

        self.node = node
        self.future = None 
Example #12
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 #13
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 #14
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        self.node.remove_waitable(self.waitable)
        # Ensure resources inside the waitable are destroyed before the node in tearDownClass
        del self.waitable 
Example #15
Source File: custom_executor.py    From examples with Apache License 2.0 5 votes vote down vote up
def add_high_priority_node(self, node):
        self.high_priority_nodes.add(node)
        # add_node inherited
        self.add_node(node) 
Example #16
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_waitable_with_subscription(self):
        self.waitable = SubscriptionWaitable(self.node)
        self.node.add_waitable(self.waitable)
        pub = self.node.create_publisher(EmptyMsg, 'test_topic', 1)

        thr = self.start_spin_thread(self.waitable)
        pub.publish(EmptyMsg())
        thr.join()

        assert self.waitable.future.done()
        assert isinstance(self.waitable.future.result()['subscription'], EmptyMsg)
        self.node.destroy_publisher(pub) 
Example #17
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_waitable_with_guard_condition(self):
        self.waitable = GuardConditionWaitable(self.node)
        self.node.add_waitable(self.waitable)

        thr = self.start_spin_thread(self.waitable)
        _rclpy.rclpy_trigger_guard_condition(self.waitable.guard_condition)
        thr.join()

        assert self.waitable.future.done()
        assert self.waitable.future.result()['guard_condition']

    # Test that waitable doesn't crash with MutuallyExclusiveCallbackGroup
    # https://github.com/ros2/rclpy/issues/264 
Example #18
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def test_waitable_with_mutually_exclusive_callback_group(self):
        self.waitable = MutuallyExclusiveWaitable()
        self.node.add_waitable(self.waitable)
        self.executor.spin_once(timeout_sec=0.1) 
Example #19
Source File: pub_sub_node.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = PubSubNode()

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('node stopped cleanly')
    finally:
        node.destroy_node()
        rclpy.shutdown() 
Example #20
Source File: client_service_node.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = ClientServiceNode()

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('node stopped cleanly')
    finally:
        node.destroy_node()
        rclpy.shutdown() 
Example #21
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def __init__(self, node):
        super().__init__(ReentrantCallbackGroup())

        with node.handle as node_capsule:
            self.server = _rclpy.rclpy_create_service(
                node_capsule, EmptySrv, 'test_server', QoSProfile(depth=10).get_c_qos_profile())
        self.server_index = None
        self.server_is_ready = False

        self.node = node
        self.future = None 
Example #22
Source File: test_waitable.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def __init__(self, node):
        super().__init__(ReentrantCallbackGroup())

        with node.handle as node_capsule:
            self.client = _rclpy.rclpy_create_client(
                node_capsule, EmptySrv, 'test_client', QoSProfile(depth=10).get_c_qos_profile())
        self.client_index = None
        self.client_is_ready = False

        self.node = node
        self.future = None 
Example #23
Source File: test_subscription.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def make_mock_subscription(namespace, topic_name, cli_args=None):
    node = Node('node_name', namespace=namespace, cli_args=cli_args)
    return node.create_subscription(
        msg_type=Empty,
        topic=topic_name,
        callback=lambda _: None,
        qos_profile=10,
    ) 
Example #24
Source File: custom_callback_group.py    From examples with Apache License 2.0 5 votes vote down vote up
def __init__(self, node):
        super().__init__()
        self.timer = node.create_timer(0.5, self.timer_callback)
        self.bucket = 10
        self.bucket_max = 10
        self.lock = threading.Lock() 
Example #25
Source File: server_not_composable.py    From examples with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    global logger
    rclpy.init(args=args)

    node = rclpy.create_node('minimal_action_server')
    logger = node.get_logger()

    # Use a ReentrantCallbackGroup to enable processing multiple goals concurrently
    # Default goal callback accepts all goals
    # Default cancel callback rejects cancel requests
    action_server = ActionServer(
        node,
        Fibonacci,
        'fibonacci',
        execute_callback=execute_callback,
        cancel_callback=cancel_callback,
        callback_group=ReentrantCallbackGroup())

    # Use a MultiThreadedExecutor to enable processing goals concurrently
    executor = MultiThreadedExecutor()

    rclpy.spin(node, executor=executor)

    action_server.destroy()
    node.destroy_node()
    rclpy.shutdown() 
Example #26
Source File: publisher_member_function.py    From examples with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    minimal_publisher = MinimalPublisher()

    rclpy.spin(minimal_publisher)

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

    minimal_subscriber = MinimalSubscriber()

    rclpy.spin(minimal_subscriber)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    minimal_subscriber.destroy_node()
    rclpy.shutdown() 
Example #28
Source File: pub.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def add_arguments(self, parser, cli_name):
        arg = parser.add_argument(
            'topic_name',
            help="Name of the ROS topic to publish to (e.g. '/chatter')")
        arg.completer = TopicNameCompleter(
            include_hidden_topics_key='include_hidden_topics')
        arg = parser.add_argument(
            'message_type',
            help="Type of the ROS message (e.g. 'std_msgs/String')")
        arg.completer = TopicTypeCompleter(
            topic_name_key='topic_name')
        arg = parser.add_argument(
            'values', nargs='?', default='{}',
            help='Values to fill the message with in YAML format '
                 "(e.g. 'data: Hello World'), "
                 'otherwise the message will be published with default values')
        arg.completer = TopicMessagePrototypeCompleter(
            topic_type_key='message_type')
        parser.add_argument(
            '-r', '--rate', metavar='N', type=positive_float, default=1.0,
            help='Publishing rate in Hz (default: 1)')
        parser.add_argument(
            '-p', '--print', metavar='N', type=int, default=1,
            help='Only print every N-th published message (default: 1)')
        group = parser.add_mutually_exclusive_group()
        group.add_argument(
            '-1', '--once', action='store_true',
            help='Publish one message and exit')
        group.add_argument(
            '-t', '--times', type=nonnegative_int, default=0,
            help='Publish this number of times and then exit')
        parser.add_argument(
            '--keep-alive', metavar='N', type=positive_float, default=0.1,
            help='Keep publishing node alive for N seconds after the last msg '
                 '(default: 0.1)')
        parser.add_argument(
            '-n', '--node-name',
            help='Name of the created publishing node')
        add_qos_arguments_to_argument_parser(
            parser, is_publisher=True, default_preset='system_default') 
Example #29
Source File: controller_node.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = ControllerNode()

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('controller stopped cleanly')
    except BaseException:
        print('exception in controller:', file=sys.stderr)
        raise
    finally:
        node.destroy_node()
        rclpy.shutdown() 
Example #30
Source File: listener_node.py    From ros2cli with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    rclpy.init(args=args)

    node = ListenerNode()

    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        print('listener stopped cleanly')
    except BaseException:
        print('exception in listener:', file=sys.stderr)
        raise
    finally:
        node.destroy_node()
        rclpy.shutdown()