From 0b32ac073ba67e7dc1fa36ec6be4022055516047 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 29 May 2023 02:12:28 +0800 Subject: [PATCH] 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. --- Cargo.lock | 14 ---- Cargo.toml | 4 +- services/net/src/api.rs | 10 +++ services/net/src/connection_manager.rs | 89 +++++++++++++++++++------- services/net/src/lib.rs | 4 +- services/shellchat/src/cmds/ssid.rs | 3 +- services/shellchat/src/cmds/test.rs | 2 +- services/status/locales/i18n.json | 14 ++++ services/status/src/preferences.rs | 4 +- services/status/src/wifi.rs | 52 +++++++++++++-- 10 files changed, 145 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index df4582118..ea15fe779 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 9bdc45913..fd7d28780 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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", diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 4419fd1d8..f37f9cf9c 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -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. Thanks, Rust! 32 APs should be enough for anyone, right?... pub(crate) list: [Option; 32], + pub(crate) state: ScanState, } /// These opcodes are reserved for private SIDs shared from a DNS server to diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index 5041955df..059133993 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -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) { @@ -232,7 +236,6 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { - 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 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 { - 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 { + 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 'Not connected' @@ -545,7 +586,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc Result, xous::Error> { + pub fn wifi_get_ssid_list(&self) -> Result<(Vec::, 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(), diff --git a/services/shellchat/src/cmds/ssid.rs b/services/shellchat/src/cmds/ssid.rs index 0a1e5be9f..501e32159 100644 --- a/services/shellchat/src/cmds/ssid.rs +++ b/services/shellchat/src/cmds/ssid.rs @@ -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(); diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index b7bf30d7c..7f00cf7a2 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -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 { diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index c04b9f66c..77a3768c6 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -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", diff --git a/services/status/src/preferences.rs b/services/status/src/preferences.rs index 22dd36aac..17b9fc7e3 100644 --- a/services/status/src/preferences.rs +++ b/services/status/src/preferences.rs @@ -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 } }; diff --git a/services/status/src/wifi.rs b/services/status/src/wifi.rs index 8c12f010f..e569498a9 100644 --- a/services/status/src/wifi.rs +++ b/services/status/src/wifi.rs @@ -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, WLANError> { - let scan_result = self.netmgr.wifi_get_ssid_list()?; + fn scan_networks(&self) -> Result<(Vec, 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; + 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() {