Перейти к основному содержимому
Эта страница ещё не переведена

Ниже показан английский оригинал.

Embedded runtime

A device service runs on embassy's executor and clock as one task. #[ruststream::app(runtime = embassy)] turns the builder function into an EmbeddedApp and an embassy task, app::task, that the board's main spawns. The handlers are the ones a server runs, written with #[subscriber].

A device with no heap builds the framework without the alloc feature. That build is a form of its own: it allocates nothing at startup or per message, and it keeps in storage of a fixed size what the heap form keeps on the heap. The selection is by features: embassy picks the runner, memory the local bus, macros the attributes, postcard or json-core the codec, and log or defmt for the logger the app selects. Cargo features add up, so one crate of the dependency graph that turns alloc on turns it on for the whole build. tokio, json, cbor and msgpack turn alloc on.

Example​

The dependency line of a device with no heap:

[dependencies]
ruststream = { version = "0.8", default-features = false, features = ["embassy", "memory", "macros", "postcard", "defmt"] }

The service reads a sensor's readings from the board's bus, reports them in degrees, and updates a display once each report is acknowledged.

/// A sensor's reading, as the other end of the bus encodes it with postcard, the build's default codec.
#[derive(Serialize, Deserialize, Outgoing)]
#[outgoing(name = "sensors/temp")]
struct Reading {
sensor: u8,
millivolts: u16,
}

/// What the board reports for a reading.
#[derive(Serialize, Deserialize, Outgoing)]
#[outgoing(name = "reports")]
struct Report {
sensor: u8,
celsius: i16,
}

/// Reports every reading in degrees.
#[subscriber(LocalMemorySource::new("sensors/temp"), reply)]
async fn on_reading(reading: &Reading) -> Report {
let millivolts = i32::from(reading.millivolts);
Report {
sensor: reading.sensor,
celsius: i16::try_from((millivolts - 500) / 10).unwrap_or(i16::MAX),
}
}

/// Takes the reports and updates the display once each is acknowledged.
#[subscriber(LocalMemorySource::new("reports"))]
async fn on_report(report: &Report) -> HandlerOutcome {
let celsius = report.celsius;
// The continuation lives in a room of 128 bytes; a capture past it does not compile.
HandlerOutcome::ack().and_after(async move { show(celsius).await })
}

/// Draws a temperature on the board's display.
async fn show(celsius: i16) {
Timer::after_millis(10).await;
let _ = celsius;
}

fn app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| {
b.include(on_report)
.include(on_reading)
.out_reply(LocalMemoryPublish)
.encode_capacity::<64>()
})
}

The board declares the bus as a static and the app function receives a broker built over it. The binary supplies the critical-section implementation the bus needs. On a core without compare-and-swap, such as a Cortex-M0+, the firmware also gives portable-atomic its critical-section feature.

/// The board's bus: each subscription holds four messages.
type Bus = LocalMemoryBroker<4>;

/// The bus is a `static` the board declares; the app function receives a broker built over it,
/// `Bus::new(&BUS)`.
static BUS: LocalMemoryBus<4> = LocalMemoryBus::new();

What the build holds​

Each part whose size the heap would decide has a fixed form.

PartForm without alloc
Headers of a messageFixedHeaders of 8 entries and 256 bytes; insert returns an error when the map is full, and an OutgoingMessage borrows the map where it was built: .with_headers(&headers)
CodecSliceCodec, which encodes into a slice and decodes from one: PostcardCodec (postcard) and JsonCoreCodec (json-core)
Continuationheld in a room of 128 bytes, aligned to 8 bytes
Failures read by .errorborrowed from the subscription's fixed buffer: async move |failures: &Failures| ..
Message of a refused publisha place of fixed size, about 700 bytes, held by the refusal until the message is read out as the publish returns: a subscription keeps one, an Out slot one, and a publisher used on its own one in each publish
ctx.after(..), ctx.after_ack(..), ctx.after_settle(..)a delivery holds four registrations; one more returns an error, and nothing registered is dropped
Batchup to 16 messages, named at the mount with .batch::<N>(), of messages that deserialize themselves, that the mount's codec decodes, or values the subscription already carries; the handler takes Out slots or returns one reply per message, and the outcomes are Outcomes<HandlerOutcome, N>
Local busa LocalMemoryBus of fixed size that the board declares as a static
Statehooks and handlers borrow it: async |state: &State| ..

