rustflexstack/management/
cbr.rs1use std::process::Command;
20use std::sync::{Arc, Mutex};
21
22pub trait CbrProvider: Send {
28 fn measure_cbr(&mut self) -> Option<f64>;
30}
31
32#[derive(Debug, Clone, Default)]
38pub struct SharedCbr {
39 latest: Arc<Mutex<Option<f64>>>,
40}
41
42impl SharedCbr {
43 pub fn new() -> Self {
45 Self::default()
46 }
47
48 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct SurveySample {
73 pub active_ms: u64,
75 pub busy_ms: u64,
77}
78
79pub 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; }
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
126pub 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#[derive(Debug, Clone)]
150pub struct Nl80211SurveyCbr {
151 iface: String,
152 previous: Option<SurveySample>,
153}
154
155impl Nl80211SurveyCbr {
156 pub fn new(iface: impl Into<String>) -> Self {
158 Self {
159 iface: iface.into(),
160 previous: None,
161 }
162 }
163
164 pub fn iface(&self) -> &str {
166 &self.iface
167 }
168
169 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
199pub 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
211pub 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 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}