Periodic Framework — Rust API
Write a function, name its period and its topics, and TAIL OS runs it on time.
Read this first
- What you need: the Raspberry Pi 3 board support package (BSP) with the TAIL OS SDK, and a Rust function to run.
- What you get: a node that runs on a fixed period, reads and publishes topics, and needs no
main, thread, sleep or retry loop. - Time to a first node: one file of 24 lines, one line in
tail.build, and one build of the disk image.
This page is the Rust API. The Python page describes the Python API.
Contents
- Quick start
- Your first nodes
#[periodic]keys- Node shapes
- Several inputs
Cycle<T>- Run-time parameters
- Actions
- The release journal
- Recording and replay
- Start-up
OverrunPolicy- Topics and lanes
- Raw ends
- Durations
- Payloads
- Frames and transforms
NodeError- Migrating a node
Executor- Glossary
A node is a function that TAIL OS runs once every period. Each run is a release. You would otherwise write a thread with a timer loop: read the clock, do the work, sleep for the rest of the period, correct the drift, repeat. The framework runs that loop for you.
A node has inputs, the topics it reads, and outputs, the topics it publishes. You declare each one on the parameter that receives it. Each input has its own freshness bound.
Quick start
counter is one file and one node. It runs every 100 ms, counts its releases, and
publishes the count:
// app/counter/src/main.rs
use periodic::{periodic, KernelLane, Out, Topic};
use wire_plain::WirePlain;
/// What the counter publishes on every release.
#[derive(Clone, Copy, Debug, WirePlain)]
#[repr(C)]
pub struct Releases {
/// Releases run so far, this one included.
pub count: u64,
/// When this release ran [ns since boot].
pub stamp_ns: u64,
}
/// The counter's releases, published by the counter alone.
const COUNTER_RELEASES: Topic<Releases, KernelLane> = Topic::new("counter/releases");
#[periodic(every = "100ms", on_overrun = Skip, init = 0u64)]
fn counter(count: &mut u64, #[publish(COUNTER_RELEASES)] releases: Out<Releases>) {
*count += 1;
releases.publish(Releases { count: *count, stamp_ns: periodic::now() });
}
init = 0u64builds the node's state once, before the first release.count: &mut u64is that state. It is the one parameter with no marker, and the body gets it by reference on every release.releases: Out<Releases>is the node's output. The value the body hands toreleases.publish(..)is published oncounter/releaseswhen the body returns.Releasesis a payload, the type a topic carries.#[derive(WirePlain)]proves that it can cross to another process unchanged.
Build, run and check it
- Save the file as
app/counter/src/main.rsin the BSP. - Add
/usr/bin/counter=counterto the[disk]section of the BSP'stail.build. - Run
./make-disk.sh. It builds the program against the SDK and puts it in/usr/binon the image (Installing TAIL OS on Raspberry Pi 3).
You write no Cargo.toml and no main: the attribute writes the main.
On the booted image, start the node in the background and look at it:
tsh> counter &
tsh> node list
counter pid 5 counter
tsh> topic echo -n 3 --as "count:u64 stamp_ns:u64" counter/releases
# counter/releases: kernel lane, --as, 16 B, layout 0x79e81151
count=1 stamp_ns=161062928
count=2 stamp_ns=260987952
count=3 stamp_ns=360967504
node list shows each running node: its name, its process and its program. Your pid and
counts differ. topic echo reads the topic as any other program would. --as names the
payload's fields, because Releases is not a standard payload that topic echo decodes on
its own. Each count is one more release. The
shell tools page describes both tools.
Your first nodes
Three nodes share two topics. A topic is a named channel that carries one payload type. The lane is how a topic's messages travel from publisher to readers.
lidar publishes sensor/range, which brake and drive read; drive also reads cmd/velocity
from a pad or planner not written here.
The example is four files in the BSP's app/ directory:
| File | Holds |
|---|---|
app/robot_topics.rs |
the topics: each one's name, payload and lane |
app/lidar/src/main.rs |
a node that publishes sensor/range |
app/brake/src/main.rs |
a node that reads sensor/range |
app/drive/src/main.rs |
a node that reads sensor/range and cmd/velocity |
The topics, defined once
// app/robot_topics.rs
// Each program uses some of these definitions and not others.
#![allow(dead_code)]
use periodic::{KernelLane, SafeLane, Topic};
pub use robot_messages::{geometry::Twist, sensor::Range};
/// The front range sensor's readings, in the `range_front` frame: one writer, so the safe
/// lane.
pub const SENSOR_RANGE: Topic<Range, SafeLane> = Topic::new("sensor/range");
/// Velocity commands, in the `base_link` frame: a pad and a planner both write them, so
/// the kernel lane.
pub const CMD_VELOCITY: Topic<Twist, KernelLane> = Topic::new("cmd/velocity");
Each constant states three facts: the topic's name, its payload and its lane. Every program opens the topic from that constant. So no program states a fact twice, and two programs that import the same definition cannot disagree. The topic's doc comment names the frame its numbers are in.
Range and Twist are standard payloads from the robot_messages crate. Python's
tail_messages is generated from the same definitions, so a Python node at the other end
holds the same type. For a payload of your own, write a struct with
#[derive(WirePlain)]; see Payloads. No program here writes unsafe.
A publisher
lidar reads a sensor every 20 ms and publishes the reading, stamped with the time it
was taken. This is the whole program:
// app/lidar/src/main.rs
#[path = "../../robot_topics.rs"]
mod robot_topics;
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
range.publish(Range {
stamp_ns: periodic::monotonic_ns(),
radiation_type: Range::INFRARED,
field_of_view: 0.05,
min_range: 0.02,
max_range: 8.0,
range: 4.2,
variance: 0.0,
});
}
Range::INFRARED is one of the payload's named values. Pick the stamp clock by what the
node does:
| The node | Stamps with |
|---|---|
reads hardware, like lidar |
periodic::monotonic_ns(): nanoseconds since boot, read as the body runs, the instant it read the device |
| decides from its inputs | periodic::now(): the current release's one clock reading in nanoseconds, the instant every input was judged against; 0 before the first release |
| passes an input on | the input's own stamp_ns |
A replay of the node hands the body the recorded now(), so a stamp from now() replays
exactly. No recording holds monotonic_ns(). See Recording and replay.
A subscriber
brake reads sensor/range every 20 ms and brakes on it:
// app/brake/src/main.rs
#[path = "../../robot_topics.rs"]
mod robot_topics;
use periodic::{periodic, Cycle};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn brake(#[subscribe(SENSOR_RANGE, stale_after = "70ms")] lidar: Cycle<Range>) {
match lidar.get() {
Some(reading) => brake_for(reading.range),
None => brake_for(0.0), // absent or stale
}
}
// Your actuator call goes here: brake for an obstacle `range` metres away, 0 meaning now.
fn brake_for(_range: f32) {}
stale_after says how old a reading may be before it counts as absent. When the sensor
goes quiet, get() returns None, so the fail-safe arm runs.
A node with two inputs
drive stops for obstacles. It reads a velocity command on the kernel lane and a range
reading on the safe lane, each with its own bound. It keeps a device handle between
releases:
// app/drive/src/main.rs
#[path = "../../robot_topics.rs"]
mod robot_topics;
use periodic::{periodic, Cycle};
use robot_topics::{Range, Twist, CMD_VELOCITY, SENSOR_RANGE};
/// The range inside which whatever is ahead is an obstacle [m].
const STOP_WITHIN: f32 = 0.3;
/// The motor driver, and the speed it was last given.
struct Motors {
speed: f64,
}
impl Motors {
/// The motors, at rest. Claim the device here.
fn attach() -> Self {
Motors { speed: 0.0 }
}
/// Drive at the commanded forward speed [m/s].
fn drive(&mut self, twist: &Twist) {
self.speed = twist.linear.x;
}
/// Stop, if moving.
fn stop(&mut self) {
if self.speed != 0.0 {
self.speed = 0.0;
}
}
}
#[periodic(every = "20ms", on_overrun = Skip, safety, init = Motors::attach())]
fn drive(
motors: &mut Motors,
#[subscribe(CMD_VELOCITY, stale_after = "310ms")] command: Cycle<Twist>,
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
) {
match (command.get(), range.get()) {
(Some(twist), Some(range)) if range.range > STOP_WITHIN => motors.drive(twist),
_ => motors.stop(), // no usable command, no usable range, or an obstacle
}
}
A command may be 310 ms old and still be used; a range reading only 70 ms. One match
arm covers every way either input can be missing.
Build and run
- Add
/usr/bin/lidar=lidar,/usr/bin/brake=brakeand/usr/bin/drive=driveto the[disk]section of the BSP'stail.build. - Run
./make-disk.sh. It builds eachapp/<name>/src/main.rsagainst the SDK'speriodiccrate and puts it in/usr/binon the image. See Installing TAIL OS on Raspberry Pi 3. - On the booted image, start the nodes in the background, in any order:
lidar &,brake &,drive &.
A program's name is at most 32 bytes. A longer name is left out of the image's program table, so the program never starts and leaves no record.
No program names another. The framework opens each topic and waits for its publisher
(see Start-up). Nothing here publishes cmd/velocity, so drive runs and
stays stopped: that input is absent, and absent takes the _ arm.
periodic, wire_plain and robot_messages are SDK libraries, so a program needs only
a use for each. Two lines exist only because the BSP's one-file programs share a file:
| Line | Why |
|---|---|
#[path = "../../robot_topics.rs"] mod robot_topics; |
compiles the shared definitions file into this program |
#![allow(dead_code)], in the definitions file |
stops a warning in each program that leaves a definition unused |
In a cargo workspace, the definitions are a library crate. Then
robot_topics/src/lib.rs needs no #![allow(dead_code)]. Each program lists periodic
and robot_topics in its Cargo.toml and starts at its use lines. A payload that a
Python program also reads lives in its own crate that depends on wire_plain alone. The
host generator that prints its Python definitions imports that crate, and it cannot import
a crate that depends on periodic.
The rest of this page shows each program from its use lines on, with its topics
imported from robot_topics.
Which examples the build checks
The build compiles the Quick start's counter and every file of Your first nodes, byte
for byte as shown, and runs counter on the emulated Raspberry Pi 3. The build also
checks every refusal under What the build refuses against the
text shown. Some short examples further down are variations written for this page and are
not compiled.
#[periodic] keys
The header states what is true of the whole node. Each input and each output is declared on its own parameter.
| Where | Key | Required |
|---|---|---|
| header | every = "<duration>" |
always |
| header | on_overrun = Skip | CatchUp | Fault |
always |
| header | init = <expr> |
exactly when the body takes a state |
| header | safety |
no |
| parameter | #[subscribe(TOPIC, stale_after = "<duration>")] |
once per input |
| parameter | #[publish(TOPIC)] |
once per output |
| parameter | #[param(default = .., range = .. ..= ..)] |
once per run-time parameter |
| parameter | #[serve(ACTION, lease = "<duration>")] |
at most once per node |
every: required
#[periodic(every = "20ms", on_overrun = Skip)]
The period: the time from one release to the next, written as a
duration. Releases fall on start + n * period, so they never drift.
on_overrun: required
#[periodic(every = "20ms", on_overrun = Skip)]
An overrun is a release whose body runs past the next release. on_overrun says
what happens then: Skip, CatchUp or Fault, written as the bare word. There is no
default, so a node without it does not compile. See OverrunPolicy.
#[publish(TOPIC)]: on a parameter
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
range.publish(Range { stamp_ns: periodic::monotonic_ns(), range: 4.2, ..Range::default() });
}
The parameter is one output: the topic the body publishes on.
- Its type is
Out<T>of the topic's payload. That isperiodic::Out<'_, T>with the lifetime left out. publishtakes a whole value and consumes the handle, so an output publishes at most once per release.- Nothing is sent at the call. Every value is published when the body ends, in the order the outputs are declared.
- A body that panics publishes nothing at all.
- An output the body does not publish on publishes nothing on that release. See Publishing on some releases.
A node has one output per #[publish] parameter, each on its own topic. A node returns
nothing: the output is the parameter, never the return value.
#[subscribe(TOPIC, stale_after = "..")]: on a parameter
#[periodic(every = "20ms", on_overrun = Skip)]
fn brake(#[subscribe(SENSOR_RANGE, stale_after = "70ms")] lidar: Cycle<Range>) {
brake_for(lidar.get().map_or(0.0, |reading| reading.range));
}
The parameter is one input: the topic, then stale_after, how old a reading may be
before this node reads it as absent.
- Its type is
Cycle<T>of the topic's payload.Cycle<Range>isperiodic::Cycle<'_, Range>with the lifetime left out. - Every input needs both parts. There is no default bound and no node-wide bound.
- A node has one input per
#[subscribe]parameter.
#[subscribe] is part of the #[periodic] declaration, which reads it and removes it. It
is not an item to import, so #[periodic::subscribe(..)] is refused.
init
use periodic::{periodic, Out};
use robot_topics::{Count, DIAG_COUNT};
/// Cycles this node has run. Built once by `init`, owned by the node for its whole life.
#[derive(Default)]
struct Cycles(u64);
#[periodic(every = "20ms", on_overrun = Skip, init = Cycles::default())]
fn counter(cycles: &mut Cycles, #[publish(DIAG_COUNT)] count: Out<Count>) {
cycles.0 += 1;
count.publish(Count { cycles: cycles.0 });
}
init builds the node's state once, before the framework opens any topic. The body takes
the state by reference: &mut S, or &S for a state it only reads. The state is the one
parameter with no marker, wherever it stands in the list.
The framework does not drop the state when it ends the node. A failed start and a Fault
stop both end in process::exit(1), so a Drop on Motors that stops the motors does not
run then. Do not rest a device's safe state on Drop.
safety
#[periodic(every = "20ms", on_overrun = Skip, safety, init = Motors::attach())]
safety is a bare flag. It says this node implements a safety function, like the drive
of your first nodes. Every topic the node declares, input or output,
must then be on a lane that may carry safety data. A topic on FastLane fails the build.
See What safety checks.
#[param(default = .., range = .. ..= ..)]: on a parameter
#[param(default = 42.0, range = 0.0..=200.0)] kp: f32,
A value the shell can change while the node runs. The body gets it by value on every release. See Run-time parameters.
#[serve(ACTION, lease = "..")]: on a parameter
#[serve(DRIVE_TO, lease = "100ms")] goal: &mut Goal<DriveTo, DriveProgress, DriveDone>,
The goal of an action the node serves, lent to the body on every release. A node serves
at most one action, and a node declared safety serves none. See Actions.
Keys as constants
use periodic::{periodic, Cycle};
use robot_topics::{Twist, CMD_VELOCITY};
/// The node's period, kept in a constant a test can read.
const PERIOD: &str = "20ms";
/// How long a command stays usable to this node.
const STALE_AFTER: &str = "310ms";
#[periodic(every = PERIOD, on_overrun = Skip)]
fn teleop(#[subscribe(CMD_VELOCITY, stale_after = STALE_AFTER)] command: Cycle<Twist>) {
set_speed(command.get().map_or(0.0, |twist| twist.linear.x));
}
// Your actuator call goes here: the forward speed [m/s].
fn set_speed(_forward: f64) {}
every and stale_after take expressions, so a test can assert on the same constant the
declaration uses.
What the build refuses
The build refuses each of these at the token you must change. The texts are the compiler's output, and the build checks each one.
| Written | The build says |
|---|---|
#[subscribe("sensor/range", stale_after = "70ms")] |
a topic is a typed definition, not a name. Define it once -- `const TOPIC: Topic<Range, SafeLane> = Topic::new("sensor/range");`, with its payload and its lane (`KernelLane`, `SafeLane` or `FastLane`) -- and name the constant here |
#[subscribe(SENSOR_RANGE)] |
input `range` must declare `stale_after = "<duration>"` after its topic: without it there is no answer to "is this data still usable", and the node would act on whatever it was last given |
stale_after = "100ms" in the header |
`stale_after` is written on each input, `#[subscribe(TOPIC, stale_after = "<duration>")]`; every input has its own and there is no node-wide default |
#[subscribe(&SENSOR_RANGE, ..)] |
a topic is named, not borrowed: write `SENSOR_RANGE` here, without the `&` |
lane = .. inside #[subscribe(..)] |
`lane` is not an input key: the lane belongs to the topic and is written in its definition, `Topic<Payload, KernelLane | SafeLane | FastLane>` |
#[periodic::subscribe(..)] on a parameter |
an input is marked `#[subscribe(..)]`, with no path in front: the marker is not an item of the `periodic` crate that could be imported or renamed, but a part of the `#[periodic]` declaration, which reads it and removes it |
| a parameter with no marker that is not a reference | `range` is not fed by anything: an input is declared on its parameter with `#[subscribe(TOPIC, stale_after = "<duration>")]`, an output with `#[publish(TOPIC)]`, a run-time parameter with `#[param(default = .., range = ..)]`; the one parameter with none of them is the node's state, which is taken by reference and built by `init = <expr>` |
#[param(default = 250.0, range = 0.0..=200.0)] kp: f32 |
`kp`'s default is outside its range, inside rustc's E0080 |
#[param(default = 300, range = 100..=1000)] on a node declared safety |
`stop_within_mm` is a parameter of a node declared `safety`; a safety function's configuration is part of its verified build: make it a `const` |
| two inputs that name one topic, through one constant or two | inputs `front` and `rear` name the same topic: a node reads a topic once, inside rustc's E0080 |
a parameter typed for another payload than its topic's, an input's Cycle<T> or an output's Out<T> |
rustc's E0308, at the parameter's type |
| two outputs that name one topic | outputs `command` and `twist` name the same topic: a node publishes a topic once, inside rustc's E0080 |
command.publish(a); command.publish(b); |
rustc's E0382, use of moved value: `command` : an output publishes once a release |
#[publish(CMD_VELOCITY)] command: &mut Out<Twist> |
`command` is an output, which the body is handed by value: write `command: Out<Twist>` |
fn lidar() -> Range |
`lidar` returns `Range`, and a node publishes through its outputs, not its return value. Declare one on a parameter, `#[publish(TOPIC)] output: Out<Range>`, write `output.publish(value)` where `lidar` returned the value, and remove `-> Range` |
publish = SENSOR_RANGE in the header |
the rewrite for that node, line by line: see Migrating a node |
#[cfg(..)] on a parameter range |
`range` is conditional, and a conditional input is not expressible: `#[periodic]` generates one `main` that opens every input this function declares, before the compiler has decided which parameters exist. Write each variant as a node function of its own, with its `#[cfg(..)]` above `#[periodic(..)]` |
#[serve(DRIVE_TO)] goal: &mut Goal<..> |
`goal` serves `DRIVE_TO` with no lease: write `#[serve(DRIVE_TO, lease = "<duration>")]`. A goal whose client has gone is stopped when its lease runs out, so the lease is what stops the robot, and it has no default |
#[serve(DRIVE_TO, lease = "100")] |
the lease of `goal` is not a duration: write digits and one of `ns`, `us`, `ms`, `s`, as `lease = "100ms"`, inside rustc's E0080 |
#[serve(..)] on a node declared safety |
`goal` serves an action, and this node is declared `safety`: a safety function takes no commands through an action's channel, which any process may write |
two arguments with #[serve] |
`second` serves a second action: a node serves one, which `goal` already does |
goal: Goal<..>, by value |
`goal` is the served goal, which the body is lent to act on: write `goal: &mut Goal<DriveTo, DriveProgress, DriveDone>` |
active.succeed(r); active.feedback(f) |
rustc's E0382, borrow of moved value: `active` : succeed ended the goal |
One node may name the same topic as an input and as an output. Each release then reads what an earlier release published.
Node shapes
A program holds one node, at the crate root. The attribute writes main for you.
Take the first row that matches.
| Your node | Shape |
|---|---|
| publishes, but only when it has something new | Publishing on some releases |
| publishes on more than one topic | Several outputs |
| reads and publishes | Pipe |
| keeps a value between releases | With state |
| needs a value that never changes after start-up | With a state it only reads |
| reads what it published on the release before | Reads what it published |
| only reads | Subscriber |
| only publishes | Publisher |
Publisher
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
range.publish(Range { stamp_ns: periodic::monotonic_ns(), range: 4.2, ..Range::default() });
}
The lidar node publishes one Range on sensor/range every 20 ms.
Publishing on some releases
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
if let Some(reading) = read_sensor_if_ready() {
range.publish(reading);
}
}
// Your driver call goes here: `None` while the sensor has nothing new.
fn read_sensor_if_ready() -> Option<Range> {
None
}
On a release where the body does not call publish, that output publishes nothing:
- The topic's sequence does not advance.
- Readers keep the previous value until their
stale_aftersays it is too old. - The release is not an overrun, and not a refused publish.
An Out that no path of the body uses is an unused_variables warning. Name it _range if that is what you mean.
A release that publishes nothing costs nothing on the stack. On SafeLane, the body builds the payload directly in the shared memory, so even a 64 KiB payload takes no stack. Limit: this holds only while the compiler inlines the body into the generated main; a body marked #[inline(never)] holds its payload on the stack. On KernelLane the framework always copies a publication into the topic, and a payload is at most 4 KiB.
Several outputs
use periodic::{periodic, Cycle, Out};
use robot_topics::{DriveState, Odometry, Twist, CMD_VELOCITY, DRIVE_STATE, ODOMETRY};
#[periodic(every = "20ms", on_overrun = Skip)]
fn drive(
#[subscribe(ODOMETRY, stale_after = "50ms")] odometry: Cycle<Odometry>,
#[publish(CMD_VELOCITY)] command: Out<Twist>,
#[publish(DRIVE_STATE)] state: Out<DriveState>,
) {
let Some(odometry) = odometry.get() else { return }; // both declined
command.publish(steer(odometry));
if odometry.moved() {
state.publish(DriveState { pose: odometry.pose, stopped: 0 });
}
} // published here: `command`, then `state` when it was handed a value
// Your control law goes here.
fn steer(_odometry: &Odometry) -> Twist {
Twist::default()
}
Each output is one parameter on one topic. The body publishes each one, or not, on its own.
publish sends nothing at the call. The framework publishes every output when the body returns, in the order the outputs are declared. A served action's status goes after all of them. So a release that stops halfway publishes nothing.
What happens in drive |
Result |
|---|---|
The body publishes state before command |
Both go out in declaration order: command, then state. |
The body panics after command.publish(..) |
Nothing goes out, on either topic. |
cmd/velocity's lane refuses 16 publishes in a row |
One ERROR record names cmd/velocity. state is still published. |
The node fails to start after it created cmd/velocity and drive/state |
One ERROR record gives the reason, then one names each output left without a writer, in order. |
A refusal on one output does not stop the others. The framework counts and reports it for that output alone (see NodeError).
Subscriber
use periodic::{periodic, Cycle};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn brake(#[subscribe(SENSOR_RANGE, stale_after = "70ms")] lidar: Cycle<Range>) {
brake_for(lidar.get().map_or(0.0, |reading| reading.range));
}
// Your actuator call goes here: brake for an obstacle `range` metres away, 0 meaning now.
fn brake_for(_range: f32) {}
The brake node reads sensor/range every 20 ms. With no usable reading, it brakes for an obstacle at 0 m.
Pipe: reads and publishes
use periodic::{periodic, Cycle, Out};
use robot_topics::{Distance, Range, ESTIMATE_DISTANCE, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn filter(
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] raw: Cycle<Range>,
#[publish(ESTIMATE_DISTANCE)] distance: Out<Distance>,
) {
distance.publish(Distance { metres: raw.get().map_or(0.0, |reading| reading.range) });
}
robot_topics defines Distance and ESTIMATE_DISTANCE the same way it defines Range and SENSOR_RANGE:
#[derive(Clone, Copy, WirePlain)]
#[repr(C)]
pub struct Distance {
pub metres: f32,
}
pub const ESTIMATE_DISTANCE: Topic<Distance, SafeLane> = Topic::new("estimate/distance");
Every other payload and topic in these sections comes from robot_topics too.
With state
use periodic::{periodic, Cycle};
use robot_topics::{Range, Twist, CMD_VELOCITY, SENSOR_RANGE};
/// One control cycle: count the cycles on which the node had to stop.
#[periodic(every = "20ms", on_overrun = Skip, init = 0u32)]
fn brake(
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
stops: &mut u32,
#[subscribe(CMD_VELOCITY, stale_after = "310ms")] command: Cycle<Twist>,
) {
let clear = range.get().is_some_and(|range| range.range > 0.3);
let commanded = command.get().is_some_and(|twist| twist.linear.x != 0.0);
if commanded && !clear {
*stops += 1;
}
}
The state is the one parameter with no marker. It may stand first, last, or between two inputs, as stops does here. The framework hands over the inputs in the order you write them.
With a state it only reads
use periodic::{periodic, Cycle};
use robot_topics::{Range, SENSOR_RANGE};
/// One control cycle: compare the newest usable range with the threshold.
#[periodic(every = "20ms", on_overrun = Skip, init = 0.3f32)]
fn brake(
stop_within: &f32,
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
) {
if !range.get().is_some_and(|range| range.range > *stop_within) {
stop();
}
}
// Your actuator call goes here.
fn stop() {}
Take the state as &S instead of &mut S when the body only reads it.
Reads what it published
use periodic::{periodic, Cycle, Out};
use robot_topics::{Tick, PROBE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn echo(
#[subscribe(PROBE, stale_after = "210ms")] previous: Cycle<Tick>,
#[publish(PROBE)] tick: Out<Tick>,
) {
tick.publish(Tick { cycle: previous.get().map_or(0, |tick| tick.cycle) + 1 });
}
Tick is pub struct Tick { pub cycle: u64 }, and PROBE is a Topic<Tick, KernelLane>. One topic may be both an input and an output of a node. Each release reads what the release before it published.
Several inputs
Each input has its own bound
#[periodic(every = "20ms", on_overrun = Skip, safety, init = Motors::attach())]
fn drive(
motors: &mut Motors,
#[subscribe(CMD_VELOCITY, stale_after = "310ms")] command: Cycle<Twist>,
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
) {
match (command.get(), range.get()) {
(Some(twist), Some(range)) if range.range > STOP_WITHIN => motors.drive(twist),
_ => motors.stop(), // no usable command, no usable range, or an obstacle
}
}
This is the drive node of your first nodes. A command stays usable for 310 ms; a range reading for 70 ms. If the range sensor goes quiet, range.get() turns None 70 to 110 ms after its last publication, while command stays usable.
Inputs may differ in payload type, lane and bound. At each release the framework:
- reads the clock once;
- reads every input, in the order written;
- judges each input against its own
stale_afterand that one clock reading.
So two inputs of one release never disagree about what time it is.
Zero, one, two or six inputs all use the same declaration. There is no separate topic list and no limit on the count.
A node reads a topic once. Two inputs on one topic fail the build, even through two constants that hold the same name:
const FRONT: Topic<Range, SafeLane> = Topic::new("sensor/range");
const REAR: Topic<Range, SafeLane> = Topic::new("sensor/range");
#[periodic(every = "20ms", on_overrun = Skip)]
fn brake(
#[subscribe(FRONT, stale_after = "70ms")] front: Cycle<Range>,
#[subscribe(REAR, stale_after = "70ms")] rear: Cycle<Range>,
) { /* ... */ }
error[E0080]: ... inputs `front` and `rear` name the same topic: a node reads a topic once
Several inputs of one payload type
use periodic::{periodic, Cycle, Out};
use robot_topics::{Distance, Range, ESTIMATE_DISTANCE, RANGE_CENTRE, RANGE_LEFT, RANGE_RIGHT};
/// The nearest obstacle any of three sensors sees; zero while any of them is silent.
#[periodic(every = "20ms", on_overrun = Skip, init = [false; 3])]
fn nearest(
#[subscribe(RANGE_LEFT, stale_after = "70ms")] left: Cycle<Range>,
#[subscribe(RANGE_CENTRE, stale_after = "70ms")] centre: Cycle<Range>,
#[subscribe(RANGE_RIGHT, stale_after = "70ms")] right: Cycle<Range>,
was_usable: &mut [bool; 3],
#[publish(ESTIMATE_DISTANCE)] nearest: Out<Distance>,
) {
let sensors = [&left, ¢re, &right];
for (sensor, was_usable) in sensors.iter().zip(was_usable) {
let usable = sensor.get().is_some();
if *was_usable && !usable {
println!("nearest: lost {}", sensor.topic()); // the binding, not the parameter
}
*was_usable = usable;
}
let range = |sensor: &&Cycle<Range>| sensor.get().map_or(0.0, |range| range.range);
nearest.publish(Distance { metres: sensors.iter().map(range).fold(f32::INFINITY, f32::min) });
}
Three topics carry one payload type. Each has its own definition (Topic<Range, SafeLane>) and its own bound.
Limit: two inputs of one payload type, written on each other's topics, compile. No type tells them apart:
use periodic::{periodic, Cycle};
use robot_topics::{Range, RANGE_LEFT, RANGE_RIGHT};
#[periodic(every = "20ms", on_overrun = Skip)]
fn clearance(
#[subscribe(RANGE_LEFT, stale_after = "70ms")] right: Cycle<Range>,
#[subscribe(RANGE_RIGHT, stale_after = "130ms")] left: Cycle<Range>,
) {
let _ = (left.get().map(|range| range.range), right.get().map(|range| range.range));
}
This builds with no warning. The parameter right receives the left sensor's readings, judged by the 70 ms bound. Two things protect you:
- Report an input by
Cycle::topic(), never by the parameter's name. Hereright.topic()is"range/left". - Test each topic's timing. Silence each topic's publisher in turn. Check that the node drops that input after that topic's own bound. A test that only checks the reported name passes on swapped bindings.
When both bounds are equal and the body treats both inputs alike, a swap changes nothing you can observe.
A monitor that publishes a permit, and the drive node that needs it
drive moves only while the monitor's permit, the range and the command are all usable.
The monitor reads the topics the other nodes already publish. It publishes a permit only while all three are usable:
use periodic::{periodic, Cycle, Out};
use robot_topics::{
Permit, Pose, Range, Twist, CMD_VELOCITY, DRIVE_PERMIT, ESTIMATE_POSE, SENSOR_RANGE,
};
/// Which monitor a permit came from. Set once and never changed.
struct Issuer {
id: u32,
}
#[periodic(
every = "50ms",
on_overrun = Skip,
safety,
init = Issuer { id: 1 }
)]
fn monitor(
#[subscribe(ESTIMATE_POSE, stale_after = "75ms")] pose: Cycle<Pose>,
#[subscribe(SENSOR_RANGE, stale_after = "125ms")] range: Cycle<Range>,
#[subscribe(CMD_VELOCITY, stale_after = "275ms")] command: Cycle<Twist>,
issuer: &Issuer,
#[publish(DRIVE_PERMIT)] permit: Out<Permit>,
) {
if pose.get().is_some() && range.get().is_some() && command.get().is_some() {
permit.publish(Permit { issuer: issuer.id });
}
}
Permit is pub struct Permit { pub issuer: u32 }, and DRIVE_PERMIT is a Topic<Permit, SafeLane>.
The drive node takes the permit as a third input:
#[periodic(every = "20ms", on_overrun = Skip, safety, init = Motors::attach())]
fn drive(
motors: &mut Motors,
#[subscribe(CMD_VELOCITY, stale_after = "310ms")] command: Cycle<Twist>,
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
#[subscribe(DRIVE_PERMIT, stale_after = "130ms")] permit: Cycle<Permit>,
) {
match (permit.get(), command.get(), range.get()) {
(Some(_), Some(twist), Some(range)) if range.range > STOP_WITHIN => {
motors.drive(twist);
}
_ => motors.stop(), // no permit, no usable command, no usable range, or an obstacle
}
}
Why this shape works:
- Every failure of another node is one branch. A node that is late, lost, or never started is not usable, so the monitor publishes no permit. The monitor calls
get()and nothing else. - Every failure of the monitor is the same branch. A monitor that cannot start, stops on
Fault, or gets no processor time is silence ondrive/permit. The drive node already stops on any absent input. - Start-up order does not matter. Until the monitor has seen all three topics, it publishes nothing, and the drive node stays stopped.
The drive node's bound on the permit follows the sizing rule. It tolerates one lost permit from a 50 ms monitor: (1 + 1) x 50 + 20 = 120 ms, written half a period off the drive node's grid as "130ms".
Here is what the drive node does, release by release. A planner sends two commands and dies. The range sensor goes quiet once and once sees an obstacle. The monitor stops permitting for a while. Ages are since receipt at the drive node.
| Release | command (310 ms) |
range (70 ms) |
permit (130 ms) |
The node |
|---|---|---|---|---|
| 0 ms | nothing received | nothing received | nothing received | stops: what was published before it started does not count |
| 20 ms | received now | received now | received now | drives at 200 mm/s |
| 40 ms | a newer one, now | 20 ms | 20 ms | drives at 250 mm/s |
| 80 ms | 40 ms | 60 ms: inside its 70 | 20 ms | drives |
| 100 ms | 60 ms | 80 ms: past its 70 | 40 ms | stops |
| 120 ms | 80 ms | received now | received now | drives |
| 200 ms | 160 ms | received now, 250 mm | 40 ms | stops: an obstacle |
| 280 ms | 240 ms | received now | 120 ms: inside its 130 | drives |
| 300 ms | 260 ms | received now | 140 ms: past its 130 | stops |
| 340 ms | 300 ms: inside its 310 | received now | received now | drives |
| 360 ms | 320 ms: past its 310 | received now | 20 ms | stops |
An input holds state, not events
use periodic::{periodic, Cycle, Out};
use robot_topics::{Imu, Odometry, Pose, ESTIMATE_POSE, IMU_DATA, WHEEL_ODOMETRY};
#[periodic(every = "10ms", on_overrun = Skip, init = Pose::default())]
fn estimator(
pose: &mut Pose,
#[subscribe(IMU_DATA, stale_after = "35ms")] imu: Cycle<Imu>,
#[subscribe(WHEEL_ODOMETRY, stale_after = "65ms")] odometry: Cycle<Odometry>,
#[publish(ESTIMATE_POSE)] estimate: Out<Pose>,
) {
let Some(imu) = imu.get() else { return }; // no usable inertial reading: publish nothing
pose.heading_mrad += imu.yaw_rate_mrad_s / 100;
if let (true, Some(wheels)) = (odometry.arrived(), odometry.get()) {
pose.x_mm = wheels.travelled_mm; // applied once, on the release it arrives
pose.corrections += 1;
}
estimate.publish(*pose);
}
An input shows the newest publication on its topic. If several arrived since the last release, the node sees only the newest one. So:
| Your topic carries | Read it with an input? |
|---|---|
| state: a total, a pose, a command | Yes. Odometry here is the distance since power-on, so a total the node skipped is contained in the next. |
| increments: "moved 5 mm since the last one" | No. Of two increments published within one of the reader's periods, the node never sees the first. |
arrived() lets you apply a measurement once. get() returns the same total for as long as it stays usable. arrived() is true only on the release that received it.
What an input costs
| Cost | How much | Limit |
|---|---|---|
| Stack | One copy of the payload per input, held for the node's life. | Nothing checks that a node's payloads fit its stack. The stack is 1 MiB with a 4 KiB guard page and no stack probes, so an overflow is not guaranteed to fault. Three 256 KiB inputs take 768 KiB before the body has a frame of its own. A debug build takes more. |
| Reads per release | One per input, on every lane. The read hands over the newest publication, however many are waiting. | A KernelLane publication is copied twice on its way to the node: out of the topic, then into the held copy. Each is at most 4 KiB. |
| Kernel memory | None for an input. A KernelLane input holds only its end record, however long it goes unread. The topic's slots came from the board's topic storage when the topic was created. |
Creating a topic can fail with NoRoom when that storage is used up. The node then does not start, and names the topic. No publish or read is ever refused for it. |
Cycle<T>
A Cycle<T> is one input's view of one release. The node gets one per input.
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] lidar: Cycle<Range>,
An input is in one of three states:
| State | get() |
was_stale() |
since_received() |
|---|---|---|---|
| nothing received since the node started | None |
false |
None |
received, and no older than stale_after |
Some(&T) |
false |
Some(age) |
received, and older than stale_after |
None |
true |
Some(age) |
Cycle is not Send, so moving one to another thread is a compile error. The node opens and reads its inputs on the one thread that runs it. Whether SafeLane and FastLane ends work from another thread is not established, so nothing of an input leaves its thread.
get() -> Option<&T>
match lidar.get() {
Some(reading) => brake_for(reading.range),
None => brake_for(0.0), // absent or stale
}
Returns the reading if one was received and is no older than stale_after. A stale reading returns None, the same as no reading, so the fail-safe branch is the default branch. The comparison is strict: a reading exactly stale_after old is still usable.
copied() -> Option<T>
let reading: Option<Range> = lidar.copied();
Returns the same reading as a copy you own. get() lends the framework's one held copy and makes no copy of its own.
arrived() -> bool
if let (true, Some(wheels)) = (odometry.arrived(), odometry.get()) {
*travelled_mm = wheels.travelled_mm; // once, on the release it arrives
}
True if at least one publication arrived at this release. get() answers "is there a usable reading?"; arrived() answers "is it new?".
topic() -> &'static str
if lidar.get().is_none() {
log::log!(WARNING, "no usable reading on {}", lidar.topic());
}
Returns the name of the topic this input is bound to, from its definition: "sensor/range". A parameter's name is only its author's claim; topic() is the binding itself (see Several inputs of one payload type).
since_received() -> Option<Duration>
if let Some(gap) = lidar.since_received() {
if gap > Duration::from_millis(40) {
raise_sensor_warning();
}
}
Returns how long since a publication last arrived at this node. It is not the publication's age: no lane timestamps a publication. It is None until something arrives, and exactly zero on the release a publication arrives.
was_stale() -> bool
if lidar.was_stale() {
log::log!(WARNING, "using fail-safe: last reading too old");
}
True if a reading was received and has aged past stale_after. Use it only when you need the difference that get() hides.
Limit: never received is never stale. An input that has received nothing returns false, however long the node has run. stale_after is not a start-up deadline. A node that acts only on was_stale() never acts on a peer that never started. Act on get() returning None: it covers "not yet", "lost" and "never".
missed() -> u32
if lidar.missed() > 0 {
count_dropped(lidar.missed());
}
Returns the publications the lane lost for this input, seen by this release's reads. It is not a running total.
Each lane counts its own losses, and they mean different things. Take a 200 ms node that reads a 50 ms publisher:
| Lane | missed() counts |
What the 200 ms node sees |
|---|---|---|
SafeLane, FastLane |
publications that newer ones overtook before this reader got them | the newest of four, and missed() = 3 on every release; nothing is wrong |
KernelLane |
publications the topic overwrote before the node read them | the newest of four, and missed() = 0: the other three were still in the topic, passed over, not lost. The topic keeps at least its newest 8. |
Limits:
missed() == 0does not mean the node saw every publication. OnKernelLanea publication passed over for a newer one is not counted.- A non-zero
missed()is not always a fault. OnSafeLane, a publisher faster than its reader is counted on every release. - A
KernelLaneinput counts loss from the moment it opened. It neither hands over nor counts what was published before.
rejected() -> u32
if lidar.rejected() > 0 {
count_rejected(lidar.rejected());
}
Returns the publications the lane refused on this input since the last release. It is not a running total.
| Lane | When it rejects |
|---|---|
SafeLane |
a malformed publication, at read; the next release reads again |
FastLane |
a frame that fails validation, counted again on every release until its writer replaces it |
KernelLane |
never: rejected() is always 0, because a writer of another payload is refused when it opens (see Payloads) |
overruns() -> u32
if lidar.overruns() > 0 {
hold_last_command();
}
Returns the releases the node missed since its last release ran. It is one count for the node, the same on every input of a release. Read it from any one input; do not add them up. The framework reports it once, then clears it.
The framework already writes each overrun to the system log, naming the node. Read overruns() to react to an overrun; logging it again records it twice.
is_healthy() -> bool
if !lidar.is_healthy() {
raise_degraded();
}
True if this input saw no loss, no rejection and no overrun on this release. It is missed(), rejected() and overruns() all zero, in one call.
What stale_after guarantees
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
The framework measures age from receipt at this node, on the clock the node's releases run on. A reading the body acts on:
- arrived no more than
stale_afterago; - was published no earlier than
stale_afterplus the gap since the previous read. That gap is one period in steady state.
Limits:
- After a late wake-up, the gap is the whole delay, and that release is not told. The drive node runs every 20 ms with a 310 ms command bound. It is kept off the processor for one second. Meanwhile its planner publishes one last command and dies. The first release after the stall gets that command as new:
since_received()is zero,arrived()is true,overruns()is zero. The node drives on it for 310 ms more.overruns()reports the missed releases on the release after. - A bound shorter than the node's period is accepted. With
every = "20ms",stale_after = "5ms"and a 40 ms publisher, the input is usable on the release a publication arrives and stale on the next, for ever. - Nothing checks the sizing rule below.
Sizing stale_after
stale_after >= (lost publications tolerated + 1) x the publisher's period + this node's period
Then move it half a node period off: never write a multiple of the node's period.
| Input | Publisher | Tolerates | Rule | Written |
|---|---|---|---|---|
range of the 20 ms drive node |
every 20 ms | 1 lost | 2 x 20 + 20 = 60 |
"70ms" |
permit of the 20 ms drive node |
every 50 ms | 1 lost | 2 x 50 + 20 = 120 |
"130ms" |
Why half a period off: the age a node sees is a whole number of its own periods, give or take wake-up jitter. With "60ms" on a 20 ms node, a reading is 60 ms old three releases later, a few microseconds either way. Whether it is still usable then depends on which wake-up ran later. "70ms" decides it 10 ms away from any release.
A node judges only at a release. So it drops an input between stale_after and stale_after plus two periods after the publisher's last publication, plus any scheduling delay.
Run-time parameters
#[periodic(every = "5ms", on_overrun = Skip)]
fn balance(
#[subscribe(IMU, stale_after = "12ms")] imu: Cycle<Imu>,
#[param(default = 42.0, range = 0.0..=200.0)] kp: f32,
#[param(default = 1.5, range = 0.0..=20.0)] kd: f32,
#[publish(MOTOR_COMMAND)] command: Out<MotorCommand>,
) {
command.publish(match imu.get() {
Some(imu) => MotorCommand::torque(kp * imu.pitch + kd * imu.pitch_rate),
None => MotorCommand::STOP,
});
}
A parameter is a value you tune while the node runs: a gain, a limit, a flag. You declare it on the argument that receives it, with its default and its range. The body is handed each value by value on every release, and reading one costs nothing.
| Rule | Detail |
|---|---|
| Name | The argument's name, at most 23 bytes. |
| Type | One of bool, i32, i64, u32, u64, f32, f64, written as the type itself. |
range |
Names both ends and includes them. Required for every type but bool, which takes none: #[param(default = false)] armed: bool. |
| Default and bounds | May be named constants. The build checks them. |
| Count | At most 16 parameters per node. |
Change one from the shell
param writes a request; the node applies it and answers with its state.
tsh> param list balance
kp = 42.0 (0.0 .. 200.0)
kd = 1.5 (0.0 .. 20.0)
tsh> param set balance kp 45.5
balance: kp = 45.5 from release 18342
tsh> param list balance
kp = 45.5 (0.0 .. 200.0, default 42.0)
kd = 1.5 (0.0 .. 20.0)
tsh> param set balance kp 250
param: balance kp = 250.0 is outside 0.0 .. 200.0; nothing was set
tsh> param list
balance 2 parameters
- A set takes effect at the start of a release. The release that
param setnames is the first one whose body gets the new value. A body never sees a value change while it runs. param setreports success only when the node answers. It exits 1 when the node refuses, or does not answer within eight of its periods plus 250 ms.- Set coupled gains in one command.
param set balance kp 50 kd 2.5is one request, applied whole at one release. Two commands are two requests: at least one release runs with the newkpand the oldkd. - The node checks every request against the declared range, both ends included. It
refuses a value outside the range, a NaN, or an unknown name, and nothing changes.
paramrefuses the same values before it sends. - Values last for the node's life. A restart or a reboot starts at the defaults again.
To keep a value, change its default in the source.
param listshows each changed value beside its default, so you can copy it. - A node declared
safetyhas no parameters. Its configuration is part of its verified build.#[param]on it fails the build; make the value aconst. paramlogs each applied change in its own ring of the system log:balance: kp 42.0 -> 45.5 from release 18342(logview -s param). A program that writes the request topic itself leaves no log record; the change is still in the node's state and its release journal.- Replay hands each body the values it ran with. A recording across sets replays as
identical. Renaming, retyping, adding, removing or reordering a parameter makes a new declaration, which replay refuses. A changed default or range still replays. node listshows every node;param listshows only nodes with parameters.node info balanceprintsParameters: 2, settablewhen they can be set.
What parameters cost
- One non-blocking read per release, of the request topic, before the body. Almost always it finds nothing. A release that finds a request also checks up to 16 values and publishes the node's state. All of it counts inside the cycle that overrun accounting measures.
- Two kernel-lane topics per node,
<node>/__paramsand<node>/__param_set. Count them in the image's[topic]budget: two table entries, plus 2 pages for up to two parameters, or 8 pages for 16. - Without those topics the node runs on its defaults and cannot be set. This happens when topic storage is full, or a recorder still holds the topics of an earlier run with another parameter table. The node says so once, at WARNING, before its first release:
balance: no parameter topics (topic storage full); runs with its defaults
- Load a settable node whose timing matters from the boot image, not from the FAT disk. A node loaded from FAT pages its request-handling code in from the disk during the release that handles its first request.
- Any program can set a parameter, within its range, by writing the request topic. No topic has writer authorisation yet. A value outside the range never reaches a body.
Actions
The client sends a goal; the node answers with a status on every release.
An action is a request that takes many releases: "drive to (2.0, 0.5)", "home the arm", "dock". A client sends a goal. The node accepts or refuses it at once, reports feedback on every release, and ends it with a result. The client can cancel it. The node stops it on its own when the client is gone.
Define the action once, in a crate both ends import:
use periodic::Action;
use wire_plain::WirePlain;
/// Where to drive, in the `odom` frame [m].
#[derive(Clone, Copy, Debug, Default, PartialEq, WirePlain)]
#[repr(C)]
pub struct DriveTo { pub x: f64, pub y: f64 }
/// How far the base still has to go [m].
#[derive(Clone, Copy, Debug, Default, PartialEq, WirePlain)]
#[repr(C)]
pub struct DriveProgress { pub remaining_m: f64 }
/// Where the base stopped, in the `odom` frame [m].
#[derive(Clone, Copy, Debug, Default, PartialEq, WirePlain)]
#[repr(C)]
pub struct DriveDone { pub x: f64, pub y: f64 }
/// Drive the base to a point.
pub const DRIVE_TO: Action<DriveTo, DriveProgress, DriveDone> = Action::new("drive_to");
Action::new fails the build at the definition for any of these:
- a payload that is not a record;
- a goal larger than 4072 bytes;
- a feedback and a result that together pass 3920 bytes, each rounded up to 8;
- a name longer than 246 bytes.
Serving it
A node serves an action on one more argument, with its lease:
#[periodic(every = "20ms", on_overrun = Skip)]
fn drive(
#[subscribe(ODOMETRY, stale_after = "50ms")] odometry: Cycle<Odometry>,
#[serve(DRIVE_TO, lease = "100ms")] goal: &mut Goal<DriveTo, DriveProgress, DriveDone>,
#[publish(CMD_VELOCITY)] command: Out<Twist>,
) {
let (Some(mut active), Some(odometry)) = (goal.active(), odometry.get()) else {
// no goal, cancelled, client gone, or odometry stale: stop
return command.publish(Twist::default());
};
let target = *active.goal();
let here = odometry.pose.position;
let remaining_m = (target.x - here.x).hypot(target.y - here.y);
if remaining_m < ARRIVED_WITHIN_M {
active.succeed(DriveDone { x: here.x, y: here.y });
return command.publish(Twist::default());
}
active.feedback(DriveProgress { remaining_m });
command.publish(steer_towards(odometry, &target)) // your control law
}
Goal / ActiveGoal |
Meaning |
|---|---|
goal.active() -> Option<ActiveGoal> |
The goal this release runs, or None. None means idle, cancelled, client gone, or replaced by a newer goal from the same client. It collapses like Cycle::get on a stale input, so the stop is the branch you write anyway. |
active.goal() -> &G |
What the client asked for. |
active.arrived() -> bool |
true on the goal's first release. Reset your controller here. |
active.feedback(F) |
This release's feedback. The last call in a release wins. |
active.succeed(R) |
Ends the goal with its result. Consumes the handle. |
active.abort(code) |
Ends the goal with a code. On the goal's first release the client gets Refused(code): this is how you refuse a goal by its content. Consumes the handle. |
- One goal at a time. A goal from another process while one runs is refused
Busy, and the running goal is untouched. A new goal from the process that owns the running goal replaces it from the same release; the old one endsPreempted. There is no queue. - Requests are read at the start of a release, after the parameters and before the
body, at most eight per release. A cancel that arrives before a release stops the goal
at that release: the body gets
Noneand publishes its stop. - The status follows the outputs. The node publishes one status per release, idle included, after all its outputs. A client that sees a goal stopped knows the stop went out first.
- A node declared
safetycannot serve. Any process can write an action's request topic, so a safety function takes no commands through one.#[serve]on asafetynode fails the build.
Sending a goal
A program sends a goal in one line:
let done = DRIVE_TO.send(DriveTo { x: 2.0, y: 0.5 })?.wait()?;
With feedback and cancel:
let mut drive = DRIVE_TO.send(DriveTo { x: 2.0, y: 0.5 })?; // accepted, or Err(Busy | Refused(code) | NoServer ..)
while let Some(progress) = drive.feedback() { // one per server release; None once it has ended
println!("{:.2} m to go", progress.remaining_m);
if bumper_pressed() {
drive.cancel()?; // returns once the server has stopped it
}
}
let done = drive.wait(); // Err(GoalError::Canceled) after the cancel
GoalHandle |
Meaning |
|---|---|
ACTION.send(goal) |
Waits until the goal is accepted or refused. A client may start before its server: it waits up to ten seconds for the server's first status, then sends the goal once. |
ACTION.start(goal) |
Returns at once. The answer comes through poll. |
poll() -> Progress |
Never blocks. Returns Pending, Running(Option<F>) with the newest feedback, or Ended(Result<R, GoalError>). Sends the keep-alive when one is due. |
feedback() -> Option<F> |
Waits for the next feedback. None once the goal has ended. |
wait(self) -> Result<R, GoalError> |
Waits for the end. |
cancel() |
Returns once a status shows the goal stopped. |
| dropping the handle | Cancels a goal that has not ended. |
GoalError is one of:
| Variant | Meaning |
|---|---|
Busy |
Another process's goal is running. |
Refused(code) |
The node aborted the goal on its first release. |
Aborted(code) |
The node aborted the goal later. |
Canceled |
The client cancelled it. |
Preempted |
A newer goal from the same client replaced it. |
Abandoned |
Its keep-alives lapsed past the server's lease. |
Lost |
It is no longer running, and how it ended was not seen. |
NoServer |
No server answered within 10 s. |
WrongDefinition |
The server holds another definition of the action. |
Topic(..) |
A topic of the action refused the client. |
A periodic node as a client never blocks. It starts a goal, polls it once per release, and cancels by dropping it:
#[periodic(every = "50ms", on_overrun = Skip, init = Patrol::default())]
fn patrol(
#[subscribe(SENSOR_RANGE, stale_after = "120ms")] range: Cycle<Range>,
patrol: &mut Patrol, // holds drive: Option<GoalHandle<DriveTo, DriveProgress, DriveDone>>
) {
if range.get().map_or(true, |reading| reading.range < STOP_WITHIN_M) {
patrol.drive = None; // dropping a goal that has not ended cancels it
return;
}
let finished = patrol.drive.as_mut().map_or(true, |drive| matches!(drive.poll(), Progress::Ended(_)));
if finished {
patrol.drive = DRIVE_TO.start(patrol.next_waypoint()).ok();
}
}
The lease
The lease is how long a goal survives without a keep-alive from its client. The handle
sends a keep-alive once per server period while it is polled. When the keep-alives stop,
the node stops the goal at the end of the lease, and the goal ends Abandoned. That covers
a client that was killed, crashed, hung, or simply stopped polling.
- The lease is required and must be at least twice the period.
lease = "39ms"on a 20 ms node does not start:could not start: lease 39ms is shorter than twice the period 20ms. - Choose about five periods, for example
lease = "100ms"on a 20 ms node. That rides out a lost keep-alive, a client one period late, and a client node up to four periods slow. - A killed client's goal stops within the lease plus two periods. At 20 ms and 100 ms that is about 140 ms after the last keep-alive, plus release lateness. No death signal stops it sooner.
- A periodic client slower than the lease loses every goal. It polls once per its own
release. A client every 150 ms against a 100 ms lease sees each goal end
Abandoned. Make the lease longer than the slowest client's period plus one server period. - A program that stops polling loses its goal. In
let drive = DRIVE_TO.send(goal)?; long_work(); drive.wait(), the goal is abandoned duringlong_work. Callpoll,feedbackorwaitwhile the goal should run.
What it costs and what it takes
- One non-blocking read per release of the request topic, which almost always finds nothing. One status publish per release, of at most 4096 bytes. Both count inside the cycle that overrun accounting measures. Nothing is allocated and nothing is logged.
- Two kernel-lane topics per action,
<action>/__goaland<action>/__status. Count them in the image's[topic]budget: two table entries, plus the pages for a goal record (24 bytes plus the goal) and a status (176 bytes plus the feedback and the result). - A serving node whose action topics cannot be opened does not start. It names the
action:
drive: could not start: action drive_to: drive_to/__goal: topic storage full. - Replay hands each body the goal it ran with and opens no action topic. Replay does not compare feedback or results, only the node's outputs.
- Any program can send, keep, cancel or replace a goal by writing the request topic with another process's id. No topic has writer authorisation yet. The lease, and the device's own lease, remain the stop.
The release journal
The record of release k goes out before the body runs.
The release journal is one record per release that every node with an output
publishes on a kernel-lane topic of its own, <node>/__releases. <node> is the node
function's name: lidar publishes lidar/__releases. You write nothing for it, and you
cannot turn it off. A node with no output has no journal.
The journal is what a recording needs to replay a node exactly. The record goes out before the body runs, so a body that panics or hangs still leaves its release behind.
| Record k carries | Detail |
|---|---|
| The release | k, the clock reading, the overruns delivered, and the publishing process. |
| Each input | Arrived, missed, rejected, and the reading if it arrived (zeros if not). |
| Each parameter | The value release k's body is handed. |
| Release k-1's outputs | What became of each (none, declined, published, refused), and each payload end to end in declaration order (zeros for one not published). |
- Size: 32 bytes plus the inputs' facts and payloads, 8 bytes per parameter and the outputs' payloads, all rounded up to 8. At most 4096 bytes, the kernel lane's limit.
- Layout identity: the node's declaration: its period, overrun policy, each input's
payload type, each parameter's name and type, and each output's payload type, in order.
topic listshows it aslayout 0x…. - No journal: a node with more than 16 outputs, or whose record would pass 4096 bytes, runs without one and logs a WARNING that says why.
What it costs
-
One kernel-lane publish per release, of at most 4096 bytes, before the body. It never waits for a reader. It counts inside the cycle that overrun accounting measures, so a journal that makes a release late shows up as an overrun.
-
One topic in the image's
[topic]budget per node with an output: one table entry and the record's pages. Count it when you size[topic]intail.build.Record size Pages up to 192 bytes 1 up to 384 bytes 2 1 KiB 5 4 KiB 20 -
4 KiB of stack in every node with an output, journal or not. It is the buffer each record is built in.
When the journal cannot be opened, the node runs exactly as it would with one. This happens when topic storage is full, the record would pass 4096 bytes, or the topic is held with another declaration's layout. The node says so once, at WARNING, before its first release:
brake: no release journal (topic storage full); this run cannot be replayed
The node description
Every node, with an output or not, also publishes its description on <node>/__node.
node list and node info read it (shell tools).
It takes one kernel-lane topic, and one page for a node of a few inputs and outputs (a
record up to 192 bytes). Count it in [topic] too. When it cannot be opened, the node runs
unlisted and says so once, at WARNING, before its first release:
brake: no node description (topic storage full); node list does not show this node
One name, one node
A node's name must be unique within an image. Two node functions with the same name share one journal topic. If their declarations differ, the second finds the topic held with another layout and runs without a journal. The same program started twice also shares one journal: its records interleave, each names its process, and replay refuses them.
A Python node journals through the same record: its page says how.
Recording and replay
tsh> topic record -o /recordings/run7.mcap & FIRST: before the nodes
tsh> lidar & brake & drive &
... the run ...
tsh> brake --replay /recordings/run7.mcap
replay: brake life 1: 2104 releases, 2103 compared, identical
facts: sensor/range: 5 releases without an arrival, 3 missed, 0 rejected; cmd/velocity: 0, 0, 0; 1 overruns
replay: running release 2103, the life's last; its output is in no record
You record a run, then run one node of it again, offline, against exactly what it saw.
Nothing in the node changes: replay reads the node's release journal,
and the generated main reads the options.
| Option | Meaning |
|---|---|
--replay FILE |
Replay the node from the recording. Goes at the end of the node's own command line. |
--life N |
After --replay FILE: pick a later life of the node. A restart during the recording is life 2. |
Replay runs the node's init, then its body once per recorded release. It hands each
input the reading, loss counts and overruns that release had, and each parameter its value,
at the recorded clock reading. It opens no topic, publishes nothing and never sleeps. It
compares what the body hands each output with what the node published, release by release.
A difference names the output by its topic, and the command exits 1:
replay: brake life 1: first divergence at release 2059:
output cmd/brake byte 0: recorded 00 00 00 00, replayed 9a 99 19 3e
replay: 1 of 2103 compared releases differ
Ask "what if"
Replay recomputes each input's age and staleness, and the body, with the binary you run.
So an edited body or a changed stale_after is a what-if: "would brake have stopped
earlier with stale_after = "40ms"?"
Replay refuses a changed declaration and names both versions:
| Changed | Replays |
|---|---|
| The body | yes |
stale_after |
yes |
| A parameter's default or range | yes |
| An input's or output's type or order | no |
| The period or the overrun policy | no |
| A parameter's name, type or order | no |
Rules and limits
- Start
topic recordbefore the nodes. Otherwise the journal is not whole from the first release, and replay refuses:life 1 starts at release 37: the recorder attached after brake started; start topic record before the nodes. A node faster than every 15 ms can lose its first records even so. - The last release runs uncompared. Its output is in no record, because the node was stopped, crashed, or the recording ended. Replay prints its verdict first, then runs it. A body that crashed in the recording crashes the same way in the replay.
- Replay runs
initand the body as written. A node that opens a device does so in a replay too. Replay such a node only where the device is absent, or replay the nodes downstream of it instead. - What replay cannot see shows up as a divergence, never as a false
identical: time read other than throughperiodic::now()or aCycle, side effects other than the outputs, the node's own command-line arguments (give the same ones), anything that depends onHashMaporder. - A node with no output cannot be replayed. There is nothing to compare, and replay
refuses before
initruns. - A journal the recorder lost part of replays up to the lost stretch, and claims nothing for the rest.
- Output streams: the verdict is on standard output. Refusals are on standard error and
exit 1. A malformed
--replay ...tail exits 2.
Start-up
Outputs open before inputs; the journal and the description open last.
Nothing published before release 0 reaches the body.
A node opens every topic it declares, and does not run until all are open. You write no retry loop and no start-up order.
- Outputs open first, in the order written. Two nodes that read each other then both start: each creates its topics before it waits for the other's.
- A served action opens after the inputs, its goal reader before its status writer. A client sends only after it reads a status, so it never sends to a reader that does not exist yet. A refusal fails the start and names the action (see Actions).
- The journal and the description open last, so they never take a table entry that one of the node's own topics needs. A refusal of either does not stop the node (see The release journal).
- One wait budget for the whole node: 2 000 "nobody publishes this yet" answers, 5 ms apart, about ten seconds whatever the number of inputs. On a busy system each wait can run longer, so the start can take longer to fail. Only that answer is waited on; any other refusal ends the start at once.
- Nothing published before the start reaches the node. Each input's collected readings are dropped, and loss from before the start is not reported.
Limits
- A node does not run until every topic it declares is open. The drive node with no
lidarwaits ten seconds, writes one ERROR record and exits with status 1; its body never runs. The rest of the system sees only silence on the topics it would publish. - A kernel-lane input never fails the start for absence. Subscribing creates the topic. So a kernel-lane topic nobody publishes, or a misspelt name, starts fine and that input stays absent for ever. The topic goes away when the node ends.
- An early kernel-lane input waits too. Inputs open in the order written, so it may wait ten seconds for a later input's publisher. What is published meanwhile is dropped at the start.
- Only the first missing topic is named. With three safe-lane publishers down, it takes three ten-second runs to learn all three.
- An output created before a failed start stays without a writer. A downstream node is
admitted against it and receives nothing. The failed node writes one record per output it
created (see
NodeError). OnKernelLanethe topic goes away with its last end, so a restarted node can create it again. - Release 0 can show a reading published during start-up. A publication that lands between an input's drop and release 0's sampling is handed over at release 0. What holds is that nothing published before the start is shown.
- A topic published once, or only on change, cannot be an input. A node that starts after the publication never receives it.
- A mistyped duration fails the start, not the build. See Durations.
OverrunPolicy
An overrun is a cycle that runs past its next release. on_overrun says what the node
does then. Take the first row that matches.
| Your node | Use | Keeps |
|---|---|---|
| Its deadline is the safety requirement | Fault |
nothing: the node stops |
| Integrates or counts, and must see every interval exactly once | CatchUp |
the count of releases |
| Anything else, such as a control loop | Skip |
the phase of the grid |
Skip
#[periodic(every = "20ms", on_overrun = Skip)]
The node abandons the missed releases and resumes on the grid. Use it for a control loop, where a late command computed from stale inputs is worse than none.
CatchUp
use periodic::{periodic, Out};
use robot_topics::{Count, DIAG_COUNT};
#[periodic(every = "20ms", on_overrun = CatchUp, init = 0u64)]
fn odometer(ticks: &mut u64, #[publish(DIAG_COUNT)] count: Out<Count>) {
*ticks += 1;
count.publish(Count { cycles: *ticks });
}
The node runs the missed releases back to back until it has caught up. Use it for an integrator or an accumulator.
Fault
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Fault)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
range.publish(read_sensor());
}
// Your driver call goes here.
fn read_sensor() -> Range {
Range { range: 4.2, ..Range::default() }
}
The first cycle that runs past its next release is the last. The node writes one ERROR record to the system log, naming itself and the releases it missed, then exits with status
- For a node named
overrun_fault, the console shows:
[ 0.218611] [FAIL] periodic overrun_fault: stopped: missed 2 release(s) under on_overrun = Fault
- That record is the overrun's only report. The node has no next cycle, so no
Cyclecarries the count. - The record outlives the process. It stays in the node's log ring, so
logview -l errorstill finds it. The BSP'stail.buildalso forwards errors to the console. - Exit status 1, not 0, lets a supervisor tell a missed deadline from a clean shutdown.
Overruns under Skip and CatchUp
Every overrun is a WARNING record, and the next cycle's overruns() (see
Cycle<T>). For a node named overrun_pipe:
[ 0.227637] [WARN] periodic overrun_pipe: missed 2 release(s)
Topics and lanes
A topic is a named channel that carries one payload type. One node publishes it, and other nodes read it.
lidar publishes sensor/range on SafeLane; brake and drive read it.
Define a topic once
pub const SENSOR_RANGE: Topic<Range, SafeLane> = Topic::new("sensor/range");
pub const CMD_VELOCITY: Topic<Twist, KernelLane> = Topic::new("cmd/velocity");
Each line states three facts: the topic's name, its payload and its lane. A node never names a lane. It names the constant, so every node that imports it agrees on all three facts. One node's inputs may be on different lanes. To change a topic's lane, change its one line.
A definition is a constant expression, so you can write it inline:
#[subscribe(Topic::<Health, KernelLane>::new("health/drive"), stale_after = "125ms")]
This compiles, but the other end of the topic then has nothing to import. Define it once and import it on both ends.
What a lane is
A lane is the way a topic's payloads travel from the publisher to the readers. TAIL OS has three.
| Lane | Publishers | Copies | May carry safety data |
|---|---|---|---|
KernelLane |
up to 4 at once | 1 in, 1 out to each reader | yes |
SafeLane |
exactly 1 | none | yes |
FastLane |
exactly 1 | none | no |
A reader is handed the latest value on every lane. A KernelLane topic also keeps its newest 8 publications, which a tool such as topic echo can show.
KernelLane carries payloads of at most 4 KiB. A larger payload on it does not compile: a kernel-lane payload is at most 4096 bytes. SafeLane and FastLane copy nothing, because the publisher and the readers share memory.
Choose a lane
Take the first row that matches your topic.
| Your topic | Use |
|---|---|
| Has more than one publisher | KernelLane |
| Carries a small payload | KernelLane |
| Carries a large payload, and a reader has a safety requirement | SafeLane |
| Carries a large payload, and nothing that reads it has a safety requirement | FastLane |
A copy-free lane is not always faster. For a small payload, the copy costs less than setting up shared memory. The crossover is about 2 KB, an estimate that has not been measured.
What safety checks
A node marked safety declares its topics only on lanes that may carry safety data. This drive node reads one topic on FastLane:
use periodic::{periodic, Cycle, FastLane, Topic};
use robot_topics::{Range, Twist, CMD_VELOCITY};
/// A scan for a viewer, on the lane that is Quality-Managed only.
const DEBUG_SCAN: Topic<Range, FastLane> = Topic::new("debug/scan");
#[periodic(every = "20ms", on_overrun = Skip, safety)]
fn drive(
#[subscribe(CMD_VELOCITY, stale_after = "310ms")] command: Cycle<Twist>,
#[subscribe(DEBUG_SCAN, stale_after = "70ms")] scan: Cycle<Range>,
) {
let _ = (command.get(), scan.get());
}
The build fails at that topic:
error[E0080]: evaluation of constant value failed
|
| #[subscribe(DEBUG_SCAN, stale_after = "70ms")] scan: Cycle<Range>,
| ^^^^^^^^^^ the evaluated program panicked at 'input `scan` is on a Quality-Managed lane, and this node is declared `safety`: a safety node reads only from lanes that may carry safety data'
FastLane may not carry safety data because its publisher keeps write access to the shared memory. It can change a payload while a reader is parsing it. An output on FastLane fails the same way.
The build checks only the topics a node declares as inputs and outputs. It does not check a topic your code opens itself, for example with periodic::subscriber(&DEBUG_SCAN) in init. Declare every topic the node uses.
Two definitions of one name
Two nodes that import one definition cannot disagree. Two programs that each write their own definition of one name can. The result depends on what differs.
| What differs | Result |
|---|---|
| The payload, in size or in layout | The node that opens second does not start. Its record says what the topic carries (see Payloads). |
The lane: the publisher on SafeLane or FastLane, the reader on KernelLane |
The reader starts and receives nothing, with no error. |
The lane: the publisher on KernelLane, the reader on SafeLane or FastLane |
The reader's node does not start: could not start: topic `cmd/velocity` never appeared. |
The lane: SafeLane against FastLane |
The reader's node does not start, and its record does not name the lane: on a SafeLane reader it says this is not the payload type the topic carries, on a FastLane reader the topic could not be joined. |
No record names the lane as the cause. Known issue: TAIL-489. Two payload types with one layout under two names, such as Point and Vector3, are one payload to every lane.
A Python node always writes its own definition, so a lane mismatch is possible between a Rust node and a Python node. Give both the same lane.
Raw ends
A raw end is a publisher or a subscriber you open yourself, outside a node. Use one in a test stand, or in a pilot that feeds or reads a node's topic.
use periodic::{KernelLane, Lane, TopicError};
use robot_messages::geometry::Vector3;
use robot_topics::{Twist, CMD_VELOCITY, SENSOR_RANGE};
/// A raw end kept in a struct names its lane again.
struct Stand {
commands: <KernelLane as Lane>::Publisher<Twist>,
}
fn main() -> Result<(), TopicError> {
// The lane and the payload come from the definition: nothing here names either.
let mut stand = Stand { commands: periodic::publisher(&CMD_VELOCITY)? };
let mut readings = periodic::subscriber(&SENSOR_RANGE)?; // NotFound until `lidar` runs
let ahead = Vector3 { x: 0.2, y: 0.0, z: 0.0 };
stand.commands.publish(&Twist { linear: ahead, ..Twist::default() })?;
if let Some(reading) = readings.read() {
println!("{} m", reading.range);
}
Ok(())
}
periodic::publisher(&TOPIC) and periodic::subscriber(&TOPIC) open the end from the topic's definition. The end cannot choose another lane or another payload.
A node does not need a raw end to publish a second topic. It declares a second output:
use periodic::{periodic, Out};
use robot_topics::{Count, Range, LIDAR_SCANS, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip, init = 0u64)]
fn lidar(
scans: &mut u64,
#[publish(SENSOR_RANGE)] range: Out<Range>,
#[publish(LIDAR_SCANS)] diagnostics: Out<Count>,
) {
*scans += 1;
range.publish(Range { stamp_ns: periodic::monotonic_ns(), range: 4.2, ..Range::default() });
diagnostics.publish(Count { cycles: *scans });
}
A declared output gets what a raw end does not:
| Declared output | Raw end | |
|---|---|---|
| Opened with the node, waiting for the topic's publisher | yes | no: a raw subscriber on SafeLane or FastLane answers TopicError::NotFound until a publisher exists |
| Named in the record when the node cannot start | yes | no |
Checked by safety |
yes | no |
| Recorded for replay | yes | no |
Limits:
- A raw
KernelLanesubscriber is a reader of its own. Beside a declared input on the same topic, both are handed every publication. - Never open a second raw publisher on a
FastLanetopic the process already publishes. Nothing stops it, and publishing on both corrupts the topic. - A raw end kept in a struct names its lane again, as
Standdoes. If the definition's lane changes, that line stops compiling, so the two cannot disagree silently. - Python has no raw end.
Durations
use std::time::Duration;
const PERIOD: &str = "20ms";
fn main() {
let period = periodic::parse_duration(PERIOD).expect("the node's own period");
assert_eq!(period, Duration::from_millis(20));
let refused = periodic::parse_duration("1.5ms").unwrap_err();
assert_eq!(refused.to_string(), "`1.5ms` is not a duration");
}
A duration is an integer and a unit, with nothing between them. There is no fractional form: write "1500us", not "1.5ms".
| Unit | Meaning | Example |
|---|---|---|
ns |
nanoseconds | "250ns" |
us |
microseconds | "500us" |
ms |
milliseconds | "20ms" |
s |
seconds | "1s" |
periodic::parse_duration reads a text the way the framework reads a declaration's. Use it in a test that derives its expectations from the constants it hands the attribute.
The framework checks a duration when the node starts, not when it is built. stale_after = "70 ms" builds. The node then exits with status 1 and one record that names the key and, for an input, its topic:
brake: could not start: `stale_after` of `sensor/range` is `70 ms`, not a duration
Every duration is checked before any topic is opened, so a typing mistake leaves no topic behind.
A served action's lease is the exception. The build checks it too, so lease = "100" does not build (see Actions).
Payloads
A payload is the type a topic carries. Use a standard payload when one fits, and declare your own when none does.
Standard payloads
The crate robot_messages has these:
| Module | Payloads |
|---|---|
geometry |
Vector3, Point, Quaternion, Pose, Twist |
sensor |
Range, Imu |
navigation |
Odometry |
They use the field names common in robotics code (position, orientation, linear, angular). Each field's doc comment gives its SI unit. A stamp_ns field is the record's time stamp, in nanoseconds since boot. Fill it with periodic::monotonic_ns() at the hardware boundary, and with periodic::now() in a node that decides, so that a replay reproduces it. A Python node reads the same payloads through tail_messages, which the build generates from these structs.
Your own payload
Declare a #[repr(C)] struct that derives WirePlain:
use wire_plain::WirePlain;
/// What the balance controller knows at the end of a cycle.
#[derive(Clone, Copy, Debug, Default, PartialEq, WirePlain)]
#[repr(C)]
pub struct BalanceState {
/// When the cycle ran [ns since boot, monotonic counter].
pub stamp_ns: u64,
/// Tilt from upright [rad].
pub tilt: f32,
/// Tilt rate [rad/s].
pub tilt_rate: f32,
/// Commanded wheel speed [rad/s].
pub wheel_speed: f32,
/// Cycles the node has run.
pub cycle: u32,
}
That is the whole definition. Write it once, beside the topic's definition, and import it on both ends. A crate that holds it, its topic and a node builds with #![forbid(unsafe_code)].
A payload crosses shared memory, where another process can store any bytes. So the derive checks, at the definition, everything that crossing needs:
| The derive requires | Because |
|---|---|
#[repr(C)], and nothing else in it |
both processes, and the generated Python, lay the type out the same way |
named fields of u8..u64, i8..i64, f32, f64, non-empty arrays of them, and other such structs |
every bit pattern must be a valid value, of a width every machine and language shares |
| no padding | a gap would carry the sender's uninitialised bytes; name it with a reserved field |
no type or lifetime parameter (a const one is allowed) |
whether the struct has padding would depend on the argument |
| field and type names no generated language reserves | the generated definitions are printed from this struct |
A field's doc comment is part of the payload. Write its unit there in square brackets, and the generated Python carries it as a comment. An integer field may name its values: #[wire_plain(values(ULTRASOUND = 0, INFRARED = 1))] gives the struct Range::ULTRASOUND and Range::INFRARED, typed as the field.
Both ends must hold one definition
The derive computes the payload's layout identity: a 32-bit hash of the field names, their order, their types, nesting, array lengths and named values. The identity travels with the topic. On every lane, an end whose identity differs is refused when it opens, and its node does not start.
Here a drive node has its own Twist, with linear and angular swapped. A pad made the topic with the standard Twist:
drive: could not start: topic `cmd/velocity` refused the open: this is not the payload type the topic carries: it carries 48-byte payloads of layout 0x38793118
A refused publisher on SafeLane or FastLane gets the reason without the shape: it ends at "carries". The system log keeps 96 bytes of a record, so logview cuts this one short; the console and the NodeError carry all of it. The type's name, the doc comments and the lane are not compared.
A KernelLane topic lives while an end holds it. Once every end of the old payload has closed, the corrected definition creates the topic anew.
What the derive refuses
The compiler refuses what cannot cross, at the struct, with the reason. Take the row that matches what you wrote.
| Written | Error |
|---|---|
{ range: f32, stamp_ns: u64 } |
this wire type has padding; a padded value carries the sender's uninitialised bytes across the process boundary. Reorder the fields, or name the gap with an explicit reserved field. |
pressed: bool |
`bool` cannot cross the wire: only 0 and 1 are valid, and a sender may send 2. .. |
key: char |
`char` cannot cross the wire: not every u32 is a valid scalar value. .. |
frame_id: &'static str, *const u8 |
`a reference` cannot cross the wire: an address is meaningless in another address space. .. |
handler: fn(u32) -> u32 |
`a function pointer` cannot cross the wire: the sender would choose where this process jumps. .. |
count: usize, isize |
`a pointer-sized integer` cannot cross the wire: its width is the building machine's, .. |
value: u128, i128 |
`a 128-bit integer` cannot cross the wire: C and Python have no fixed-width type to declare it with. .. |
id: NonZeroU32 |
`a niche-optimised type` cannot cross the wire: zero is a valid byte pattern and an invalid value. .. |
| the derive on an enum or a union | `WirePlain` describes a struct: an enum has bit patterns that are not valid values, and a union has no single layout to read |
no repr |
a wire type declares `#[repr(C)]`: a default Rust layout is whatever the compiler chose for this build, and both sides of the wire must agree forever |
#[repr(C, packed)], #[repr(C, align(16))], #[repr(transparent)] |
a wire type is plain `#[repr(C)]`: `packed`, `align` and `transparent` state a layout the C and Python definitions generated from this struct would not follow |
struct Metres(pub f32);, struct Ping; |
a wire type names its fields: C and Python read a field by its name, and a tuple or unit struct has none to give them |
struct Nothing {} |
a wire type has at least one field: zero bytes give the two ends nothing to agree on |
align: [u64; 0] |
a zero-length array carries nothing and has no C or Python declaration |
struct Stamped<T> { .. }, struct Borrowed<'a> { .. } |
a wire type has no type or lifetime parameter: whether it has padding would depend on the argument, and the witness would exist before that was checked. Write the struct for the one type it carries; a `const` parameter is allowed. |
a field named register, from or r#struct; a type named None |
`register` is a keyword of C, C++ or Python: this field could not be declared in the definitions generated from this struct. Rename it. |
a field named __reserved |
`__reserved` starts with two underscores: C reserves such a name and Python rewrites it inside a class. Rename this field. |
#[wire_plain(unit = "m")] |
the only field attribute is `values(NAME = integer, ..)` |
values(REVERSE = -1) |
a named value is a plain non-negative integer: it is printed as an unsigned constant in C and Python |
values(..) on an f32 field |
E0308 mismatched types |
| a field whose struct lacks the derive | E0277 the trait bound `Inner: WirePlain` is not satisfied |
unsafe impl WirePlain for Range {} |
E0046 not all trait items implemented, missing: `LAYOUT` |
const TICKS: Topic<u32, KernelLane> = Topic::new(..), and [u64; 6] |
a topic carries a record: a bare scalar or array has no field name for C or Python to read it by. Wrap it in a `#[repr(C)]` struct that derives `WirePlain`. |
A struct with a const parameter is checked where a concrete one is used. So a padded Watched<2> is refused when the program that uses it is built, not by cargo check. The same holds for a scalar topic written inside a function.
A struct without the derive, used as a payload, is refused at the topic:
error[E0277]: the trait bound `Range: Payload` is not satisfied
|
12 | pub const SENSOR_RANGE: Topic<Range, SafeLane> = Topic::new("sensor/range");
| ^^^^^^^^^^ the trait `Payload` is not implemented for `Range`
Payload is the framework's name for wire_plain::WirePlain.
Out of tree
An SDK program derives its own payloads and uses the standard ones as shown here. The SDK ships wire_plain, robot_messages and the derive. It does not ship the Python generator. So a Python node declares an SDK program's own payload inline with Payload(..), and the layout identity checks it against the Rust end.
Frames and transforms
"Where is the obstacle relative to the wheels?" You declare a robot's coordinate frames once, at build time, with frames! from the crate frames. A frame is a coordinate frame: an origin and three axes. A transform takes coordinates in one frame to coordinates in another. lookup gives the transform between any two frames, and the geometry payloads of robot_messages do the arithmetic. Your code holds no frame index, no frame string, no sign convention and no trigonometry: a conversion is one line.
BASE_LINK moves in ODOM by odometry; RANGE_FRONT is mounted on BASE_LINK 0.10 m forward, turned 15 degrees left.
The example is four files in the BSP's app/ directory:
| File | Is |
|---|---|
app/robot_frames.rs |
the rover's frames: each one's parent, and how it is placed in that parent |
app/robot_topics.rs |
the topics, each naming the frame its numbers are in |
app/obstacle/src/main.rs |
a node that places the reading in base_link, through the mount |
app/obstacle_odom/src/main.rs |
a node that places it in odom, through odometry as well |
The build compiles each block below as shown, and runs both programs on the emulated Raspberry Pi 3. Build and run them as in Build and run. frames is an SDK library: name it with a use. Both programs start with #![forbid(unsafe_code)] and #![deny(warnings)] so that the build refuses any unsafe or warning in them; your own program needs neither line.
The conventions
Each convention is written in the doc comment of a robot_messages payload. The build copies it into tail_messages, so a Python node reads the same words. These are the conventions most robotics software already uses.
| Convention | Stated on |
|---|---|
| Right-handed; a body frame has x forward, y left, z up; SI units: m, rad, s | Vector3, Point, Pose |
| Positive angles turn counter-clockwise about the axis (right-hand rule): a yaw of +15 degrees turns left | Quaternion |
| Hamilton algebra (i*j = k); stored x, y, z, w, with w the scalar; q and -q are one rotation; the identity is (0, 0, 0, 1); all four zero means "not estimated" and is not a rotation | Quaternion |
| Roll, pitch and yaw are about fixed axes: R = Rz(yaw)*Ry(pitch)*Rx(roll) | Quaternion |
| A pose used as a transform is the pose of the child frame in the parent frame, T_P_C, which takes p_C to p_P = R(q)*p_C + t; T_A_C = T_A_B * T_B_C | Pose |
A transform rotates and translates a Point; it only rotates a Vector3 (a direction, a velocity) |
Vector3, Point |
| A range reading lies on the sensor frame's +x axis | Range |
The standard frames: map, odom, base_link; pose is base_link in odom, twist is in the body frame |
Odometry |
The frames, declared once
// app/robot_frames.rs
use frames::{frames, Angle};
frames! {
/// The rover's coordinate frames, with the standard frame names.
pub ROVER {
/// World-fixed and continuous; drifts without bound.
ODOM,
/// The body: origin on the wheel axis, x forward, y left, z up.
BASE_LINK moves in ODOM,
/// The front range sensor: 0.10 m ahead of the wheel axis, turned 15 degrees left.
RANGE_FRONT in BASE_LINK at { x: 0.10, yaw: Angle::from_degrees(15.0) },
}
}
Write each frame in one of three forms, in any order:
| Written | Is |
|---|---|
ODOM |
the root: the one frame with no parent |
BASE_LINK moves in ODOM |
a moving link: its pose in the parent is supplied each release |
RANGE_FRONT in BASE_LINK at { x: 0.10, yaw: Angle::from_degrees(15.0) } |
a mount: x, y, z in metres and roll, pitch, yaw as an Angle, each zero when omitted |
Each frame becomes a constant of the module, with its doc comment, and the set becomes a static. A frame prints in lower case: RANGE_FRONT prints range_front. Write an angle as Angle::from_degrees or Angle::from_radians, never as a bare number. A set holds at most 256 frames, and a module holds one set.
The build refuses a set that is not one tree:
| Written | Error |
|---|---|
PLATE in SONAR at { .. } and SONAR in PLATE at { .. } |
frames!: every frame's parents must lead to the root |
RANGE_FRONT in BASE_LNK at { .. }, a parent never declared |
cannot find value `BASE_LNK` in this scope |
BASE_LINK declared twice |
the name `BASE_LINK` is defined multiple times |
no bare name, or two: ODOM and MAP |
frames!: a frame set has exactly one root |
yaw: 15.0 |
expected `Angle`, found floating-point number |
a frame of another robot's set given to lookup |
the trait bound `Frame<rover::__Frames>: From<Frame<arm::__Frames>>` is not satisfied |
a frame of another robot's set named as a parent, by a mount or by a moving frame: GRIPPER in BASE_LINK at { .. } in the arm's set, with the rover's BASE_LINK imported |
expected `arm::__Frames`, found `rover::__Frames` |
a mount given a pose, ROVER.with(RANGE_FRONT, ..) |
expected `MovingFrame<__Frames>`, found `Frame<__Frames>` |
a view kept in the node's init state and given each release's odometry |
`odometry` does not live long enough |
The topics
// app/robot_topics.rs
// Each program uses some of these definitions and not others.
#![allow(dead_code)]
use periodic::{SafeLane, Topic};
pub use robot_messages::{geometry::Point, navigation::Odometry, sensor::Range};
/// The front range sensor's readings, in the [`RANGE_FRONT`](crate::robot_frames::RANGE_FRONT) frame.
pub const SENSOR_RANGE: Topic<Range, SafeLane> = Topic::new("sensor/range");
/// The pose of [`BASE_LINK`](crate::robot_frames::BASE_LINK) in [`ODOM`](crate::robot_frames::ODOM), from wheel odometry.
pub const ODOMETRY: Topic<Odometry, SafeLane> = Topic::new("odometry");
/// The nearest obstacle, in the [`BASE_LINK`](crate::robot_frames::BASE_LINK) frame.
pub const OBSTACLE: Topic<Point, SafeLane> = Topic::new("obstacle");
/// The nearest obstacle, in the [`ODOM`](crate::robot_frames::ODOM) frame.
pub const OBSTACLE_IN_ODOM: Topic<Point, SafeLane> = Topic::new("obstacle/odom");
A topic's doc comment names the frame its numbers are in, by a link to the frame constant. The link spells the full path because robot_topics.rs does not import the frames: an import used only by a doc link is an unused import, which #![deny(warnings)] refuses. Each program includes both files by #[path], so crate::robot_frames is the same module in every program. The link is a reading aid: nothing checks that a node converts a topic's readings through the right frame.
Through a mount
// app/obstacle/src/main.rs
#![forbid(unsafe_code)]
#![deny(warnings)]
#[path = "../../robot_frames.rs"]
mod robot_frames;
#[path = "../../robot_topics.rs"]
mod robot_topics;
use periodic::{periodic, Cycle, Out};
use robot_frames::{BASE_LINK, RANGE_FRONT, ROVER};
use robot_topics::{Point, Range, OBSTACLE, SENSOR_RANGE};
// "Where is the obstacle relative to the wheels?"
#[periodic(every = "20ms", on_overrun = Skip)]
fn obstacle(
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
#[publish(OBSTACLE)] obstacle: Out<Point>,
) {
let Ok(ranger_in_base) = ROVER.lookup(BASE_LINK, RANGE_FRONT) else { return };
let Some(point) = range.get().and_then(Range::point) else { return };
obstacle.publish(ranger_in_base.transform_point(point));
}
lookup(target, source) returns T_target_source, the transform that takes coordinates in source to coordinates in target. The target comes first, as in the transform's name. The lookup walks both frames up the tree to where they meet and composes the links it crosses. It crosses at most N - 1 links of an N-frame set, with no allocation, no lock and no clock.
A lookup between frames joined only by mounts always succeeds. range.get().and_then(Range::point) is None when the reading is absent, stale, or not a measured distance. For the 4.2 m reading (an f32), the obstacle is at (4.156888286178356, 1.087039940064772, 0) in base_link: 4.2967 m away, 14.65 degrees to the left.
Across a moving link
// app/obstacle_odom/src/main.rs
#![forbid(unsafe_code)]
#![deny(warnings)]
#[path = "../../robot_frames.rs"]
mod robot_frames;
#[path = "../../robot_topics.rs"]
mod robot_topics;
use periodic::{periodic, Cycle, Out};
use robot_frames::{BASE_LINK, ODOM, RANGE_FRONT, ROVER};
use robot_topics::{Odometry, Point, Range, OBSTACLE_IN_ODOM, ODOMETRY, SENSOR_RANGE};
// The same obstacle in odom: nothing is published while odometry is absent or stale.
#[periodic(every = "20ms", on_overrun = Skip)]
fn obstacle_in_odom(
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] range: Cycle<Range>,
#[subscribe(ODOMETRY, stale_after = "70ms")] odometry: Cycle<Odometry>,
#[publish(OBSTACLE_IN_ODOM)] obstacle: Out<Point>,
) {
let frames = ROVER.with(BASE_LINK, odometry.get().map(|o| &o.pose));
let Ok(ranger_in_odom) = frames.lookup(ODOM, RANGE_FRONT) else { return };
let Some(point) = range.get().and_then(Range::point) else { return };
obstacle.publish(ranger_in_odom.transform_point(point));
}
with(BASE_LINK, ..) supplies the moving link's pose for this release, borrowed from the input. Its age limit is the input's stale_after, applied by Cycle::get(); frames has no clock of its own. Every lookup that crosses the link then gives one of these results:
| Supplied | lookup(ODOM, RANGE_FRONT) |
|---|---|
None: odometry absent, or older than 70 ms |
Err(Absent { frame: "BASE_LINK", parent: "ODOM" }), printed no usable pose of base_link in odom |
| a NaN or infinite position, or an orientation 1 % or more from unit length (all zero included) | Err(NotAPose { .. }), printed the pose of base_link in odom is not a rigid transform |
| a finite position and an orientation less than 1 % from unit length | Ok: the orientation normalised to unit length, then composed |
So when odometry stops, obstacle_in_odom publishes nothing while obstacle goes on. With base_link at (1, 2, 0) m in odom, turned 90 degrees left, the obstacle is at (-0.0870399400647699, 6.156888286178356, 0) in odom.
A second .with(..) supplies a second moving link. A second value for the same link replaces the first. The view borrows the input, so it cannot outlive the release that judged the input fresh.
The arithmetic on the standard payloads
| Item | Is |
|---|---|
Quaternion::IDENTITY, Pose::IDENTITY |
no rotation; no rotation and no translation. Quaternion::default() is all zero, "not estimated", and is not the identity |
Quaternion::from_rpy(roll, pitch, yaw) |
a rotation from fixed-axis angles in radians: an odometry node writes Quaternion::from_rpy(0.0, 0.0, heading) |
q.compose(child), q.inverse(), q.rotate(vector) |
the Hamilton product, the inverse of a unit quaternion, a Vector3 rotated |
q.to_unit() |
the rotation normalised to unit length; None when its squared length is 1 % or more from 1 (ROTATION_TOLERANCE), NaN, infinite or all zero |
pose.compose(child), pose.inverse(), pose.transform_point(point) |
T_A_B.compose(T_B_C) is T_A_C; T_P_C.inverse() is T_C_P; a Point rotated and translated |
range.point() |
the reading on the sensor's +x axis; None for anything but a measured distance, including -inf, closer than min_range: a brake reads range itself |
There is no * operator: Pose * Point and Pose * Vector3 would differ by operand type alone.
A mount is a constant
Write a mount in the frame set; never publish it. A transform published once never reaches a node that starts later: a reader starts at a topic's newest publication, and a node drops what arrived while it was starting. A mount is not a #[param] either: a parameter holds a scalar, and a safety node may not declare one. To recalibrate a mount, rebuild.
What each language has
| Rust | Python | |
|---|---|---|
| The conventions | the doc comments of robot_messages |
the comments of tail_messages |
The arithmetic, frames! and lookup |
robot_messages and frames |
not yet |
Until Python has them, a Python node computes transforms by hand, against the conventions in its definitions. Out of tree, the SDK ships frames with its source, beside robot_messages, for an application's host tests.
NodeError
[ 10.704226] [FAIL] periodic upstream: could not start: topic `orphan/input` never appeared
[ 10.712284] [FAIL] periodic upstream: its publication `orphan/output` is left without a writer
The node upstream created its output orphan/output. Then it waited 10 s for an input
that nobody publishes, and gave up.
A NodeError says why a node ended. Either it could not start, or the Fault policy
stopped it. The node writes ERROR records to the system log and exits with status 1. Each
record starts with the node's name.
The text opens with the phase: could not start or stopped. So a node that ran for an
hour and then missed a deadline never reads as a node that failed to start.
Where the records go
The framework registers the node's log ring before the first release. Each record is one
write into that ring, so a record never makes a cycle wait. logview -s periodic reads the
ring, also after the node is gone.
| Your image | The records go to |
|---|---|
has log_server, already running |
the node's log ring |
has log_server, which starts after the node |
the console, until the ring is registered (within 2 s of the node's start), then the ring |
has no log_server |
the console |
A record written before the ring is registered stays on the console and is not in the ring.
Why a node ended
Every record in this table means the node is not running. Fix the cause, then start the node again.
| Cause | NodeError |
The record, after <node>: |
|---|---|---|
every is not a duration |
BadDuration { key: DurationKey::Every, text } |
could not start: `every` is `20 ms`, not a duration |
an input's stale_after is not a duration |
BadDuration { key: DurationKey::StaleAfter(topic), text } |
could not start: `stale_after` of `sensor/range` is `70 ms`, not a duration |
| the period is zero, or rounds to zero ticks | UnusablePeriod |
could not start: the period rounds to zero ticks on this clock |
| a topic still has no publisher after 10 s | NeverAppeared(topic) |
could not start: topic `sensor/range` never appeared |
| the transport refuses the open, and waiting will not help | Refused(topic, TopicError) |
could not start: topic `sensor/range` refused the open: and the transport's reason |
a hand-written lease is not a duration |
BadDuration { key: DurationKey::Lease, text } |
could not start: `lease` is `100 ms`, not a duration |
| the lease is shorter than twice the period | LeaseTooShort { lease, every } |
could not start: lease 39ms is shorter than twice the period 20ms |
| a topic of the served action cannot be opened | ActionRefused { action, topic, reason } |
could not start: action drive_to: drive_to/__goal: and a reason (below) |
the Fault policy stopped the node |
DeadlineMissed(overruns) |
stopped: missed 2 release(s) under on_overrun = Fault |
The #[serve] attribute refuses a bad lease at build time, so you meet the lease row
only if you call the framework by hand.
An ActionRefused record ends in one of these reasons: topic storage full,
held by another definition, no seat free, name too long, or the transport's own words.
What a failed start leaves behind
drive: could not start: topic `odometry` never appeared
drive: its publication `cmd/velocity` is left without a writer
drive: its publication `drive/state` is left without a writer
The drive node has two outputs, cmd/velocity and drive/state, and one input,
odometry, that never appears. A node opens its outputs first, in declaration order. So
both outputs exist when the input fails, and each gets a record.
A node that reads an orphaned topic starts and stays silent. It reports nothing. The "left without a writer" record is the only place that names the topic.
A failed start is a NodeFailure:
| Item | Is |
|---|---|
NodeFailure::reason() |
the NodeError |
NodeFailure::orphaned_publications() |
the outputs left without a writer, in declaration order; empty if none |
NodeFailure::records() |
FailureRecord::Ended(reason), then one FailureRecord::Orphaned(topic) per orphaned output: one log record each |
Display of NodeFailure |
those records joined by "; ", for a place with room for one line |
Limits of a record
A record of the system log holds 96 bytes after the periodic tag. That is why a failure
is several records, one fact each, and each record leads with its names.
- A refused-open record can lose its end. Its tail is the transport's reason, which can
be long. The node and topic names always fit. The
NodeErrorcarries the whole reason. - A mistyped-duration record fits while the node's name, the topic and the text are 36 bytes or fewer together. Past that it loses its end, never the key or the start of the topic.
- "Left without a writer" does not check other writers. A
KernelLanetopic can have other writers, and one of them may still be alive. - A publisher your program opened itself is not named (see Raw ends).
Records from a running node
| Record | Level | When |
|---|---|---|
<node>: missed 2 release(s) |
WARNING | after each cycle that was handed an overrun count |
<node>: 16 consecutive publishes to <topic> refused (<reason>); still trying |
ERROR | on the 16th refused publish in a row on one output |
The node keeps running after both records.
missed N release(s): act if it repeats. The node's work does not fit its period.16 consecutive publishes ... refused: act. Readers of that topic get nothing new. The record comes once per run of refusals. A new run starts after a publish on that output succeeds or the body declines to publish. Each output keeps its own count, and a refusal on one output does not stop the others.
<reason> is the transport's. On SafeLane, a publication the kernel refused is
Refused.
The body runs once on every release, whatever the transports answer.
A Python node writes the refused-publishes record, in the same words, to the console and
not to its log ring, so logview does not show it.
Migrating a node
From a hand-written timer loop
Before: you write the thread, the clock and the sleep.
use std::thread;
use std::time::{Duration, Instant};
use robot_topics::{Range, SENSOR_RANGE};
fn main() -> Result<(), periodic::TopicError> {
let mut range = periodic::publisher(&SENSOR_RANGE)?;
let period = Duration::from_millis(20);
loop {
let started = Instant::now();
range.publish(&read_sensor())?;
thread::sleep(period.saturating_sub(started.elapsed()));
}
}
After: you write the work.
use periodic::{periodic, Out};
use robot_topics::{Range, SENSOR_RANGE};
#[periodic(every = "20ms", on_overrun = Skip)]
fn lidar(#[publish(SENSOR_RANGE)] range: Out<Range>) {
range.publish(read_sensor());
}
| You wrote | You now write |
|---|---|
fn main, a thread and a loop |
the body, as a function with #[periodic(..)] |
| a sleep for "the rest of the period" | every = "20ms" |
| nothing, or your own code for a late cycle | on_overrun = Skip, CatchUp or Fault |
periodic::publisher(&TOPIC)? |
#[publish(TOPIC)] range: Out<Range> on a parameter |
periodic::subscriber(&TOPIC)? and a read() |
#[subscribe(TOPIC, stale_after = "70ms")] range: Cycle<Range> |
| a retry loop until the topic exists | nothing: the node waits up to 10 s for its topics |
| state in local variables before the loop | init = <expr>, and &mut S as a parameter |
The relative sleep in the "before" loop adds each cycle's scheduling delay to the period,
so the loop drifts. A node's releases fall on start + n * period and never drift.
From the old header keys
A node written for an older SDK does not build. subscribe, stale_after, lane and
publish are no longer header keys, and a node no longer returns what it publishes. The
compiler error prints the edit for your node.
Before:
#[periodic(
every = "20ms",
subscribe = "overrun/raw",
publish = "overrun/piped",
lane = safe,
stale_after = "100ms",
on_overrun = Skip
)]
fn overrun_pipe(raw: Cycle<Tick>) -> Tick {
raw.copied().unwrap_or(Tick { cycle: 0 })
}
The build says:
error: `subscribe`, `publish`, `lane` and `stale_after` are not node keys: a topic is a typed definition that carries its payload and its lane, and each input and each output is declared on the parameter it belongs to. For this node:
import use periodic::{Out, SafeLane, Topic};
define const INPUT: Topic<Tick, SafeLane> = Topic::new("overrun/raw");
write #[subscribe(INPUT, stale_after = "100ms")] raw: Cycle<Tick>
define const OUTPUT: Topic<Tick, SafeLane> = Topic::new("overrun/piped");
write #[publish(OUTPUT)] output: Out<Tick>, a parameter of `overrun_pipe`
write output.publish(value) where `overrun_pipe` returned the value, and remove `-> Tick`
remove `subscribe`, `publish`, `lane`, `stale_after` from `#[periodic(..)]`
After, with those lines applied:
use periodic::{periodic, Cycle, Out, SafeLane, Topic};
/// The chain's first topic.
const OVERRUN_RAW: Topic<Tick, SafeLane> = Topic::new("overrun/raw");
/// The chain's second topic.
const OVERRUN_PIPED: Topic<Tick, SafeLane> = Topic::new("overrun/piped");
#[periodic(every = "20ms", on_overrun = Skip)]
fn overrun_pipe(
#[subscribe(OVERRUN_RAW, stale_after = "100ms")] raw: Cycle<Tick>,
#[publish(OVERRUN_PIPED)] tick: Out<Tick>,
) {
tick.publish(raw.copied().unwrap_or(Tick { cycle: 0 }));
}
The error prints the names INPUT, OUTPUT and output. Rename them after the topics and
the output. If another program also uses a topic, move the topic and its payload to a file
both programs import, as in your first nodes.
A node that already uses typed topics but still writes publish = RANGE and returns its
value gets the same kind of error. For
#[periodic(every = "20ms", on_overrun = Skip, publish = RANGE)] fn lidar() -> Range:
error: `publish` is not a node key: a topic is a typed definition that carries its payload and its lane, and each input and each output is declared on the parameter it belongs to. For this node:
import use periodic::Out;
write #[publish(RANGE)] output: Out<Range>, a parameter of `lidar`
write output.publish(value) where `lidar` returned the value, and remove `-> Range`
remove `publish` from `#[periodic(..)]`
A node that returned Option<Range> is told to publish where `lidar` returned `Some(value)` (and nothing where it returned `None`). A release that returned None
becomes a release on which the body does not call publish.
| You wrote | You now write |
|---|---|
subscribe = "sensor/range" in the header |
#[subscribe(SENSOR_RANGE, stale_after = "70ms")] on the parameter |
one stale_after = ".." in the header, for the node |
one stale_after on each input |
lane = safe in the header, in every program |
the lane in the topic's type, once: Topic<Range, SafeLane> |
publish = "sensor/range" or publish = SENSOR_RANGE, and -> Range |
#[publish(SENSOR_RANGE)] range: Out<Range>, and range.publish(value) where the body returned it |
-> Option<Range>, returning None to publish nothing |
no return type; call range.publish(value) only on the releases that publish |
the payload struct and unsafe impl ShmSafe in each program |
the payload once, beside the topic's definition, with #[derive(WirePlain)] |
the state first, as &mut S |
the state as the one parameter with no marker, anywhere in the list, as &mut S or &S |
zero_copy::Subscriber::<Range>::open("sensor/range") |
periodic::subscriber(&SENSOR_RANGE) |
A node can now have any number of inputs and outputs. The migration changes syntax only:
each stale_after keeps its value. Check it against the
sizing rule yourself.
What changes when you rebuild
Rebuild every node against the current SDK, also a node whose source does not change. A binary built against an older SDK is terminated at its first topic call.
| Older SDK | Now | |
|---|---|---|
| The first release | handed whatever the input held at open | has no input: nothing published before the node started reaches it |
| An input whose topic never appears | the node opened no output | the node creates its outputs first, then fails, and names each one in a record |
| Time a node waits for its topics | 20 s per topic | 10 s for the whole node |
| A period that rounds to zero ticks | refused after the topics were opened | refused before any topic is opened |
| The order a node's inputs open in | SafeLane and FastLane first |
as written |
| A body whose publish is refused | did not run on that release | runs on every release |
A KernelLane input slower than its publisher |
handed the oldest queued publication | handed the newest |
A FastLane input whose publisher stops |
never went stale | goes stale after stale_after |
A KernelLane end of another payload |
admitted; each publication counted in rejected() |
refused at open, naming the topic and the payload it carries |
rejected() on a KernelLane input |
a publication of another size | always 0 |
missed() on a KernelLane input |
drops in the reader's own ring | what the topic overwrote since the input opened |
The largest KernelLane payload |
the largest message-pool cell | 4 KiB; a larger one does not build |
| A mistyped duration's record | could not start: `70 ms` is not a duration |
names the key and, for an input, its topic |
NodeError::BadDuration |
BadDuration(text) |
BadDuration { key, text } |
periodic::parse_duration returns |
Result<Duration, NodeError> |
Result<Duration, NotADuration>; both print with {} |
Cycle |
has topic() and arrived() |
Executor
let mut executor = Executor::new(clock, Duration::from_millis(20), OverrunPolicy::Skip)?;
let missed = executor.run(|_overruns| do_work());
The Executor is the release loop that #[periodic] drives. Most nodes never use it. It
is public so you can test a cadence without a topic.
Executor::new(clock, period, policy)
let mut executor = Executor::new(clock, Duration::from_millis(20), OverrunPolicy::Skip)?;
Starts releasing every period, from now. It fails with StartError::UnusablePeriod if the
period is zero or rounds to zero ticks. On the target, periodic::executor::MonotonicClock
is the system clock.
run(body) -> u32
let mut executor = Executor::new(clock, Duration::from_millis(20), policy)?;
let missed = executor.run(|overruns| {
if overruns > 0 { log::log!(WARNING, "lidar: missed {overruns} release(s)"); }
do_work();
});
// Only Fault gets here.
log::log!(ERROR, "lidar: stopped: missed {missed} release(s) under on_overrun = Fault");
std::process::exit(1);
Runs until the policy stops the node, then returns how many releases the stopping cycle ran past. The closure gets each cycle's overrun count.
| Policy | The closure sees | run returns |
|---|---|---|
Skip |
the releases missed since the previous cycle | never |
CatchUp |
always 0: missed releases run back to back | never |
Fault |
always 0 | the releases the stopping cycle ran past |
Under Fault the return value is the only place the count goes, so run is
#[must_use]. A hand-built executor logs nothing. Log both counts yourself, as above.
step(body) -> ControlFlow<u32>
let missed = loop {
if let ControlFlow::Break(missed) = executor.step(|_overruns| do_work()) {
break missed;
}
};
Runs one cycle. It returns Continue(()) to go on, or Break(missed) once the policy has
stopped the node. Only Fault stops it. missed is the count run returns, and step is
#[must_use] for the same reason.
release() / period()
let next = executor.release();
The next release, and the declared period, in clock ticks.
Clock
What the executor sleeps against: now(), ticks_per_second() and
sleep_until(deadline). The executor sleeps until each release, never for
"now + period". A relative sleep adds each cycle's scheduling delay to the period and never
recovers it.
next_release(policy, release, period, now)
let (missed, next) = next_release(OverrunPolicy::Skip, release, period, now);
A pure function over ticks. It returns how many releases were missed, and where the next release falls.
period_ticks(period, ticks_per_second)
let ticks = period_ticks(Duration::from_millis(20), clock.ticks_per_second())?;
A declared period in ticks, or None if it is zero or cannot be represented.
Glossary
action: a request that takes many releases, such as "drive to (2.0, 0.5)": a client sends a goal, and the serving node reports feedback on every release and ends it with a result.
frame (coordinate frame): one of the robot's coordinate systems, declared once at build
time with frames!, so a lookup gives the transform between any two.
goal: one request of an action, sent by a client and lent to the serving node's body on every release until it ends.
input: a topic a node reads, declared on a Cycle<T> parameter with
#[subscribe(TOPIC, stale_after = "..")].
lane: how a topic's messages travel, written in the topic's type: KernelLane copies
through the kernel (up to 4 writers, 4 KiB), SafeLane shares memory with one writer and
may carry safety data, FastLane shares memory with one writer and may not.
layout identity: a 32-bit hash of a payload's fields, their order and types, which
WirePlain derives; an end whose identity differs from the topic's is refused at open.
lease: how long a served goal lives without its client's keep-alive, at least twice the
period, after which the node ends the goal Abandoned.
node: a function with #[periodic(..)] whose body the framework runs once on every
release.
output: a topic a node publishes, declared on an Out<T> parameter with
#[publish(TOPIC)] and published when the body returns.
overrun: a cycle that runs past its next release; on_overrun says what happens then.
parameter: a run-time parameter, a value declared with #[param(default = .., range = ..)]
that the shell can change while the node runs.
payload: the type a topic carries, a standard robot_messages record or your own
#[repr(C)] struct that derives WirePlain.
period: the interval every sets; releases fall on start + n * period.
release: one scheduled instant on the period's grid, at which the body runs once.
release journal: the record that every node with an output publishes on
<node>/__releases at every release, which replay reads.
replay: running one node again, offline, against a recording with --replay FILE, and
comparing its outputs with the recorded ones.
stale_after: an input's bound on how old a reading may be, measured from receipt at this node, before it reads as absent.
topic: a named channel that carries one payload type on one lane, defined once as a
Topic<Payload, Lane> constant.