1use std::collections::HashMap;
9
10use serde::Serialize;
11
12use crate::generic::Error;
13use crate::lists;
14use crate::read::{Reader, Values};
15use crate::status;
16
17mod details;
18pub mod join;
19
20pub use details::{Details, Hint, Night, Radio, Security, Statistics, Wps};
21
22pub const MAX_CLIENTS: u32 = 1000;
25
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28pub struct Views {
29 pub clients: bool,
31 pub details: bool,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
38pub struct Wlan {
39 pub service: String,
41 pub ssid: Option<String>,
42 pub band: Option<String>,
44 pub channel: Option<u32>,
45 pub standard: Option<String>,
47 pub enabled: Option<bool>,
48 pub status: Option<String>,
50 pub guest: bool,
52 pub client_count: Option<u32>,
54 #[serde(skip_serializing_if = "Option::is_none")]
56 pub clients: Option<Vec<Client>>,
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub details: Option<Details>,
60}
61
62struct Read {
64 wlan: Wlan,
65 info: Values,
66 ext: Option<Values>,
67}
68
69#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
71pub struct Client {
72 pub name: Option<String>,
74 pub ip: Option<String>,
75 pub mac: Option<String>,
76 pub signal: Option<u8>,
78 pub rate: Option<u32>,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
85struct Listed {
86 client: Client,
87 channel: Option<u32>,
88 guest: Option<bool>,
89}
90
91pub async fn wlans(reader: &mut Reader, views: Views) -> Result<Vec<Wlan>, Error> {
99 let networks = networks(reader).await?;
100 with_views(reader, networks, views).await
101}
102
103pub async fn named(reader: &mut Reader, network: &str, views: Views) -> Result<Vec<Wlan>, Error> {
111 let mut networks = networks(reader).await?;
112 networks.retain(|n| is_named(&n.wlan, network));
113 with_views(reader, networks, views).await
114}
115
116fn is_named(wlan: &Wlan, network: &str) -> bool {
118 let number = wlan
119 .service
120 .get("WLANConfiguration".len()..)
121 .filter(|_| wlan.service.starts_with("WLANConfiguration"));
122 wlan.service.eq_ignore_ascii_case(network)
123 || number == Some(network)
124 || wlan.ssid.as_deref() == Some(network)
125}
126
127async fn networks(reader: &mut Reader) -> Result<Vec<Read>, Error> {
129 let mut networks = Vec::new();
130 for service in reader.services("WLANConfiguration") {
131 let Some(info) = reader.try_read(&service, "GetInfo", &[]).await? else {
132 continue;
133 };
134 let client_count = reader
135 .try_read(&service, "GetTotalAssociations", &[])
136 .await?
137 .and_then(|v| v.number("NewTotalAssociations"));
138 let ext = reader
139 .try_read(&service, "X_AVM-DE_GetWLANExtInfo", &[])
140 .await?;
141 let guest = ext
142 .as_ref()
143 .and_then(|v| v.text("NewX_AVM-DE_APType"))
144 .is_some_and(|kind| kind == "guest");
145 let wlan = Wlan {
146 band: info.get("NewX_AVM-DE_FrequencyBand").and_then(band),
147 ssid: info.text("NewSSID"),
148 channel: info.number("NewChannel"),
149 standard: info.text("NewStandard"),
150 enabled: info.flag("NewEnable"),
151 status: info.text("NewStatus"),
152 guest,
153 client_count,
154 clients: None,
155 details: None,
156 service,
157 };
158 networks.push(Read { wlan, info, ext });
159 }
160 Ok(networks)
161}
162
163async fn with_views(
165 reader: &mut Reader,
166 networks: Vec<Read>,
167 views: Views,
168) -> Result<Vec<Wlan>, Error> {
169 let mut wlans = Vec::new();
170 for Read {
171 mut wlan,
172 info,
173 ext,
174 } in networks
175 {
176 if views.details {
177 let details = details::read(reader, &wlan.service, &info, ext.as_ref()).await?;
178 wlan.details = Some(details);
179 }
180 wlans.push(wlan);
181 }
182 if views.clients {
183 add_clients(reader, &mut wlans).await?;
184 }
185 if wlans
186 .iter()
187 .any(|w| w.clients.as_ref().is_some_and(|c| !c.is_empty()))
188 {
189 let names = names(&status::hosts(reader).await?.hosts);
190 for client in wlans
191 .iter_mut()
192 .flat_map(|w| w.clients.iter_mut().flatten())
193 {
194 client.name = client
195 .mac
196 .as_deref()
197 .and_then(|mac| names.get(&lists::normal_mac(mac)))
198 .cloned();
199 }
200 }
201 Ok(wlans)
202}
203
204async fn add_clients(reader: &mut Reader, wlans: &mut [Wlan]) -> Result<(), Error> {
211 let mut list = None;
212 for wlan in wlans.iter() {
213 if let Some(xml) = reader
214 .document(
215 &wlan.service,
216 "X_AVM-DE_GetWLANDeviceListPath",
217 "NewX_AVM-DE_WLANDeviceListPath",
218 )
219 .await?
220 {
221 list = Some(client_list(&xml)?);
222 break;
223 }
224 }
225 for wlan in wlans.iter_mut() {
226 let listed = list
227 .as_deref()
228 .map(|list| of_network(list, wlan))
229 .filter(|clients| {
230 wlan.client_count
231 .is_none_or(|count| count as usize == clients.len())
232 });
233 wlan.clients = Some(match listed {
234 Some(clients) => clients,
235 None => one_per_call(reader, &wlan.service).await?,
236 });
237 }
238 Ok(())
239}
240
241fn of_network(list: &[Listed], wlan: &Wlan) -> Vec<Client> {
243 list.iter()
244 .filter(|l| {
245 if wlan.guest {
246 l.guest == Some(true)
247 } else {
248 l.guest != Some(true) && l.channel.is_some() && l.channel == wlan.channel
249 }
250 })
251 .map(|l| l.client.clone())
252 .collect()
253}
254
255async fn one_per_call(reader: &mut Reader, service: &str) -> Result<Vec<Client>, Error> {
257 let entries = reader
258 .entries(
259 service,
260 ("GetTotalAssociations", "NewTotalAssociations"),
261 ("GetGenericAssociatedDeviceInfo", "NewAssociatedDeviceIndex"),
262 MAX_CLIENTS,
263 )
264 .await?;
265 Ok(entries.map_or_else(Vec::new, |(_, entries)| {
266 entries.iter().map(client).collect()
267 }))
268}
269
270fn client_list(xml: &str) -> Result<Vec<Listed>, Error> {
278 let items = lists::items(xml, "WLAN device list", "List", "Item")?;
279 Ok(items
280 .iter()
281 .map(|item| Listed {
282 client: Client {
283 name: None,
284 ip: item.text("AssociatedDeviceIPAddress"),
285 mac: item.text("AssociatedDeviceMACAddress"),
286 signal: item.number("X_AVM-DE_SignalStrength"),
287 rate: item.number("X_AVM-DE_Speed"),
288 },
289 channel: item.number("AssociatedDeviceChannel"),
290 guest: item.flag("AssociatedDeviceGuest"),
291 })
292 .collect())
293}
294
295fn client(values: &Values) -> Client {
297 Client {
298 name: None,
299 ip: values.text("NewAssociatedDeviceIPAddress"),
300 mac: values.text("NewAssociatedDeviceMACAddress"),
301 signal: values.number("NewX_AVM-DE_SignalStrength"),
302 rate: values.number("NewX_AVM-DE_Speed"),
303 }
304}
305
306fn names(hosts: &[status::Host]) -> HashMap<String, String> {
309 hosts
310 .iter()
311 .filter_map(|h| Some((lists::normal_mac(h.mac.as_deref()?), h.name.clone()?)))
312 .collect()
313}
314
315pub(crate) fn band(megahertz: &str) -> Option<String> {
317 match megahertz {
318 "2400" => Some("2.4 GHz".to_owned()),
319 "5000" => Some("5 GHz".to_owned()),
320 "6000" => Some("6 GHz".to_owned()),
321 _ => None,
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn finds_networks_by_name() {
331 let wlan = Wlan {
332 service: "WLANConfiguration2".to_owned(),
333 ssid: Some("wlan-1".to_owned()),
334 ..Wlan::default()
335 };
336 for name in ["WLANConfiguration2", "wlanconfiguration2", "2", "wlan-1"] {
337 assert!(is_named(&wlan, name), "{name}");
338 }
339 for name in ["1", "WLANConfiguration1", "wlan", ""] {
340 assert!(!is_named(&wlan, name), "{name}");
341 }
342 let other = Wlan {
343 service: "2".to_owned(),
344 ..Wlan::default()
345 };
346 assert!(is_named(&other, "2"));
347 assert!(!is_named(&Wlan::default(), "1"));
348 }
349
350 #[test]
351 fn names_bands() {
352 assert_eq!(band("2400").as_deref(), Some("2.4 GHz"));
353 assert_eq!(band("5000").as_deref(), Some("5 GHz"));
354 assert_eq!(band("6000").as_deref(), Some("6 GHz"));
355 assert_eq!(band("unknown"), None);
356 }
357
358 #[test]
359 fn parses_the_list_of_clients() {
360 let xml = "<List><TotalAssociations>1</TotalAssociations><Item>\
361 <AssociatedDeviceIndex>0</AssociatedDeviceIndex>\
362 <AssociatedDeviceMACAddress>AA:BB:CC:00:00:01</AssociatedDeviceMACAddress>\
363 <AssociatedDeviceIPAddress></AssociatedDeviceIPAddress>\
364 <X_AVM-DE_Speed>72</X_AVM-DE_Speed>\
365 <X_AVM-DE_SignalStrength>71</X_AVM-DE_SignalStrength>\
366 <AssociatedDeviceChannel>6</AssociatedDeviceChannel>\
367 <AssociatedDeviceGuest>1</AssociatedDeviceGuest>\
368 </Item></List>";
369 assert_eq!(
370 client_list(xml).unwrap(),
371 [Listed {
372 client: Client {
373 mac: Some("AA:BB:CC:00:00:01".to_owned()),
374 signal: Some(71),
375 rate: Some(72),
376 ..Client::default()
377 },
378 channel: Some(6),
379 guest: Some(true),
380 }]
381 );
382 assert!(matches!(
383 client_list("<Other/>"),
384 Err(Error::InvalidDocument { .. })
385 ));
386 }
387
388 #[test]
389 fn assigns_clients_to_networks() {
390 let listed = |mac: &str, channel: Option<u32>, guest: Option<bool>| Listed {
391 client: Client {
392 mac: Some(mac.to_owned()),
393 ..Client::default()
394 },
395 channel,
396 guest,
397 };
398 let list = [
399 listed("1", Some(6), Some(false)),
400 listed("2", Some(48), Some(false)),
401 listed("3", Some(6), Some(true)),
402 listed("4", Some(6), None),
403 listed("5", None, Some(false)),
404 ];
405 let wlan = |channel: Option<u32>, guest: bool| Wlan {
406 channel,
407 guest,
408 ..Wlan::default()
409 };
410 let macs = |wlan: &Wlan| -> Vec<String> {
411 of_network(&list, wlan)
412 .into_iter()
413 .filter_map(|c| c.mac)
414 .collect()
415 };
416 assert_eq!(macs(&wlan(Some(6), false)), ["1", "4"]);
417 assert_eq!(macs(&wlan(Some(48), false)), ["2"]);
418 assert_eq!(macs(&wlan(Some(6), true)), ["3"]);
419 assert_eq!(macs(&wlan(None, false)), [] as [String; 0]);
420 }
421
422 #[test]
423 fn finds_names_by_mac() {
424 let host = |name: Option<&str>, mac: Option<&str>| status::Host {
425 name: name.map(str::to_owned),
426 mac: mac.map(str::to_owned),
427 ..status::Host::default()
428 };
429 let names = names(&[
430 host(Some("device-1"), Some("aa:bb:cc:00:00:01")),
431 host(None, Some("AA:BB:CC:00:00:02")),
432 host(Some("device-3"), None),
433 ]);
434 assert_eq!(names.len(), 1);
435 assert_eq!(names["AABBCC000001"], "device-1");
436 }
437}