Skip to main content

Crate nros

Crate nros 

Source
Expand description

§nros

A lightweight ROS 2 client library for embedded systems.

This crate provides a unified API for building ROS 2 nodes in Rust, with support for no_std environments and embedded targets.

§Features

  • no_std compatible: Works on bare-metal and RTOS targets
  • Zero-copy where possible: Minimizes memory allocations
  • Type-safe: Compile-time verification of message types
  • ROS 2 compatible: Interoperates with standard ROS 2 nodes via rmw_zenoh

§Quick Start

use nros::prelude::*;
use std_msgs::msg::Int32;

let config = ExecutorConfig::from_env().node_name("my_node");
let mut executor = Executor::open(&config)?;

let node = executor.node_builder("my_node").build()?;
let publisher = executor.node_mut(node).create_publisher::<Int32>("/my_topic")?;
publisher.publish(&Int32 { data: 42 })?;

executor.node_mut(node).create_subscription::<Int32, _>("/topic", |msg: &Int32| {
    println!("Received: {}", msg.data);
})?;

executor.spin_blocking(SpinOptions::default());

§Executor Sizing

The executor’s static memory layout is controlled via environment variables at build time:

  • NROS_EXECUTOR_MAX_CBS (default 4) — maximum number of registered callbacks (subscriptions + timers + services + guard conditions).
  • NROS_EXECUTOR_ARENA_SIZE (default 4096) — byte budget for storing callback closures inline.

For messages larger than the default 1024-byte receive buffer, size the subscription via the builder’s .rx_buffer::<N>() knob (e.g. node_mut(id).subscription(t).typed::<M>().rx_buffer::<4096>().build(cb)).

§Transport Backends

Phase 248 C5c — nros is RMW- and platform-AGNOSTIC. It carries only the rmw-cffi vtable; the concrete backend (zenoh / xrce / cyclonedds) enters the link graph via the board crate (embedded), the board-less app’s own nros-rmw-* dep (native), or the nros-c/nros-cpp staticlib root (D3), and self-registers through the RMW_INIT_ENTRIES walker at Executor::open. The concrete session type is resolved automatically; advanced users can access it via nros::internals::RmwSession.

§Crate Features

nros exposes only FUNCTIONAL features — std/alloc, the rmw-cffi vtable, lending, bridge/config, param-services, lifecycle-services, safety-e2e, stream, ffi-sync, and the ROS edition (ros-humble/ros-iron). There are NO platform-* or concrete rmw-* selector features (Phase 248 C7). Platform + RMW are selected by the board / staticlib root via dependencies, not nros features. The zephyr_component_main! entry macro is gated only on rmw-cffi (it’s framework entry codegen, like nros::main!), not a platform feature.

ROS version (select one):

  • ros-humble - ROS 2 Humble
  • ros-iron - ROS 2 Iron

Other:

  • std (default) - Enable standard library support
  • alloc - Enable heap allocation without full std

§Further Reading

  • guide — tutorials: getting started, services, configuration, ROS 2 interop, and troubleshooting
  • Message Generation — codegen reference (all options, output structure, bundled interfaces)
  • Environment Variables — complete buffer tuning reference
  • ROS 2 Interop — protocol details (key expressions, liveliness, attachments)
  • Examples — working examples by platform (native, QEMU, ESP32, Zephyr)

Re-exports§

