use std::collections::HashMap;
use eave_dbus::{Snapshot, Stream};
use zbus::Connection;
use zbus::zvariant::{OwnedObjectPath, OwnedValue};
mod agent;
pub use agent::connect_with;
pub use zbus;
const SERVICE: &str = "net.connman.iwd";
const DEVICE: &str = "net.connman.iwd.Device";
const STATION: &str = "net.connman.iwd.Station";
const NETWORK: &str = "net.connman.iwd.Network";
const KNOWN: &str = "net.connman.iwd.KnownNetwork";
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Wifi {
pub access: Access,
pub station: Option<Station>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Access {
Ready,
#[default]
Absent,
Denied,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Station {
pub device: OwnedObjectPath,
pub interface: String,
pub address: String,
pub powered: bool,
pub state: String,
pub scanning: bool,
pub networks: Vec<Network>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Network {
pub path: OwnedObjectPath,
pub name: String,
pub security: Security,
pub strength: u8,
pub signal: i16,
pub known: Option<Known>,
pub connected: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Known {
pub path: OwnedObjectPath,
pub autoconnect: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Security {
Open,
Psk,
Eap,
Wep,
}
impl Security {
fn from_iwd(kind: &str) -> Self {
match kind {
"open" => Self::Open,
"8021x" => Self::Eap,
"wep" => Self::Wep,
_ => Self::Psk,
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Diagnostics {
pub bssid: Option<String>,
pub frequency: Option<u32>,
pub channel: Option<u16>,
pub security: Option<String>,
pub rssi: Option<i16>,
pub tx_rate: Option<f32>,
pub rx_rate: Option<f32>,
}
pub async fn read() -> Option<Wifi> {
use futures_util::StreamExt;
std::pin::pin!(watch()).next().await
}
pub fn watch() -> impl Stream<Item = Wifi> {
eave_dbus::watch_all(SERVICE, snapshot)
}
async fn snapshot(connection: Connection) -> zbus::Result<Snapshot<Wifi>> {
let objects = match eave_dbus::managed_objects(&connection, SERVICE, "/").await {
Ok(objects) => objects,
Err(error) => {
let access = if eave_dbus::is_access_denied(&error) {
Access::Denied
} else if eave_dbus::is_unavailable(&error) {
Access::Absent
} else {
return Err(error);
};
return Ok(Snapshot {
state: Wifi {
access,
station: None,
},
watch: Vec::new(),
});
}
};
let objects = Objects::from(objects);
let device = objects.first_device();
let ordered = match device
.as_ref()
.filter(|device| objects.has(device, STATION))
{
Some(device) => ordered_networks(&connection, device)
.await
.unwrap_or_default(),
None => Vec::new(),
};
let station = device.map(|device| objects.station(&device, &ordered));
Ok(Snapshot {
state: Wifi {
access: Access::Ready,
station,
},
watch: Vec::new(),
})
}
async fn ordered_networks(
connection: &Connection,
device: &OwnedObjectPath,
) -> zbus::Result<Vec<(OwnedObjectPath, i16)>> {
let reply = connection
.call_method(
Some(SERVICE),
device,
Some(STATION),
"GetOrderedNetworks",
&(),
)
.await?;
reply.body().deserialize()
}
type Properties = HashMap<String, OwnedValue>;
struct Objects(HashMap<String, HashMap<String, Properties>>);
impl From<zbus::fdo::ManagedObjects> for Objects {
fn from(objects: zbus::fdo::ManagedObjects) -> Self {
Self(
objects
.into_iter()
.map(|(path, interfaces)| {
let interfaces = interfaces
.into_iter()
.map(|(name, properties)| (name.to_string(), properties))
.collect();
(path.to_string(), interfaces)
})
.collect(),
)
}
}
fn get<T: TryFrom<OwnedValue> + Default>(properties: &Properties, name: &str) -> T {
properties
.get(name)
.and_then(|value| value.try_clone().ok())
.and_then(|value| T::try_from(value).ok())
.unwrap_or_default()
}
fn object_path(properties: &Properties, name: &str) -> Option<OwnedObjectPath> {
let value = properties.get(name)?.try_clone().ok()?;
let path = OwnedObjectPath::try_from(value).ok()?;
(path.as_str() != "/").then_some(path)
}
impl Objects {
fn interface(&self, path: &str, interface: &str) -> Option<&Properties> {
self.0.get(path)?.get(interface)
}
fn has(&self, path: &OwnedObjectPath, interface: &str) -> bool {
self.interface(path.as_str(), interface).is_some()
}
fn first_device(&self) -> Option<OwnedObjectPath> {
let first = self
.0
.iter()
.filter(|(_, interfaces)| {
interfaces
.get(DEVICE)
.is_some_and(|device| get::<String>(device, "Mode") == "station")
})
.map(|(path, _)| path)
.min()?;
OwnedObjectPath::try_from(first.as_str()).ok()
}
fn station(&self, device: &OwnedObjectPath, ordered: &[(OwnedObjectPath, i16)]) -> Station {
let empty = Properties::new();
let properties = self.interface(device.as_str(), DEVICE).unwrap_or(&empty);
let station = self.interface(device.as_str(), STATION);
let networks = ordered
.iter()
.filter_map(|(path, signal)| self.network(path, *signal))
.collect();
Station {
device: device.clone(),
interface: get(properties, "Name"),
address: get(properties, "Address"),
powered: get(properties, "Powered"),
state: station
.map(|station| get(station, "State"))
.unwrap_or_default(),
scanning: station.is_some_and(|station| get(station, "Scanning")),
networks,
}
}
fn network(&self, path: &OwnedObjectPath, signal: i16) -> Option<Network> {
let network = self.interface(path.as_str(), NETWORK)?;
let known = object_path(network, "KnownNetwork").map(|known| {
let autoconnect = self
.interface(known.as_str(), KNOWN)
.is_some_and(|properties| get(properties, "AutoConnect"));
Known {
path: known,
autoconnect,
}
});
let dbm = signal / 100;
Some(Network {
path: path.clone(),
name: get(network, "Name"),
security: Security::from_iwd(&get::<String>(network, "Type")),
strength: strength(dbm),
signal: dbm,
known,
connected: get(network, "Connected"),
})
}
}
fn strength(dbm: i16) -> u8 {
(2 * (i32::from(dbm) + 100)).clamp(0, 100) as u8
}
async fn call(
path: &OwnedObjectPath,
interface: &'static str,
method: &'static str,
) -> zbus::Result<()> {
let connection = eave_dbus::system().await?;
connection
.call_method(Some(SERVICE), path, Some(interface), method, &())
.await?;
Ok(())
}
async fn set(
path: &OwnedObjectPath,
interface: &'static str,
name: &'static str,
value: bool,
) -> zbus::Result<()> {
let connection = eave_dbus::system().await?;
let properties = zbus::fdo::PropertiesProxy::builder(&connection)
.destination(SERVICE)?
.path(path.as_ref())?
.build()
.await?;
let interface = zbus::names::InterfaceName::try_from(interface)?;
properties
.set(interface, name, zbus::zvariant::Value::from(value))
.await?;
Ok(())
}
pub async fn scan(station: &Station) -> zbus::Result<()> {
call(&station.device, STATION, "Scan").await
}
pub async fn connect(network: &Network) -> zbus::Result<()> {
call(&network.path, NETWORK, "Connect").await
}
pub async fn disconnect(station: &Station) -> zbus::Result<()> {
call(&station.device, STATION, "Disconnect").await
}
pub async fn forget(known: &Known) -> zbus::Result<()> {
call(&known.path, KNOWN, "Forget").await
}
pub async fn set_autoconnect(known: &Known, on: bool) -> zbus::Result<()> {
set(&known.path, KNOWN, "AutoConnect", on).await
}
pub async fn set_powered(station: &Station, on: bool) -> zbus::Result<()> {
set(&station.device, DEVICE, "Powered", on).await
}
pub async fn diagnostics(station: &Station) -> zbus::Result<Diagnostics> {
let connection = eave_dbus::system().await?;
let reply = connection
.call_method(
Some(SERVICE),
&station.device,
Some("net.connman.iwd.StationDiagnostic"),
"GetDiagnostics",
&(),
)
.await?;
let properties: Properties = reply.body().deserialize()?;
let some = |properties: &Properties, name: &str| properties.contains_key(name);
Ok(Diagnostics {
bssid: some(&properties, "ConnectedBss").then(|| get(&properties, "ConnectedBss")),
frequency: some(&properties, "Frequency").then(|| get(&properties, "Frequency")),
channel: some(&properties, "Channel").then(|| get(&properties, "Channel")),
security: some(&properties, "Security").then(|| get(&properties, "Security")),
rssi: some(&properties, "RSSI").then(|| get(&properties, "RSSI")),
tx_rate: some(&properties, "TxBitrate")
.then(|| get::<u32>(&properties, "TxBitrate") as f32 / 10.0),
rx_rate: some(&properties, "RxBitrate")
.then(|| get::<u32>(&properties, "RxBitrate") as f32 / 10.0),
})
}
pub fn reason(error: &zbus::Error) -> &'static str {
let name = match error {
zbus::Error::MethodError(name, ..) => name.as_str(),
_ => return "Couldn't reach iwd",
};
match name.rsplit('.').next().unwrap_or("") {
"InvalidFormat" => "That password isn't valid for this network",
"Failed" | "AuthenticationFailed" => "Couldn't join. Check the password and try again",
"Aborted" | "Canceled" => "Joining was cancelled",
"Busy" | "InProgress" => "Already joining a network",
"NotSupported" => "This network's security isn't supported",
"NotConfigured" => "This network needs setting up first",
"AccessDenied" => "Not allowed to change Wi-Fi",
"Timeout" => "The network didn't answer",
_ => "Couldn't join the network",
}
}
#[cfg(test)]
mod tests {
use super::*;
fn value<T: Into<zbus::zvariant::Value<'static>>>(value: T) -> OwnedValue {
OwnedValue::try_from(value.into()).unwrap()
}
fn object(path: &str) -> OwnedObjectPath {
OwnedObjectPath::try_from(path).unwrap()
}
fn fixture() -> Objects {
let mut objects = HashMap::new();
let mut device = HashMap::new();
device.insert(
DEVICE.to_string(),
Properties::from([
("Name".into(), value("wlan0")),
("Address".into(), value("c8:89:f3:db:f8:c1")),
("Powered".into(), value(true)),
("Mode".into(), value("station")),
]),
);
device.insert(
STATION.to_string(),
Properties::from([
("State".into(), value("connected")),
("Scanning".into(), value(false)),
]),
);
objects.insert("/net/connman/iwd/0/2".to_string(), device);
let network = |name: &str, kind: &str, connected: bool, known: Option<&str>| {
let mut properties = Properties::from([
("Name".into(), value(name.to_string())),
("Type".into(), value(kind.to_string())),
("Connected".into(), value(connected)),
]);
if let Some(known) = known {
properties.insert("KnownNetwork".into(), value(object(known)));
}
HashMap::from([(NETWORK.to_string(), properties)])
};
objects.insert(
"/net/connman/iwd/0/2/home_psk".into(),
network("Home", "psk", true, Some("/net/connman/iwd/home_psk")),
);
objects.insert(
"/net/connman/iwd/0/2/cafe_open".into(),
network("Cafe", "open", false, None),
);
objects.insert(
"/net/connman/iwd/home_psk".into(),
HashMap::from([(
KNOWN.to_string(),
Properties::from([("AutoConnect".into(), value(true))]),
)]),
);
Objects(objects)
}
#[test]
fn reads_the_station_and_its_networks_in_order() {
let objects = fixture();
let device = objects.first_device().unwrap();
assert_eq!(device.as_str(), "/net/connman/iwd/0/2");
let ordered = [
(object("/net/connman/iwd/0/2/home_psk"), -4100),
(object("/net/connman/iwd/0/2/cafe_open"), -8000),
(object("/net/connman/iwd/0/2/gone_psk"), -9000),
];
let station = objects.station(&device, &ordered);
assert_eq!(station.interface, "wlan0");
assert!(station.powered);
assert_eq!(station.state, "connected");
assert_eq!(
station.networks.len(),
2,
"a network that's gone is skipped"
);
let home = &station.networks[0];
assert_eq!(home.name, "Home");
assert!(home.connected);
assert_eq!(home.security, Security::Psk);
assert_eq!(home.signal, -41);
assert_eq!(home.strength, 100);
assert!(home.known.as_ref().is_some_and(|known| known.autoconnect));
let cafe = &station.networks[1];
assert_eq!(cafe.security, Security::Open);
assert_eq!(cafe.known, None);
assert_eq!(cafe.strength, 40);
}
#[test]
#[ignore = "needs iwd"]
fn live() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async {
use futures_util::StreamExt;
let wifi = std::pin::pin!(watch()).next().await.unwrap();
println!("{wifi:#?}");
if let Some(station) = &wifi.station {
println!("{:#?}", diagnostics(station).await);
}
});
}
#[test]
fn signal_maps_like_the_kernels() {
assert_eq!(strength(-100), 0);
assert_eq!(strength(-75), 50);
assert_eq!(strength(-50), 100);
assert_eq!(strength(-30), 100);
assert_eq!(strength(-110), 0);
}
#[test]
fn errors_read_as_reasons() {
let error = zbus::Error::MethodError(
zbus::names::OwnedErrorName::try_from("net.connman.iwd.Failed").unwrap(),
None,
zbus::Message::method_call("/", "x")
.unwrap()
.build(&())
.unwrap(),
);
assert_eq!(
reason(&error),
"Couldn't join. Check the password and try again"
);
}
}