scd30_interface/data/
measurement.rs1use byteorder::{BigEndian, ByteOrder};
2
3use crate::{error::DataError, util::check_deserialization};
4
5#[derive(Debug)]
7pub struct Measurement {
8 pub co2_concentration: f32,
10 pub temperature: f32,
12 pub humidity: f32,
14}
15
16#[cfg(feature = "defmt")]
17impl defmt::Format for Measurement {
18 fn format(&self, f: defmt::Formatter) {
19 defmt::write!(
20 f,
21 "{}ppm, {}°C, {}%",
22 self.co2_concentration,
23 self.temperature,
24 self.humidity
25 )
26 }
27}
28
29impl TryFrom<&[u8]> for Measurement {
30 type Error = DataError;
31
32 fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
40 check_deserialization(data, 18)?;
41 Ok(Self {
42 co2_concentration: f32::from_bits(BigEndian::read_u32(&[
43 data[0], data[1], data[3], data[4],
44 ])),
45 temperature: f32::from_bits(BigEndian::read_u32(&[
46 data[6], data[7], data[9], data[10],
47 ])),
48 humidity: f32::from_bits(BigEndian::read_u32(&[
49 data[12], data[13], data[15], data[16],
50 ])),
51 })
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn sample_measurement_deserializes_properly() {
61 let data: [u8; 18] = [
62 0x43, 0xDB, 0xCB, 0x8C, 0x2E, 0x8F, 0x41, 0xD9, 0x70, 0xE7, 0xFF, 0xF5, 0x42, 0x43,
63 0xBF, 0x3A, 0x1B, 0x74,
64 ];
65 let result = Measurement::try_from(&data[..]).unwrap();
66 assert_eq!(result.co2_concentration, 439.09515);
67 assert_eq!(result.temperature, 27.23828);
68 assert_eq!(result.humidity, 48.806744);
69 }
70}