pub use init::Context;
pub use init::ContextSource;
pub use init::InitError;
pub use init::init;
pub use init::init_with_args;
pub use init::init_with_launch;
pub use init::init_with_launch_auto;
pub use node::NodeExecutorRuntime;
pub use node::ActionExecutor;
pub use node::Callback;
pub use node::CallbackCtx;
pub use node::CallbackEffects;
pub use node::ClientDispatch;
pub use node::DeclaredNode;
pub use node::DeclaredNodeRuntime;
pub use node::ExecutableNode;
pub use node::MISSING_NODE_EXPORT_ERROR;
pub use node::Node;
pub use node::NodeActionClient;
pub use node::NodeActionServer;
pub use node::NodeContext;
pub use node::NodeDeclError;
pub use node::NodeOptions;
pub use node::NodeParameter;
pub use node::NodePublisher;
pub use node::NodeResult;
pub use node::NodeRuntime;
pub use node::NodeRuntimeAdapter;
pub use node::NodeServiceClient;
pub use node::NodeServiceServer;
pub use node::NodeSubscription;
pub use node::NodeTimer;
pub use node::PublisherResolver;
pub use node::RuntimeNodeRecord;
pub use node::TickCtx;
pub use node::record_node_metadata;
pub use node::register_node;
pub use node_metadata::SourceMetadataExport;
pub use node_metadata::CallbackEffectKind;
pub use node_metadata::CallbackEffectMetadata;
pub use node_metadata::EntityKind;
pub use node_metadata::EntityMetadata;
pub use node_metadata::MetadataRecorder;
pub use node_metadata::MetadataString;
pub use node_metadata::NodeMetadata;
pub use node_metadata::NodeMetadataError;
pub use node_metadata::ParameterDefault;
pub use node_metadata::SourceLocationMetadata;
pub use node_metadata::SourceNameKind;
pub use dispatch_tag::ActionTag;
pub use dispatch_tag::ServiceTag;
pub use dispatch_tag::SubscriptionTag;
pub use node_runtime::ExecutorError;
pub use node_runtime::ExecutorNodeRuntime;
pub use node_runtime::RegisteredNode;
pub use node_runtime::install_node_typed;
pub use nros_core::heapless;

Modules§

cdr
CDR encapsulation constants and helpers for FFI layers that handle raw CDR bytes (e.g. nros-c, nros-cpp action and service paths).
derive
Derive macros for message types
dispatch_tag
Phase 216.A.4 — tag types Node authors hold on Self::State to match against incoming Callback in ExecutableNode::on_callback.
guide
Tutorials and guides for using nros.
init
Phase 212.L.5 — top-level init API.
internals
Backend-specific internal types.
lifecycle
Re-export of the full lifecycle module so examples can reach LifecycleCallbackSlot, LifecyclePollingNodeCtx, etc.
node
Rust component API shared by metadata discovery and generated runtimes.
node_metadata
Node source metadata recorded without opening middleware.
node_runtime
Phase 212.M.5.a.2 — executor-backed component runtime.
prelude
Prelude module for convenient imports
qos
Phase 108.B — standard ROS-2-equivalent QoS profiles. Match upstream rmw_qos_profile_default etc. field-by-field. Backends validate against these synchronously at create time; no silent downgrade.
sizes
Compile-time opaque storage sizes for FFI consumers.

Macros§

declarative_component
Emit a no-op ExecutableNode impl for a declarative-only component (W.5.1). The generated runtime calls on_callback unconditionally, so a component instantiated into a generated binary must impl ExecutableNode; components without callback bodies use this to satisfy that contract:
main
One-line fn main() for Entry pkgs. Four forms:
node
Export a Rust type implementing nros::Node as the package node.
zephyr_component_main
Define Zephyr’s rust_main for a self-bringup Rust component package.

Structs§

