Crate rclrs

Crate rclrs 

Source
Expand description

Rust client library for ROS 2.

Since this library depends on the ROS ecosystem, see the README for setup instructions.

This client library is made to be familiar for ROS users who are used to the conventional client libraries rcl, rclcpp, and rclpy, while taking full advantage of the unique strengths of the Rust programming language.

The library provides structs that will be familiar to ROS users:

It also provides some unique utilities to help leverage Rust language features, such as async programming:

§Basic Usage

To build a typical ROS application, create a Context, followed by an Executor, and then a Node. Create whatever primitives you need, and then tell the Executor to spin:

use rclrs::*;

let context = Context::default_from_env()?;
let mut executor = context.create_basic_executor();
let node = executor.create_node("example_node")?;

let subscription = node.create_subscription(
    "topic_name",
    |msg: example_interfaces::msg::String| {
        println!("Received message: {}", msg.data);
    }
)?;

executor.spin(SpinOptions::default()).first_error()?;

If your callback needs to interact with some state data, consider using a Worker, especially if that state data needs to be shared with other callbacks:

// This worker will manage the data for us.
// The worker's data is called its payload.
let worker = node.create_worker::<Option<String>>(None);

// We use the worker to create a subscription.
// This subscription's callback can borrow the worker's
// payload with its first function argument.
let subscription = worker.create_subscription(
    "topic_name",
    |data: &mut Option<String>, msg: example_interfaces::msg::String| {
        // Print out the previous message, if one exists.
        if let Some(previous) = data {
            println!("Previous message: {}", *previous)
        }

        // Save the latest message, to be printed out the
        // next time this callback is triggered.
        *data = Some(msg.data);
    }
)?;

§Parameters

rclrs provides an ergonomic way to declare and use node parameters. A parameter can be declared as mandatory, optional, or read-only. The API of each reflects their respective constraints.

  • Mandatory and read-only parameters always have a value that you can get
  • Optional parameters will return an Option when you get from them.
  • Read-only parameters do not allow you to modify them after they have been declared.

The following is a simple example of using a mandatory parameter:

use rclrs::*;
use std::sync::Arc;

let mut executor = Context::default_from_env()?.create_basic_executor();
let node = executor.create_node("parameter_demo")?;

let greeting: MandatoryParameter<Arc<str>> = node
    .declare_parameter("greeting")
    .default("Hello".into())
    .mandatory()?;

let _subscription = node.create_subscription(
    "greet",
    move |msg: example_interfaces::msg::String| {
        println!("{}, {}", greeting.get(), msg.data);
    }
)?;

executor.spin(SpinOptions::default()).first_error()?;

§Logging

rclrs provides the same logging utilites as rclcpp and rclpy with an ergonomic Rust API. ToLogParams can be used to dictate how logging is performed.

use rclrs::*;
use std::time::Duration;

let mut executor = Context::default_from_env()?.create_basic_executor();
let node = executor.create_node("logging_demo")?;

let _subscription = node.clone().create_subscription(
    "logging_demo",
    move |msg: example_interfaces::msg::String| {
        let data = msg.data;

        // You can apply modifiers such as .once() to node.logger()
        // to dictate how the logging behaves.
        log!(
            node.logger().once(),
            "First message: {data}",
        );

        log!(
            node.logger().skip_first(),
            "Subsequent message: {data}",
        );

        // You can chain multiple modifiers together.
        log_warn!(
            node
            .logger()
            .skip_first()
            .throttle(Duration::from_secs(5)),
            "Throttled message: {data}",
        );
    }
)?;

// Any &str can be used as the logger name and have
// logging modifiers applied to it.
log_info!(
    "notice".once(),
    "Ready to begin logging example_interfaces/msg/String messages published to 'logging_demo'.",
);
log_warn!(
    "help",
    "Try running\n \
    $ ros2 topic pub logging_demo example_interfaces/msg/String \"data: message\"",
);
executor.spin(SpinOptions::default()).first_error()?;

Modules§

vendor
Created by vendor_interfaces.py

Macros§

log
log a message to rosout
log_debug
Debug log message. See log for usage.
log_error
Error log message. See log for usage.
log_fatal
Fatal log message. See log for usage.
log_info
Info log message. See log for usage.
log_warn
Warning log message. See log for usage.

