1use std::collections::HashMap;
11
12use eave_dbus::{Snapshot, Stream};
13use zbus::Connection;
14use zbus::zvariant::{OwnedObjectPath, OwnedValue};
15
16mod agent;
17
18pub use agent::connect_with;
19pub use zbus;
20
21const SERVICE: &str = "net.connman.iwd";
22const DEVICE: &str = "net.connman.iwd.Device";
23const STATION: &str = "net.connman.iwd.Station";
24const NETWORK: &str = "net.connman.iwd.Network";
25const KNOWN: &str = "net.connman.iwd.KnownNetwork";
26
27#[derive(Debug, Clone, Default, PartialEq)]
29pub struct Wifi {
30 pub access: Access,
31 pub station: Option<Station>,
33}
34
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub enum Access {
37 Ready,
39 #[default]
41 Absent,
42 Denied,
44}
45
46#[derive(Debug, Clone, PartialEq)]
48pub struct Station {
49 pub device: OwnedObjectPath,
51 pub interface: String,
53 pub address: String,
55 pub powered: bool,
56 pub state: String,
58 pub scanning: bool,
59 pub networks: Vec<Network>,
61}
62
63#[derive(Debug, Clone, PartialEq)]
65pub struct Network {
66 pub path: OwnedObjectPath,
67 pub name: String,
68 pub security: Security,
69 pub strength: u8,
71 pub signal: i16,
73 pub known: Option<Known>,
75 pub connected: bool,
76}
77
78#[derive(Debug, Clone, PartialEq)]
80pub struct Known {
81 pub path: OwnedObjectPath,
82 pub autoconnect: bool,
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Security {
87 Open,
88 Psk,
90 Eap,
92 Wep,
93}
94
95impl Security {
96 fn from_iwd(kind: &str) -> Self {
97 match kind {
98 "open" => Self::Open,
99 "8021x" => Self::Eap,
100 "wep" => Self::Wep,
101 _ => Self::Psk,
102 }
103 }
104}
105
106#[derive(Debug, Clone, Default, PartialEq)]
108pub struct Diagnostics {
109 pub bssid: Option<String>,
111 pub frequency: Option<u32>,
113 pub channel: Option<u16>,
114 pub security: Option<String>,
116 pub rssi: Option<i16>,
118 pub tx_rate: Option<f32>,
120 pub rx_rate: Option<f32>,
121}
122
123pub async fn read() -> Option<Wifi> {
125 use futures_util::StreamExt;
126 std::pin::pin!(watch()).next().await
127}
128
129pub fn watch() -> impl Stream<Item = Wifi> {
132 eave_dbus::watch_all(SERVICE, snapshot)
133}
134
135async fn snapshot(connection: Connection) -> zbus::Result<Snapshot<Wifi>> {
136 let objects = match eave_dbus::managed_objects(&connection, SERVICE, "/").await {
137 Ok(objects) => objects,
138 Err(error) => {
139 let access = if eave_dbus::is_access_denied(&error) {
140 Access::Denied
141 } else if eave_dbus::is_unavailable(&error) {
142 Access::Absent
143 } else {
144 return Err(error);
145 };
146 return Ok(Snapshot {
147 state: Wifi {
148 access,
149 station: None,
150 },
151 watch: Vec::new(),
152 });
153 }
154 };
155 let objects = Objects::from(objects);
156 let device = objects.first_device();
157 let ordered = match device
158 .as_ref()
159 .filter(|device| objects.has(device, STATION))
160 {
161 Some(device) => ordered_networks(&connection, device)
162 .await
163 .unwrap_or_default(),
164 None => Vec::new(),
165 };
166 let station = device.map(|device| objects.station(&device, &ordered));
167 Ok(Snapshot {
168 state: Wifi {
169 access: Access::Ready,
170 station,
171 },
172 watch: Vec::new(),
173 })
174}
175
176async fn ordered_networks(
178 connection: &Connection,
179 device: &OwnedObjectPath,
180) -> zbus::Result<Vec<(OwnedObjectPath, i16)>> {
181 let reply = connection
182 .call_method(
183 Some(SERVICE),
184 device,
185 Some(STATION),
186 "GetOrderedNetworks",
187 &(),
188 )
189 .await?;
190 reply.body().deserialize()
191}
192
193type Properties = HashMap<String, OwnedValue>;
194
195struct Objects(HashMap<String, HashMap<String, Properties>>);
197
198impl From<zbus::fdo::ManagedObjects> for Objects {
199 fn from(objects: zbus::fdo::ManagedObjects) -> Self {
200 Self(
201 objects
202 .into_iter()
203 .map(|(path, interfaces)| {
204 let interfaces = interfaces
205 .into_iter()
206 .map(|(name, properties)| (name.to_string(), properties))
207 .collect();
208 (path.to_string(), interfaces)
209 })
210 .collect(),
211 )
212 }
213}
214
215fn get<T: TryFrom<OwnedValue> + Default>(properties: &Properties, name: &str) -> T {
216 properties
217 .get(name)
218 .and_then(|value| value.try_clone().ok())
219 .and_then(|value| T::try_from(value).ok())
220 .unwrap_or_default()
221}
222
223fn object_path(properties: &Properties, name: &str) -> Option<OwnedObjectPath> {
224 let value = properties.get(name)?.try_clone().ok()?;
225 let path = OwnedObjectPath::try_from(value).ok()?;
226 (path.as_str() != "/").then_some(path)
227}
228
229impl Objects {
230 fn interface(&self, path: &str, interface: &str) -> Option<&Properties> {
231 self.0.get(path)?.get(interface)
232 }
233
234 fn has(&self, path: &OwnedObjectPath, interface: &str) -> bool {
235 self.interface(path.as_str(), interface).is_some()
236 }
237
238 fn first_device(&self) -> Option<OwnedObjectPath> {
240 let first = self
241 .0
242 .iter()
243 .filter(|(_, interfaces)| {
244 interfaces
245 .get(DEVICE)
246 .is_some_and(|device| get::<String>(device, "Mode") == "station")
247 })
248 .map(|(path, _)| path)
249 .min()?;
250 OwnedObjectPath::try_from(first.as_str()).ok()
251 }
252
253 fn station(&self, device: &OwnedObjectPath, ordered: &[(OwnedObjectPath, i16)]) -> Station {
254 let empty = Properties::new();
255 let properties = self.interface(device.as_str(), DEVICE).unwrap_or(&empty);
256 let station = self.interface(device.as_str(), STATION);
257 let networks = ordered
258 .iter()
259 .filter_map(|(path, signal)| self.network(path, *signal))
260 .collect();
261 Station {
262 device: device.clone(),
263 interface: get(properties, "Name"),
264 address: get(properties, "Address"),
265 powered: get(properties, "Powered"),
266 state: station
267 .map(|station| get(station, "State"))
268 .unwrap_or_default(),
269 scanning: station.is_some_and(|station| get(station, "Scanning")),
270 networks,
271 }
272 }
273
274 fn network(&self, path: &OwnedObjectPath, signal: i16) -> Option<Network> {
275 let network = self.interface(path.as_str(), NETWORK)?;
276 let known = object_path(network, "KnownNetwork").map(|known| {
277 let autoconnect = self
278 .interface(known.as_str(), KNOWN)
279 .is_some_and(|properties| get(properties, "AutoConnect"));
280 Known {
281 path: known,
282 autoconnect,
283 }
284 });
285 let dbm = signal / 100;
287 Some(Network {
288 path: path.clone(),
289 name: get(network, "Name"),
290 security: Security::from_iwd(&get::<String>(network, "Type")),
291 strength: strength(dbm),
292 signal: dbm,
293 known,
294 connected: get(network, "Connected"),
295 })
296 }
297}
298
299fn strength(dbm: i16) -> u8 {
302 (2 * (i32::from(dbm) + 100)).clamp(0, 100) as u8
303}
304
305async fn call(
306 path: &OwnedObjectPath,
307 interface: &'static str,
308 method: &'static str,
309) -> zbus::Result<()> {
310 let connection = eave_dbus::system().await?;
311 connection
312 .call_method(Some(SERVICE), path, Some(interface), method, &())
313 .await?;
314 Ok(())
315}
316
317async fn set(
318 path: &OwnedObjectPath,
319 interface: &'static str,
320 name: &'static str,
321 value: bool,
322) -> zbus::Result<()> {
323 let connection = eave_dbus::system().await?;
324 let properties = zbus::fdo::PropertiesProxy::builder(&connection)
325 .destination(SERVICE)?
326 .path(path.as_ref())?
327 .build()
328 .await?;
329 let interface = zbus::names::InterfaceName::try_from(interface)?;
330 properties
331 .set(interface, name, zbus::zvariant::Value::from(value))
332 .await?;
333 Ok(())
334}
335
336pub async fn scan(station: &Station) -> zbus::Result<()> {
338 call(&station.device, STATION, "Scan").await
339}
340
341pub async fn connect(network: &Network) -> zbus::Result<()> {
343 call(&network.path, NETWORK, "Connect").await
344}
345
346pub async fn disconnect(station: &Station) -> zbus::Result<()> {
347 call(&station.device, STATION, "Disconnect").await
348}
349
350pub async fn forget(known: &Known) -> zbus::Result<()> {
352 call(&known.path, KNOWN, "Forget").await
353}
354
355pub async fn set_autoconnect(known: &Known, on: bool) -> zbus::Result<()> {
357 set(&known.path, KNOWN, "AutoConnect", on).await
358}
359
360pub async fn set_powered(station: &Station, on: bool) -> zbus::Result<()> {
362 set(&station.device, DEVICE, "Powered", on).await
363}
364
365pub async fn diagnostics(station: &Station) -> zbus::Result<Diagnostics> {
367 let connection = eave_dbus::system().await?;
368 let reply = connection
369 .call_method(
370 Some(SERVICE),
371 &station.device,
372 Some("net.connman.iwd.StationDiagnostic"),
373 "GetDiagnostics",
374 &(),
375 )
376 .await?;
377 let properties: Properties = reply.body().deserialize()?;
378 let some = |properties: &Properties, name: &str| properties.contains_key(name);
379 Ok(Diagnostics {
380 bssid: some(&properties, "ConnectedBss").then(|| get(&properties, "ConnectedBss")),
381 frequency: some(&properties, "Frequency").then(|| get(&properties, "Frequency")),
382 channel: some(&properties, "Channel").then(|| get(&properties, "Channel")),
383 security: some(&properties, "Security").then(|| get(&properties, "Security")),
384 rssi: some(&properties, "RSSI").then(|| get(&properties, "RSSI")),
385 tx_rate: some(&properties, "TxBitrate")
387 .then(|| get::<u32>(&properties, "TxBitrate") as f32 / 10.0),
388 rx_rate: some(&properties, "RxBitrate")
389 .then(|| get::<u32>(&properties, "RxBitrate") as f32 / 10.0),
390 })
391}
392
393pub fn reason(error: &zbus::Error) -> &'static str {
395 let name = match error {
396 zbus::Error::MethodError(name, ..) => name.as_str(),
397 _ => return "Couldn't reach iwd",
398 };
399 match name.rsplit('.').next().unwrap_or("") {
400 "InvalidFormat" => "That password isn't valid for this network",
401 "Failed" | "AuthenticationFailed" => "Couldn't join. Check the password and try again",
402 "Aborted" | "Canceled" => "Joining was cancelled",
403 "Busy" | "InProgress" => "Already joining a network",
404 "NotSupported" => "This network's security isn't supported",
405 "NotConfigured" => "This network needs setting up first",
406 "AccessDenied" => "Not allowed to change Wi-Fi",
407 "Timeout" => "The network didn't answer",
408 _ => "Couldn't join the network",
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 fn value<T: Into<zbus::zvariant::Value<'static>>>(value: T) -> OwnedValue {
417 OwnedValue::try_from(value.into()).unwrap()
418 }
419
420 fn object(path: &str) -> OwnedObjectPath {
421 OwnedObjectPath::try_from(path).unwrap()
422 }
423
424 fn fixture() -> Objects {
425 let mut objects = HashMap::new();
426 let mut device = HashMap::new();
427 device.insert(
428 DEVICE.to_string(),
429 Properties::from([
430 ("Name".into(), value("wlan0")),
431 ("Address".into(), value("c8:89:f3:db:f8:c1")),
432 ("Powered".into(), value(true)),
433 ("Mode".into(), value("station")),
434 ]),
435 );
436 device.insert(
437 STATION.to_string(),
438 Properties::from([
439 ("State".into(), value("connected")),
440 ("Scanning".into(), value(false)),
441 ]),
442 );
443 objects.insert("/net/connman/iwd/0/2".to_string(), device);
444 let network = |name: &str, kind: &str, connected: bool, known: Option<&str>| {
445 let mut properties = Properties::from([
446 ("Name".into(), value(name.to_string())),
447 ("Type".into(), value(kind.to_string())),
448 ("Connected".into(), value(connected)),
449 ]);
450 if let Some(known) = known {
451 properties.insert("KnownNetwork".into(), value(object(known)));
452 }
453 HashMap::from([(NETWORK.to_string(), properties)])
454 };
455 objects.insert(
456 "/net/connman/iwd/0/2/home_psk".into(),
457 network("Home", "psk", true, Some("/net/connman/iwd/home_psk")),
458 );
459 objects.insert(
460 "/net/connman/iwd/0/2/cafe_open".into(),
461 network("Cafe", "open", false, None),
462 );
463 objects.insert(
464 "/net/connman/iwd/home_psk".into(),
465 HashMap::from([(
466 KNOWN.to_string(),
467 Properties::from([("AutoConnect".into(), value(true))]),
468 )]),
469 );
470 Objects(objects)
471 }
472
473 #[test]
474 fn reads_the_station_and_its_networks_in_order() {
475 let objects = fixture();
476 let device = objects.first_device().unwrap();
477 assert_eq!(device.as_str(), "/net/connman/iwd/0/2");
478 let ordered = [
479 (object("/net/connman/iwd/0/2/home_psk"), -4100),
480 (object("/net/connman/iwd/0/2/cafe_open"), -8000),
481 (object("/net/connman/iwd/0/2/gone_psk"), -9000),
482 ];
483 let station = objects.station(&device, &ordered);
484 assert_eq!(station.interface, "wlan0");
485 assert!(station.powered);
486 assert_eq!(station.state, "connected");
487 assert_eq!(
488 station.networks.len(),
489 2,
490 "a network that's gone is skipped"
491 );
492 let home = &station.networks[0];
493 assert_eq!(home.name, "Home");
494 assert!(home.connected);
495 assert_eq!(home.security, Security::Psk);
496 assert_eq!(home.signal, -41);
497 assert_eq!(home.strength, 100);
498 assert!(home.known.as_ref().is_some_and(|known| known.autoconnect));
499 let cafe = &station.networks[1];
500 assert_eq!(cafe.security, Security::Open);
501 assert_eq!(cafe.known, None);
502 assert_eq!(cafe.strength, 40);
503 }
504
505 #[test]
508 #[ignore = "needs iwd"]
509 fn live() {
510 let runtime = tokio::runtime::Builder::new_current_thread()
511 .enable_all()
512 .build()
513 .unwrap();
514 runtime.block_on(async {
515 use futures_util::StreamExt;
516 let wifi = std::pin::pin!(watch()).next().await.unwrap();
517 println!("{wifi:#?}");
518 if let Some(station) = &wifi.station {
519 println!("{:#?}", diagnostics(station).await);
520 }
521 });
522 }
523
524 #[test]
525 fn signal_maps_like_the_kernels() {
526 assert_eq!(strength(-100), 0);
527 assert_eq!(strength(-75), 50);
528 assert_eq!(strength(-50), 100);
529 assert_eq!(strength(-30), 100);
530 assert_eq!(strength(-110), 0);
531 }
532
533 #[test]
534 fn errors_read_as_reasons() {
535 let error = zbus::Error::MethodError(
536 zbus::names::OwnedErrorName::try_from("net.connman.iwd.Failed").unwrap(),
537 None,
538 zbus::Message::method_call("/", "x")
539 .unwrap()
540 .build(&())
541 .unwrap(),
542 );
543 assert_eq!(
544 reason(&error),
545 "Couldn't join. Check the password and try again"
546 );
547 }
548}