Skip to main content

fritz_core/
traffic.rs

1//! The traffic of the internet connection: the current rates, how much of
2//! the line they use, the split by priority and multicast, and the byte and
3//! packet counters, read with the getters of `WANCommonInterfaceConfig`
4//! only.
5//!
6//! The online monitor reports bytes per second as lists, the latest value
7//! first; these are shown as bits per second. The counters only grow, until
8//! they wrap around or the connection restarts. [`Traffic::since`] turns two
9//! reads into the averages in between, see [`grown`].
10
11use serde::Serialize;
12
13use crate::generic::Error;
14use crate::interfaces::{Counters, grown, per_second};
15use crate::read::{Reader, Values};
16
17/// The service with the traffic of the internet connection.
18const SERVICE: &str = "WANCommonInterfaceConfig";
19
20/// The traffic of the internet connection.
21#[derive(Debug, Clone, Default, PartialEq, Serialize)]
22pub struct Traffic {
23    /// Whether the device has the service with the traffic. Repeaters have
24    /// not.
25    pub supported: bool,
26    pub downstream: Flow,
27    pub upstream: Flow,
28}
29
30/// The traffic in one direction. Values the device does not report are
31/// `None`.
32#[derive(Debug, Clone, Default, PartialEq, Serialize)]
33pub struct Flow {
34    /// The latest rate the device measured, in bit/s.
35    pub current_bps: Option<u64>,
36    /// The highest rate the line allows now, in bit/s.
37    pub max_bps: Option<u64>,
38    /// The current rate in percent of the highest.
39    pub utilization_percent: Option<f64>,
40    /// The highest of the recent rates the device keeps, in bit/s.
41    pub peak_bps: Option<u64>,
42    /// The bytes since the connection started.
43    pub total_bytes: Option<u64>,
44    /// The packets since the connection started.
45    pub total_packets: Option<u64>,
46    /// Of the downstream, the latest rate of multicast, like IPTV, in bit/s.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub multicast_bps: Option<u64>,
49    /// Of the upstream, the latest rates by priority class.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub priorities: Option<Priorities>,
52}
53
54/// The latest upstream rates by priority class, in bit/s.
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
56pub struct Priorities {
57    pub realtime_bps: Option<u64>,
58    pub high_bps: Option<u64>,
59    pub default_bps: Option<u64>,
60    pub low_bps: Option<u64>,
61}
62
63/// The names of the values of one direction.
64struct Names {
65    /// The rates of the online monitor in bytes/s, the latest first.
66    monitor: &'static str,
67    /// The highest rate of the online monitor in bytes/s.
68    max: &'static str,
69    /// The rates of `GetCommonLinkProperties` in bytes/s, the latest first.
70    utilization: &'static str,
71    /// The rate of the physical line in bit/s.
72    layer1: &'static str,
73}
74
75const DOWNSTREAM: Names = Names {
76    monitor: "Newds_current_bps",
77    max: "Newmax_ds",
78    utilization: "NewX_AVM-DE_DownstreamCurrentUtilization",
79    layer1: "NewLayer1DownstreamMaxBitRate",
80};
81
82const UPSTREAM: Names = Names {
83    monitor: "Newus_current_bps",
84    max: "Newmax_us",
85    utilization: "NewX_AVM-DE_UpstreamCurrentUtilization",
86    layer1: "NewLayer1UpstreamMaxBitRate",
87};
88
89/// Reads the traffic of the internet connection. Actions the device lacks,
90/// like the online monitor on older firmware, leave their values `None`.
91///
92/// # Errors
93///
94/// The errors of reading other than missing parts, see
95/// [`Reader::try_read`].
96pub async fn traffic(reader: &mut Reader) -> Result<Traffic, Error> {
97    let Some(service) = reader.services(SERVICE).into_iter().next() else {
98        return Ok(Traffic::default());
99    };
100    let index = [("NewSyncGroupIndex", "0")];
101    let monitor = reader.try_read(&service, "X_AVM-DE_GetOnlineMonitor", &index);
102    let monitor = monitor.await?.unwrap_or_default();
103    let link = reader.try_read(&service, "GetCommonLinkProperties", &[]);
104    let link = link.await?.unwrap_or_default();
105    let mut totals = Vec::new();
106    for action in [
107        "GetTotalBytesSent",
108        "GetTotalBytesReceived",
109        "GetTotalPacketsSent",
110        "GetTotalPacketsReceived",
111    ] {
112        totals.extend(reader.try_read(&service, action, &[]).await?);
113    }
114    Ok(from_values(&monitor, &link, &totals))
115}
116
117/// The traffic in the answers of the online monitor, of
118/// `GetCommonLinkProperties` and of the counters.
119fn from_values(monitor: &Values, link: &Values, totals: &[Values]) -> Traffic {
120    let counters = Counters::from_values(totals);
121    let mut downstream = flow(monitor, link, &DOWNSTREAM);
122    downstream.total_bytes = counters.bytes_received;
123    downstream.total_packets = counters.packets_received;
124    downstream.multicast_bps = latest(monitor, "Newmc_current_bps");
125    let mut upstream = flow(monitor, link, &UPSTREAM);
126    upstream.total_bytes = counters.bytes_sent;
127    upstream.total_packets = counters.packets_sent;
128    let priorities = Priorities {
129        realtime_bps: latest(monitor, "Newprio_realtime_bps"),
130        high_bps: latest(monitor, "Newprio_high_bps"),
131        default_bps: latest(monitor, "Newprio_default_bps"),
132        low_bps: latest(monitor, "Newprio_low_bps"),
133    };
134    upstream.priorities = (priorities != Priorities::default()).then_some(priorities);
135    Traffic {
136        supported: true,
137        downstream,
138        upstream,
139    }
140}
141
142/// The rates of one direction: from the online monitor, else from
143/// `GetCommonLinkProperties`.
144fn flow(monitor: &Values, link: &Values, names: &Names) -> Flow {
145    let rates = history(monitor, names.monitor);
146    let rates = if rates.is_empty() {
147        history(link, names.utilization)
148    } else {
149        rates
150    };
151    let current_bps = rates.first().copied();
152    let max_bps = monitor
153        .number(names.max)
154        .map(bits)
155        .or_else(|| link.number(names.layer1));
156    Flow {
157        current_bps,
158        max_bps,
159        utilization_percent: share(current_bps.map(u64_to_f64), max_bps),
160        peak_bps: rates.into_iter().max(),
161        ..Flow::default()
162    }
163}
164
165/// The latest value of a list of rates in bytes/s, in bit/s.
166fn latest(values: &Values, name: &str) -> Option<u64> {
167    history(values, name).first().copied()
168}
169
170/// A list of rates in bytes/s, the latest first, like `40712,218205`, in
171/// bit/s. Values that are not numbers are left out.
172fn history(values: &Values, name: &str) -> Vec<u64> {
173    values.get(name).map_or_else(Vec::new, |list| {
174        list.split(',')
175            .filter_map(|v| v.trim().parse().ok())
176            .map(bits)
177            .collect()
178    })
179}
180
181fn bits(bytes: u64) -> u64 {
182    bytes.saturating_mul(8)
183}
184
185/// A rate in bit/s as a float, to compute and show it.
186#[must_use]
187#[expect(clippy::cast_precision_loss, reason = "rates need no exact counts")]
188pub fn u64_to_f64(value: u64) -> f64 {
189    value as f64
190}
191
192/// `rate` in percent of `max`, with one decimal.
193fn share(rate: Option<f64>, max: Option<u64>) -> Option<f64> {
194    let max = u64_to_f64(max.filter(|m| *m > 0)?);
195    Some((rate? * 1000.0 / max).round() / 10.0)
196}
197
198/// The traffic between two reads.
199#[derive(Debug, Clone, Default, PartialEq, Serialize)]
200pub struct Sample {
201    /// The seconds between the reads.
202    pub seconds: f64,
203    pub downstream: Rate,
204    pub upstream: Rate,
205}
206
207/// The traffic in one direction between two reads.
208#[derive(Debug, Clone, Default, PartialEq, Serialize)]
209pub struct Rate {
210    /// The average from the byte counters, in bit/s. `None` without
211    /// counters, or if one was reset in between, like after a reconnect.
212    pub average_bps: Option<f64>,
213    /// The average of packets per second.
214    pub packets_per_second: Option<f64>,
215    /// The latest rate the device measured at the second read, in bit/s.
216    pub current_bps: Option<u64>,
217    /// The highest rate the line allows, in bit/s.
218    pub max_bps: Option<u64>,
219    /// The average, else the latest rate, in percent of the highest.
220    pub utilization_percent: Option<f64>,
221    /// The bytes in between.
222    pub bytes: Option<u64>,
223}
224
225impl Rate {
226    fn new(now: &Flow, then: &Flow, seconds: f64) -> Self {
227        let grown = |now: Option<u64>, then: Option<u64>| grown(then?, now?);
228        let bytes = grown(now.total_bytes, then.total_bytes);
229        let average_bps = bytes.map(|b| per_second(b, seconds) * 8.0);
230        let packets = grown(now.total_packets, then.total_packets);
231        let rate = average_bps.or(now.current_bps.map(u64_to_f64));
232        Self {
233            average_bps,
234            packets_per_second: packets.map(|p| per_second(p, seconds)),
235            current_bps: now.current_bps,
236            max_bps: now.max_bps,
237            utilization_percent: share(rate, now.max_bps),
238            bytes,
239        }
240    }
241}
242
243impl Traffic {
244    /// The traffic since `earlier`, read `seconds` before.
245    #[must_use]
246    pub fn since(&self, earlier: &Self, seconds: f64) -> Sample {
247        Sample {
248            seconds,
249            downstream: Rate::new(&self.downstream, &earlier.downstream, seconds),
250            upstream: Rate::new(&self.upstream, &earlier.upstream, seconds),
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::read::values;
259
260    fn monitor() -> Values {
261        values(&[
262            ("Newds_current_bps", "1000,4000,x"),
263            ("Newus_current_bps", "100, 300"),
264            ("Newmax_ds", "2000000"),
265            ("Newmax_us", "0"),
266            ("Newmc_current_bps", "250,0"),
267            ("Newprio_realtime_bps", "10"),
268            ("Newprio_default_bps", "90"),
269        ])
270    }
271
272    fn link() -> Values {
273        values(&[
274            ("NewX_AVM-DE_DownstreamCurrentUtilization", "7,8"),
275            ("NewX_AVM-DE_UpstreamCurrentUtilization", "5"),
276            ("NewLayer1DownstreamMaxBitRate", "100000000"),
277            ("NewLayer1UpstreamMaxBitRate", "40000000"),
278        ])
279    }
280
281    #[test]
282    fn reads_the_online_monitor_first() {
283        let totals = [
284            values(&[("NewTotalBytesReceived", "5000000000")]),
285            values(&[("NewTotalPacketsSent", "12")]),
286        ];
287        let traffic = from_values(&monitor(), &link(), &totals);
288        assert!(traffic.supported);
289        let down = &traffic.downstream;
290        assert_eq!(down.current_bps, Some(8000));
291        assert_eq!(down.peak_bps, Some(32_000));
292        assert_eq!(down.max_bps, Some(16_000_000));
293        assert_eq!(down.utilization_percent, Some(0.1));
294        assert_eq!(down.multicast_bps, Some(2000));
295        assert_eq!(down.total_bytes, Some(5_000_000_000));
296        assert_eq!(down.priorities, None);
297        let up = &traffic.upstream;
298        assert_eq!(up.current_bps, Some(800));
299        assert_eq!(up.max_bps, Some(0));
300        assert_eq!(up.utilization_percent, None);
301        assert_eq!(up.total_packets, Some(12));
302        assert_eq!(up.total_bytes, None);
303        let priorities = up.priorities.unwrap();
304        assert_eq!(priorities.realtime_bps, Some(80));
305        assert_eq!(priorities.default_bps, Some(720));
306        assert_eq!(priorities.high_bps, None);
307    }
308
309    #[test]
310    fn falls_back_to_the_link_properties() {
311        let traffic = from_values(&Values::default(), &link(), &[]);
312        let down = &traffic.downstream;
313        assert_eq!(down.current_bps, Some(56));
314        assert_eq!(down.peak_bps, Some(64));
315        assert_eq!(down.max_bps, Some(100_000_000));
316        assert_eq!(down.multicast_bps, None);
317        assert_eq!(traffic.upstream.priorities, None);
318        let json = serde_json::to_value(&traffic).unwrap();
319        // Without the split, its fields are left out.
320        assert!(json["downstream"].get("multicast_bps").is_none(), "{json}");
321        assert!(json["upstream"].get("priorities").is_none(), "{json}");
322        assert!(json["upstream"]["total_bytes"].is_null(), "{json}");
323        let nothing = from_values(&Values::default(), &Values::default(), &[]);
324        assert_eq!(nothing.downstream, Flow::default());
325    }
326
327    #[test]
328    fn averages_the_counters_between_reads() {
329        let earlier = Traffic {
330            supported: true,
331            downstream: Flow {
332                total_bytes: Some(u64::from(u32::MAX) - 999),
333                total_packets: Some(10),
334                ..Flow::default()
335            },
336            upstream: Flow {
337                total_bytes: Some(1 << 40),
338                ..Flow::default()
339            },
340        };
341        let now = Traffic {
342            supported: true,
343            downstream: Flow {
344                current_bps: Some(1000),
345                max_bps: Some(100_000),
346                total_bytes: Some(1000),
347                total_packets: Some(30),
348                ..Flow::default()
349            },
350            upstream: Flow {
351                current_bps: Some(500),
352                max_bps: Some(1000),
353                total_bytes: Some(5),
354                ..Flow::default()
355            },
356        };
357        let sample = now.since(&earlier, 2.0);
358        assert_eq!(sample.seconds, 2.0);
359        // The 32-bit counter wrapped around: 2000 bytes in 2 seconds.
360        let down = &sample.downstream;
361        assert_eq!(down.bytes, Some(2000));
362        assert_eq!(down.average_bps, Some(8000.0));
363        assert_eq!(down.packets_per_second, Some(10.0));
364        assert_eq!(down.utilization_percent, Some(8.0));
365        assert_eq!(down.current_bps, Some(1000));
366        // The 64-bit counter fell: no average, the latest rate instead.
367        let up = &sample.upstream;
368        assert_eq!(up.bytes, None);
369        assert_eq!(up.average_bps, None);
370        assert_eq!(up.packets_per_second, None);
371        assert_eq!(up.utilization_percent, Some(50.0));
372    }
373}