Skip to main content

rustflexstack/management/
cbr.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Channel Busy Ratio (CBR) sources for the DCC entity.
5//!
6//! The DCC algorithms of ETSI TS 102 687 V1.2.1 (2018-04) are access-technology
7//! independent, but the CBR they consume is measured by the access layer
8//! (clause 5.2). This module decouples the two through the [`CbrProvider`]
9//! trait, which the [`DccEntity`](super::DccEntity) polls once per evaluation.
10//!
11//! Provided implementations:
12//! - [`SharedCbr`]: a thread-safe cell for access layers that *push* CBR
13//!   measurements (e.g. a radio SDK callback or an external process).
14//! - [`Nl80211SurveyCbr`]: derives CBR on Linux IEEE 802.11p (ITS-G5) interfaces
15//!   from the nl80211 channel survey counters (`iw dev <iface> survey dump`).
16//!
17//! Mirrors `flexstack/management/cbr.py`.
18
19use std::process::Command;
20use std::sync::{Arc, Mutex};
21
22/// A source of Channel Busy Ratio measurements.
23///
24/// Implementations return the most recent CBR in `[0.0, 1.0]`, or `None` when
25/// no (new) measurement is available. The DCC entity keeps its previous output
26/// when `None` is returned.
27pub trait CbrProvider: Send {
28    /// Return the current CBR measurement, if any.
29    fn measure_cbr(&mut self) -> Option<f64>;
30}
31
32/// Thread-safe CBR cell for push-based access layers.
33///
34/// Clones share the same underlying value: the access layer keeps one clone
35/// and calls [`report`](Self::report); the DCC entity owns another clone as
36/// its [`CbrProvider`]. The latest reported value is returned on every poll.
37#[derive(Debug, Clone, Default)]
38pub struct SharedCbr {
39    latest: Arc<Mutex<Option<f64>>>,
40}
41
42impl SharedCbr {
43    /// Create an empty cell (no measurement yet).
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    /// Report a new CBR measurement. Values outside `[0.0, 1.0]` (or NaN) are ignored.
49    pub fn report(&self, cbr: f64) {
50        if !(0.0..=1.0).contains(&cbr) {
51            return;
52        }
53        if let Ok(mut v) = self.latest.lock() {
54            *v = Some(cbr);
55        }
56    }
57
58    /// Latest reported CBR, if any.
59    pub fn latest(&self) -> Option<f64> {
60        self.latest.lock().ok().and_then(|v| *v)
61    }
62}
63
64impl CbrProvider for SharedCbr {
65    fn measure_cbr(&mut self) -> Option<f64> {
66        self.latest()
67    }
68}
69
70/// Cumulative channel-time counters of the in-use channel, in milliseconds.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct SurveySample {
73    /// `channel active time` (time the radio was on the channel).
74    pub active_ms: u64,
75    /// `channel busy time` (time the channel was sensed busy, own TX included).
76    pub busy_ms: u64,
77}
78
79/// Parse the output of `iw dev <iface> survey dump` and return the counters of
80/// the channel marked `[in use]`.
81///
82/// Returns `None` if no in-use channel with both counters is present (some
83/// drivers do not report survey data).
84pub fn parse_survey_dump(text: &str) -> Option<SurveySample> {
85    let mut in_use = false;
86    let mut active = None;
87    let mut busy = None;
88
89    for line in text.lines() {
90        let line = line.trim();
91        if line.starts_with("Survey data from") {
92            if in_use {
93                break;
94            }
95            active = None;
96            busy = None;
97            continue;
98        }
99        if line.starts_with("frequency:") {
100            if in_use {
101                break; // next channel block of the same dump
102            }
103            in_use = line.contains("[in use]");
104            continue;
105        }
106        if !in_use {
107            continue;
108        }
109        if let Some(v) = line.strip_prefix("channel active time:") {
110            active = parse_ms(v);
111        } else if let Some(v) = line.strip_prefix("channel busy time:") {
112            busy = parse_ms(v);
113        }
114    }
115
116    match (in_use, active, busy) {
117        (true, Some(active_ms), Some(busy_ms)) => Some(SurveySample { active_ms, busy_ms }),
118        _ => None,
119    }
120}
121
122fn parse_ms(v: &str) -> Option<u64> {
123    v.trim().trim_end_matches("ms").trim().parse().ok()
124}
125
126/// CBR between two consecutive survey samples: `Δbusy / Δactive`, clamped to `[0, 1]`.
127///
128/// Returns `None` if the active-time counter did not advance (or was reset).
129pub fn cbr_from_samples(previous: SurveySample, current: SurveySample) -> Option<f64> {
130    if current.active_ms <= previous.active_ms || current.busy_ms < previous.busy_ms {
131        return None;
132    }
133    let d_active = (current.active_ms - previous.active_ms) as f64;
134    let d_busy = (current.busy_ms - previous.busy_ms) as f64;
135    Some((d_busy / d_active).clamp(0.0, 1.0))
136}
137
138/// CBR provider for Linux IEEE 802.11p (ITS-G5) interfaces based on nl80211
139/// channel survey counters, as exposed by e.g. the `ath9k` driver.
140///
141/// Each poll runs `iw dev <iface> survey dump` and returns the busy fraction of
142/// the in-use channel since the previous poll, so the measurement window equals
143/// the DCC evaluation period. The first poll only records a reference sample and
144/// returns `None`.
145///
146/// **Approximation**: the driver's busy time is based on the radio's CCA
147/// threshold, not the −85 dBm threshold that ETSI TS 102 687 §5.2 (via ETSI
148/// TS 102 917) uses to define CBR. The `iw` binary must be installed.
149#[derive(Debug, Clone)]
150pub struct Nl80211SurveyCbr {
151    iface: String,
152    previous: Option<SurveySample>,
153}
154
155impl Nl80211SurveyCbr {
156    /// Create a provider for the given wireless interface (e.g. `"wlan0"`).
157    pub fn new(iface: impl Into<String>) -> Self {
158        Self {
159            iface: iface.into(),
160            previous: None,
161        }
162    }
163
164    /// Interface name this provider reads from.
165    pub fn iface(&self) -> &str {
166        &self.iface
167    }
168
169    /// Feed one survey sample and return the CBR since the previous one.
170    ///
171    /// Exposed so the delta logic can be driven without running `iw`.
172    pub fn ingest(&mut self, sample: SurveySample) -> Option<f64> {
173        let cbr = self
174            .previous
175            .and_then(|prev| cbr_from_samples(prev, sample));
176        self.previous = Some(sample);
177        cbr
178    }
179
180    fn read_survey(&self) -> Option<SurveySample> {
181        let out = Command::new("iw")
182            .args(["dev", &self.iface, "survey", "dump"])
183            .output()
184            .ok()?;
185        if !out.status.success() {
186            return None;
187        }
188        parse_survey_dump(&String::from_utf8_lossy(&out.stdout))
189    }
190}
191
192impl CbrProvider for Nl80211SurveyCbr {
193    fn measure_cbr(&mut self) -> Option<f64> {
194        let sample = self.read_survey()?;
195        self.ingest(sample)
196    }
197}
198
199/// Transmit power in dBm from the output of `iw dev <iface> info`
200/// (`txpower 20.00 dBm`).
201pub fn parse_tx_power_dbm(text: &str) -> Option<f64> {
202    for line in text.lines() {
203        let parts: Vec<&str> = line.split_whitespace().collect();
204        if parts.len() >= 3 && parts[0] == "txpower" && parts[2] == "dBm" {
205            return parts[1].parse().ok();
206        }
207    }
208    None
209}
210
211/// Transmit power of a Linux wireless interface (`iw dev <iface> info`), if
212/// reported; e.g. for the DCC-MCO field of DCC_NET.
213pub fn nl80211_tx_power_dbm(iface: &str) -> Option<f64> {
214    let out = Command::new("iw")
215        .args(["dev", iface, "info"])
216        .output()
217        .ok()?;
218    if !out.status.success() {
219        return None;
220    }
221    parse_tx_power_dbm(&String::from_utf8_lossy(&out.stdout))
222}
223
224#[cfg(test)]
225mod tests {
226    #[test]
227    fn parse_iw_info() {
228        let text = "Interface wlan0\n\tifindex 4\n\ttype IBSS\n\tchannel 180 (5900 MHz), width: 10 MHz\n\ttxpower 23.00 dBm\n";
229        assert_eq!(super::parse_tx_power_dbm(text), Some(23.0));
230        assert_eq!(super::parse_tx_power_dbm("Interface wlan0\n"), None);
231    }
232
233    use super::*;
234
235    const DUMP: &str = "Survey data from wlan0\n\
236        \tfrequency:\t\t\t5880 MHz\n\
237        \tnoise:\t\t\t\t-95 dBm\n\
238        \tchannel active time:\t\t999 ms\n\
239        \tchannel busy time:\t\t111 ms\n\
240        Survey data from wlan0\n\
241        \tfrequency:\t\t\t5900 MHz [in use]\n\
242        \tnoise:\t\t\t\t-92 dBm\n\
243        \tchannel active time:\t\t20000 ms\n\
244        \tchannel busy time:\t\t5000 ms\n\
245        \tchannel receive time:\t\t4000 ms\n\
246        \tchannel transmit time:\t\t500 ms\n\
247        Survey data from wlan0\n\
248        \tfrequency:\t\t\t5910 MHz\n\
249        \tchannel active time:\t\t7 ms\n\
250        \tchannel busy time:\t\t7 ms\n";
251
252    #[test]
253    fn test_shared_cbr_empty_then_reported() {
254        let cell = SharedCbr::new();
255        let mut provider = cell.clone();
256        assert_eq!(provider.measure_cbr(), None);
257        cell.report(0.42);
258        assert_eq!(provider.measure_cbr(), Some(0.42));
259        // Latest value is returned on every poll.
260        assert_eq!(provider.measure_cbr(), Some(0.42));
261    }
262
263    #[test]
264    fn test_shared_cbr_ignores_invalid_values() {
265        let cell = SharedCbr::new();
266        cell.report(0.3);
267        cell.report(1.5);
268        cell.report(-0.1);
269        cell.report(f64::NAN);
270        assert_eq!(cell.latest(), Some(0.3));
271    }
272
273    #[test]
274    fn test_parse_survey_dump_selects_in_use_channel() {
275        let s = parse_survey_dump(DUMP).unwrap();
276        assert_eq!(
277            s,
278            SurveySample {
279                active_ms: 20000,
280                busy_ms: 5000
281            }
282        );
283    }
284
285    #[test]
286    fn test_parse_survey_dump_without_in_use_channel() {
287        let text = "Survey data from wlan0\n\tfrequency:\t5880 MHz\n\tchannel active time:\t10 ms\n\tchannel busy time:\t1 ms\n";
288        assert_eq!(parse_survey_dump(text), None);
289        assert_eq!(parse_survey_dump(""), None);
290    }
291
292    #[test]
293    fn test_parse_survey_dump_missing_busy_counter() {
294        let text = "Survey data from wlan0\n\tfrequency:\t5900 MHz [in use]\n\tchannel active time:\t10 ms\n";
295        assert_eq!(parse_survey_dump(text), None);
296    }
297
298    #[test]
299    fn test_cbr_from_samples() {
300        let a = SurveySample {
301            active_ms: 1000,
302            busy_ms: 100,
303        };
304        let b = SurveySample {
305            active_ms: 1200,
306            busy_ms: 160,
307        };
308        let cbr = cbr_from_samples(a, b).unwrap();
309        assert!((cbr - 0.3).abs() < 1e-12);
310    }
311
312    #[test]
313    fn test_cbr_from_samples_rejects_stalled_or_reset_counters() {
314        let a = SurveySample {
315            active_ms: 1000,
316            busy_ms: 100,
317        };
318        assert_eq!(cbr_from_samples(a, a), None);
319        let reset = SurveySample {
320            active_ms: 10,
321            busy_ms: 1,
322        };
323        assert_eq!(cbr_from_samples(a, reset), None);
324    }
325
326    #[test]
327    fn test_cbr_from_samples_clamps_to_one() {
328        let a = SurveySample {
329            active_ms: 1000,
330            busy_ms: 100,
331        };
332        let b = SurveySample {
333            active_ms: 1100,
334            busy_ms: 300,
335        };
336        assert_eq!(cbr_from_samples(a, b), Some(1.0));
337    }
338
339    #[test]
340    fn test_nl80211_ingest_first_sample_is_reference() {
341        let mut p = Nl80211SurveyCbr::new("wlan0");
342        assert_eq!(p.iface(), "wlan0");
343        assert_eq!(
344            p.ingest(SurveySample {
345                active_ms: 0,
346                busy_ms: 0
347            }),
348            None
349        );
350        let cbr = p
351            .ingest(SurveySample {
352                active_ms: 200,
353                busy_ms: 50,
354            })
355            .unwrap();
356        assert!((cbr - 0.25).abs() < 1e-12);
357        let cbr = p
358            .ingest(SurveySample {
359                active_ms: 400,
360                busy_ms: 150,
361            })
362            .unwrap();
363        assert!((cbr - 0.5).abs() < 1e-12);
364    }
365}