scd30_interface/data/
altitude_compensation.rs

1use byteorder::{BigEndian, ByteOrder};
2
3use crate::{error::DataError, util::check_deserialization};
4
5/// Altitude compensation value ranging from 0 m to 65535 m above sea level.
6#[derive(Debug, PartialEq)]
7pub struct AltitudeCompensation(u16);
8
9#[cfg(feature = "defmt")]
10impl defmt::Format for AltitudeCompensation {
11    fn format(&self, f: defmt::Formatter) {
12        defmt::write!(f, "{}m", self.0)
13    }
14}
15
16impl AltitudeCompensation {
17    /// Returns a big endian byte representation of the altitude compensation value.
18    pub const fn to_be_bytes(&self) -> [u8; 2] {
19        self.0.to_be_bytes()
20    }
21}
22
23impl From<u16> for AltitudeCompensation {
24    fn from(altitude: u16) -> Self {
25        Self(altitude)
26    }
27}
28
29impl TryFrom<&[u8]> for AltitudeCompensation {
30    type Error = DataError;
31
32    /// Converts buffered data to an [AltitudeCompensation] 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, 3)?;
41        Ok(Self(BigEndian::read_u16(&data[..2])))
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn deserialize_specification_sample_works() {
51        let data = [0x03, 0xE8, 0xD4];
52        let altitude = AltitudeCompensation::try_from(&data[..]).unwrap();
53        assert_eq!(altitude.0, 1000);
54    }
55
56    #[test]
57    fn serialize_specification_sample_works() {
58        let altitude = AltitudeCompensation(1000);
59        assert_eq!(altitude.to_be_bytes(), [0x03, 0xE8]);
60    }
61
62    #[test]
63    fn creating_from_u16_works() {
64        let altitude = AltitudeCompensation::from(1000);
65        assert_eq!(altitude, AltitudeCompensation(1000));
66    }
67}