Structs§

AcceptedGoal
This manages a goal which has been accepted but has not begun executing yet. It is allowed to transition into the executing or cancelling state.
ActionClientHandle
Manage the lifecycle of an rcl_action_client_t, including managing its dependencies on rcl_node_t and rcl_context_t by ensuring that these dependencies are dropped after the rcl_action_client_t.
ActionClientOptions
ActionClientOptions are used by Node::create_action_client to initialize an ActionClient.
ActionClientReady
This is the ready information for an action client.
ActionClientState
The inner state of an ActionClient.
ActionGoalReceiver
This is an alternative tool for implementing an ActionServer. Instead of specifying a callback to receive goal requests, you can use this receiver to obtain incoming goal requests and then process them in an async task.
ActionServerOptions
ActionServerOptions are used by Node::create_action_server to initialize an ActionServer.
ActionServerReady
This is the ready information for an action server.
ActionServerState
The inner state of an ActionServer.
ActivityListener
ActivityListener is used to watch the activity of the primitives of a Worker.
AvailableValues
This struct is given to the discriminator function of the ParameterBuilder so it knows what values are available to choose from.
BasicExecutorRuntime
The implementation of this runtime is based off of the async Rust reference book: https://rust-lang.github.io/async-book/02_execution/04_executor.html
CancelResponse
This is returned by CancellationClient to inform whether a cancellation of a single goal was successful.
CancelResponseClient
This will allow you to receive a response to your cancellation request so you can know if the cancellation was successful or not.
CancellationClient
This can be used to request the cancellation of a specific goal. When you put in the request you will get a one-shot receiver which will tell you whether the request was accepted or rejected.
ClientOptions
ClientOptions are used by Node::create_client to initialize a Client for a service.
ClientState
The inner state of a Client.
Clock
Struct that implements a Clock and wraps rcl_clock_t.
ClockSource
A clock source that can be used to drive the contained clock. Created when a clock of type ClockType::RosTime is constructed
Context
Shared state between nodes and similar entities.
ExecutingGoal
This represents a goal that is in the Executing state. This struct is held by an action server implementation and is used to provide feedback to the client, to listen for cancellation requests, and to transition the goal into its next state.
Executor
An executor that can be used to create nodes and run their callbacks.
ExecutorCommands
This allows commands, such as creating a new node, to be run on the executor while the executor is spinning.
ExecutorWorkerOptions
This is constructed by ExecutorCommands and passed to the ExecutorRuntime to create a new worker. Downstream users of rclrs should not be using this class unless you are implementing your own ExecutorRuntime.
FeedbackClient
This struct allows you to receive feedback messages for the goal. Through the DerefMut trait you can use the UnboundedReceiver API to await new feedback messages.
FeedbackPublisher
Use this to send feedback from an action server. This struct can be cloned and sent to other threads without the main goal handle. It can continue to send feedback until the goal has reached a terminal state.
GoalClient
The goal client bundles a set of receivers that will allow you to await different information from the action server, such as feedback messages, status updates, and the final result. It also provides a way to request cancelling a goal.
GoalClientStream
Use this to receive a stream of messages from the action server which may be a mix of feedback messages, status updates, and the final result. These are multiplexed by the GoalEvent enum.
GoalStatus
A status update for a goal. Includes the status code, the goal uuid, and the timestamp of when the status was set by the action server.
GoalUuid
A unique identifier for a goal request.
GuardCondition
A waitable entity used for waking up a wait set manually.
InitOptions
Additional options for initializing the Context.
LoanedMessage
A message that is owned by the middleware, loaned for publishing.
LogParams
These parameters determine the behavior of an instance of logging.
Logger
Logger can be passed in as the first argument into one of the logging macros provided by rclrs. When passing it into one of the logging macros, you can optionally apply any of the methods from ToLogParams to tweak the logging behavior.
MandatoryParameter
A parameter that must have a value This struct has ownership of the declared parameter. Additional parameter declaration will fail while this struct exists and the parameter will be undeclared when it is dropped.
MessageInfo
Additional information about a received message.
MultiCancelResponse
This is returned by ActionClientState::cancel_all_goals and ActionClientState::cancel_goals_prior_to.
MultiCancelResponseClient
This will allow you to receive a response to a cancellation request that impacts multiple goals.
NodeNameInfo
Stores a node’s name and namespace
NodeOptions
A set of options for creating a Node.
NodeState
The inner state of a Node.
OptionalParameter
A parameter that might not have a value, represented by Option<T>. This struct has ownership of the declared parameter. Additional parameter declaration will fail while this struct exists and the parameter will be undeclared when it is dropped.
ParameterBuilder
Builder used to declare a parameter. Obtain this by calling crate::NodeState::declare_parameter.
ParameterOptions
Options that can be attached to a parameter, such as description, ranges. Some of this data will be used to populate the ParameterDescriptor
ParameterRange
Describes the range for paramter type T.
ParameterRanges
Contains all the possible type of ranges that can be applied to a value. Usually only one of these ranges will be applied, but all have to be stored since:
Parameters
Allows access to all parameters via get / set functions, using their name as a key.
PrimitiveOptions
PrimitiveOptions are the subset of options that are relevant across all primitives (e.g. Subscription, Publisher, Client, and Service).
Promise
A future for a value that will be provided by another asynchronous task.
PublisherGid
An identifier for a publisher in the local context.
PublisherOptions
PublisherOptions are used by NodeState::create_publisher to initialize a Publisher.
PublisherState
The inner state of a Publisher.
QoSProfile
A Quality of Service profile.
RclErrorMsg
Struct encapsulating an error message from the rcl layer or below.
ReadOnlyLoanedMessage
A message that is owned by the middleware, loaned out for reading.
ReadOnlyParameter
A parameter that must have a value and cannot be written to This struct has ownership of the declared parameter. Additional parameter declaration will fail while this struct exists and the parameter will be undeclared when it is dropped.
RequestId
Unique identifier for a service request.
RequestedGoal
An action goal that has been requested but not accepted yet. If this is dropped without being accepted then the goal request will be rejected.
RequestedGoalClient
This struct allows you to receive a GoalClient for a goal that you requested. Call .await on this to obtain the response to the goal request. Note that the GoalClient can only be received once.
ResultClient
This struct allows you to receive the result of the goal. Through the DerefMut trait you can use the oneshot::Receiver API to await the final result. Note that it can only be received once.
ServiceHandle
Manage the lifecycle of an rcl_service_t, including managing its dependencies on rcl_node_t and rcl_context_t by ensuring that these dependencies are dropped after the rcl_service_t.
ServiceInfo
Information about an incoming service request.
ServiceOptions
ServiceOptions are used by [Node::create_service][1] to initialize a [Service`] provider.
ServiceState
The inner state of a Service.
SpinConditions
A bundle of conditions that tell the ExecutorRuntime how long to keep spinning. This combines conditions that users specify with SpinOptions and standard conditions that are set by the Executor.
SpinOptions
A bundle of optional conditions that a user may want to impose on how long an executor spins for.
StatusClient
This struct allows you to receive every status update experienced by a goal.
StatusWatcher
This struct allows you to monitor the status of the goal. Through the DerefMut trait you can use the watch::Receiver API to check the latest status and monitor changes.
SubscriptionOptions
SubscriptionOptions are used by Node::create_subscription to initialize a Subscription.
SubscriptionState
The inner state of a Subscription.
TerminatedGoal
This represents a goal that has reached a terminated state. This struct is used as the return value for action server callbacks to guide the user to bring the goal to a terminal state.
Time
Struct that represents time.
TimerOptions
Options for creating a Timer.
TimerState
The inner state of a Timer.
TopicEndpointInfo
Contains topic endpoint information
WaitSet
A struct for waiting on subscriptions and other waitable entities to become ready.
WaitSetRunConditions
These are the conditions used by the WaitSetRunner to determine when it needs to halt.
WaitSetRunner
This is a utility class that executors can use to easily run and manage their wait set.
Waitable
This struct manages the presence of an rcl primitive inside the wait set. It will keep track of where the primitive is within the wait set as well as automatically remove the primitive from the wait set once it isn’t being used anymore.
WaitableCount
Count the number of rcl primitives in the wait set.
WaitableLifecycle
This is used internally to track whether an rcl primitive is still being used. When this gets dropped, the rcl primitive will automatically be removed from the wait set.
WorkerOptions
Options used while creating a new Worker.
WorkerState
The inner state of a Worker.

Enums§

ActivityListenerCallback
Enum for the different types of callbacks that a listener may have
AnyClientOutputSender
Can send any kind of response for a client call.
AnyServiceCallback
An enum capturing the various possible function signatures for service callbacks.
AnySubscriptionCallback
An enum capturing the various possible function signatures for subscription callbacks.
AnyTimerCallback
A callback that can be triggered when a timer elapses.
BeginAcceptedGoal
While a goal was waiting to be executed, it is possible for cancellation requests to arrive for it. An accepted goal may transition directly into either executing or cancelling.
CancelResponseCode
The response returned by an ActionServer’s cancel callback when a goal is requested to be cancelled.
ClockType
Enum to describe clock type. Redefined for readability and to eliminate the uninitialized case from the rcl_clock_type_t enum in the binding.
DeclarationError
Error that can be generated when doing operations on parameters.
GoalEvent
Any of the possible update events that can happen for a goal.
GoalStatusCode
Values defined by action_msgs/msg/GoalStatus
InnerGuardConditionHandle
We need to wrap the underlying condition variable with this because some condition variables are owned at the rclrs layer while others were obtained from rcl and either have static lifetimes or lifetimes that depend on something else.
LogOccurrence
Specify when a log message should be published
LoggerName
This is used to borrow a logger name which might be validated (e.g. came from a Logger struct) or not (e.g. a user-defined &str). If an unvalidated logger name is used with one of the logging macros, we will log an error about it, and the original log message will be logged with the default logger.
NodeServiceCallback
An enum capturing the various possible function signatures for service callbacks.
NodeSubscriptionCallback
An enum capturing the various possible function signatures for subscription callbacks that can be used with the async worker.
ParameterKind
Describes the parameter’s type. Similar to ParameterValue but also includes a Dynamic variant for dynamic parameters.
ParameterValue
A parameter value.
ParameterValueError
Describes errors that can be generated when trying to set a parameter’s value.
QoSDurabilityPolicy
The DURABILITY DDS QoS policy.
QoSDuration
A duration that can take two special values: System default and infinite.
QoSHistoryPolicy
The HISTORY DDS QoS policy.
QoSLivelinessPolicy
The LIVELINESS DDS QoS policy.
QoSReliabilityPolicy
The RELIABILITY DDS QoS policy.
RclPrimitiveHandle
Used by the wait set to obtain the handle of a primitive.
RclPrimitiveKind
Enum to describe the kind of an executable.
RclReturnCode
Return codes of rcl functions.
RclrsError
The main error type.
ReadyKind
Describe the way in which a waitable is ready.
RmwParameterConversionError
An error that occured when trying to convert a parameter from an rcl_interfaces::msg::ParameterValue
ThrottleClock
This parameter can specify a type of clock for a logger to use when throttling.
TimerClock
This parameter can specify a type of clock for a timer to use
WorkerServiceCallback
An enum capturing the various possible function signatures for service callbacks that can be used by a Worker.
WorkerSubscriptionCallback
An enum capturing the various possible function signatures for subscription callbacks that can be used by a Worker.

Constants§

QOS_PROFILE_ACTION_STATUS_DEFAULT
Equivalent to rcl_action_qos_profile_status_default from the rcl_action package.
QOS_PROFILE_CLOCK
Equivalent to ClockQos from the rclcpp package. Same as sensor data but with a history depth of 1
QOS_PROFILE_DEFAULT
Equivalent to rmw_qos_profile_default from the rmw package.
QOS_PROFILE_PARAMETERS
Equivalent to rmw_qos_profile_parameters from the rmw package.
QOS_PROFILE_PARAMETER_EVENTS
Equivalent to rmw_qos_profile_parameter_events from the rmw package.
QOS_PROFILE_SENSOR_DATA
Equivalent to rmw_qos_profile_sensor_data from the rmw package.
QOS_PROFILE_SERVICES_DEFAULT
Equivalent to rmw_qos_profile_services_default from the rmw package.
QOS_PROFILE_SYSTEM_DEFAULT
Equivalent to rmw_qos_profile_system_default from the rmw package.

Traits§

ActionIDL
Trait for actions.
ClientAsyncCallback
A trait to deduce async callbacks of service clients.
ClientCallback
A trait to deduce regular callbacks of service clients.
ClientOutput
This trait allows us to deduce how much information a user wants to receive from a client call. A user can choose to receive only the response from the service or may include the RequestId or ServiceInfo metadata.
CreateBasicExecutor
This trait allows Context to create a basic executor.
ExecutorChannel
This trait defines the interface for passing new items into an executor to run.
ExecutorRuntime
This trait defines the interface for having an executor run.
IntoActionClientOptions
Trait to implicitly convert a compatible object into ActionClientOptions.
IntoActionServerOptions
Trait to implicitly convert a compatible object into ActionServerOptions.
IntoAsyncServiceCallback
A trait for async callbacks of services.
IntoAsyncSubscriptionCallback
A trait for async callbacks of subscriptions.
IntoNodeOptions
This trait helps to build NodeOptions which can be passed into Executor::create_node.
IntoNodeServiceCallback
A trait to deduce regular callbacks of services.
IntoNodeSubscriptionCallback
A trait for regular callbacks of subscriptions.
IntoNodeTimerOneshotCallback
This trait is used to create timer callbacks for one-shot timers in a Node.
IntoNodeTimerRepeatingCallback
This trait is used to create timer callbacks for repeating timers in a Node.
IntoPrimitiveOptions
Trait to implicitly convert a compatible object into PrimitiveOptions.
IntoTimerOptions
Trait to implicitly convert a suitable object into TimerOptions.
IntoWorkerServiceCallback
A trait used to deduce callbacks for services that run on a worker.
IntoWorkerSubscriptionCallback
A trait for callbacks of subscriptions that run on a worker.
IntoWorkerTimerOneshotCallback
This trait is used to create timer callbacks for one-shot timers in a Worker.
IntoWorkerTimerRepeatingCallback
This trait is used to create timer callbacks for repeating timers in a Worker.
MessageCow
Convenience trait for PublisherState::publish.
MessageIDL
Trait for types that can be used in a rclrs::Subscription and a rclrs::Publisher.
ParameterVariant
A trait that describes a value that can be converted into a parameter.
RclPrimitive
This provides the public API for executing a waitable item.
RclrsErrorFilter
A helper trait to disregard timeouts as not an error.
RmwMessageIDL
Trait for RMW-native messages.
ServiceIDL
Trait for services.
TakeFailedAsNone
A helper trait to handle common error handling flows
ToLogParams
Methods for defining the behavior of a logging instance.
WorkScope
This is used to determine what kind of payload a callback can accept, as well as what kind of callbacks can be used with it. Users should not implement this trait.
WorkerChannel
Channel to send commands related to a specific worker.

Functions§

default_initial_value_discriminator
The default discriminator that chooses the initial value for a parameter. The implementation here uses a simple preference of
extract_non_ros_args
Extract non-ROS arguments from program’s input arguments.

Type Aliases§

ActionClient
Main class responsible for sending goals to a ROS action server.
ActionServer
An action server that can respond to requests sent by ROS action clients.
Client
Main class responsible for sending requests to a ROS service.
Node
A processing unit that can communicate with other nodes. See the API of NodeState to find out what methods you can call on a Node.
PayloadTask
Encapsulates a task that can operate on the payload of a worker
Publisher
Struct for sending messages of type T.
Service
Provide a service that can respond to requests sent by ROS service clients.
Subscription
Struct for receiving messages of type T.
Timer
Struct for executing periodic events.
TopicNamesAndTypes
Stores a list of types associated with each topic.
WeakActivityListener
This type is used by executor runtimes to keep track of listeners.
Worker
A worker that carries a payload and synchronizes callbacks for subscriptions and services. Workers share much in common with “callback groups” from rclcpp, with the addition of holding a data payload to share between the callbacks.
WorkerService
Provide a Service that runs on a Worker.
WorkerSubscription
A Subscription that runs on a Worker.
WorkerTimer
A Timer that runs on a Worker.
rmw_request_id_t