sen66_interface/data/
data_status.rs

1use crate::{error::DataError, util::check_deserialization};
2
3const DATA_STATUS_VALUE: &str = "Data ready status";
4const DATA_STATUS_EXPECTED: &str = "0 or 1";
5
6/// Describes whether a new measurement is ready to be read from the sensor.
7#[derive(Debug, PartialEq)]
8pub enum DataStatus {
9    /// New Data is ready and can be read.
10    Ready,
11    /// No new data is available to be read.
12    NotReady,
13}
14
15#[cfg(feature = "defmt")]
16impl defmt::Format for DataStatus {
17    fn format(&self, f: defmt::Formatter) {
18        match self {
19            DataStatus::Ready => defmt::write!(f, "Ready"),
20            DataStatus::NotReady => defmt::write!(f, "Not Ready"),
21        }
22    }
23}
24
25impl TryFrom<&[u8]> for DataStatus {
26    type Error = DataError;
27
28    /// Converts buffered data to an [DataStatus] value.
29    ///
30    /// # Errors
31    ///
32    /// - [ReceivedBufferWrongSize](crate::error::DataError::ReceivedBufferWrongSize) if the `data`
33    ///   buffer is not big enough for the data that should have been received.
34    /// - [CrcFailed](crate::error::DataError::CrcFailed) if the CRC of the received data does not
35    ///   match.
36    /// - [UnexpectedValueReceived](crate::error::DataError::UnexpectedValueReceived) if the
37    ///   received value is not `0` or `1`.
38    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
39        check_deserialization(data, 3)?;
40        match data[1] {
41            0x00 => Ok(Self::NotReady),
42            0x01 => Ok(Self::Ready),
43            val => Err(DataError::UnexpectedValueReceived {
44                parameter: DATA_STATUS_VALUE,
45                expected: DATA_STATUS_EXPECTED,
46                actual: val as u16,
47            }),
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn data_status_is_enabled_if_one_is_send() {
58        let data = [0x00, 0x01, 0xB0];
59        assert_eq!(DataStatus::try_from(&data[..]).unwrap(), DataStatus::Ready);
60    }
61
62    #[test]
63    fn data_status_is_disabled_if_zero_is_send() {
64        let data = [0x00, 0x00, 0x81];
65        assert_eq!(
66            DataStatus::try_from(&data[..]).unwrap(),
67            DataStatus::NotReady
68        );
69    }
70
71    #[test]
72    fn receiving_invalid_value_for_data_status_emits_error() {
73        let data = [0x00, 0x03, 0xD2];
74        assert!(DataStatus::try_from(&data[..]).is_err());
75    }
76}