A first log¶
The drive is a motor controller board. It should keep the last days of its log lines, its mode, its bus frames and its battery voltage on its Secure Digital (SD) card. This chapter answers what its firmware has to do for that. The firmware describes the streams once and lends the logger its buffers. It then mounts the ring at boot, pushes each item as it happens and calls a tick now and then.
All code on this page is the drive's firmware from the crate logring_example. It runs on a card simulated in RAM, so
it runs on a personal computer (PC) as it is. The same code builds for the drive's microcontroller.
The drive's streams¶
The drive already has a WireWeaver API, so its streams have names and types. Each stream becomes a track of the ring, and each value a stream sends becomes an item of that track:
#[ww_api_root]
pub trait Drive {
/// The firmware's log lines, a few per second.
stream!(log: LogLine<'i>);
/// The controller's mode, sent on every change.
stream!(mode: Mode);
/// Frames seen on the vehicle bus, about a thousand per second.
stream!(can0: CanFrame<'i>);
/// The battery voltage, once a second.
stream!(vbat: Vbat);
}
The item types are ordinary shrink_wrap types, the same ones the API sends over its link. A log line borrows its text, and a frame of the Controller Area Network (CAN) bus borrows its data bytes. Nothing on the way to the card allocates.
Describing the tracks¶
The firmware tells the ring which tracks it has in a TrackDesc per track. A track names its stream by its path in
the API: UNib32(2) is the third stream, can0. The path, not a string, identifies a track on the card, as Tracks,
sessions and recordings explains.
/// The drive's tracks, in the order of [track]: each names its stream by its path in the API.
pub static TRACK_DESCS: [TrackDesc<'static>; TRACKS - 1] = [
TrackDesc {
rate: Some(2),
..TrackDesc::new(&[UNib32(0)])
},
// a change of mode is on the card before `mode` returns
TrackDesc {
durability: Durability::Immediate,
..TrackDesc::new(&[UNib32(1)])
},
TrackDesc {
rate: Some(1000),
..TrackDesc::new(&[UNib32(2)])
},
TrackDesc {
rate: Some(1),
..TrackDesc::new(&[UNib32(3)])
},
];
The rate is a hint for a reader on a PC: about how many items per second the track carries. The mode track is
Immediate, so a change of mode is on the card before the call returns. Flushes and power
cuts says what that costs and when it pays.
The descriptions go into a SessionInfo together with the API's name and version and the drive's serial number,
firmware and hardware versions. drive::session builds it.
Mounting at boot¶
The logger needs RAM, and the firmware lends it in a Buffers. Its two numbers are the size of the [[stage
buffer]], 4096 bytes, and the number of tracks, five: the drive's four and the system track. The firmware keeps
Buffers in a static or on its main task's stack, since logring has no heap.
/// Mount the ring on `card` in a new session, with the buffers `bufs` lent for the logger's life.
pub async fn mount(
card: M,
bufs: &'a mut Buffers<BUF, TRACKS>,
cfg: Config,
) -> Result<Self, Error<M::Error>> {
let mut lr = Logring::new(card, bufs, cfg, session())?;
lr.mount().await?;
Ok(Drive {
lr,
item: [0; ITEM_MAX],
})
}
Logring::new checks the Config against the card and the tracks against the buffers, and writes nothing. The
mount then finds where the log ended, recovers every track's position and starts a new session. On a new
card it starts a new log instead. The config's segment size is 64 KiB on the simulated card, a size that fits the
small card in RAM. The SD card explains how a real card sets it.
Pushing items¶
Each track gets one call in the drive's logger. The call encodes the item into a buffer of 128 bytes. It then pushes the item to its track with the time it happened, in microseconds since boot:
/// Record a frame of the vehicle bus at `t_us`.
pub async fn can_frame(
&mut self,
t_us: u64,
id: u32,
data: &[u8],
) -> Result<(), Error<M::Error>> {
let frame = CanFrame {
id,
data: RefVec::Slice { slice: data },
};
self.push(track::CAN0, t_us, &frame).await
}
Logring::push turns the item into a record: the item's bytes with its track, its position and its time. The
record goes into the stage buffer in RAM. Most pushes return at once. The push that fills the stage buffer also writes
it to the card.
The tick¶
The records reach the card in a flush, which the stage buffer builds a piece at a time. The drive ends a flush once it holds 16 KiB, or once it has been open for a second. The first case needs no help, but the second needs a clock. The firmware therefore calls a tick with its millisecond clock about every 100 ms:
/// Write the flush being filled once it has been open for the flush interval. The firmware calls it every
/// 100 ms or so with its millisecond clock; returns whether it flushed.
pub async fn tick(&mut self, now_ms: u64) -> Result<bool, Error<M::Error>> {
Ok(self.lr.flush_if_due(now_ms).await?)
}
The first minute¶
The bench run bench::run drives the logger as the drive does on its endurance bench. It boots and runs the motor
from the first second on. It records a frame a millisecond, a voltage a second and a log line every two seconds. This
block mounts a ring on a new simulated card and runs the first minute:
use logring::Buffers;
use logring::tests_support::block_on;
use logring_example::bench::{self, Bench};
use logring_example::card::SIM_CARD_BYTES;
use logring_example::{Drive, SimCard, drive};
let mut card = vec![0u8; SIM_CARD_BYTES];
let mut bufs = Buffers::new();
let totals = block_on(async {
let mut drive = Drive::mount(SimCard::new(&mut card), &mut bufs, drive::config()).await?;
bench::run(&mut drive, Bench::FIRST_MINUTE).await
})
.unwrap();
assert_eq!(totals.can0, 60_000);
assert_eq!(totals.vbat, 60);
The minute holds 60 000 frames, 60 voltages, 31 log lines and 3 changes of mode. The ring took them in 70 flushes, which
filled 17 segments of 64 KiB. They take 1032 KiB of the card. A frame's item is 13 bytes, and its record adds its track,
position and time. The example's story prints these numbers (cargo run -p logring_example --features std --example
story).
The drive logs now, but a reader of its card still wants to know which boot and which test run a record belongs to. Tracks, sessions and recordings is about that.
can0, named by its path in the device's API.pub struct TrackDesc<'a> {
/// The stream's resource path in the device API as wire_weaver ids, array indices included: the form requests
/// use (wire_weaver `docs/api/addressing.md`), up to [MAX_PATH] ids.
pub path: RefVec<'a, UNib32>,
/// The item type's `ww_self` signature (`ww_self::signature`, 8 bytes), `None` when the firmware doesn't know it.
pub signature: Option<[u8; 8]>,
/// The `ww_global` id of the item type's crate (`GlobalTypeId`), when it has one.
pub global_id: Option<u32>,
pub durability: Durability,
/// Nominal items per second, for sizing and the view; `None` when unknown.
pub rate: Option<u32>,
}
A track as the firmware declares it: a stream of a #ww_trait in the session's API bundle. Numbers only: the
names (can[1].rx, ww_can_bus::Frame) are made on the PC from the bundle stored with the session.
pub struct SessionInfo<'a> {
/// The API root: `<ROOT_TRAIT>_FULL_GID` of the API crate. Its [api_root_id] is part of every track's stable
/// key; the name and version themselves are stored only in the session's meta record, as a fallback for a host
/// without the bundle.
pub api: FullVersion<'a>,
/// Device id, firmware and hardware descriptions (up to 64 bytes each), stored with the session.
pub device_id: &'a str,
pub fw: &'a str,
pub hw: &'a str,
/// Data tracks: track `i + 1` is `tracks[i]`; track 0 is the system track.
pub tracks: &'a [TrackDesc<'a>],
/// The API bundle the tracks' types come from (`ww_self`), stored once per hash in the meta area.
pub bundle: Option<&'a [u8]>,
}
What a session (one mount) tells the ring about itself.
pub fn session() -> SessionInfo<'static> {
SessionInfo {
api: DRIVE_FULL_GID,
device_id: "drive-0042",
fw: "drive fw 1.4.0",
hw: "drive rev C",
tracks: &TRACK_DESCS,
bundle: Some(DRIVE_BUNDLE),
}
}
What the drive tells the ring about itself at every mount.
pub struct Buffers<const BUF: usize, const TRACKS: usize> {
stage: StageBuf<BUF>,
tracks: [Track; TRACKS],
/// Every track's `next` as of the last sealed block, and as of the last block written
sealed_next: [u64; TRACKS],
durable_next: [u64; TRACKS],
/// Every track's newest record as of the last sealed block, and as of the last block written
sealed_newest: [Option<u64>; TRACKS],
durable_newest: [Option<u64>; TRACKS],
}
The writer's memory that grows with BUF and TRACKS: the stage buffer and the per-track state.
pub fn new(
medium: M,
b: &'a mut Buffers<BUF, TRACKS>,
cfg: Config,
info: SessionInfo<'a>,
) -> Result<Self, Error<M::Error>>
A writer on medium with the lent buffers (reset here), not mounted yet: Logring::mount or
Logring::format next.
pub struct Config
How a Logring lays out and runs its medium.
pub async fn push(
&mut self,
track: u32,
item: &[u8],
t: Option<Second>,
) -> Result<(), Error<M::Error>>
Store item on track as the next event: position from the track's state, one unit, time t.
pub async fn run<M: LogMedium>(
drive: &mut Drive<'_, M>,
bench: Bench,
) -> Result<Totals, Error<M::Error>> {
let mut n = Totals::default();
run_counting(drive, bench, &mut n).await?;
Ok(n)
}
Run the bench on a mounted drive, then write what is left to the card.