scd30_interface/data/
measurement.rs

1use byteorder::{BigEndian, ByteOrder};
2
3use crate::{error::DataError, util::check_deserialization};
4
5/// A measurement read from the SCD30.
6#[derive(Debug)]
7pub struct Measurement {
8    /// The CO2 concentration in ppm, ranging from 0 to 10.000 ppm.
9    pub co2_concentration: f32,
10    /// The ambient temperature in °C, ranging from -40 to 125 °C.
11    pub temperature: f32,
12    /// The relative humidity in %, ranging from 0 to 100 %.
13    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    /// Converts buffered data to a [Measurement] value.
33    ///
34    /// # Errors
35    ///
36    /// - [ReceivedBufferWrongSize](crate::error::DataError::ReceivedBufferWrongSize) if the `data` buffer is not big enough for the data
37    ///   that should have been received.
38    /// - [CrcFailed](crate::error::DataError::CrcFailed) if the CRC of the received data does not match.
39    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}