summaryrefslogtreecommitdiffstats
path: root/src/data_collection/temperature.rs
blob: b7413244c968f000822908f6fb9af462dbd1ea58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//! Data collection for temperature metrics.
//!
//! For Linux and macOS, this is handled by Heim.
//! For Windows, this is handled by sysinfo.

cfg_if::cfg_if! {
    if #[cfg(target_os = "linux")] {
        pub mod linux;
        pub use self::linux::*;
    } else if #[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "windows", target_os = "android", target_os = "ios"))] {
        pub mod sysinfo;
        pub use self::sysinfo::*;
    }
}

#[derive(Default, Debug, Clone)]
pub enum TemperatureReading {
    Value(f32),
    #[default]
    Unavailable,
    Off,
}

#[derive(Default, Debug, Clone)]
pub struct TempHarvest {
    pub name: String,
    pub temperature: TemperatureReading,
}

#[derive(Clone, Debug, Copy, PartialEq, Eq, Default)]
pub enum TemperatureType {
    #[default]
    Celsius,
    Kelvin,
    Fahrenheit,
}

impl TemperatureType {
    /// Given a temperature in Celsius, covert it if necessary for a different unit.
    pub fn convert_temp_unit(&self, temp_celsius: f32) -> f32 {
        fn convert_celsius_to_kelvin(celsius: f32) -> f32 {
            celsius + 273.15
        }

        fn convert_celsius_to_fahrenheit(celsius: f32) -> f32 {
            (celsius * (9.0 / 5.0)) + 32.0
        }

        match self {
            TemperatureType::Celsius => temp_celsius,
            TemperatureType::Kelvin => convert_celsius_to_kelvin(temp_celsius),
            TemperatureType::Fahrenheit => convert_celsius_to_fahrenheit(temp_celsius),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::data_collection::temperature::TemperatureType;

    #[test]
    fn temp_conversions() {
        const TEMP: f32 = 100.0;

        assert_eq!(
            TemperatureType::Celsius.convert_temp_unit(TEMP),
            TEMP,
            "celsius to celsius is the same"
        );

        assert_eq!(TemperatureType::Kelvin.convert_temp_unit(TEMP), 373.15);

        assert_eq!(TemperatureType::Fahrenheit.convert_temp_unit(TEMP), 212.0);
    }
}