A mount that names no codec uses the default codec of the build: JsonCoreCodec when json-core is on, PostcardCodec otherwise. A mount names another at its site: b.with_codec(PostcardCodec) for the handlers, .out_reply(policy).codec(PostcardCodec) for a reply and .out(marker, policy).codec(PostcardCodec) for an Out slot.

Capacities​

A capacity is a const generic or a crate constant, and each is declared at one place.

CapacityWhereValue
Messages, payload bytes and subscriptions of the busLocalMemoryBus<MESSAGES, PAYLOAD, SUBSCRIPTIONS>PAYLOAD is 64 and SUBSCRIPTIONS is 8 unless named
Delayed retries waiting at once.retry_capacity::<CAP>()a count above zero; on a batch mount at least N, and at most 1024
Bytes a reply is encoded into.encode_capacity::<N>()256 unless named
Places for the messages of refused publishes.refusal_capacity::<N>() on the mount, or on a publisher used on its ownone for a subscription, whatever it holds at once, and one in each publish of a publisher, unless named
Workers of a subscription.pool::<N>() or .keyed::<N>()a count above zero
Messages of a batch.batch::<N>()1 to 16
Continuationcrate constant128 bytes
Registrations of a deliverycrate constant4
Payload kept in a copy of a deliverycrate constant256 bytes

The compiler holds the capacities that a mount names:

  • A continuation that captures more than 128 bytes does not build. The error is an overflow in ROOM - size_of::<Work>() that prints both numbers. It appears at cargo build, not at cargo check.
  • A continuation aligned to more than 8 bytes does not build either, and the error names the limit. A future that awaits an embassy-time timer is aligned to 8 bytes and fits on every core.
  • A batch size outside 1 to 16 is an error that names .batch::<N>() and the limit.
  • An .encode_capacity::<N>() past what the reply publisher can carry is an error that names both numbers. A publisher that keeps the payload (Take) is handed a buffer of 256 bytes; a publisher that only reads the bytes has no such limit.
  • A retry store, a pool, a worker count or a count of places of zero does not build.
  • A batch mount whose .retry_capacity::<CAP>() is below its batch size N is an error that names both numbers: a batch that retries whole needs one record per element.

A capacity that a run exceeds is a failure the handler hears of:

  • A reply that does not fit its buffer is a publish error, CodecFailure::BufferFull, and reaches the handler's .error like any failed reply.
  • A delayed retry that finds the retry store full is the "no free record" error of the same kind.
  • A retry or dead-letter copy of a delivery whose payload is larger than 256 bytes cannot be kept, delayed or sent at once, and is a failed publish as well.
  • A refused publish that finds every place taken reaches .error with its error and without its message: no bytes and no headers.

Continuations and retries​

A continuation attaches to an outcome with and_after, or to the context with ctx.after_ack(..). In this build the context calls return a Result, and the handler decides what a refusal means.

/// A humidity reading.
#[derive(Serialize, Deserialize, Outgoing)]
#[outgoing(name = "sensors/humidity")]
struct Humidity {
sensor: u8,
percent: u8,
}

/// Asks for the reading again in a minute, and counts a retry that found no room to wait.
#[subscriber(LocalMemorySource::new("sensors/humidity"))]
async fn on_humidity(reading: &Humidity, ctx: &mut Context<'_, (), Lost>) -> HandlerOutcome {
let lost = ctx.state().0;
let _ = reading.sensor;
HandlerOutcome::retry_after(Duration::from_secs(60)).error(async move |failures: &Failures| {
lost.fetch_add(failures.len(), Ordering::Relaxed);
})
}

fn retrying_app(bus: Bus) -> EmbeddedApp<impl Mounts<State = Lost>> {
EmbeddedApp::new()
.with_state(Lost(&LOST))
.with_broker(bus, |b| {
// Room for two delayed retries at a time.
b.include(on_humidity).retry_capacity::<2>()
})
}

The retry store sits in the app's type, so its capacity is part of the registration. The .error closure borrows the failure, so it does not copy the message into the continuation's room.

Batches​

A batch handler takes a slice, and the mount names the size. The slice holds messages that deserialize themselves, or messages the mount's codec decodes.

/// A frame from the sensor, as its bytes.
#[derive(Deserialized)]
struct Frame<'a>(&'a [u8]);

/// Takes the frames that arrived together, up to eight.
#[subscriber(LocalMemorySource::new("sensors/burst"))]
async fn on_burst(frames: &[Frame<'_>]) -> HandlerOutcome {
let bytes: usize = frames.iter().map(|frame| frame.0.len()).sum();
let _ = bytes;
HandlerOutcome::ack()
}

fn batching_app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| b.include(on_burst.batch::<8>()))
}

