Skip to main content

kiwi_measurements/
lib.rs

1#![no_std]
2#![deny(missing_docs)]
3
4//! A unified measurement representation for sensors on the Kiwi mainboard.
5//! This library provides types and serialization/deserialization methods
6//! for common sensor measurements such as accelerometer, gyroscope,
7//! magnetometer, temperature, and barometric pressure.
8
9#[cfg(feature = "defmt")]
10use defmt::Format;
11
12use heapless::String;
13
14type CrcState = crc16::State<crc16::XMODEM>;
15
16/// Accelerometer measurement type code
17pub const ACCEL_CODE: u16 = 0xACC1;
18/// Gyroscope measurement type code
19pub const GYRO_CODE: u16 = 0x6e50;
20/// Magnetometer measurement type code
21pub const MAG_CODE: u16 = 0x9A61;
22/// Temperature measurement type code
23pub const TEMP_CODE: u16 = 0x7E70;
24/// Barometric pressure measurement type code
25pub const BARO_CODE: u16 = 0xB480;
26/// Humidity measurement type code
27pub const HUMI_CODE: u16 = 0xF0AC;
28/// Ambient light measurement type code
29pub const LUX_CODE: u16 = 0x1A2B;
30/// Device identity measurement type code
31pub const ID_CODE: u16 = 0x1D1D;
32/// Received Signal Strength Indicator measurement type code
33pub const RSSI_CODE: u16 = 0x5A5A;
34
35/// Unified measurement enum
36#[derive(Debug, Clone, PartialEq)]
37#[cfg_attr(feature = "defmt", derive(Format))]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39#[non_exhaustive]
40pub enum CommonMeasurement {
41    /// Accelerometer measurement in g
42    Accel(f32, f32, f32),
43    /// Gyroscope measurement in degrees per second
44    Gyro(f32, f32, f32),
45    /// Magnetometer measurement in milligauss
46    Mag(f32, f32, f32),
47    /// Temperature measurement in degrees Celsius
48    Temp(heapless::String<8>, f32),
49    /// Temperature, pressure and altitude measurement
50    Baro(f32, f32, f32),
51    /// Temperature (degree Celsius), humidity (%), AQI measurement
52    Humi(f32, f32, f32),
53    /// Ambient light measurement in lux
54    Lux(heapless::String<8>, f32),
55    /// Device Identity
56    Id(heapless::String<12>),
57    /// Received Signal Strength Indicator measurement in dBm
58    Rssi(bool, f32),
59}
60
61/// Size of the common measurement in bytes, as returned by [`into`](CommonMeasurement::into)
62pub const COMMON_MEASUREMENT_SIZE: usize = 2 + 12; // type (2 bytes) + 12 bytes (3 * f32, 8 bytes for Temp label + f32 value)
63
64#[allow(clippy::from_over_into)]
65impl Into<[u8; COMMON_MEASUREMENT_SIZE]> for CommonMeasurement {
66    #[inline]
67    fn into(self) -> [u8; COMMON_MEASUREMENT_SIZE] {
68        self.into_bytes()
69    }
70}
71
72impl CommonMeasurement {
73    /// Represents the measurement as a byte array.
74    #[inline]
75    fn into_bytes(self) -> [u8; COMMON_MEASUREMENT_SIZE] {
76        match self {
77            CommonMeasurement::Accel(x, y, z) => encode_xyz(ACCEL_CODE, x, y, z),
78            CommonMeasurement::Gyro(x, y, z) => encode_xyz(GYRO_CODE, x, y, z),
79            CommonMeasurement::Mag(x, y, z) => encode_xyz(MAG_CODE, x, y, z),
80            CommonMeasurement::Temp(label, value) => encode_label_value(TEMP_CODE, &label, value),
81            CommonMeasurement::Baro(temp, pres, alt) => encode_xyz(BARO_CODE, temp, pres, alt),
82            CommonMeasurement::Humi(temp, humi, aqi) => encode_xyz(HUMI_CODE, temp, humi, aqi),
83            CommonMeasurement::Lux(label, value) => encode_label_value(LUX_CODE, &label, value),
84            CommonMeasurement::Id(id) => encode_id(ID_CODE, &id),
85            CommonMeasurement::Rssi(flag, value) => encode_bool_value(RSSI_CODE, flag, value),
86        }
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[cfg_attr(feature = "defmt", derive(Format))]
92/// Errors that can occur when parsing a CommonMeasurement
93pub enum CommonMeasurementError {
94    /// Invalid length of input byte slice
95    Length,
96    /// Invalid UTF-8 string for temperature label
97    String,
98    /// Invalid measurement type
99    Type,
100    /// CRC mismatch error
101    CrcMismatch,
102}
103
104impl TryFrom<&[u8]> for CommonMeasurement {
105    type Error = CommonMeasurementError;
106    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
107        if value.len() != COMMON_MEASUREMENT_SIZE {
108            return Err(CommonMeasurementError::Length);
109        }
110        let measurement = match u16::from_le_bytes(value[0..2].try_into().unwrap()) {
111            ACCEL_CODE => {
112                let (x, y, z) = parse_xyz(value);
113                CommonMeasurement::Accel(x, y, z)
114            }
115            GYRO_CODE => {
116                let (x, y, z) = parse_xyz(value);
117                CommonMeasurement::Gyro(x, y, z)
118            }
119            MAG_CODE => {
120                let (x, y, z) = parse_xyz(value);
121                CommonMeasurement::Mag(x, y, z)
122            }
123            TEMP_CODE => {
124                let (label, value) = parse_label_value(value);
125                CommonMeasurement::Temp(label, value)
126            }
127            BARO_CODE => {
128                let (t, p, a) = parse_xyz(value);
129                CommonMeasurement::Baro(t, p, a)
130            }
131            HUMI_CODE => {
132                let (t, h, a) = parse_xyz(value);
133                CommonMeasurement::Humi(t, h, a)
134            }
135            LUX_CODE => {
136                let (label, value) = parse_label_value(value);
137                CommonMeasurement::Lux(label, value)
138            }
139            ID_CODE => {
140                let id_str = core::str::from_utf8(&value[2..14])
141                    .map_err(|_| CommonMeasurementError::String)?
142                    .trim_end_matches(char::from(0));
143                CommonMeasurement::Id(String::try_from(id_str).map_err(|_| CommonMeasurementError::String)?)
144            }
145            RSSI_CODE => {
146                let (flag, value) = parse_bool_value(value);
147                CommonMeasurement::Rssi(flag, value)
148            }
149            _ => return Err(CommonMeasurementError::Type),
150        };
151        Ok(measurement)
152    }
153}
154
155/// Size of a single measurement in bytes, as returned by [`SingleMeasurement::into`]
156pub const SINGLE_MEASUREMENT_SIZE: usize = 24;
157
158#[derive(Debug, Clone, PartialEq)]
159#[cfg_attr(feature = "defmt", derive(Format))]
160#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
161/// A single measurement with a timestamp
162pub struct SingleMeasurement {
163    /// Measurement data
164    pub measurement: CommonMeasurement,
165    /// Timestamp in microseconds
166    /// Note: This timestamp is relative to an arbitrary epoch, e.g., system start time.
167    pub timestamp: u64,
168}
169
170#[allow(clippy::from_over_into)]
171impl Into<[u8; SINGLE_MEASUREMENT_SIZE]> for SingleMeasurement {
172    #[inline]
173    fn into(self) -> [u8; SINGLE_MEASUREMENT_SIZE] {
174        self.into_bytes()
175    }
176}
177
178impl SingleMeasurement {
179    /// Represents the single measurement as a byte array.
180    /// This is a form of binary serialization that includes a CRC for integrity checking.
181    #[inline]
182    fn into_bytes(self) -> [u8; SINGLE_MEASUREMENT_SIZE] {
183        // Byte map:
184        // [2 byte TYPE] [12 bytes measurement data] [8 bytes timestamp] [2 bytes CRC]
185        let mut bytes = [0u8; SINGLE_MEASUREMENT_SIZE];
186        bytes[0..COMMON_MEASUREMENT_SIZE].copy_from_slice(&self.measurement.into_bytes());
187        bytes[COMMON_MEASUREMENT_SIZE..COMMON_MEASUREMENT_SIZE + 8]
188            .copy_from_slice(&self.timestamp.to_le_bytes());
189        let crc = CrcState::calculate(&bytes[0..SINGLE_MEASUREMENT_SIZE - 2]);
190        bytes[SINGLE_MEASUREMENT_SIZE - 2..].copy_from_slice(&crc.to_le_bytes());
191        bytes
192    }
193}
194
195impl TryFrom<&[u8]> for SingleMeasurement {
196    type Error = CommonMeasurementError;
197    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
198        if value.len() != SINGLE_MEASUREMENT_SIZE {
199            return Err(CommonMeasurementError::Length);
200        }
201        let received_crc = u16::from_le_bytes(
202            value[SINGLE_MEASUREMENT_SIZE - 2..SINGLE_MEASUREMENT_SIZE]
203                .try_into()
204                .unwrap(),
205        );
206        let computed_crc = CrcState::calculate(&value[0..SINGLE_MEASUREMENT_SIZE - 2]);
207        if received_crc != computed_crc {
208            return Err(CommonMeasurementError::CrcMismatch);
209        }
210        let measurement = CommonMeasurement::try_from(&value[0..COMMON_MEASUREMENT_SIZE])?;
211        let timestamp = u64::from_le_bytes(
212            value[COMMON_MEASUREMENT_SIZE..COMMON_MEASUREMENT_SIZE + 8]
213                .try_into()
214                .unwrap(),
215        );
216        Ok(SingleMeasurement {
217            measurement,
218            timestamp,
219        })
220    }
221}
222
223fn encode_bool_value(code: u16, flag: bool, value: f32) -> [u8; COMMON_MEASUREMENT_SIZE] {
224    let mut bytes = [0u8; COMMON_MEASUREMENT_SIZE];
225    bytes[0..2].copy_from_slice(&code.to_le_bytes());
226    bytes[2..6].copy_from_slice(&(if flag { 1u32 } else { 0 }).to_le_bytes());
227    bytes[6..10].copy_from_slice(&value.to_le_bytes());
228    bytes
229}
230
231fn parse_xyz(value: &[u8]) -> (f32, f32, f32) {
232    let x = f32::from_le_bytes(value[2..6].try_into().unwrap_or([0u8; 4]));
233    let y = f32::from_le_bytes(value[6..10].try_into().unwrap_or([0u8; 4]));
234    let z = f32::from_le_bytes(
235        value[10..COMMON_MEASUREMENT_SIZE]
236            .try_into()
237            .unwrap_or([0u8; 4]),
238    );
239    (x, y, z)
240}
241
242fn parse_bool_value(value: &[u8]) -> (bool, f32) {
243    let flag = u32::from_le_bytes(value[2..6].try_into().unwrap_or([0u8; 4])) != 0;
244    let val = f32::from_le_bytes(value[6..10].try_into().unwrap_or([0u8; 4]));
245    (flag, val)
246}
247
248fn parse_label_value(value: &[u8]) -> (String<8>, f32) {
249    let label_end = value[2..10].iter().position(|&b| b == 0).unwrap_or(8);
250    let label: String<8> =
251        String::try_from(core::str::from_utf8(&value[2..2 + label_end]).unwrap_or("Unknown"))
252            .unwrap_or_else(|_| String::new());
253    let val = f32::from_le_bytes(
254        value[10..COMMON_MEASUREMENT_SIZE]
255            .try_into()
256            .unwrap_or([0u8; 4]),
257    );
258    (label, val)
259}
260
261fn encode_xyz(code: u16, x: f32, y: f32, z: f32) -> [u8; COMMON_MEASUREMENT_SIZE] {
262    let mut bytes = [0u8; COMMON_MEASUREMENT_SIZE];
263    bytes[0..2].copy_from_slice(&code.to_le_bytes());
264    bytes[2..6].copy_from_slice(&x.to_le_bytes());
265    bytes[6..10].copy_from_slice(&y.to_le_bytes());
266    bytes[10..COMMON_MEASUREMENT_SIZE].copy_from_slice(&z.to_le_bytes());
267    bytes
268}
269
270fn encode_label_value(code: u16, label: &str, value: f32) -> [u8; COMMON_MEASUREMENT_SIZE] {
271    let mut bytes = [0u8; COMMON_MEASUREMENT_SIZE];
272    bytes[0..2].copy_from_slice(&code.to_le_bytes());
273    let label_bytes = label.as_bytes();
274    let len = label_bytes.len().min(8);
275    bytes[2..2 + len].copy_from_slice(&label_bytes[..len]);
276    bytes[10..COMMON_MEASUREMENT_SIZE].copy_from_slice(&value.to_le_bytes());
277    bytes
278}
279
280fn encode_id(code: u16, id_str: &str) -> [u8; COMMON_MEASUREMENT_SIZE] {
281    let mut bytes = [0u8; COMMON_MEASUREMENT_SIZE];
282    bytes[0..2].copy_from_slice(&code.to_le_bytes());
283    let id_bytes = id_str.as_bytes();
284    let len = id_bytes.len().min(12);
285    bytes[2..2 + len].copy_from_slice(&id_bytes[..len]);
286    bytes
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    extern crate std;
293
294    #[test]
295    fn test_common_measurement_serialization() {
296        let original = CommonMeasurement::Temp(heapless::String::try_from("CPU").unwrap(), 36.5);
297        let bytes: [u8; _] = original.clone().into();
298        let deserialized = CommonMeasurement::try_from(&bytes[..]).unwrap();
299        assert_eq!(original, deserialized);
300    }
301
302    #[test]
303    fn test_single_measurement_serialization() {
304        let original = SingleMeasurement {
305            measurement: CommonMeasurement::Accel(0.1, 0.2, 0.3),
306            timestamp: 123456789,
307        };
308        let bytes: [u8; _] = original.clone().into();
309        let deserialized = SingleMeasurement::try_from(&bytes[..]).unwrap();
310        assert_eq!(original, deserialized);
311    }
312
313    #[test]
314    fn test_single_measurement_crc_mismatch() {
315        let original = SingleMeasurement {
316            measurement: CommonMeasurement::Gyro(1.0, 2.0, 3.0),
317            timestamp: 987654321,
318        };
319        let mut bytes: [u8; _] = original.into();
320        // Corrupt a byte to simulate CRC mismatch
321        bytes[5] ^= 0xFF;
322        let result = SingleMeasurement::try_from(&bytes[..]);
323        assert!(matches!(result, Err(CommonMeasurementError::CrcMismatch)));
324    }
325
326    #[test]
327    fn test_common_measurement_humi() {
328        let original = CommonMeasurement::Humi(25.0, 60.0, 42.0);
329        let bytes: [u8; _] = original.clone().into();
330        let deserialized = CommonMeasurement::try_from(&bytes[..]).unwrap();
331        assert_eq!(original, deserialized);
332    }
333
334    #[test]
335    fn test_common_measurement_lux() {
336        let original = CommonMeasurement::Lux(heapless::String::try_from("Room").unwrap(), 350.0);
337        let bytes: [u8; _] = original.clone().into();
338        let deserialized = CommonMeasurement::try_from(&bytes[..]).unwrap();
339        assert_eq!(original, deserialized);
340    }
341    #[test]
342    fn test_common_measurement_id() {
343        let original = CommonMeasurement::Id(heapless::String::try_from("kiwi#0001").unwrap());
344        let bytes: [u8; _] = original.clone().into();
345        let deserialized = CommonMeasurement::try_from(&bytes[..]).unwrap();
346        assert_eq!(original, deserialized);
347    }
348
349    #[test]
350    fn test_single_measurement_id() {
351        let original = CommonMeasurement::Id(heapless::String::try_from("kiwi#0001").unwrap());
352        let original = SingleMeasurement {
353            measurement: original,
354            timestamp: 555555555,
355        };
356        let bytes: [u8; _] = original.clone().into();
357        let deserialized = SingleMeasurement::try_from(&bytes[..]).unwrap();
358        assert_eq!(original, deserialized);
359    }
360
361    #[test]
362    fn test_common_measurement_rssi() {
363        let original = CommonMeasurement::Rssi(true, -42.0);
364        let bytes: [u8; _] = original.clone().into();
365        let deserialized = CommonMeasurement::try_from(&bytes[..]).unwrap();
366        assert_eq!(original, deserialized);
367    }
368
369    #[test]
370    #[cfg(feature = "serde")]
371    fn test_single_measurement_serde_baro() {
372        let original = SingleMeasurement {
373            measurement: CommonMeasurement::Baro(25.0, 1013.25, 150.0),
374            timestamp: 555555555,
375        };
376        let serialized = serde_json::to_string(&original).unwrap();
377        let deserialized: SingleMeasurement = serde_json::from_str(&serialized).unwrap();
378        std::println!("Serialized: {}", serialized);
379        assert_eq!(original, deserialized);
380    }
381
382    #[test]
383    #[cfg(feature = "serde")]
384    fn test_single_measurement_serde_temp() {
385        let original = SingleMeasurement {
386            measurement: CommonMeasurement::Temp(heapless::String::try_from("CPU").unwrap(), 36.5),
387            timestamp: 123456789,
388        };
389        let serialized = serde_json::to_string(&original).unwrap();
390        let deserialized: SingleMeasurement = serde_json::from_str(&serialized).unwrap();
391        std::println!("Serialized: {}", serialized);
392        assert_eq!(original, deserialized);
393    }
394}