-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwifi.rs
207 lines (177 loc) · 6.15 KB
/
wifi.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use super::PowerSavingMode;
use crate::{
config::STATIC_IP_CONFIG,
os_debug,
sysc::{OsError, OsResult, ReportableError},
};
use esp_idf_svc::{
eventloop::{EspEventLoop, EspEventSource, EspSystemEventLoop, System, Wait},
hal::modem::Modem,
ipv4::{
ClientConfiguration as IpClientConfiguration, Configuration as IpConfiguration,
DHCPClientSettings,
},
netif::{EspNetif, IpEvent, NetifConfiguration, NetifStack},
nvs::EspDefaultNvsPartition,
sys::{esp_wifi_set_ps, EspError},
wifi::{
config::{ScanConfig, ScanType},
AccessPointInfo, AuthMethod, ClientConfiguration, Configuration, EspWifi, WifiDeviceId,
WifiDriver, WifiEvent,
},
};
use pwmp_client::pwmp_msg::mac::Mac;
use std::{thread::sleep, time::Duration};
pub struct WiFi {
driver: EspWifi<'static>,
event_loop: EspEventLoop<System>,
}
#[allow(clippy::unused_self)]
impl WiFi {
#[allow(clippy::needless_pass_by_value)]
pub fn new(
modem: Modem,
sys_loop: EspSystemEventLoop,
nvs: EspDefaultNvsPartition,
) -> OsResult<Self> {
let wifi = WifiDriver::new(modem, sys_loop.clone(), Some(nvs))?;
let ip_config = if STATIC_IP_CONFIG.is_some() {
Self::generate_static_ip_config()
} else {
Self::generate_dhcp_config(&wifi)
};
os_debug!("Configuring WiFi interface");
let mut wifi = EspWifi::wrap_all(
wifi,
EspNetif::new_with_conf(&ip_config)?,
EspNetif::new(NetifStack::Ap)?,
)?;
wifi.set_configuration(&Configuration::Client(ClientConfiguration::default()))?;
os_debug!("Starting WiFi interface");
wifi.start()?;
Ok(Self {
driver: wifi,
event_loop: sys_loop,
})
}
pub fn set_power_saving(&self, mode: PowerSavingMode) -> OsResult<()> {
EspError::convert(unsafe { esp_wifi_set_ps(mode as u32) })?;
Ok(())
}
pub fn scan<const MAXN: usize>(
&mut self,
timeout: Duration,
) -> OsResult<heapless::Vec<AccessPointInfo, MAXN>> {
self.driver.start_scan(
&ScanConfig {
bssid: None,
ssid: None,
channel: None,
scan_type: ScanType::Passive(timeout),
show_hidden: false,
},
false,
)?;
sleep(timeout);
self.driver.stop_scan()?;
Ok(self.driver.get_scan_result_n()?.0)
}
pub fn connect(
&mut self,
ssid: &str,
psk: &str,
auth: AuthMethod,
timeout: Duration,
) -> OsResult<()> {
if ssid.len() > 32 {
return Err(OsError::SsidTooLong);
}
if psk.len() > 64 {
return Err(OsError::PskTooLong);
}
self.driver
.set_configuration(&Configuration::Client(ClientConfiguration {
ssid: unsafe { ssid.try_into().unwrap_unchecked() },
password: unsafe { psk.try_into().unwrap_unchecked() },
auth_method: auth,
..Default::default()
}))?;
os_debug!("Starting connection to AP");
self.driver.connect().map_err(OsError::WifiConnect)?;
os_debug!("Waiting for connection result");
// wait until connected
self.await_event::<WifiEvent, _, _>(
|| self.driver.is_connected(),
OsError::WifiConnect,
timeout,
)?;
if STATIC_IP_CONFIG.is_some() {
os_debug!("Static IP configuration detected, skipping wait for IP address");
return Ok(());
}
os_debug!("Waiting for IP address");
// wait until we get an IP
self.await_event::<IpEvent, _, _>(|| self.driver.is_up(), OsError::WifiConnect, timeout)?;
Ok(())
}
fn await_event<S, F, U>(&self, matcher: F, err_map: U, timeout: Duration) -> OsResult<()>
where
S: EspEventSource,
F: Fn() -> Result<bool, EspError>,
U: Fn(EspError) -> OsError,
{
let wait = Wait::new::<S>(&self.event_loop)?;
wait.wait_while(|| matcher().map(|s| !s), Some(timeout))
.map_err(err_map)
}
#[cfg(debug_assertions)]
pub fn get_ip_info(&self) -> OsResult<esp_idf_svc::ipv4::IpInfo> {
Ok(self.driver.sta_netif().get_ip_info()?)
}
pub fn get_mac(&self) -> OsResult<Mac> {
let raw = self.driver.get_mac(WifiDeviceId::Sta)?;
Ok(Mac::new(raw[0], raw[1], raw[2], raw[3], raw[4], raw[5]))
}
fn connected(&self) -> bool {
self.driver.is_connected().unwrap_or(false)
}
fn generate_dhcp_config(wifi_driver: &WifiDriver) -> NetifConfiguration {
NetifConfiguration {
ip_configuration: Some(IpConfiguration::Client(IpClientConfiguration::DHCP(
DHCPClientSettings {
hostname: Some(Self::generate_hostname(wifi_driver)),
},
))),
..NetifConfiguration::wifi_default_client()
}
}
fn generate_static_ip_config() -> NetifConfiguration {
NetifConfiguration {
ip_configuration: Some(IpConfiguration::Client(IpClientConfiguration::Fixed(
unsafe { STATIC_IP_CONFIG.unwrap_unchecked() },
))),
..NetifConfiguration::wifi_default_client()
}
}
fn generate_hostname(wifi_driver: &WifiDriver) -> heapless::String<30> {
let mut buffer = heapless::String::new();
let last_two_bytes = &wifi_driver.get_mac(WifiDeviceId::Sta).unwrap_or_default()[4..6];
// SAFETY: This is less than 30 characters, so it will always fit.
unsafe {
buffer.push_str("pixelweather-node-").unwrap_unchecked(); // 18 chars
buffer
.push_str(&format!("{last_two_bytes:02X?}"))
.unwrap_unchecked(); // max 4 characters
}
buffer
}
}
impl Drop for WiFi {
fn drop(&mut self) {
os_debug!("Deinitializing WiFi");
if self.connected() {
self.driver.disconnect().report("Failed to disconnect");
}
self.driver.stop().report("Failed to disable");
}
}