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§

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
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.
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.
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.
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.
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.
SubscriptionOptions
SubscriptionOptions are used by Node::create_subscription to initialize a Subscription.
SubscriptionState
The inner state of a Subscription.
Time
Struct that represents time.
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.
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.
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.
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.
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_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§

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.
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.
IntoPrimitiveOptions
Trait to implicitly convert a compatible object into PrimitiveOptions.
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.
MessageCow
Convenience trait for PublisherState::publish.
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.
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§

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.
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.
rmw_request_id_t