sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
//! A real sensor driver, end to end: BME280 → typed record → flash → remount.
//!
//! ```sh
//! cargo run --example bme280
//! ```
//!
//! **The claim: nothing between the driver and the query changes a reading.**
//! What [`bme280`](https://crates.io/crates/bme280) measures is converted once,
//! at the point of sampling, and every later step — page buffer, CRC, sector
//! seal, remount, query — hands back those exact bytes. The example asserts it
//! for every reading, after a remount.
//!
//! This is the shape a device actually has, with one substitution: the I²C bus
//! is an `embedded-hal-mock` [`I2cMock`] rather than an RP2350 peripheral, so it
//! runs in CI. The driver is the real published crate, driven through its real
//! register conversation — `init` reads the chip id, resets, and pulls the
//! factory calibration; each `measure` triggers a forced conversion and reads
//! the eight data registers. On hardware you replace `I2cMock` with
//! `embassy_rp::i2c::I2c` and delete nothing else.
//!
//! # The part that transfers: the record
//!
//! The driver hands back `Measurements { temperature: f32, pressure: f32,
//! humidity: f32 }`. You cannot implement `SensorData` for it — from this crate
//! both the trait and the type are foreign, so the orphan rule refuses, and it
//! carries none of zerocopy's derives. So declare what you want on flash and
//! convert at the boundary. See the README's *Adapting a driver's reading type*.
//!
//! `Climate` below is 8 bytes against 12 for the three `f32`s, needs no
//! floating point to read back, and has no padding — which `IntoBytes` would
//! refuse to derive over anyway.

use bme280::i2c::BME280;
use embedded_hal_mock::eh1::delay::NoopDelay;
use embedded_hal_mock::eh1::i2c::{Mock as I2cMock, Transaction};

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

// =============================================================================
// What goes on flash
// =============================================================================

/// One climate reading, in fixed point.
///
/// Field order is widest-first so `repr(C)` inserts no padding: 4 + 2 + 2 = 8.
#[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Climate {
    /// Pascals. The BME280's range is 30_000..=110_000.
    pascals: u32,
    /// Degrees celsius ×100. Covers −327.68..=327.67, against the part's −40..=85.
    celsius_x100: i16,
    /// Percent relative humidity ×100, so 0..=10_000.
    humidity_x100: u16,
}

impl SensorData for Climate {
    const SENSOR_ID: u16 = 0x01;
    const SCHEMA_VERSION: u8 = 1;
}

/// The whole adaptation: one conversion, at the point of sampling.
///
/// Generic over the driver's bus-error type, because `Measurements` carries it
/// as a phantom parameter.
///
/// `as` truncates rather than rounds, so 21.2857 °C stores as 2128 — up to
/// 0.01 °C low, an order of magnitude inside the part's own ±0.5 °C accuracy.
/// Rounding would mean `f32::round`, which is in `std`, not `core`: on a target
/// without an FPU that is a `libm` dependency bought for nothing.
impl<E> From<&bme280::Measurements<E>> for Climate {
    fn from(m: &bme280::Measurements<E>) -> Self {
        Self {
            pascals: m.pressure as u32,
            celsius_x100: (m.temperature * 100.0) as i16,
            humidity_x100: (m.humidity * 100.0) as u16,
        }
    }
}

// =============================================================================
// The device
// =============================================================================

const PAGE: usize = 256;
const SECTOR: usize = 4096;
const SECTORS: usize = 16;

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