A batch handler that returns one HandlerOutcome settles the whole batch with it. To settle each message on its own, it returns Outcomes<HandlerOutcome, N>, one entry per message in the order of the slice, with N the size the mount names.

/// Settles each frame on its own: an empty frame is dropped, the others are acknowledged.
#[subscriber(LocalMemorySource::new("sensors/frames"))]
async fn on_frames(frames: &[Frame<'_>]) -> Outcomes<HandlerOutcome, 4> {
let mut outcomes = Outcomes::new();
for frame in frames {
let outcome = if frame.0.is_empty() {
HandlerOutcome::drop()
} else {
HandlerOutcome::ack()
};
// The mount takes at most four frames, so every outcome has its place.
let _ = outcomes.push(outcome);
}
outcomes
}

fn framing_app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| b.include(on_frames.batch::<4>()))
}

Retries and dead letters​

A batch mount takes the steps of a single-message one: .retry_capacity::<CAP>(), .max_attempts(n).dead_letter(..) and .out_retry(..). retry_after and dead letters work for each element, whether the handler returns one outcome for the batch or one per message. The store keeps one record for each element a batch retries at once, so CAP is at least N.

/// A reading that may be a spike.
#[derive(Serialize, Deserialize, Outgoing)]
#[outgoing(name = "sensors/spikes")]
struct Spike {
sensor: u8,
millivolts: u16,
}

/// Asks for the whole burst again in a minute when the display is busy.
#[subscriber(LocalMemorySource::new("sensors/spikes"))]
async fn on_spikes(readings: &[Spike]) -> Outcomes<HandlerOutcome, 4> {
readings
.iter()
.map(|reading| {
if reading.millivolts > 3000 {
HandlerOutcome::retry_after(Duration::from_secs(60))
} else {
HandlerOutcome::ack()
}
})
.collect()
}

fn spiking_app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| {
// Room for the four delayed copies a full batch can ask for.
b.include(on_spikes.batch::<4>()).retry_capacity::<4>()
})
}

Replies​

A batch handler mounted with reply publishes one reply for each element, in the order of the slice, and returns them as Outcomes<Reply, N>. A reply the bus refuses is lost together with the replies behind it, and the .error continuation receives them; there are at most N.

/// A reading of the burst.
#[derive(Serialize, Deserialize, Outgoing)]
#[outgoing(name = "sensors/batch")]
struct Sample {
sensor: u8,
millivolts: u16,
}

/// Reports every reading of the batch, one report for each.
#[subscriber(LocalMemorySource::new("sensors/batch"), reply)]
async fn on_readings(readings: &[Sample]) -> Outcomes<Report, 4> {
readings
.iter()
.map(|reading| Report {
sensor: reading.sensor,
celsius: i16::try_from((i32::from(reading.millivolts) - 500) / 10).unwrap_or(i16::MAX),
})
.collect()
}

fn reporting_app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| {
b.include(on_report)
.include(on_readings.batch::<4>())
.out_reply(LocalMemoryPublish)
})
}

Continuations​

An outcome that follows the whole batch has one .error, which reads every failed copy once, after the last copy is reported. Its .then runs once when at least one element succeeded. The failures of a batch gather in one place for the mount, so a second batch outcome with an .error waits until the first has run its closure. With retry_after, the wait lasts the delay of the first batch's copies. Outcomes without an .error, one outcome per element, and copies that go out at once do not wait.

An outcome for one element carries its own .then and .error. Each worker of the mount has one continuation slot, so the continuations of the elements run one after another, in the order of the batch.

Out slots​

A batch handler may take Out slots and publish through them as a single-message handler does. A slot encodes a typed value with the codec its mount names, or with the default codec of the build. A handler that both replies and takes Out is refused, as on a single delivery.

Diagnostics​

The app selects the logger with .logger(..) on the EmbeddedApp, and nothing is reported until it does. tracing needs the heap, so this build selects LogLogger or DefmtLogger, whichever feature the build enables; a heap-backed app selects TracingLogger. The reports are the same ones the tokio runner makes: a reply the bus did not take, a continuation that never runs, a retry that found no room. Each names the subscription and the message type, and the level of the logger's backend decides which show.

# A host or a board with a logger.
ruststream = { version = "0.8", default-features = false, features = ["embassy", "memory", "macros", "postcard", "log"] }

Testing​

The harness follows the build: without alloc the embedded TestApp drives the fixed form, with the mock clock and the same assertions as with a heap. See Testing an embedded app.