Skip to main content

A device service on the local memory broker

A thermometer board runs a RustStream service on the embassy runtime with no heap, and tests it on the host under an allocator that fails on any allocation the framework makes.

The shop of the earlier chapters runs on MemoryBroker and the tokio runtime. A firmware has its own pair: the embedded runtime and the local memory broker, a queue between the parts of one board. The subscribers read the same, and the mounts have the same chain form. This chapter builds a small board: a sensor publishes readings, the board reports them in degrees and raises an alert when one is hot.

The dependency​

Cargo.toml
[dependencies]
ruststream = { version = "0.8", default-features = false, features = ["embassy", "memory", "macros", "postcard"] }
serde = { version = "1", default-features = false, features = ["derive"] }

default-features = false leaves out tokio and json, and embassy brings the embedded runner. postcard is the build's default codec: it encodes into a slice and decodes from one, so the board keeps no buffer on a heap. A mount that names no codec uses it. Nothing in this list turns the framework's alloc feature on, so every part whose size a heap would decide has a fixed form.

The bus​

The board declares the bus as a static, and the app function receives a broker built over it. Each subscription holds four messages, counting the one a handler has in its hands. The binary supplies the critical-section implementation the bus sits behind. 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();

A handler and its reply​

A reading and its report are plain serde types that name where they go.

device.rs
/// 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,
}

The handler takes a reading and returns its report. The reply goes to the destination the report names, so the handler publishes nothing itself.

device.rs
/// 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),
}
}

The app mounts the handler on the board's bus. out_reply publishes the report through the bus in the build's default codec, and encode_capacity gives each worker the bytes to encode a reply into, 256 by default. A reply that does not fit is refused with CodecFailure::BufferFull, never cut: the delivery is acknowledged and the failure reaches the handler's .error continuation.

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

Publishing to another topic​

A second handler listens to the reports and raises an alert when one passes fifty degrees. The alert is a serde type like the report, and it leaves through an Out slot, as in the shop's notices. The slot encodes it with the build's default codec.

device.rs
/// The alert the board raises for a sensor.
#[derive(Debug, PartialEq, Serialize, Deserialize, Outgoing)]
#[outgoing(name = "alerts")]
struct Alert {
sensor: u8,
}

/// The slot alerts leave through.
#[derive(OutSlot)]
#[publishes(Alert)]
struct Alarms;

/// Raises an alert for a report past fifty degrees.
#[subscriber(LocalMemorySource::new("reports"))]
async fn on_hot(report: &Report, Out(alarms): Out<impl Publisher, Alarms>) -> HandlerOutcome {
if report.celsius <= 50 {
return HandlerOutcome::ack();
}
let alert = Alert {
sensor: report.sensor,
};
match alarms.message(&alert).publish().await {
Ok(()) => HandlerOutcome::ack(),
Err(_) => HandlerOutcome::retry(),
}
}

The mount adds the handler and names the publisher behind the slot.

device.rs
fn device_app(bus: Bus) -> EmbeddedApp<impl Mounts> {
EmbeddedApp::new().with_broker(bus, |b| {
b.include(on_reading)
.out_reply(LocalMemoryPublish)
.encode_capacity::<64>()
.include(on_hot)
.out(Alarms, LocalMemoryPublish)
})
}

On the device, #[ruststream::app(runtime = embassy)] puts this function in front of the board's executor. The embedded runtime page shows the rest of the device surface: retries on the board's clock, continuations and batches.

Testing it on the host​

The tests run on the host, with std, through the embedded TestApp. It starts the app that the board runs, unchanged, and the bus is its own in-process mode, so no stand-in broker is needed. The harness keeps its own bookkeeping (the record of what each subscription received and what each slot published) on the host's heap. The framework under it stays in the form of the device: the test build does not turn alloc on, and the app is polled in its fixed form.

A test binary can prove the service allocates nothing. It installs assert_no_alloc::AllocDisabler as its global allocator, and every allocation the framework makes while the app is polled fails the test. The harness's own bookkeeping runs where the allocator lets it through. The guard works in a debug build, which is what cargo test builds.

Cargo.toml
[dev-dependencies]
ruststream = { version = "0.8", default-features = false, features = ["testing"] }
assert_no_alloc = "1.1"
futures = "0.3"
tests/device.rs
/// Fails an allocation made while the harness polls the app.
#[global_allocator]
static ALLOCATOR: AllocDisabler = AllocDisabler;
tests/device.rs
#[test]
fn a_hot_reading_raises_an_alert() -> Result<(), Box<dyn Error>> {
block_on(async {
let tb = TestApp::start(device_app(Bus::new(&BUS))).await?;
let reading = Reading {
sensor: 2,
millivolts: 1200,
};
tb.broker::<Bus>().message(&reading).publish().await?;
tb.broker::<Bus>()
.subscriber("reports")
.assert_called_once();
tb.out::<Alarms>()
.assert_called_once()
.decoded_as::<Alert>()
.with(&Alert { sensor: 2 });
tb.shutdown().await?;
Ok(())
})
}

The test publishes a reading of 1200 millivolts, which the handler reports as 70 degrees. It checks that the report reached reports and that the alert for sensor 2 left through its slot. A publish from the test returns once everything it set off has settled, so the checks follow it directly. The board's clock moves only when the test calls advance, as on the paused clock of the shop's tests.

Keeping the test in the device's form​

Cargo builds a crate once per build, with the union of the features every crate in that build asks for. A dev-dependency, or any other crate in the test build, that turns the framework's alloc feature on turns it on for the service under test too. Then the test checks the heap form of the framework, and the allocator proves nothing about the device.

The usual cause is a dependency line that keeps the default features, ruststream = { version = "0.8", features = ["testing"] }, which brings json and tokio, and both imply alloc. alloc, tokio, compio, tracing, json, msgpack, cbor and conformance do the same. So every ruststream line of the service, dev-dependencies included, carries default-features = false, and no other crate of the test build asks for one of these features.

The core keeps its own no-alloc builds apart in checks/noalloc, because the dev-dependencies of a crate's own unit tests turn alloc on. Its just test-no-alloc recipe lists the feature tree of each build with cargo tree -e features and fails if alloc appears in it. The same check fits a service:

cargo tree -e features,normal,build,dev -i ruststream-core | grep 'feature "alloc"'

The command prints nothing while the service stays in the device's form.