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§
- Activity
Listener ActivityListener
is used to watch the activity of the primitives of aWorker
.- Available
Values - This struct is given to the discriminator function of the
ParameterBuilder
so 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
- Client
Options ClientOptions
are used byNode::create_client
to initialize aClient
for 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::RosTime
is constructed - Context
- Shared state between nodes and similar entities.
- 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
ExecutorCommands
and passed to theExecutorRuntime
to create a new worker. Downstream users of rclrs should not be using this class unless you are implementing your ownExecutorRuntime
. - 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
ToLogParams
to 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.
- 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 PrimitiveOptions
are 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 PublisherOptions
are used byNodeState::create_publisher
to 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.
- Service
Handle - Manage the lifecycle of an
rcl_service_t
, including managing its dependencies onrcl_node_t
andrcl_context_t
by 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
ExecutorRuntime
how long to keep spinning. This combines conditions that users specify withSpinOptions
and 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.
- Subscription
Options SubscriptionOptions
are used byNode::create_subscription
to initialize aSubscription
.- Subscription
State - The inner state of a
Subscription
. - Time
- Struct that represents time.
- 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
WaitSetRunner
to 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.
- Clock
Type - Enum to describe clock type. Redefined for readability and to eliminate the uninitialized case
from the
rcl_clock_type_t
enum in the binding. - Declaration
Error - Error that can be generated when doing operations on parameters.
- 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
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. - 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
ParameterValue
but also includes aDynamic
variant 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
DURABILITY
DDS QoS policy. - QoSDuration
- A duration that can take two special values: System default and infinite.
- QoSHistory
Policy - The
HISTORY
DDS QoS policy. - QoSLiveliness
Policy - The
LIVELINESS
DDS QoS policy. - QoSReliability
Policy - The
RELIABILITY
DDS 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
rcl
functions. - Rclrs
Error - The main error type.
- 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.
- 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_ CLOCK - Equivalent to
ClockQos
from therclcpp
package. Same as sensor data but with a history depth of 1 - QOS_
PROFILE_ DEFAULT - Equivalent to
rmw_qos_profile_default
from thermw
package. - QOS_
PROFILE_ PARAMETERS - Equivalent to
rmw_qos_profile_parameters
from thermw
package. - QOS_
PROFILE_ PARAMETER_ EVENTS - Equivalent to
rmw_qos_profile_parameter_events
from thermw
package. - QOS_
PROFILE_ SENSOR_ DATA - Equivalent to
rmw_qos_profile_sensor_data
from thermw
package. - QOS_
PROFILE_ SERVICES_ DEFAULT - Equivalent to
rmw_qos_profile_services_default
from thermw
package. - QOS_
PROFILE_ SYSTEM_ DEFAULT - Equivalent to
rmw_qos_profile_system_default
from thermw
package.
Traits§
- 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
RequestId
orServiceInfo
metadata. - Create
Basic Executor - This trait allows
Context
to 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
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
NodeOptions
which 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
Primitive Options - Trait to implicitly convert a compatible object into
PrimitiveOptions
. - 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.
- Message
Cow - Convenience trait for
PublisherState::publish
. - 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.
- 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§
- 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 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
. - 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
Service
that runs on aWorker
. - Worker
Subscription - A
Subscription
that runs on aWorker
. - rmw_
request_ id_ t