use sensor_db::mock::MockFlash;
use sensor_db::{Error, SensorData, SensorDb, sensor_registry};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
const PAGE: usize = 256;
const SECTOR: usize = 4096;
const SECTORS: usize = 8;
type Flash = MockFlash<PAGE, SECTOR>;
type Db = SensorDb<Flash, PAGE, SECTORS>;
#[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct TemperatureV0 {
celsius: f32,
}
impl SensorData for TemperatureV0 {
const SENSOR_ID: u16 = 0x01;
}
#[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct TemperatureV1 {
millikelvin: u32,
}
impl SensorData for TemperatureV1 {
const SENSOR_ID: u16 = 0x01;
const SCHEMA_VERSION: u8 = 1;
}
#[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct TemperatureV2 {
millikelvin: u32,
sensor_ok: u8,
_pad: [u8; 3],
}
impl SensorData for TemperatureV2 {
const SENSOR_ID: u16 = 0x01;
const SCHEMA_VERSION: u8 = 2;
}
sensor_registry![TemperatureV0, TemperatureV1, TemperatureV2];
fn celsius_to_mk(c: f32) -> u32 {
((c + 273.15) * 1000.0) as u32
}
fn main() -> Result<(), Error> {
println!("=== schema evolution: a firmware update mid-deployment ===\n");
let mut db: Db = SensorDb::new(Flash::new(SECTORS * SECTOR), 0, SECTORS as u16, 1)?;
db.format()?;
println!("1. Months of readings from the shipped firmware");
for i in 0..10u64 {
db.append_sensor(
i * 1_000,
&TemperatureV0 {
celsius: 20.0 + i as f32,
},
)?;
}
db.sync()?;
println!(" logged 10 readings as TemperatureV0 (celsius: f32)");
println!("\n2. The update lands. New readings use the new layout.");
for i in 10..20u64 {
db.append_sensor(
i * 1_000,
&TemperatureV1 {
millikelvin: celsius_to_mk(20.0 + i as f32),
},
)?;
}
db.sync()?;
println!(" logged 10 more as TemperatureV1 (millikelvin: u32)");
println!(" the log now holds two eras under one sensor id, unmigrated");
println!("\n3. A query reads its own era and steps over the other");
let mut old = Vec::new();
db.query_all_sensor::<TemperatureV0, _>(|h, v| {
old.push((h.timestamp, v.celsius));
true
})?;
let mut new = Vec::new();
db.query_all_sensor::<TemperatureV1, _>(|h, v| {
new.push((h.timestamp, v.millikelvin));
true
})?;
println!(
" TemperatureV0 sees {} readings, t={}..{}",
old.len(),
old[0].0,
old[old.len() - 1].0
);
println!(
" TemperatureV1 sees {} readings, t={}..{}",
new.len(),
new[0].0,
new[new.len() - 1].0
);
assert_eq!(old.len(), 10);
assert_eq!(new.len(), 10);
assert_eq!(old[0], (0, 20.0));
assert_eq!(new[0].0, 10_000);
assert!(old.iter().all(|(t, _)| *t < 10_000));
assert!(new.iter().all(|(t, _)| *t >= 10_000));
let unified: Vec<(u64, u32)> = old
.iter()
.map(|&(t, c)| (t, celsius_to_mk(c)))
.chain(new.iter().copied())
.collect();
println!(
" converting the old era in RAM gives {} readings end to end",
unified.len()
);
assert_eq!(unified.len(), 20);
println!("\n4. A single-entry read *raises* instead of skipping");
match db.latest_sensor::<TemperatureV0>() {
Err(Error::SchemaMismatch { expected, found }) => {
println!(
" latest_sensor::<TemperatureV0>() -> SchemaMismatch {{ expected: {expected}, found: {found} }}"
);
assert_eq!((expected, found), (0, 1));
}
other => panic!("expected SchemaMismatch, got {other:?}"),
}
let (h, v) = db
.latest_sensor::<TemperatureV1>()?
.expect("v1 entries exist");
println!(
" latest_sensor::<TemperatureV1>() -> {} mK at t={}",
v.millikelvin, h.timestamp
);
println!("\n5. The mistake the tag exists to catch");
db.append_sensor(
20_000,
&TemperatureV2 {
millikelvin: 300_000,
sensor_ok: 1,
_pad: [0; 3],
},
)?;
db.sync()?;
match db.latest_sensor::<TemperatureV1>() {
Err(Error::BufferTooSmall) => {
println!(" a v2 entry read as v1 -> BufferTooSmall");
println!(" the entry is longer than a Tagged<V1>, so the tag never lands and");
println!(" the version cannot be reported. Hence the rule: when several eras");
println!(" may be present, dispatch from the *largest* candidate type down.");
}
other => panic!("expected BufferTooSmall, got {other:?}"),
}
let (_, v2) = db.latest_sensor::<TemperatureV2>()?.expect("the v2 entry");
println!(
" latest_sensor::<TemperatureV2>() -> {} mK, sensor_ok={}",
v2.millikelvin, v2.sensor_ok
);
let short_but_tagged_v2 = [TemperatureV2::SCHEMA_VERSION, 0, 0];
db.append(TemperatureV2::SENSOR_ID, 21_000, &short_but_tagged_v2)?;
db.sync()?;
match db.latest_sensor::<TemperatureV2>() {
Err(Error::SizeMismatch { expected, actual }) => {
println!(
" same version, wrong length -> SizeMismatch {{ expected: {expected}, actual: {actual} }}"
);
println!(" i.e. the struct changed and SCHEMA_VERSION did not — a forgotten bump.");
assert_eq!((expected, actual), (1 + size_of::<TemperatureV2>(), 3));
}
other => panic!("expected SizeMismatch, got {other:?}"),
}
println!("\n6. What the tag does not cover");
db.append_value(0x77, 30_000, &1234u32)?;
db.sync()?;
let mut buf = [0u8; 8];
let (_, n) = db.latest(0x77, &mut buf)?.expect("just written");
println!(" append_value stored {n} bytes — no tag, and unreadable as a T");
assert_eq!(n, 4, "four bytes, not five: the raw path adds nothing");
println!(" two same-sized types at one (id, version) are undetectable at");
println!(" runtime — `sensor_registry!` makes it a compile error instead.");
println!("\nOK");
Ok(())
}