sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! The shortest useful program: store readings, read them back, survive a reboot.
//!
//! Everything else in `examples/` takes one claim this crate makes and
//! demonstrates it. This one is just the shape of the API:
//!
//! ```sh
//! cargo run --example quickstart
//! ```
//!
//! On real hardware the only line that changes is the flash device. Swap
//! [`MockFlash`] for `embassy_rp::flash::Flash` (or any `embedded-storage`
//! `NorFlash`) and the rest is identical.

use sensor_db::mock::MockFlash;
use sensor_db::{Error, SensorData, SensorDb};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

// A reading is a plain `#[repr(C)]` struct. The zerocopy derives let it go to
// flash without a serialiser; `SensorData` binds it to an id so the id stops
// being an argument you have to remember at every call site.
//
// With the `derive` feature this is `#[derive(SensorData)]` plus
// `#[sensor(id = 0x01)]`; written out here so the example needs no feature.
#[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Temperature {
    celsius: f32,
}

impl SensorData for Temperature {
    const SENSOR_ID: u16 = 0x01;
}

/// 256-byte pages, 4 KB sectors, 8 sectors — 32 KB of flash.
const PAGE: usize = 256;
const SECTOR: usize = 4096;
const SECTORS: usize = 8;

type Db = SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>;

fn main() -> Result<(), Error> {
    // `PAGE` must be a whole number of the driver's `WRITE_SIZE`; that is
    // checked at compile time, so a mismatched geometry fails the build rather
    // than the first flush.
    let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
    let mut db: Db = SensorDb::new(flash, 0, SECTORS as u16, 1)?;

    // `format` wipes and mounts. On a device that already holds a log you want
    // `mount()` instead — see the reboot below.
    db.format()?;

    // ---------------------------------------------------------------------
    // Write
    // ---------------------------------------------------------------------
    for i in 0..20u64 {
        db.append_sensor(
            i * 1_000, // timestamp, in whatever unit you keep time
            &Temperature {
                celsius: 20.0 + i as f32 * 0.25,
            },
        )?;
    }

    // Appends land in a one-page RAM buffer. `sync` is what makes them durable,
    // and it is the *only* thing it is for: the reads below would see these
    // entries either way. Batching syncs trades a power-loss window for flash
    // endurance — see `examples/power_loss.rs` for exactly what that window is.
    db.sync()?;

    // ---------------------------------------------------------------------
    // Read
    // ---------------------------------------------------------------------
    let (header, latest) = db.latest_sensor::<Temperature>()?.expect("20 were stored");
    println!("latest:  {:.2} C at t={}", latest.celsius, header.timestamp);

    let (_, oldest) = db.oldest_sensor::<Temperature>()?.expect("20 were stored");
    println!("oldest:  {:.2} C", oldest.celsius);
    println!("stored:  {} readings", db.count_sensor::<Temperature>()?);

    // Queries stream into a callback rather than allocating — this crate is
    // `no_std` and has no allocator to reach for. Return `false` to stop early.
    let mut warm = 0;
    db.query_all_sensor::<Temperature, _>(|_, t| {
        if t.celsius > 23.0 {
            warm += 1;
        }
        true
    })?;
    println!("above 23 C: {warm}");

    // A time range, inclusive at both ends.
    let mut window = Vec::new();
    db.query_sensor::<Temperature, _>(5_000, 8_000, |h, t| {
        window.push((h.timestamp, t.celsius));
        true
    })?;
    println!("t in [5000, 8000]: {window:?}");

    // ---------------------------------------------------------------------
    // Reboot
    // ---------------------------------------------------------------------
    // Taking the flash back out and building a fresh `SensorDb` over it is
    // exactly what a power cycle looks like to this crate: nothing but the
    // flash contents carries over.
    let flash = db.into_inner();
    let mut db: Db = SensorDb::new(flash, 0, SECTORS as u16, 1)?;
    let stats = db.mount()?;

    println!(
        "\nafter reboot: {} entries recovered, {} sector bodies read",
        stats.total_entries, stats.scanned_sectors,
    );

    // `scanned_sectors` is the mount cost that scales with data stored rather
    // than with sector count: sealed sectors carry a footer that indexes them
    // in one page read, so only the sector left active has to be walked.

    let (_, after) = db.latest_sensor::<Temperature>()?.expect("it survived");
    assert_eq!(after, latest, "the same reading, byte for byte");
    println!("latest still: {:.2} C", after.celsius);

    // And the log is writable again immediately.
    db.append_sensor(99_000, &Temperature { celsius: -40.0 })?;
    db.sync()?;
    assert_eq!(db.count_sensor::<Temperature>()?, 21);

    println!("\nOK");
    Ok(())
}