wifi_rs/connectivity/providers/
linux.rs

1use crate::connectivity::{Connectivity, WifiConnectionError};
2use crate::platforms::{Connection, WiFi, WifiError, WifiInterface};
3use std::process::Command;
4
5/// Wireless network connectivity functionality.
6impl Connectivity for WiFi {
7    /// Attempts to connect to a wireless network with a given SSID and password.
8    fn connect(&mut self, ssid: &str, password: &str) -> Result<bool, WifiConnectionError> {
9        if !WiFi::is_wifi_enabled().map_err(|err| WifiConnectionError::Other { kind: err })? {
10            return Err(WifiConnectionError::Other {
11                kind: WifiError::WifiDisabled,
12            });
13        }
14
15        let output = Command::new("nmcli")
16            .args(&[
17                "d",
18                "wifi",
19                "connect",
20                ssid,
21                "password",
22                &password,
23                "ifname",
24                &self.interface,
25            ])
26            .output()
27            .map_err(|err| WifiConnectionError::FailedToConnect(format!("{}", err)))?;
28
29        if !String::from_utf8_lossy(&output.stdout)
30            .as_ref()
31            .contains("successfully activated")
32        {
33            return Ok(false);
34        }
35
36        self.connection = Some(Connection {
37            // ssid: String::from(ssid),
38        });
39
40        Ok(true)
41    }
42
43    /// Attempts to disconnect from a wireless network currently connected to.
44    fn disconnect(&self) -> Result<bool, WifiConnectionError> {
45        let output = Command::new("nmcli")
46            .args(&["d", "disconnect", "ifname", &self.interface])
47            .output()
48            .map_err(|err| WifiConnectionError::FailedToDisconnect(format!("{}", err)))?;
49
50        Ok(String::from_utf8_lossy(&output.stdout)
51            .as_ref()
52            .contains("disconnect"))
53    }
54}