Skip to main content

fritz_core/
system.rs

1//! The load of the device: CPU load, CPU temperature and memory, read from
2//! the page `ecoStat` of the web interface, which shows the energy monitor
3//! and the system load, with a [`Session`].
4//!
5//! Experimental: the page is not documented, and its fields may change
6//! with FRITZ!OS. On FRITZ!OS 8.25, it holds three charts, oldest value
7//! first: `cpuutil` and `cputemp` with a value every 6 minutes, and
8//! `ramusage` with a value every hour, as the shares of memory that is
9//! used, used as cache and free. Labels name the hour of the day where a
10//! new hour begins.
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15pub use crate::session::DATA;
16use crate::session::{Error, Session};
17use crate::status::Right;
18
19/// The page with the charts.
20pub const PAGE: &str = "ecoStat";
21
22/// The right to see the settings of the device, which the page needs.
23const RIGHT: &str = "BoxAdmin";
24
25/// The load of the device now, and over the time the device keeps.
26#[derive(Debug, Clone, Default, PartialEq, Serialize)]
27pub struct System {
28    /// The latest CPU load in percent.
29    pub cpu_load_percent: Option<f64>,
30    /// The latest CPU temperature in °C.
31    pub cpu_temperature_celsius: Option<f64>,
32    /// The latest memory use.
33    pub memory: Memory,
34    /// The values the device keeps.
35    pub history: History,
36}
37
38/// The shares of the memory in percent.
39#[derive(Debug, Clone, Default, PartialEq, Serialize)]
40pub struct Memory {
41    pub used_percent: Option<f64>,
42    pub cache_percent: Option<f64>,
43    pub free_percent: Option<f64>,
44}
45
46/// The lowest, average and highest values the device keeps.
47#[derive(Debug, Clone, Default, PartialEq, Serialize)]
48pub struct History {
49    /// How many hours the values cover.
50    pub hours: Option<usize>,
51    pub cpu_load_percent: Option<Range>,
52    pub cpu_temperature_celsius: Option<Range>,
53    pub memory_used_percent: Option<Range>,
54}
55
56/// The lowest, average and highest of several values.
57#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
58pub struct Range {
59    pub min: f64,
60    /// Rounded to one decimal.
61    pub avg: f64,
62    pub max: f64,
63}
64
65/// The load of the device, or why it is missing.
66#[derive(Debug, Clone, PartialEq, Serialize)]
67pub struct Section {
68    /// The load, or `null` if the device does not show it.
69    pub system: Option<System>,
70    /// Why the load is missing.
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub system_note: Option<String>,
73}
74
75impl Section {
76    /// A section without values, because of `note`.
77    pub fn missing(note: String) -> Self {
78        Self {
79            system: None,
80            system_note: Some(note),
81        }
82    }
83}
84
85/// Reads the load. Never fails: if the page cannot be read, the section
86/// tells why, with a hint if the user lacks the right to see the settings.
87pub async fn section(session: &Session) -> Section {
88    match system(session).await {
89        Ok(system) => Section {
90            system: Some(system),
91            system_note: None,
92        },
93        Err(error) => Section::missing(note(&error, session.rights())),
94    }
95}
96
97/// Why the load could not be read, with a hint if the user lacks the
98/// right to see the settings.
99fn note(error: &Error, rights: &[Right]) -> String {
100    let hint = if rights.iter().any(|r| r.area == RIGHT) {
101        ""
102    } else {
103        "; the user may need the right to see the settings of the device"
104    };
105    format!("the device shows no system load: {error}{hint}")
106}
107
108/// Reads the load.
109///
110/// # Errors
111///
112/// The errors of the request, and [`Error::Invalid`] if the answer holds
113/// none of the charts.
114pub async fn system(session: &Session) -> Result<System, Error> {
115    parse(&session.page(PAGE, &[]).await?)
116}
117
118/// The load in the page `ecoStat`.
119///
120/// # Errors
121///
122/// [`Error::Invalid`] if `json` is not the page or holds none of the
123/// charts.
124pub fn parse(json: &str) -> Result<System, Error> {
125    let invalid = |reason: String| Error::Invalid {
126        what: "the system load page",
127        reason,
128    };
129    let page: Page = serde_json::from_str(json).map_err(|e| invalid(e.to_string()))?;
130    let Data {
131        cpuutil,
132        cputemp,
133        ramusage,
134    } = page.data;
135    if [&cpuutil, &cputemp, &ramusage].iter().all(|c| c.is_none()) {
136        return Err(invalid("no CPU or memory values".to_owned()));
137    }
138    let series = |chart: &Option<Chart>, index: usize| {
139        chart
140            .as_ref()
141            .and_then(|c| c.series.get(index))
142            .map_or_else(Vec::new, |values| {
143                values.iter().filter_map(number).collect::<Vec<f64>>()
144            })
145    };
146    let (load, temperature) = (series(&cpuutil, 0), series(&cputemp, 0));
147    let (used, cache, free) = (
148        series(&ramusage, 0),
149        series(&ramusage, 1),
150        series(&ramusage, 2),
151    );
152    let hours = [&cpuutil, &cputemp, &ramusage]
153        .iter()
154        .filter_map(|c| c.as_ref().map(Chart::hours))
155        .max()
156        .filter(|h| *h > 0);
157    Ok(System {
158        cpu_load_percent: load.last().copied(),
159        cpu_temperature_celsius: temperature.last().copied(),
160        memory: Memory {
161            used_percent: used.last().copied(),
162            cache_percent: cache.last().copied(),
163            free_percent: free.last().copied(),
164        },
165        history: History {
166            hours,
167            cpu_load_percent: range(&load),
168            cpu_temperature_celsius: range(&temperature),
169            memory_used_percent: range(&used),
170        },
171    })
172}
173
174/// A number, also as text like `"68"`.
175fn number(value: &Value) -> Option<f64> {
176    match value {
177        Value::Number(n) => n.as_f64(),
178        Value::String(s) => s.trim().parse().ok(),
179        _ => None,
180    }
181    .filter(|n: &f64| n.is_finite())
182}
183
184#[expect(clippy::cast_precision_loss, reason = "a few hundred values")]
185pub(crate) fn range(values: &[f64]) -> Option<Range> {
186    let first = *values.first()?;
187    let (min, max) = values
188        .iter()
189        .fold((first, first), |(min, max), v| (min.min(*v), max.max(*v)));
190    let avg = values.iter().sum::<f64>() / values.len() as f64;
191    Some(Range {
192        min,
193        avg: (avg * 10.0).round() / 10.0,
194        max,
195    })
196}
197
198#[derive(Debug, Deserialize)]
199struct Page {
200    data: Data,
201}
202
203#[derive(Debug, Deserialize)]
204struct Data {
205    cpuutil: Option<Chart>,
206    cputemp: Option<Chart>,
207    ramusage: Option<Chart>,
208}
209
210#[derive(Debug, Deserialize)]
211struct Chart {
212    #[serde(default)]
213    labels: Vec<Value>,
214    #[serde(default)]
215    series: Vec<Vec<Value>>,
216}
217
218impl Chart {
219    /// The number of hours the chart covers: its labels, which name the
220    /// hours, while the others are `false`.
221    fn hours(&self) -> usize {
222        self.labels.iter().filter(|l| number(l).is_some()).count()
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn reads_the_latest_values_and_the_history() {
232        let system = parse(
233            r#"{"data": {
234                "cpuutil": {"labels": [false, 20, false, 21], "series": [["5", "9", "", "7"], ["0", "0", "0", "0"]]},
235                "cputemp": {"labels": [false, 20, false, 21], "series": [["60", "64", "62", "66"]]},
236                "ramusage": {"labels": [20, 21], "series": [[48.9, 49], [11.1, 11], [40, 40]]}
237            }, "sid": "0123456789abcdef"}"#,
238        )
239        .unwrap();
240        assert_eq!(
241            system,
242            System {
243                cpu_load_percent: Some(7.0),
244                cpu_temperature_celsius: Some(66.0),
245                memory: Memory {
246                    used_percent: Some(49.0),
247                    cache_percent: Some(11.0),
248                    free_percent: Some(40.0),
249                },
250                history: History {
251                    hours: Some(2),
252                    cpu_load_percent: Some(Range {
253                        min: 5.0,
254                        avg: 7.0,
255                        max: 9.0
256                    }),
257                    cpu_temperature_celsius: Some(Range {
258                        min: 60.0,
259                        avg: 63.0,
260                        max: 66.0
261                    }),
262                    memory_used_percent: Some(Range {
263                        min: 48.9,
264                        avg: 49.0,
265                        max: 49.0
266                    }),
267                },
268            }
269        );
270    }
271
272    #[test]
273    fn leaves_out_what_the_device_does_not_report() {
274        let system = parse(r#"{"data": {"cputemp": {"series": []}}}"#).unwrap();
275        assert_eq!(system, System::default());
276    }
277
278    #[test]
279    fn rejects_pages_without_charts() {
280        for json in ["<html>", r#"{"data": {}}"#, r#"{"pid": "ecoStat"}"#] {
281            let error = parse(json).unwrap_err().to_string();
282            assert!(
283                error.starts_with("invalid answer from the system load page: "),
284                "{json}: {error}"
285            );
286        }
287    }
288
289    #[test]
290    fn hints_at_the_right() {
291        let error = Error::Invalid {
292            what: "the system load page",
293            reason: "no CPU or memory values".to_owned(),
294        };
295        assert_eq!(
296            note(&error, &[]),
297            "the device shows no system load: invalid answer from the system load page: \
298             no CPU or memory values; the user may need the right to see the settings of the device"
299        );
300        let admin = Right {
301            area: RIGHT.to_owned(),
302            access: "read".to_owned(),
303        };
304        assert!(!note(&error, &[admin]).contains("right"));
305    }
306}