humidity_core/sensors/
hygrometer.rs

1//! All about hygrometer sensors.
2
3use super::Sensor;
4use crate::serde::{self, Deserializable, Serializable};
5
6/// Represents a variety of soil moisture sensors.
7#[derive(Debug, Clone, Copy, PartialEq)]
8#[repr(u8)]
9pub enum Hygrometer {
10    /// Models the YL-69 resistive sensor.
11    YL69,
12    /// Models HW-390 capacitive sensor.
13    HW390,
14}
15
16impl Sensor for Hygrometer {
17    /// The ADC reading for the sensor when exposed to water.
18    fn low(&self) -> u16 {
19        match self {
20            Hygrometer::YL69 => 220,
21            Hygrometer::HW390 => 1000,
22        }
23    }
24
25    /// The ADC reading for the sensor when exposed to air.
26    fn high(&self) -> u16 {
27        match self {
28            Hygrometer::YL69 => 2053,
29            Hygrometer::HW390 => 2050,
30        }
31    }
32}
33
34impl Serializable for Hygrometer {
35    fn serialize(&self, ser: &mut serde::Serializer) -> Result<usize, serde::Error> {
36        ser.write_u8(*self as u8)
37    }
38}
39
40impl Deserializable for Hygrometer {
41    fn deserialize(de: &mut serde::Deserializer) -> Result<Self, serde::Error> {
42        match de.read_u8()? {
43            0 => Ok(Self::YL69),
44            1 => Ok(Self::HW390),
45            _ => Err(serde::Error::Other),
46        }
47    }
48}
49
50#[cfg(test)]
51mod test {
52    use super::*;
53    use test_case::test_case;
54
55    #[test_case(Hygrometer::YL69)]
56    #[test_case(Hygrometer::HW390)]
57    fn test_percentage_boundaries(sut: Hygrometer) {
58        let actual = sut.percentage(sut.low());
59        assert_eq!(0.0, actual);
60
61        let actual = sut.percentage(sut.high());
62        assert_eq!(1.0, actual);
63    }
64
65    #[test_case(Hygrometer::YL69, 1400, 0.6437534)]
66    #[test_case(Hygrometer::HW390, 1400, 0.3809524)]
67    fn test_percentage(sut: Hygrometer, input: u16, expected: f32) {
68        let actual = sut.percentage(input);
69        assert_eq!(expected, actual);
70    }
71}