Skip to main content

percepter_scd41/
error.rs

1//! # Error types for the SCD41 driver
2//!
3//! This module defines the `Scd41Error` enum, which covers various error
4//! conditions that can occur during communication with the SCD41 sensor.
5
6use std::error::Error;
7use std::fmt::{Display, Formatter, Debug};
8
9/// Errors that can occur when interacting with the SCD41 sensor.
10#[derive(Debug)]
11pub enum Scd41Error<E> {
12    /// I2C communication error.
13    I2c(E),
14    /// CRC mismatch when reading data from the sensor.
15    CrcMismatch {
16        /// The expected CRC value.
17        expected: u8,
18        /// The actual CRC value received from the sensor.
19        actual: u8,
20        /// The data bytes that the CRC was calculated for.
21        bytes: [u8; 2],
22    },
23    /// Data not ready yet (e.g., when calling `read_measurement` before the sensor has finished).
24    DataNotReady,
25    /// Recalibration failed.
26    RecalibrationFailed,
27}
28
29impl<E: Display> Display for Scd41Error<E> {
30    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Scd41Error::I2c(error) => write!(f, "I2C communication error: {}", error),
33            Scd41Error::CrcMismatch {
34                expected,
35                actual,
36                bytes,
37            } => write!(
38                f,
39                "CRC mismatch: expected: {}, actual: {}, bytes: {:?}",
40                expected, actual, bytes
41            ),
42            Scd41Error::DataNotReady => write!(f, "Data not ready"),
43            Scd41Error::RecalibrationFailed => write!(f, "Recalibration failed"),
44        }
45    }
46}
47
48impl<E: Debug + Display> Error for Scd41Error<E> {}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_display() {
56        let error: Scd41Error<linux_embedded_hal::I2CError> = Scd41Error::CrcMismatch {
57            expected: 0x00,
58            actual: 0x01,
59            bytes: [0x00, 0x01],
60        };
61        assert_eq!(format!("{}", error), "CRC mismatch: expected: 0, actual: 1, bytes: [0, 1]");
62
63        let error: Scd41Error<linux_embedded_hal::I2CError> = Scd41Error::DataNotReady;
64        assert_eq!(format!("{}", error), "Data not ready");
65    }
66}