fn main() -> Result<(), Error> {
    println!("=== BME280 → sensor-db, end to end ===\n");

    let mut delay = NoopDelay::new();
    // The mock shares its state between clones, which is what lets the bus be
    // checked at the end even though the driver has swallowed it.
    let mut bus = I2cMock::new(&bus_conversation());
    let mut sensor = BME280::new_primary(bus.clone());
    sensor.init(&mut delay).expect("the mock answers init");

    let mut db: Db = SensorDb::new(MockFlash::new(SECTORS * SECTOR), 0, SECTORS as u16, 2)?;
    db.format()?;

    // -------------------------------------------------------------------
    // Sample. On hardware this is a timer task; here the readings come from
    // three prepared register images, so the values differ and the round-trip
    // assertion below has something to catch.
    // -------------------------------------------------------------------
    let mut taken = Vec::new();
    for (i, _) in RAW_MEASUREMENTS.iter().enumerate() {
        let measured = sensor
            .measure(&mut delay)
            .expect("the mock answers measure");
        let record = Climate::from(&measured);

        println!(
            "  sample {i}: {:.2} °C  {:.2} %RH  {} Pa  →  {:?}",
            measured.temperature, measured.humidity, measured.pressure as u32, record
        );

        db.append_sensor(1_700_000_000 + i as u64, &record)?;
        taken.push(record);
    }
    // Durability is a separate decision from visibility: the readings were
    // already queryable above, but only this survives a power cut.
    db.sync()?;

    // The driver performed exactly the conversation scripted below — no
    // transaction skipped, none left over.
    bus.done();

    // -------------------------------------------------------------------
    // The power cycle. A fresh database over the same flash, mounted from what
    // is actually stored — no state carried over from the run that wrote it.
    // -------------------------------------------------------------------
    let flash = db.into_inner();
    let mut db: Db = SensorDb::new(flash, 0, SECTORS as u16, 2)?;
    let stats = db.mount()?;
    println!(
        "\n  remounted: {} entries in {} sector bodies read",
        stats.total_entries, stats.scanned_sectors
    );

    let mut read_back = Vec::new();
    db.query_all_sensor::<Climate, _>(|_, c| {
        read_back.push(*c);
        true
    })?;

    assert_eq!(
        read_back, taken,
        "every reading must come back exactly as the driver reported it"
    );
    println!(
        "  all {} readings identical to what the driver measured",
        taken.len()
    );

    // And the typed read path agrees about which one is newest.
    let (header, latest) = db
        .latest_sensor::<Climate>()?
        .expect("something was written");
    assert_eq!(latest, *taken.last().unwrap());
    println!(
        "  latest:  {} centi-°C at ts={}",
        latest.celsius_x100, header.timestamp
    );

    println!(
        "\n  {} bytes per entry ({} payload + 21 framing), against {} storing three f32s",
        21 + size_of::<Climate>(),
        size_of::<Climate>(),
        21 + 12
    );

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

// =============================================================================
// The I²C bus, which on hardware is a peripheral rather than a script
// =============================================================================

/// Primary I²C address of a BME280.
const ADDR: u8 = 0x76;

/// Factory calibration, as the part's registers report it.
///
/// Named rather than dumped as hex, because every one of these is a datasheet
/// coefficient and a blob would say nothing about what the driver does with it.
struct Calibration {
    t: [i32; 3],
    p: [i32; 9],
    h1: u8,
    h2: i16,
    h3: u8,
    h4: i16,
    h5: i16,
    h6: i8,
}

/// A plausible set, in the range a real part reports.
const CALIB: Calibration = Calibration {
    t: [28960, 26619, 50],
    p: [38364, -10497, 3024, 6812, -118, -7, 15500, -14600, 6000],
    h1: 75,
    h2: 353,
    h3: 0,
    h4: 339,
    h5: 0,
    h6: 30,
};

/// The 26 bytes at `0x88`: temperature and pressure coefficients, little endian,
/// with `dig_h1` tacked on the end.
fn pt_calib_bytes() -> Vec<u8> {
    let mut out = Vec::with_capacity(26);
    for v in CALIB.t {
        out.extend_from_slice(&(v as i16).to_le_bytes());
    }
    for v in CALIB.p {
        out.extend_from_slice(&(v as i16).to_le_bytes());
    }
    out.push(0); // 0xA0, unused
    out.push(CALIB.h1);
    out
}

/// The 7 bytes at `0xE1`. `dig_h4` and `dig_h5` share a nibble in the middle
/// byte, which is why this one cannot be a straight list of little-endian words.
fn h_calib_bytes() -> Vec<u8> {
    let h2 = CALIB.h2.to_le_bytes();
    vec![
        h2[0],
        h2[1],
        CALIB.h3,
        (CALIB.h4 >> 4) as u8,
        ((CALIB.h4 & 0x0F) as u8) | (((CALIB.h5 & 0x0F) as u8) << 4),
        (CALIB.h5 >> 4) as u8,
        CALIB.h6 as u8,
    ]
}

/// Three sets of raw ADC words: `(pressure, temperature, humidity)`.
///
/// 20-bit pressure and temperature, 16-bit humidity — the format of the eight
/// bytes at `0xF7`.
const RAW_MEASUREMENTS: [(u32, u32, u16); 3] = [
    (0x0006_5A00, 0x0008_1E00, 0x6E00),
    (0x0006_5B80, 0x0008_2400, 0x6C40),
    (0x0006_5920, 0x0008_1800, 0x7180),
];

/// The eight data registers at `0xF7`, packed as the part reports them.
fn data_bytes(pressure: u32, temperature: u32, humidity: u16) -> Vec<u8> {
    vec![
        (pressure >> 12) as u8,
        (pressure >> 4) as u8,
        ((pressure << 4) & 0xF0) as u8,
        (temperature >> 12) as u8,
        (temperature >> 4) as u8,
        ((temperature << 4) & 0xF0) as u8,
        (humidity >> 8) as u8,
        humidity as u8,
    ]
}

/// Every I²C transaction the driver performs, in order.
///
/// Spelled out rather than answered by a register simulator, because the point
/// is that this is the *real* driver's conversation: an expectation list that
/// drifts from what the crate does fails loudly on the next `cargo update`,
/// where a simulator would quietly keep answering.
fn bus_conversation() -> Vec<Transaction> {
    // `init`: identify, reset, read calibration, then configure. The register
    // values are what `BME280::init` documents — 2× temperature and 16×
    // pressure oversampling with IIR coefficient 16.
    let mut t = vec![
        Transaction::write_read(ADDR, vec![0xD0], vec![0x60]), // chip id
        Transaction::write(ADDR, vec![0xE0, 0xB6]),            // soft reset
        Transaction::write_read(ADDR, vec![0x88], pt_calib_bytes()),
        Transaction::write_read(ADDR, vec![0xE1], h_calib_bytes()),
        Transaction::write_read(ADDR, vec![0xF4], vec![0x00]), // mode: sleep
        Transaction::write(ADDR, vec![0xF2, 0x01]),            // ctrl_hum: 1×
        Transaction::write_read(ADDR, vec![0xF4], vec![0x00]),
        Transaction::write(ADDR, vec![0xF4, 0x54]), // ctrl_meas: 16× P, 2× T
        Transaction::write_read(ADDR, vec![0xF5], vec![0x00]),
        Transaction::write(ADDR, vec![0xF5, 0x10]), // config: IIR 16
    ];

    // Each `measure`: check the mode, trigger a forced conversion, read the
    // eight data registers.
    for (pressure, temperature, humidity) in RAW_MEASUREMENTS {
        t.extend([
            Transaction::write_read(ADDR, vec![0xF4], vec![0x00]),
            Transaction::write_read(ADDR, vec![0xF4], vec![0x00]),
            Transaction::write(ADDR, vec![0xF4, 0x01]), // forced mode
            Transaction::write_read(
                ADDR,
                vec![0xF7],
                data_bytes(pressure, temperature, humidity),
            ),
        ]);
    }
    t
}