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
Optionwhen 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
logfor usage. - log_
error - Error log message. See
logfor usage. - log_
fatal - Fatal log message. See
logfor usage. - log_
info - Info log message. See
logfor usage. - log_
warn - Warning log message. See
logfor usage.
Structs§
- Accepted
Goal - 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.
- Action
Client Handle - Manage the lifecycle of an
rcl_action_client_t, including managing its dependencies onrcl_node_tandrcl_context_tby ensuring that these dependencies are dropped after thercl_action_client_t. - Action
Client Options ActionClientOptionsare used byNode::create_action_clientto initialize anActionClient.- Action
Client Ready - This is the ready information for an action client.
- Action
Client State - The inner state of an
ActionClient. - Action
Goal Receiver - 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. - Action
Server Options ActionServerOptionsare used byNode::create_action_serverto initialize anActionServer.- Action
Server Ready - This is the ready information for an action server.
- Action
Server State - The inner state of an
ActionServer. - Activity
Listener ActivityListeneris used to watch the activity of the primitives of aWorker.- Available
Values - This struct is given to the discriminator function of the
ParameterBuilderso it knows what values are available to choose from. - Basic
Executor Runtime - 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
- Cancel
Response - This is returned by
CancellationClientto inform whether a cancellation of a single goal was successful. - Cancel
Response Client - This will allow you to receive a response to your cancellation request so you can know if the cancellation was successful or not.
- Cancellation
Client - 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.
- Client
Options ClientOptionsare used byNode::create_clientto initialize aClientfor a service.- Client
State - The inner state of a
Client. - Clock
- Struct that implements a Clock and wraps
rcl_clock_t. - Clock
Source - A clock source that can be used to drive the contained clock. Created when a clock of type
ClockType::RosTimeis constructed - Context
- Shared state between nodes and similar entities.
- Executing
Goal - 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.
- Executor
Commands - This allows commands, such as creating a new node, to be run on the executor while the executor is spinning.
- Executor
Worker Options - This is constructed by
ExecutorCommandsand passed to theExecutorRuntimeto create a new worker. Downstream users of rclrs should not be using this class unless you are implementing your ownExecutorRuntime. - Feedback
Client - This struct allows you to receive feedback messages for the goal. Through the
DerefMuttrait you can use theUnboundedReceiverAPI to await new feedback messages. - Feedback
Publisher - 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.
- Goal
Client - 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.
- Goal
Client Stream - 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
GoalEventenum. - Goal
Status - 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.
- Goal
Uuid - A unique identifier for a goal request.
- Guard
Condition - A waitable entity used for waking up a wait set manually.
- Init
Options - Additional options for initializing the Context.
- Loaned
Message - 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
ToLogParamsto tweak the logging behavior. - Mandatory
Parameter - 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.
- Message
Info - Additional information about a received message.
- Multi
Cancel Response - This is returned by
ActionClientState::cancel_all_goalsandActionClientState::cancel_goals_prior_to. - Multi
Cancel Response Client - This will allow you to receive a response to a cancellation request that impacts multiple goals.
- Node
Name Info - Stores a node’s name and namespace
- Node
Options - A set of options for creating a
Node. - Node
State - The inner state of a
Node. - Optional
Parameter - 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. - Parameter
Builder - Builder used to declare a parameter. Obtain this by calling
crate::NodeState::declare_parameter. - Parameter
Options - Options that can be attached to a parameter, such as description, ranges. Some of this data will be used to populate the ParameterDescriptor
- Parameter
Range - Describes the range for paramter type T.
- Parameter
Ranges - 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.
- Primitive
Options PrimitiveOptionsare the subset of options that are relevant across all primitives (e.g.Subscription,Publisher,Client, andService).- Promise
- A future for a value that will be provided by another asynchronous task.
- Publisher
Gid - An identifier for a publisher in the local context.
- Publisher
Options PublisherOptionsare used byNodeState::create_publisherto initialize aPublisher.- Publisher
State - The inner state of a
Publisher. - QoSProfile
- A Quality of Service profile.
- RclError
Msg - Struct encapsulating an error message from the rcl layer or below.
- Read
Only Loaned Message - A message that is owned by the middleware, loaned out for reading.
- Read
Only Parameter - 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.
- Request
Id - Unique identifier for a service request.
- Requested
Goal - 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.
- Requested
Goal Client - This struct allows you to receive a
GoalClientfor a goal that you requested. Call.awaiton this to obtain the response to the goal request. Note that theGoalClientcan only be received once. - Result
Client - This struct allows you to receive the result of the goal. Through the
DerefMuttrait you can use theoneshot::ReceiverAPI to await the final result. Note that it can only be received once. - Service
Handle - Manage the lifecycle of an
rcl_service_t, including managing its dependencies onrcl_node_tandrcl_context_tby ensuring that these dependencies are dropped after thercl_service_t. - Service
Info - Information about an incoming service request.
- Service
Options ServiceOptions are used by [Node::create_service][1] to initialize a [Service`] provider.- Service
State - The inner state of a
Service. - Spin
Conditions - A bundle of conditions that tell the
ExecutorRuntimehow long to keep spinning. This combines conditions that users specify withSpinOptionsand standard conditions that are set by theExecutor. - Spin
Options - A bundle of optional conditions that a user may want to impose on how long an executor spins for.
- Status
Client - This struct allows you to receive every status update experienced by a goal.
- Status
Watcher - This struct allows you to monitor the status of the goal. Through the
DerefMuttrait you can use thewatch::ReceiverAPI to check the latest status and monitor changes. - Subscription
Options SubscriptionOptionsare used byNode::create_subscriptionto initialize aSubscription.- Subscription
State - The inner state of a
Subscription. - Terminated
Goal - 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.
- Timer
Options - Options for creating a
Timer. - Timer
State - The inner state of a
Timer. - Topic
Endpoint Info - Contains topic endpoint information
- WaitSet
- A struct for waiting on subscriptions and other waitable entities to become ready.
- Wait
SetRun Conditions - These are the conditions used by the
WaitSetRunnerto determine when it needs to halt. - Wait
SetRunner - 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.
- Waitable
Count - Count the number of rcl primitives in the wait set.
- Waitable
Lifecycle - 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.
- Worker
Options - Options used while creating a new
Worker. - Worker
State - The inner state of a
Worker.
Enums§
- Activity
Listener Callback - Enum for the different types of callbacks that a listener may have
- AnyClient
Output Sender - Can send any kind of response for a client call.
- AnyService
Callback - An enum capturing the various possible function signatures for service callbacks.
- AnySubscription
Callback - An enum capturing the various possible function signatures for subscription callbacks.
- AnyTimer
Callback - A callback that can be triggered when a timer elapses.
- Begin
Accepted Goal - 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.
- Cancel
Response Code - The response returned by an
ActionServer’s cancel callback when a goal is requested to be cancelled. - Clock
Type - Enum to describe clock type. Redefined for readability and to eliminate the uninitialized case
from the
rcl_clock_type_tenum in the binding. - Declaration
Error - Error that can be generated when doing operations on parameters.
- Goal
Event - Any of the possible update events that can happen for a goal.
- Goal
Status Code - Values defined by
action_msgs/msg/GoalStatus - Inner
Guard Condition Handle - 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
- Logger
Name - This is used to borrow a logger name which might be validated (e.g. came
from a
Loggerstruct) 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. - Node
Service Callback - An enum capturing the various possible function signatures for service callbacks.
- Node
Subscription Callback - An enum capturing the various possible function signatures for subscription callbacks that can be used with the async worker.
- Parameter
Kind - Describes the parameter’s type. Similar to
ParameterValuebut also includes aDynamicvariant for dynamic parameters. - Parameter
Value - A parameter value.
- Parameter
Value Error - Describes errors that can be generated when trying to set a parameter’s value.
- QoSDurability
Policy - The
DURABILITYDDS QoS policy. - QoSDuration
- A duration that can take two special values: System default and infinite.
- QoSHistory
Policy - The
HISTORYDDS QoS policy. - QoSLiveliness
Policy - The
LIVELINESSDDS QoS policy. - QoSReliability
Policy - The
RELIABILITYDDS QoS policy. - RclPrimitive
Handle - Used by the wait set to obtain the handle of a primitive.
- RclPrimitive
Kind - Enum to describe the kind of an executable.
- RclReturn
Code - Return codes of
rclfunctions. - Rclrs
Error - The main error type.
- Ready
Kind - Describe the way in which a waitable is ready.
- RmwParameter
Conversion Error - An error that occured when trying to convert a parameter from an
rcl_interfaces::msg::ParameterValue - Throttle
Clock - This parameter can specify a type of clock for a logger to use when throttling.
- Timer
Clock - This parameter can specify a type of clock for a timer to use
- Worker
Service Callback - An enum capturing the various possible function signatures for service
callbacks that can be used by a
Worker. - Worker
Subscription Callback - 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_defaultfrom thercl_actionpackage. - QOS_
PROFILE_ CLOCK - Equivalent to
ClockQosfrom therclcpppackage. Same as sensor data but with a history depth of 1 - QOS_
PROFILE_ DEFAULT - Equivalent to
rmw_qos_profile_defaultfrom thermwpackage. - QOS_
PROFILE_ PARAMETERS - Equivalent to
rmw_qos_profile_parametersfrom thermwpackage. - QOS_
PROFILE_ PARAMETER_ EVENTS - Equivalent to
rmw_qos_profile_parameter_eventsfrom thermwpackage. - QOS_
PROFILE_ SENSOR_ DATA - Equivalent to
rmw_qos_profile_sensor_datafrom thermwpackage. - QOS_
PROFILE_ SERVICES_ DEFAULT - Equivalent to
rmw_qos_profile_services_defaultfrom thermwpackage. - QOS_
PROFILE_ SYSTEM_ DEFAULT - Equivalent to
rmw_qos_profile_system_defaultfrom thermwpackage.
Traits§
- ActionIDL
- Trait for actions.
- Client
Async Callback - A trait to deduce async callbacks of service clients.
- Client
Callback - A trait to deduce regular callbacks of service clients.
- Client
Output - 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
RequestIdorServiceInfometadata. - Create
Basic Executor - This trait allows
Contextto create a basic executor. - Executor
Channel - This trait defines the interface for passing new items into an executor to run.
- Executor
Runtime - This trait defines the interface for having an executor run.
- Into
Action Client Options - Trait to implicitly convert a compatible object into
ActionClientOptions. - Into
Action Server Options - Trait to implicitly convert a compatible object into
ActionServerOptions. - Into
Async Service Callback - A trait for async callbacks of services.
- Into
Async Subscription Callback - A trait for async callbacks of subscriptions.
- Into
Node Options - This trait helps to build
NodeOptionswhich can be passed intoExecutor::create_node. - Into
Node Service Callback - A trait to deduce regular callbacks of services.
- Into
Node Subscription Callback - A trait for regular callbacks of subscriptions.
- Into
Node Timer Oneshot Callback - This trait is used to create timer callbacks for one-shot timers in a Node.
- Into
Node Timer Repeating Callback - This trait is used to create timer callbacks for repeating timers in a Node.
- Into
Primitive Options - Trait to implicitly convert a compatible object into
PrimitiveOptions. - Into
Timer Options - Trait to implicitly convert a suitable object into
TimerOptions. - Into
Worker Service Callback - A trait used to deduce callbacks for services that run on a worker.
- Into
Worker Subscription Callback - A trait for callbacks of subscriptions that run on a worker.
- Into
Worker Timer Oneshot Callback - This trait is used to create timer callbacks for one-shot timers in a Worker.
- Into
Worker Timer Repeating Callback - This trait is used to create timer callbacks for repeating timers in a Worker.
- Message
Cow - Convenience trait for
PublisherState::publish. - MessageIDL
- Trait for types that can be used in a
rclrs::Subscriptionand arclrs::Publisher. - Parameter
Variant - A trait that describes a value that can be converted into a parameter.
- RclPrimitive
- This provides the public API for executing a waitable item.
- Rclrs
Error Filter - A helper trait to disregard timeouts as not an error.
- RmwMessageIDL
- Trait for RMW-native messages.
- ServiceIDL
- Trait for services.
- Take
Failed AsNone - A helper trait to handle common error handling flows
- ToLog
Params - Methods for defining the behavior of a logging instance.
- Work
Scope - 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.
- Worker
Channel - 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§
- Action
Client - Main class responsible for sending goals to a ROS action server.
- Action
Server - 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
NodeStateto find out what methods you can call on aNode. - Payload
Task - 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.
- Topic
Names AndTypes - Stores a list of types associated with each topic.
- Weak
Activity Listener - 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.
- Worker
Service - Provide a
Servicethat runs on aWorker. - Worker
Subscription - A
Subscriptionthat runs on aWorker. - Worker
Timer - A
Timerthat runs on aWorker. - rmw_
request_ id_ t