ActionClient
Typed action client handle.
ActionClientCore
Type-agnostic action client core handling the raw-bytes protocol.
ActionServer
Typed action server with goal state management.
ActionServerCore
Type-agnostic action server core handling the raw-bytes protocol.
ActionServerHandle
Handle to an action server registered in the executor’s arena.
ActionServerRawHandle
Handle to a raw (untyped) action server registered in the executor’s arena.
ActiveGoal
Active goal tracking for action server.
CdrReader
CDR reader for deserialization
CdrWriter
CDR writer for serialization.
Clock
A clock for querying time
CompletedGoal
Completed goal with result.
Duration
ROS Duration representation
EmbeddedPublisher
Typed publisher handle.
EmbeddedRawPublisher
Typeless publisher handle. Use when the wire format is not ROS CDR (e.g. PX4 uORB raw POD bytes, custom binary protocols).
EmbeddedServiceClient
Typed service client handle with internal buffers.
EmbeddedServiceServer
Typed service server handle with internal buffers.
Executor
ExecutorConfig
Configuration for opening an embedded executor session.
FeedbackStream
A stream of feedback messages from an action server.
FileParamStore
Hosted file-backed parameter store (the only built-in backend today). Hosted ParamStore persisting scalar parameter overrides to a text file: one name<TAB>kind<TAB>value line per scalar parameter (kind ∈ b/i/d/s). Arrays and NotSet are not persisted; names or values containing a tab or newline are skipped (they would corrupt the line format). Writes are atomic (temp file + rename).
GoalFeedbackStream
A goal-filtered feedback stream.
GoalId
Unique identifier for a goal
GoalInfo
Information about a goal
GoalStatusStamped
Goal status with associated goal info
GuardConditionHandle
Handle for triggering a guard condition from outside the executor.
HandleId
Opaque handle identifier returned by registration methods.
HandleSet
A set of handle IDs, represented as a bitset.
LifecyclePollingNode
Standalone lifecycle state machine for no_std environments.
Logger
A logger associated with a ROS node
MandatoryParameter
A parameter that must always have a value
MessageInfo
Metadata about a received message
NodeConfig
Node configuration
NodeHandle
Backend-agnostic node — borrows the session to create typed entities.
NullParamStore
No-op store: the default when persistence is disabled.
OptUs
Optional time field with a sentinel 0 for “absent”.
OptionalParameter
A parameter that may or may not have a value
Parameter
A named parameter with value and optional descriptor
ParameterBuilder
Builder for declaring a typed parameter
ParameterDescriptor
Parameter descriptor containing metadata
ParameterServer
Parameter server with static storage
Promise
A pending reply from a non-blocking service or action call.
PublishLoan
Writable loan into a EmbeddedRawPublisher’s slot.
PublisherHandle
Handle to a publisher
PublisherOptions
Options for creating a publisher
QosOverride
Phase 211.H — one per-topic QoS override, lowered from a ROS 2 qos_overrides.<topic>.<role>.<policy> launch parameter by the planner and baked into a &'static [QosOverride] table by the entry codegen. The node folds the matching entries into the entity’s QosSettings at create_publisher / create_subscription time (setup-time, single linear scan, no alloc), before the backend-compat validate_against — so an override the active RMW can’t honour still errors loudly, never a silent downgrade.
QosPolicyMask
Bitmask of QoS policies a backend can honour. See Session::supported_qos_policies.
QosSettings
Full DDS-shaped QoS profile. Matches the field set of upstream rmw_qos_profile_t.
RawActionClientSpec
Inputs for raw (untyped) action-client registration.
RawActionServerSpec
Inputs for raw (untyped) action-server registration.
RawActiveGoal
Goal tracked by the core — only GoalId + status, no typed data.
RawMessageInfo
Raw-subscription message info: MessageInfo metadata plus the sample’s wire-level attachment bytes, borrowed for the callback scope.
RawSubscription
Typeless subscription handle. Counterpart of EmbeddedRawPublisher.
ReadOnlyParameter
A parameter whose value cannot be changed after declaration
ReadinessSnapshot
Snapshot of handle readiness at the start of a spin iteration.
RecvView
Read-only view into a RawSubscription’s receive buffer.
RmwConfig
Middleware-agnostic session configuration.
SchedContext
First-class scheduling capability — one SC per scheduling concern, shared by every callback that should run under the same budget / period / deadline / class.
SchedContextId
Identifier for a SchedContext registered with an Executor. 110.B.b adds storage [Option<SchedContext>; MAX_SC]; this index addresses into that array.
ServiceClient
Service client handle
ServiceInfo
Service information for service client/server
ServiceRequest
Service request from a client
ServiceServer
Service server handle
SessionHandle
Phase 228.E — an opaque, Send handle to an Executor’s RMW session.
SessionSpec
Phase 128.F.1 — per-backend session declaration for Executor::open_multi. Each spec names an RMW backend (must match one a backend registered under via nros_rmw_cffi_register_named / the RMW_INIT_ENTRIES linker section) and the locator + domain id to open against it.
SpinOnceResult
Result of a single spin iteration
SpinOptions
Options controlling blocking spin behavior.
SpinPeriodPollingResult
Result from a single period of polling execution (no_std compatible).
SpinPeriodResult
Result from a single period with wall-clock measurement (std only).
StandaloneNode
ROS 2 Node for embedded systems
SubscriberHandle
Handle to a subscriber
SubscriberOptions
Options for creating a subscriber
Subscription
Typed subscription handle with internal receive buffer.
Time
ROS Time representation
TimeTriggeredSchedule
Fixed-size, no_std-friendly cyclic schedule. N is the declared maximum window count; window_count is the active length (callers can build the array up to N and set window_count to the actual size used).
TimeTriggeredWindow
One slot in a time-triggered schedule.
TimerDuration
Duration type for timer periods
TimerHandle
A handle to a timer stored in a node
TimerState
Internal timer state
TopicInfo
Topic information for pub/sub
TransportConfig
Transport session configuration

