Skip to main content

fritz_core/
interfaces.rs

1//! The counters of the LAN interfaces and the wireless networks, and the
2//! LAN ports of the web interface, through actions and requests that only
3//! read.
4//!
5//! The counters only grow, until they wrap around or the device restarts.
6//! [`Interfaces::since`] turns two reads into the changes and rates in
7//! between.
8
9use serde::Serialize;
10use serde_json::Value;
11
12use crate::generic::Error;
13use crate::read::{Reader, Values};
14use crate::session::{self, Session};
15use crate::settings;
16
17/// The LAN interfaces, the LAN ports and the wireless networks.
18#[derive(Debug, Clone, Default, PartialEq, Serialize)]
19pub struct Interfaces {
20    pub lan: Vec<Lan>,
21    /// The LAN ports, from the web interface. They have no counters.
22    pub ports: Vec<Port>,
23    /// Why the LAN ports could not be read.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub ports_unavailable: Option<String>,
26    pub wlan: Vec<Wireless>,
27}
28
29/// A LAN interface and its counters.
30#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
31pub struct Lan {
32    /// The service, like `LANEthernetInterfaceConfig1`.
33    pub service: String,
34    pub enabled: Option<bool>,
35    /// Like `Up` or `NoLink`.
36    pub status: Option<String>,
37    /// The speed, like `Auto` or `1000`.
38    pub speed: Option<String>,
39    /// Like `Auto`, `Half` or `Full`.
40    pub duplex: Option<String>,
41    #[serde(flatten)]
42    pub counters: Counters,
43}
44
45/// A port of the LAN, from the module `eth_ports` of the web interface.
46#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
47pub struct Port {
48    /// Like `LAN 1`.
49    pub name: Option<String>,
50    pub connected: Option<bool>,
51    /// The speed of the link in Mbit/s, 0 without a link.
52    pub speed: Option<u32>,
53    /// The highest speed of the port in Mbit/s.
54    pub max_speed: Option<u32>,
55    /// Energy Efficient Ethernet, like `on` or `off`.
56    pub energy_saving: Option<String>,
57    /// Like `default` or `green`.
58    pub mode: Option<String>,
59}
60
61/// A wireless network and its counters.
62#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
63pub struct Wireless {
64    /// The service, like `WLANConfiguration1`.
65    pub service: String,
66    pub ssid: Option<String>,
67    /// Like `2.4 GHz`.
68    pub band: Option<String>,
69    pub channel: Option<u32>,
70    /// Like `Up` or `Disabled`.
71    pub status: Option<String>,
72    #[serde(flatten)]
73    pub counters: Counters,
74}
75
76/// The counters of an interface, where the device reports them.
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
78pub struct Counters {
79    pub bytes_sent: Option<u64>,
80    pub bytes_received: Option<u64>,
81    pub packets_sent: Option<u64>,
82    pub packets_received: Option<u64>,
83    pub errors_sent: Option<u64>,
84    pub errors_received: Option<u64>,
85    pub discarded_sent: Option<u64>,
86    pub discarded_received: Option<u64>,
87}
88
89impl Counters {
90    /// The counters in the answers of statistics actions. The first answer
91    /// that has a counter wins.
92    pub(crate) fn from_values(answers: &[Values]) -> Self {
93        let find = |names: &[&str]| {
94            answers
95                .iter()
96                .find_map(|values| names.iter().find_map(|name| values.number(name)))
97        };
98        Self {
99            bytes_sent: find(&["NewBytesSent", "NewTotalBytesSent"]),
100            bytes_received: find(&["NewBytesReceived", "NewTotalBytesReceived"]),
101            packets_sent: find(&["NewPacketsSent", "NewTotalPacketsSent"]),
102            packets_received: find(&["NewPacketsReceived", "NewTotalPacketsReceived"]),
103            errors_sent: find(&["NewErrorsSent"]),
104            errors_received: find(&["NewErrorsReceived"]),
105            discarded_sent: find(&["NewDiscardPacketsSent"]),
106            discarded_received: find(&["NewDiscardPacketsReceived"]),
107        }
108    }
109
110    /// How much each counter grew since `earlier`, see [`grown`].
111    #[must_use]
112    pub fn since(&self, earlier: &Self) -> Self {
113        let grown = |now: Option<u64>, then: Option<u64>| grown(then?, now?);
114        Self {
115            bytes_sent: grown(self.bytes_sent, earlier.bytes_sent),
116            bytes_received: grown(self.bytes_received, earlier.bytes_received),
117            packets_sent: grown(self.packets_sent, earlier.packets_sent),
118            packets_received: grown(self.packets_received, earlier.packets_received),
119            errors_sent: grown(self.errors_sent, earlier.errors_sent),
120            errors_received: grown(self.errors_received, earlier.errors_received),
121            discarded_sent: grown(self.discarded_sent, earlier.discarded_sent),
122            discarded_received: grown(self.discarded_received, earlier.discarded_received),
123        }
124    }
125}
126
127/// How much a counter grew from `then` to `now`. A counter that fell
128/// wrapped around at 2^32 if it fit into 32 bits, else the device reset it,
129/// like after a restart, and the growth is unknown.
130pub fn grown(then: u64, now: u64) -> Option<u64> {
131    if now >= then {
132        Some(now - then)
133    } else if u32::try_from(then).is_ok() {
134        Some((1 << 32) - then + now)
135    } else {
136        None
137    }
138}
139
140/// What changed on the interfaces between two reads.
141#[derive(Debug, Clone, Default, PartialEq, Serialize)]
142pub struct Sample {
143    /// The seconds between the reads.
144    pub seconds: f64,
145    pub interfaces: Vec<Rate>,
146}
147
148/// What changed on an interface between two reads.
149#[derive(Debug, Clone, Default, PartialEq, Serialize)]
150pub struct Rate {
151    /// The service, like `WLANConfiguration1`.
152    pub service: String,
153    /// The SSID of a wireless network.
154    pub ssid: Option<String>,
155    pub status: Option<String>,
156    /// How much the counters grew, see [`grown`].
157    pub changes: Counters,
158    pub bytes_sent_per_second: Option<f64>,
159    pub bytes_received_per_second: Option<f64>,
160    pub packets_sent_per_second: Option<f64>,
161    pub packets_received_per_second: Option<f64>,
162}
163
164impl Rate {
165    fn new(service: &str, now: &Counters, earlier: &Counters, seconds: f64) -> Self {
166        let changes = now.since(earlier);
167        let rate = |count: Option<u64>| count.map(|c| per_second(c, seconds));
168        Self {
169            service: service.to_owned(),
170            bytes_sent_per_second: rate(changes.bytes_sent),
171            bytes_received_per_second: rate(changes.bytes_received),
172            packets_sent_per_second: rate(changes.packets_sent),
173            packets_received_per_second: rate(changes.packets_received),
174            changes,
175            ..Self::default()
176        }
177    }
178}
179
180#[expect(clippy::cast_precision_loss, reason = "rates need no exact counts")]
181pub(crate) fn per_second(count: u64, seconds: f64) -> f64 {
182    if seconds > 0.0 {
183        count as f64 / seconds
184    } else {
185        0.0
186    }
187}
188
189impl Interfaces {
190    /// What changed since `earlier`, read `seconds` before. Interfaces that
191    /// were not in both reads are left out.
192    #[must_use]
193    pub fn since(&self, earlier: &Self, seconds: f64) -> Sample {
194        let lan = self.lan.iter().filter_map(|now| {
195            let then = earlier.lan.iter().find(|l| l.service == now.service)?;
196            Some(Rate {
197                status: now.status.clone(),
198                ..Rate::new(&now.service, &now.counters, &then.counters, seconds)
199            })
200        });
201        let wlan = self.wlan.iter().filter_map(|now| {
202            let then = earlier.wlan.iter().find(|w| w.service == now.service)?;
203            Some(Rate {
204                ssid: now.ssid.clone(),
205                status: now.status.clone(),
206                ..Rate::new(&now.service, &now.counters, &then.counters, seconds)
207            })
208        });
209        Sample {
210            seconds,
211            interfaces: lan.chain(wlan).collect(),
212        }
213    }
214}
215
216/// Reads the LAN interfaces and the wireless networks with their counters,
217/// without the ports.
218///
219/// # Errors
220///
221/// The errors of reading other than missing parts, see
222/// [`Reader::try_read`].
223pub async fn interfaces(reader: &mut Reader) -> Result<Interfaces, Error> {
224    let mut lan = Vec::new();
225    for service in reader.services("LANEthernetInterfaceConfig") {
226        let info = reader.try_read(&service, "GetInfo", &[]).await?;
227        let statistics = reader.try_read(&service, "GetStatistics", &[]).await?;
228        if info.is_none() && statistics.is_none() {
229            continue;
230        }
231        let info = info.unwrap_or_default();
232        lan.push(Lan {
233            enabled: info.flag("NewEnable"),
234            status: info.text("NewStatus"),
235            speed: info.text("NewMaxBitRate"),
236            duplex: info.text("NewDuplexMode"),
237            counters: Counters::from_values(&statistics.into_iter().collect::<Vec<_>>()),
238            service,
239        });
240    }
241    let mut wlan = Vec::new();
242    for service in reader.services("WLANConfiguration") {
243        let Some(info) = reader.try_read(&service, "GetInfo", &[]).await? else {
244            continue;
245        };
246        let mut answers = Vec::new();
247        for action in ["GetStatistics", "GetPacketStatistics"] {
248            answers.extend(reader.try_read(&service, action, &[]).await?);
249        }
250        wlan.push(Wireless {
251            ssid: info.text("NewSSID"),
252            band: info
253                .get("NewX_AVM-DE_FrequencyBand")
254                .and_then(crate::wlan::band),
255            channel: info.number("NewChannel"),
256            status: info.text("NewStatus"),
257            counters: Counters::from_values(&answers),
258            service,
259        });
260    }
261    Ok(Interfaces {
262        lan,
263        wlan,
264        ..Interfaces::default()
265    })
266}
267
268/// Reads the LAN ports from the module `eth_ports` of the web interface.
269///
270/// # Errors
271///
272/// The errors of [`settings::module`].
273pub async fn ports(session: &Session) -> Result<Vec<Port>, session::Error> {
274    Ok(parse_ports(&settings::module(session, "eth_ports").await?))
275}
276
277/// The ports in the module `eth_ports`, like
278/// `{"eth": [{"label": "LAN 1", "carrier": "1", "speed": "1000", …}]}`.
279fn parse_ports(module: &Value) -> Vec<Port> {
280    let Some(ports) = module.get("eth").and_then(Value::as_array) else {
281        return Vec::new();
282    };
283    let text = |port: &Value, name| {
284        port.get(name)
285            .and_then(Value::as_str)
286            .filter(|t| !t.is_empty())
287            .map(str::to_owned)
288    };
289    let number = |port: &Value, name| text(port, name)?.trim().parse().ok();
290    ports
291        .iter()
292        .map(|port| Port {
293            name: text(port, "label"),
294            connected: text(port, "carrier").map(|c| c == "1"),
295            speed: number(port, "speed"),
296            max_speed: number(port, "maxspeed"),
297            energy_saving: text(port, "eee_mode"),
298            mode: text(port, "mode"),
299        })
300        .collect()
301}
302
303#[cfg(test)]
304mod tests {
305    use serde_json::json;
306
307    use super::*;
308    use crate::read::values;
309
310    #[test]
311    fn counts_growth_across_wrap_arounds() {
312        assert_eq!(grown(5, 7), Some(2));
313        assert_eq!(grown(7, 7), Some(0));
314        // A 32-bit counter wrapped around.
315        assert_eq!(grown(u64::from(u32::MAX) - 1, 3), Some(5));
316        // A 64-bit counter fell: the device restarted.
317        assert_eq!(grown(1 << 40, 3), None);
318    }
319
320    #[test]
321    fn reads_counters_from_several_answers() {
322        let first = values(&[("NewTotalPacketsSent", "10"), ("NewErrorsSent", "x")]);
323        let second = values(&[
324            ("NewTotalPacketsSent", "20"),
325            ("NewErrorsSent", "2"),
326            ("NewDiscardPacketsReceived", "3"),
327        ]);
328        let counters = Counters::from_values(&[first, second]);
329        assert_eq!(counters.packets_sent, Some(10));
330        assert_eq!(counters.errors_sent, Some(2));
331        assert_eq!(counters.discarded_received, Some(3));
332        assert_eq!(counters.bytes_sent, None);
333    }
334
335    #[test]
336    fn computes_rates_between_reads() {
337        let earlier = Interfaces {
338            lan: vec![Lan {
339                service: "LANEthernetInterfaceConfig1".to_owned(),
340                counters: Counters {
341                    bytes_sent: Some(1000),
342                    bytes_received: Some(u64::from(u32::MAX)),
343                    errors_received: Some(4),
344                    ..Counters::default()
345                },
346                ..Lan::default()
347            }],
348            wlan: vec![Wireless {
349                service: "WLANConfiguration1".to_owned(),
350                ..Wireless::default()
351            }],
352            ..Interfaces::default()
353        };
354        let mut now = earlier.clone();
355        now.lan[0].status = Some("Up".to_owned());
356        now.lan[0].counters.bytes_sent = Some(3000);
357        now.lan[0].counters.bytes_received = Some(9);
358        now.lan[0].counters.errors_received = Some(5);
359        now.wlan[0].ssid = Some("wlan-1".to_owned());
360        now.wlan.push(Wireless {
361            service: "WLANConfiguration2".to_owned(),
362            ..Wireless::default()
363        });
364        let sample = now.since(&earlier, 2.0);
365        assert_eq!(sample.seconds, 2.0);
366        assert_eq!(sample.interfaces.len(), 2, "{sample:?}");
367        let lan = &sample.interfaces[0];
368        assert_eq!(lan.status.as_deref(), Some("Up"));
369        assert_eq!(lan.changes.bytes_sent, Some(2000));
370        assert_eq!(lan.changes.bytes_received, Some(10));
371        assert_eq!(lan.changes.errors_received, Some(1));
372        assert_eq!(lan.bytes_sent_per_second, Some(1000.0));
373        assert_eq!(lan.bytes_received_per_second, Some(5.0));
374        assert_eq!(lan.packets_sent_per_second, None);
375        assert_eq!(sample.interfaces[1].ssid.as_deref(), Some("wlan-1"));
376        assert_eq!(per_second(10, 0.0), 0.0);
377    }
378
379    #[test]
380    fn parses_ports() {
381        let module = json!({ "eth": [
382            { "UID": "eth0", "carrier": "1", "eee_mode": "on", "label": "LAN 1",
383              "maxspeed": "2500", "mode": "default", "speed": "1000" },
384            { "carrier": "0", "label": "", "speed": "x" },
385        ]});
386        assert_eq!(
387            parse_ports(&module),
388            [
389                Port {
390                    name: Some("LAN 1".to_owned()),
391                    connected: Some(true),
392                    speed: Some(1000),
393                    max_speed: Some(2500),
394                    energy_saving: Some("on".to_owned()),
395                    mode: Some("default".to_owned()),
396                },
397                Port {
398                    connected: Some(false),
399                    ..Port::default()
400                },
401            ]
402        );
403        assert_eq!(parse_ports(&json!({})), []);
404    }
405}