scd30_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/// Information whether a measurement is ready or not for readout.
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub enum DataStatus {
9    /// Data is available.
10    Ready,
11    /// No data is available.
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` buffer is not big enough for the data
33    ///   that should have been received.
34    /// - [CrcFailed](crate::error::DataError::CrcFailed) if the CRC of the received data does not match.
35    /// - [UnexpectedValueReceived](crate::error::DataError::UnexpectedValueReceived) if the received value is not `0` or `1`.
36    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
37        check_deserialization(data, 3)?;
38        match data[1] {
39            0 => Ok(Self::NotReady),
40            1 => Ok(Self::Ready),
41            val => Err(DataError::UnexpectedValueReceived {
42                parameter: DATA_STATUS_VALUE,
43                expected: DATA_STATUS_EXPECTED,
44                actual: val as u16,
45            }),
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn deserialize_not_ready_spec_sample_works() {
56        let data = [0x00, 0x00, 0x81];
57        assert_eq!(
58            DataStatus::try_from(&data[..]).unwrap(),
59            DataStatus::NotReady
60        );
61    }
62
63    #[test]
64    fn deserialize_ready_works() {
65        let data = [0x00, 0x01, 0xB0];
66        assert_eq!(DataStatus::try_from(&data[..]).unwrap(), DataStatus::Ready);
67    }
68
69    #[test]
70    fn deserialize_out_of_specification_value_errors() {
71        let data = [0x00, 0x02, 0xE3];
72        assert_eq!(
73            DataStatus::try_from(&data[..]).unwrap_err(),
74            DataError::UnexpectedValueReceived {
75                parameter: DATA_STATUS_VALUE,
76                expected: DATA_STATUS_EXPECTED,
77                actual: 2
78            }
79        );
80    }
81}