Enums§

CancelResponse
Cancel goal response codes
ClockType
Type of clock to use for time queries
DeadlinePolicy
How an EDF deadline is interpreted relative to a callback firing.
DeserError
Deserialization error.
DispatchStrategy
How a Node expects its callbacks to fire.
ExecutorSemantics
Data communication semantics for the executor.
GoalResponse
Goal accept/reject response codes
GoalStatus
Goal status states
InvocationMode
Per-callback invocation mode.
LifecycleError
Error type for lifecycle transitions.
LifecycleState
Lifecycle state (REP-2002)
LifecycleTransition
Lifecycle transition (REP-2002)
LoanError
Error type for EmbeddedRawPublisher::try_loan.
NodeError
Error type for generic embedded node operations.
ParamStoreError
Error from a ParamStore backend.
ParameterError
Error type for typed parameter operations
ParameterType
ROS 2 parameter types
ParameterValue
Parameter value container
Priority
Criticality bucket for SchedContext. Phase 110.C uses this to pick which BucketedFifoSet / BucketedEdfSet slot a callback dispatches through; later phases (110.D) map it to OS priority.
QosDurabilityPolicy
QoS durability policy
QosHistoryPolicy
QoS history policy
QosLivelinessPolicy
QoS liveliness policy. Matches DDS LIVELINESS semantics.
QosOverrideRole
Phase 211.H — which side of a topic a QosOverride targets. Mirrors the <role> segment of a ROS 2 qos_overrides.<topic>.<role>.<policy> launch parameter.
QosOverrideValue
Phase 211.H — a single policy value a QosOverride sets. A typed enum (not a string) so the codegen that bakes these from the plan catches an unknown policy / mistyped value at generation time rather than silently no-op-ing at runtime.
QosReliabilityPolicy
QoS reliability policy
SchedClass
Scheduling class — picks the runtime queue + selection policy for the contained callbacks.
SerError
Serialization error.
SessionMode
Session mode
SetParameterResult
Result of setting a parameter
TimeTriggeredScheduleError
Validation errors for a TimeTriggeredSchedule.
TimerMode
Timer mode (repeating, one-shot, or inert)
TransitionResult
Result of a lifecycle transition callback.
TransportError
Transport error types.
Trigger
Executor-level trigger condition.

Constants§

PUBLISHER_GID_SIZE
Size of the publisher Global Identifier (GID)

Traits§

BoardConfig
Universal board configuration accessors.
BoardTransportConfig
Phase 173.5 — mutable transport knobs the orchestration generator writes into a board Config from nros.toml [[transport]] (the NanoRosOwned net-stack path: the board owns smoltcp/lwIP/NetX, so the IP / baud value lands in the board Config rather than an RTOS config fragment).
Deserialize
Trait for types that can be deserialized from CDR format
ParamStore
Backend that persists runtime parameter overrides across restarts (172.H).
ParameterVariant
Trait for types that can be used as typed parameters
Publisher
Publisher trait for sending messages.
Rmw
Factory trait for compile-time middleware selection.
RosAction
Trait for ROS 2 action types
RosMessage
Trait for ROS message types
RosService
Trait for ROS service types
Serialize
Trait for types that can be serialized to CDR format
ServiceClientTrait
Service client trait for sending requests.
ServiceServerTrait
Service server trait for handling requests.
Session
Transport session trait — the per-process anchor an RMW backend gives to the executor.
Subscriber
Subscriber trait for receiving messages.
Transport
Transport backend trait (legacy).

Type Aliases§

LifecycleCallbackFn
Lifecycle callback function pointer (no_std compatible).
RawCancelCallback
Raw action cancel callback.
RawGoalCallback
Raw action goal callback that receives CDR bytes without deserialization.
RawServiceCallback
Raw service callback that receives and produces CDR bytes.
RawSubscriptionCallback
Raw subscription callback that receives CDR bytes without deserialization.
TimerCallbackFn
Timer callback as a bare function pointer (no_std, no heap required).