add scan state information to ssid scans

ssid scans can now be in-progress, and they also record
the time elapsed since the last scan was performed.

this allows the network manager to be a bit smarter about when
it decides to kick off a scan.

the ssid scan dialog box is also updated to show
the scan results in progress. This addresses #336.
This commit is contained in:
bunnie 2023-05-29 02:12:28 +08:00
parent 86459b02c5
commit 0b32ac073b
10 changed files with 145 additions and 51 deletions

14
Cargo.lock generated
View file

@ -3855,13 +3855,6 @@ dependencies = [
"no-std-net",
]
[[package]]
name = "spawn"
version = "0.1.0"
dependencies = [
"xous 0.9.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "spin"
version = "0.5.2"
@ -4057,13 +4050,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "test-spawn"
version = "0.1.0"
dependencies = [
"xous 0.9.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "textwrap"
version = "0.11.0"

View file

@ -82,8 +82,8 @@ members = [
"services/libstd-test",
"services/ffi-test",
"services/tts",
"services/test-spawn",
"services/test-spawn/spawn",
#"services/test-spawn",
#"services/test-spawn/spawn",
"services/usb-test",
"services/usb-device-xous",
"tools/perflib",

View file

@ -369,12 +369,22 @@ pub(crate) enum Opcode {
#[allow(dead_code)]
pub(crate) const NONBLOCKING_FLAG:usize = 0x8000; // when set, modulates a Peek or Read to be nonblocking
#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone, Default)]
pub enum ScanState {
#[default]
Idle,
/// Scan is in progress
Updating,
/// Indicates that the wifi susbsystem is off
Off,
}
#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone, Default)]
pub(crate) struct SsidList {
/// IPC memory structures have to pre-allocate all their memory, but are always allocated in 4096-byte chunks.
/// We could allocate up to maybe 100+ return values, but then we'd have to write a default initializer that
/// covers a 64-length array. So, we limit at 32. <s>Thanks, Rust!</s> 32 APs should be enough for anyone, right?...
pub(crate) list: [Option<SsidRecord>; 32],
pub(crate) state: ScanState,
}
/// These opcodes are reserved for private SIDs shared from a DNS server to

View file

@ -10,6 +10,7 @@ use num_traits::*;
use std::io::Read;
use std::collections::{HashMap, HashSet};
use crate::ComIntSources;
use std::time::{Instant, Duration};
#[allow(dead_code)]
const BOOT_POLL_INTERVAL_MS: usize = 4_758; // a slightly faster poll during boot so we acquire wifi faster once PDDB is mounted
@ -18,6 +19,7 @@ const BOOT_POLL_INTERVAL_MS: usize = 4_758; // a slightly faster poll during boo
const POLL_INTERVAL_MS: usize = 7_151; // stagger slightly off of an integer-seconds interval to even out loads. impacts rssi update frequency.
const INTERVALS_BEFORE_RETRY: usize = 3; // how many poll intervals we'll wait before we give up and try a new AP
const SCAN_COUNT_MAX: usize = 5;
const SSID_SCAN_AGING_THRESHOLD: Duration = Duration::from_secs(10); // time before a scan is considered "stale" and needs to be redone
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum ConnectionManagerOpcode {
@ -56,8 +58,10 @@ enum WifiState {
}
#[derive(Eq, PartialEq)]
enum SsidScanState {
Idle,
/// Records the time when the last scan had finished, so we can judge if the scan cache is stale, and/or rate-limit scan requests.
Idle(Instant),
Scanning,
Invalid,
}
pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU32>) {
@ -232,7 +236,6 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
log::info!("{:?}", source);
wifi_state = match ConnectResult::decode_u16(raw_arg as u16) {
ConnectResult::Success => {
scan_state = SsidScanState::Idle;
activity_interval.store(0, Ordering::SeqCst);
WifiState::WaitDhcp
},
@ -278,7 +281,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
},
_ => continue,
}
scan_state = SsidScanState::Idle;
scan_state = SsidScanState::Idle(Instant::now());
}
ComIntSources::WlanIpConfigUpdate => {
log::info!("{:?}", source);
@ -353,28 +356,37 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
}
match wifi_state {
WifiState::Unknown | WifiState::Disconnected | WifiState::InvalidAp | WifiState::InvalidAuth => {
if (scan_state == SsidScanState::Idle) || scan_count > SCAN_COUNT_MAX {
scan_count = 0;
// wait until we're done scanning before trying to connect
if let Some(ssid) = get_next_ssid(&mut ssid_list, &mut ssid_attempted, ap_list) {
let mut wpa_pw_file = pddb.get(AP_DICT_NAME, &ssid, None, false, false, None, Some(||{})).expect("couldn't retrieve AP password");
let mut wp_pw_raw = [0u8; com::api::WF200_PASS_MAX_LEN];
if let Ok(readlen) = wpa_pw_file.read(&mut wp_pw_raw) {
let pw = std::str::from_utf8(&wp_pw_raw[..readlen]).expect("password was not valid utf-8");
log::info!("Attempting wifi connection: {}", ssid);
com.wlan_set_ssid(&ssid).expect("couldn't set SSID");
com.wlan_set_pass(pw).expect("couldn't set password");
com.wlan_join().expect("couldn't issue join command");
wifi_state = WifiState::Connecting;
}
} else {
// no SSIDs available, scan again
log::info!("No SSIDs found, restarting SSID scan...");
if scan_count > SCAN_COUNT_MAX {
scan_state = SsidScanState::Idle(Instant::now());
log::warn!("scan timed out, forcing scan state to idle!");
}
match scan_state {
SsidScanState::Scanning => scan_count += 1,
SsidScanState::Invalid => {
scan_count = 0;
com.set_ssid_scanning(true).unwrap();
scan_state = SsidScanState::Scanning;
},
SsidScanState::Idle(_last_scan_time) => {
scan_count = 0;
if let Some(ssid) = get_next_ssid(&mut ssid_list, &mut ssid_attempted, ap_list) {
let mut wpa_pw_file = pddb.get(AP_DICT_NAME, &ssid, None, false, false, None, Some(||{})).expect("couldn't retrieve AP password");
let mut wp_pw_raw = [0u8; com::api::WF200_PASS_MAX_LEN];
if let Ok(readlen) = wpa_pw_file.read(&mut wp_pw_raw) {
let pw = std::str::from_utf8(&wp_pw_raw[..readlen]).expect("password was not valid utf-8");
log::info!("Attempting wifi connection: {}", ssid);
com.wlan_set_ssid(&ssid).expect("couldn't set SSID");
com.wlan_set_pass(pw).expect("couldn't set password");
com.wlan_join().expect("couldn't issue join command");
wifi_state = WifiState::Connecting;
}
} else {
// no SSIDs available, scan again
log::info!("No SSIDs found, restarting SSID scan...");
com.set_ssid_scanning(true).unwrap();
scan_state = SsidScanState::Scanning;
}
}
} else {
scan_count += 1;
}
}
WifiState::WaitDhcp | WifiState::Connecting => {
@ -475,6 +487,35 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
rssi: *rssi,
});
}
if wifi_state == WifiState::Off || wifi_state == WifiState::Error || wifi_state == WifiState::Unknown {
ret_list.state = ScanState::Off;
} else {
match scan_state {
SsidScanState::Idle(last_scan_time) => {
if last_scan_time.elapsed() > SSID_SCAN_AGING_THRESHOLD {
log::info!("scan out of date, restarting!");
com.set_ssid_scanning(true).unwrap();
scan_state = SsidScanState::Scanning;
scan_count = 0;
ret_list.state = ScanState::Updating;
} else {
log::info!("scan is {}s old", last_scan_time.elapsed().as_secs());
ret_list.state = ScanState::Idle;
}
},
SsidScanState::Invalid => {
log::info!("scan data is invalid, kicking off a new scan");
com.set_ssid_scanning(true).unwrap();
scan_state = SsidScanState::Scanning;
scan_count = 0;
ret_list.state = ScanState::Updating;
}
SsidScanState::Scanning => {
log::info!("still scanning...");
ret_list.state = ScanState::Updating
},
}
}
buffer.replace(ret_list).expect("couldn't return config");
},
Some(ConnectionManagerOpcode::Run) => msg_scalar_unpack!(msg, _, _, _, _, {
@ -517,7 +558,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
wifi_state = WifiState::Disconnected;
ssid_list.clear();
com.set_ssid_scanning(false).unwrap();
scan_state = SsidScanState::Idle;
scan_state = SsidScanState::Invalid;
intervals_without_activity = 0;
scan_count = 0;
// this will force the UI to transition from 'WiFi Off' -> 'Not connected'
@ -545,7 +586,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
intervals_without_activity = 0;
scan_count = 0;
com.set_ssid_scanning(false).unwrap();
scan_state = SsidScanState::Idle;
scan_state = SsidScanState::Invalid;
tt.sleep_ms(250).unwrap(); // give a moment to clean-up after leave before turning things off
com.wlan_set_off().expect("couldn't turn off wifi");

View file

@ -147,7 +147,7 @@ impl NetManager {
}
Ok(())
}
pub fn wifi_get_ssid_list(&self) -> Result<Vec::<SsidRecord>, xous::Error> {
pub fn wifi_get_ssid_list(&self) -> Result<(Vec::<SsidRecord>, ScanState), xous::Error> {
let alloc = SsidList::default();
let mut buf = Buffer::into_buf(alloc).map_err(|_| xous::Error::InternalError)?;
buf.lend_mut(self.netconn.conn(), Opcode::FetchSsidList.to_u32().unwrap())?;
@ -158,7 +158,7 @@ impl NetManager {
ret.push(*item);
}
}
Ok(ret)
Ok((ret, ssid_list.state))
}
pub fn connection_manager_stop(&self) -> Result<(), xous::Error> {
send_message(self.netconn.conn(),

View file

@ -37,13 +37,14 @@ impl<'a> ShellCmdApi<'a> for Ssid {
}
"scan" => {
// SSID scanning is automatically initiated by the connection manager, so we don't initiate it explicitly, just report results
let ssid_list = env.netmgr.wifi_get_ssid_list().unwrap();
let (ssid_list, state) = env.netmgr.wifi_get_ssid_list().unwrap();
write!(ret, "RSSI reported in dBm:\n").unwrap();
for ssid in ssid_list {
if ssid.name.len() > 0 {
write!(ret, "-{} {}\n", ssid.rssi, &ssid.name.as_str().unwrap_or("UTF-8 error")).unwrap();
}
}
write!(ret, "Scan state: {:?}\n", state).unwrap();
}
_ => {
write!(ret, "{}", helpstring).unwrap();

View file

@ -487,7 +487,7 @@ impl<'a> ShellCmdApi<'a> for Test {
match oqc_status(oqc_cid) {
Some(true) => {
log::info!("wrapping up: fetching SSID list");
let ssid_list = env.netmgr.wifi_get_ssid_list().unwrap();
let (ssid_list, _state) = env.netmgr.wifi_get_ssid_list().unwrap();
write!(ret, "RSSI reported in dBm:\n").unwrap();
for ssid in ssid_list {
if ssid.name.len() > 0 {

View file

@ -805,6 +805,20 @@
"ja": "{ssid} のパスワードを入力してください:",
"zh": "请输入 {ssid} 的密码:"
},
"wlan.ssid_scanning": {
"en": "Please wait, scanning...",
"en-tts": "Please wait, scanning...",
"fr": "Veuillez patienter, recherche de réseaux... *MT*",
"ja": "スキャン中です。お待ちください...",
"zh": "请稍候,正在扫描..."
},
"wlan.ssid_off_error": {
"en": "WiFi is off!",
"en-tts": "WiFi is off!",
"fr": "Le WiFi est désactivé! *MT*",
"ja": "Wi-Fiがオフになっています!",
"zh": "WiFi 已关闭!"
},
"wlan.status": {
"en": "Network status",
"en-tts": "Network status",

View file

@ -121,7 +121,7 @@ impl PrefHandler for DevicePrefs {
true
}
_ => {
log::error!("Got unknown message");
log::error!("Got unknown message: {}", op);
false
}
} {
@ -135,7 +135,7 @@ impl PrefHandler for DevicePrefs {
true
}
_ => {
log::error!("Got unknown message");
log::error!("Got unknown message: {}", op);
false
}
};

View file

@ -1,6 +1,7 @@
use crate::preferences::PrefHandler;
use core::fmt::Display;
use locales::t;
use net::ScanState;
use num_traits::*;
use std::io::Write;
@ -212,17 +213,58 @@ impl WLANMan {
}
}
fn scan_networks(&self) -> Result<Vec<String>, WLANError> {
let scan_result = self.netmgr.wifi_get_ssid_list()?;
fn scan_networks(&self) -> Result<(Vec<String>, ScanState), WLANError> {
let (scan_result, state) = self.netmgr.wifi_get_ssid_list()?;
Ok(scan_result
Ok((scan_result
.iter()
.map(|ssid| ssid.name.to_string())
.collect())
.collect(),
state
)
)
}
fn show_available_networks(&mut self) -> Result<(), WLANError> {
let networks = self.scan_networks()?;
let mut networks: Vec<String>;
let mut state: ScanState;
let tt = ticktimer_server::Ticktimer::new().unwrap();
let mut showing_wait = false;
loop {
(networks, state) = self.scan_networks()?;
// note to self: if we wanted to "scan more", probably this is the place
// where we would want to insert multiple calls to scan_networks() and
// accumulate the results.
match state {
ScanState::Updating => {
let mut progress = t!("wlan.ssid_scanning", xous::LANG).to_string();
let networks: Vec<&str> = networks.iter().map(|s| s.as_str()).collect();
progress.push_str("\n\n");
for network in networks {
progress.push_str(&format!("\t{}\n", network));
}
if !showing_wait {
self.modals.dynamic_notification(Some(&progress), None).unwrap();
showing_wait = true;
} else {
self.modals.dynamic_notification_update(Some(&progress), None).unwrap();
};
tt.sleep_ms(1000).ok();
},
ScanState::Idle => break,
ScanState::Off => {
if showing_wait {
self.modals.dynamic_notification_close().unwrap();
}
self.modals.show_notification(t!("wlan.ssid_off_error", xous::LANG), None).unwrap();
return Ok(());
}
}
}
if showing_wait {
self.modals.dynamic_notification_close().ok();
}
let mut networks: Vec<&str> = networks.iter().map(|s| s.as_str()).collect();
if networks.is_empty() {