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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use log::{error, trace, warn};
use serde::Deserialize;

use crate::io::live_data::{check_age, AgeType, CachedPrevious};

use super::{Sensor, TemperatureManager};

/// How old the temps.json file is allowed to be before being considered invalid.
const MAX_FILE_AGE: i64 = 60;
/// How old a sensor reading is allowed to be before the reading being considered stale.
const MAX_READING_AGE: i64 = 90;

pub struct LiveFileTemperatures {
    file: PathBuf,
    last_data: CachedPrevious<TempsFileData>,
}

impl LiveFileTemperatures {
    pub fn new(file: PathBuf) -> Self {
        Self {
            file,
            last_data: CachedPrevious::none(),
        }
    }

    pub fn read_temps_data(&self) -> Result<TempsFileData, String> {
        let s = fs::read_to_string(&self.file)
            .map_err(|e| format!("Failed to read {:?}: {}", self.file, e))?;

        serde_json::from_str(&s)
            .map_err(|e| format!("Failed to deserialize: {:?}: {}\n{}", self.file, e, s))
    }
}

#[async_trait]
impl TemperatureManager for LiveFileTemperatures {
    async fn retrieve_sensors(&mut self) -> Result<(), String> {
        Ok(())
    }

    async fn retrieve_temperatures(&self) -> Result<HashMap<Sensor, f32>, String> {
        let temps_data = match self.read_temps_data() {
            Ok(data) => {
                self.last_data.update(data.clone());
                data
            }
            Err(e) => {
                let previous_data = self.last_data.get().ok_or_else(|| {
                    format!(
                        "Failed to get temps ({:?}) and no last was available: {}",
                        self.file, e
                    )
                })?;
                warn!("Error reading current data: {}, using last valid", e);
                previous_data
            }
        };

        let file_age = check_age(temps_data.timestamp, MAX_FILE_AGE);
        match file_age.age_type() {
            AgeType::Good => {
                trace!("{:?}: {}", self.file, file_age);
            }
            AgeType::GettingOld => {
                warn!("{:?}: {}", self.file, file_age);
            }
            AgeType::TooOld => {
                return Err(format!(
                    "{:?}: {} - is it being updated?",
                    self.file, file_age
                ));
            }
        };

        let mut temps = HashMap::new();
        for (sensor, reading) in temps_data.temps {
            let reading_age = check_age(reading.timestamp, MAX_READING_AGE);
            match reading_age.age_type() {
                AgeType::Good => {
                    trace!("{} {}", sensor, reading_age);
                }
                AgeType::GettingOld => {
                    warn!("{} {} - will reject soon.", sensor, reading_age);
                }
                AgeType::TooOld => {
                    error!(
                        "Rejecting {} {} - Treating it as having no value.",
                        sensor, reading_age
                    );
                    continue;
                }
            };
            temps.insert(sensor, reading.value);
        }

        Ok(temps)
    }
}

#[derive(Deserialize, Debug, PartialEq, Clone)]
pub struct TempsFileData {
    timestamp: DateTime<Utc>,
    temps: HashMap<Sensor, TimestampedTemperature>,
}

#[derive(Deserialize, Debug, PartialEq, Clone)]
pub struct TimestampedTemperature {
    value: f32,
    timestamp: DateTime<Utc>,
}

#[cfg(test)]
mod test {
    use chrono::TimeZone;

    use crate::time_util::test_utils::{date, time};

    use super::*;

    const EXAMPLE_DATA: &str = r#"
    {
        "temps": {
            "TKBT": {
                "timestamp": "2024-01-03T19:51:42Z",
                "value": 14.79
            },
            "TKEN": {
                "timestamp": "2024-01-03T19:51:29Z",
                "value": 12.58
            },
            "TKEX": {
                "timestamp": "2024-01-03T19:51:29Z",
                "value": 46.54
            },
            "TKTP": {
                "timestamp": "2024-01-03T19:51:42Z",
                "value": 51.93
            }
        },
        "timestamp": "2024-01-03T19:51:42Z"
    }
    "#;

    #[test]
    fn test_deserialize() {
        let file_data: TempsFileData = serde_json::from_str(EXAMPLE_DATA).unwrap();

        let data_timestamp = Utc.from_utc_datetime(&date(2024, 1, 3).and_time(time(19, 51, 42)));
        let tkbt_tktp_timestamp =
            Utc.from_utc_datetime(&date(2024, 1, 3).and_time(time(19, 51, 42)));
        let tken_tkex_timestamp =
            Utc.from_utc_datetime(&date(2024, 1, 3).and_time(time(19, 51, 29)));

        let mut temps = HashMap::new();
        temps.insert(
            Sensor::TKBT,
            TimestampedTemperature {
                value: 14.79,
                timestamp: tkbt_tktp_timestamp,
            },
        );
        temps.insert(
            Sensor::TKEN,
            TimestampedTemperature {
                value: 12.58,
                timestamp: tken_tkex_timestamp,
            },
        );
        temps.insert(
            Sensor::TKEX,
            TimestampedTemperature {
                value: 46.54,
                timestamp: tken_tkex_timestamp,
            },
        );
        temps.insert(
            Sensor::TKTP,
            TimestampedTemperature {
                value: 51.93,
                timestamp: tkbt_tktp_timestamp,
            },
        );

        let expected = TempsFileData {
            timestamp: data_timestamp,
            temps,
        };
        assert_eq!(file_data, expected);
    }
}