Skip to main content

sensor_registry

Macro sensor_registry 

Source
macro_rules! sensor_registry {
    ($($ty:ty),* $(,)?) => { ... };
}
Expand description

Assert at compile time that no two sensor types collide.

Lists the SensorData types a firmware uses and fails the build if any two share a SENSOR_ID at the same SCHEMA_VERSION.

use sensor_db::{SensorData, sensor_registry};
use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Temperature { celsius: f32 }
impl SensorData for Temperature {
    const SENSOR_ID: u16 = 0x01;
}

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Humidity { percent: f32 }
impl SensorData for Humidity {
    const SENSOR_ID: u16 = 0x02;
}

sensor_registry! {
    Temperature,
    Humidity,
}

Give Humidity the same SENSOR_ID and the build stops, naming both types:

ⓘ
use sensor_db::{SensorData, sensor_registry};
use sensor_db::zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Temperature { celsius: f32 }
impl SensorData for Temperature {
    const SENSOR_ID: u16 = 0x01;
}

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Humidity { percent: f32 }
impl SensorData for Humidity {
    const SENSOR_ID: u16 = 0x01;   // <-- taken, and the same size
}

sensor_registry! { Temperature, Humidity }
error[E0080]: evaluation panicked: sensor registry: `Temperature` and
`Humidity` share a SENSOR_ID at the same SCHEMA_VERSION. ...

§Schema evolution is not a collision

Sharing an ID at different versions is the supported way to evolve a payload — each type reads its own era out of one log — so the registry accepts it:

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct TemperatureV0 { celsius: f32 }
impl SensorData for TemperatureV0 {
    const SENSOR_ID: u16 = 0x01;
    const SCHEMA_VERSION: u8 = 0;
}

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
struct TemperatureV1 { millikelvin: u32 }
impl SensorData for TemperatureV1 {
    const SENSOR_ID: u16 = 0x01;
    const SCHEMA_VERSION: u8 = 1;
}

sensor_registry! { TemperatureV0, TemperatureV1 }

§What it checks, and what it cannot

The macro expands to an anonymous const block of assertions and defines nothing, so it can appear in any module, as often as you like — but it only ever knows about the types you list. It cannot see across crate boundaries, and a type left off the list is not checked. Keep one invocation naming every type the firmware writes, next to the ID definitions, and add to it in the same commit that adds a sensor.

The pairwise expansion is quadratic in the number of types. At the scale a sensor ID space actually reaches — tens — that is free; it is not built for thousands.