From 035bdaf98628674f435a0cd696abbc1669c992cb Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 20 Sep 2022 19:36:55 +0800 Subject: [PATCH] complete wifi on/off interface fully integrates wifi on and off commands. measured standby power when wifi is off is "immeasurable" (0 mA), so probably < 1-2mA. fix ui transitions so that the off request is respected, through sleep/resume cycles as well. --- services/com/src/lib.rs | 13 +++- services/com/src/main.rs | 30 +++++++- services/net/src/connection_manager.rs | 95 ++++++++++++++++++++++---- services/net/src/lib.rs | 10 +++ services/net/src/main.rs | 28 ++++++++ services/status/locales/i18n.json | 6 ++ services/status/src/main.rs | 18 +++-- services/status/src/wifi.rs | 6 +- 8 files changed, 179 insertions(+), 27 deletions(-) diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 951639c95..4a5aacda4 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -451,10 +451,11 @@ impl Com { } } + /// This blocks until the COM responds from initializing the Wifi chip pub fn wlan_set_on(&mut self) -> Result { send_message( self.conn, - Message::new_scalar(Opcode::WlanOn.to_usize().unwrap(), 0, 0, 0, 0), + Message::new_blocking_scalar(Opcode::WlanOn.to_usize().unwrap(), 0, 0, 0, 0), ) } @@ -505,7 +506,7 @@ impl Com { /// Note: applications should poll the `NetManager::read_wifi_state()` call for wifi status information, not the COM directly. /// This is because the `wlan_status` call is fairly heavy weight, and the `NetManager::read_wifi_state()` will cache /// this information making the status check lighter-weight overall. - pub fn wlan_status(&mut self) -> Result { + pub fn wlan_status(&self) -> Result { let status = WlanStatusIpc::default(); let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::WlanStatus.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; @@ -616,6 +617,14 @@ impl Com { Err(xous::Error::InternalError) } } + pub fn wlan_is_reset_hold(&self) -> Result { + let status = self.wlan_status()?; + if status.link_state == com_rs_ref::LinkState::ResetHold { + Ok(true) + } else { + Ok(false) + } + } pub fn ints_enable(&self, int_list: &[ComIntSources]) { let mut mask_val: u16 = 0; diff --git a/services/com/src/main.rs b/services/com/src/main.rs index c99662797..bd1245b04 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -891,11 +891,37 @@ fn main() -> ! { buffer.replace(ssid_ret).unwrap(); } Some(Opcode::WlanOn) => { - info!("TODO: implement WlanOn"); com.txrx(ComState::WLAN_ON.verb); + // re-sync the link, because the COM will take about a second to reload the Wifi drivers + #[cfg(not(any(windows, unix)))] // avoid errors in hosted mode + { + ticktimer.sleep_ms(100).unwrap(); // give the EC a moment to de-chatter + let mut attempts = 0; + let ping_value = 0xaeedu16; // for various reasons, this is a string that is "unlikely" to happen randomly + loop { + com.txrx(ComState::LINK_PING.verb); + com.txrx(ping_value); + let pong = com.wait_txrx(ComState::LINK_READ.verb, Some(150)); // this should "stall" until the EC comes out of reset + let phase = com.wait_txrx(ComState::LINK_READ.verb, Some(150)); + if pong == !ping_value && + phase == 0x600d { // 0x600d is a hard-coded constant. It's included to confirm that we aren't "wedged" just sending one value back at us + log::info!("Wifi on: link established"); + break; + } else { + log::info!("Wifi on: establishing link sync, attempt {} [{:04x}/{:04x}]", attempts, pong, phase); + com.txrx(ComState::LINK_SYNC.verb); + ticktimer.sleep_ms(200).unwrap(); + attempts += 1; + } + if attempts > 50 { + log::error!("EC didn't sync after wifi on...continuing and praying for the best."); + break; + } + } + } + xous::return_scalar(msg.sender, 1).ok(); } Some(Opcode::WlanOff) => { - info!("TODO: implement WlanOff"); com.txrx(ComState::WLAN_OFF.verb); } Some(Opcode::WlanRssi) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index cb345e77c..372225767 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -24,6 +24,8 @@ pub(crate) enum ConnectionManagerOpcode { Run, Poll, Stop, + DisconnectAndStop, + WifiOnAndRun, SubscribeWifiStats, UnsubWifiStats, FetchSsidList, @@ -48,6 +50,7 @@ enum WifiState { InvalidAuth, Connected, Disconnected, + Off, Error } #[derive(Eq, PartialEq)] @@ -191,6 +194,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { + // wifi was manually forced "off", leave it off; presume connection manager is also stopped. + wifi_state = WifiState::Off; + } _ => { // should approximately be a "disconnected" state. match wifi_state { WifiState::Connected => { @@ -239,10 +246,14 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { log::info!("{:?}", source); - ssid_list.clear(); // clear the ssid list because a likely cause of disconnect is we've moved out of range - com.set_ssid_scanning(true).unwrap(); - scan_state = SsidScanState::Scanning; - wifi_state = WifiState::Disconnected; + if wifi_state != WifiState::Off { + ssid_list.clear(); // clear the ssid list because a likely cause of disconnect is we've moved out of range + com.set_ssid_scanning(true).unwrap(); + scan_state = SsidScanState::Scanning; + wifi_state = WifiState::Disconnected; + } else { + log::info!("Wifi intent is off. Ignoring disconnect interrupt."); + } }, ComIntSources::WlanSsidScanUpdate => { log::info!("{:?}", source); @@ -273,18 +284,22 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { log::info!("{:?}", source); @@ -392,6 +407,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { + // this state should not be reachable + log::warn!("Wifi state was manually forced off; did you remember to turn it on before setting the connection manager to RUN?"); + } } } } @@ -467,6 +486,54 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc msg_scalar_unpack!(msg, _, _, _, _, { run.store(false, Ordering::SeqCst); }), + Some(ConnectionManagerOpcode::WifiOnAndRun) => msg_scalar_unpack!(msg, _, _, _, _, { + com.wlan_set_on().expect("couldn't turn on wifi"); + wifi_state = WifiState::Disconnected; + ssid_list.clear(); + com.set_ssid_scanning(true).unwrap(); + scan_state = SsidScanState::Scanning; + intervals_without_activity = 0; + scan_count = 0; + // this will force the UI to transition from 'WiFi Off' -> 'Not connected' + wifi_stats_cache = WlanStatus { + ssid: None, + link_state: com_rs_ref::LinkState::Disconnected, + ipv4: com::Ipv4Conf::default(), + }; + log::debug!("stats update: {:?}", wifi_stats_cache); + for &sub in status_subscribers.keys() { + let buf = Buffer::into_buf(com::WlanStatusIpc::from_status(wifi_stats_cache)).or(Err(xous::Error::InternalError)).unwrap(); + buf.send(sub, WifiStateCallback::Update.to_u32().unwrap()).or(Err(xous::Error::InternalError)).unwrap(); + } + if !run.swap(true, Ordering::SeqCst) { + if !pumping.load(Ordering::SeqCst) { // avoid having multiple pump messages being sent if a user tries to rapidly toggle the run/stop switch + send_message(run_cid, Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't kick off next poll"); + } + } + }), + Some(ConnectionManagerOpcode::DisconnectAndStop) => { + run.store(false, Ordering::SeqCst); + wifi_state = WifiState::Off; + com.wlan_leave().expect("couldn't issue leave command"); + ssid_list.clear(); + intervals_without_activity = 0; + scan_count = 0; + com.set_ssid_scanning(false).unwrap(); + scan_state = SsidScanState::Idle; + + 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"); + wifi_stats_cache = WlanStatus { + ssid: None, + link_state: com_rs_ref::LinkState::ResetHold, + ipv4: com::Ipv4Conf::default(), + }; + log::debug!("stats update: {:?}", wifi_stats_cache); + for &sub in status_subscribers.keys() { + let buf = Buffer::into_buf(com::WlanStatusIpc::from_status(wifi_stats_cache)).or(Err(xous::Error::InternalError)).unwrap(); + buf.send(sub, WifiStateCallback::Update.to_u32().unwrap()).or(Err(xous::Error::InternalError)).unwrap(); + } + } Some(ConnectionManagerOpcode::EcReset) => msg_scalar_unpack!(msg, _, _, _, _, { // this opcode is used by other processes to inform us that the net link was reset by something other than us. // (e.g. an update) diff --git a/services/net/src/lib.rs b/services/net/src/lib.rs index 142722c29..1acda17c1 100644 --- a/services/net/src/lib.rs +++ b/services/net/src/lib.rs @@ -170,6 +170,16 @@ impl NetManager { Message::new_scalar(Opcode::ConnMgrStartStop.to_usize().unwrap(), 1, 0,0, 0) ).map(|_| ()) } + pub fn connection_manager_wifi_off_and_stop(&self) -> Result<(), xous::Error> { + send_message(self.netconn.conn(), + Message::new_scalar(Opcode::ConnMgrStartStop.to_usize().unwrap(), 2, 0,0, 0) + ).map(|_| ()) + } + pub fn connection_manager_wifi_on_and_run(&self) -> Result<(), xous::Error> { + send_message(self.netconn.conn(), + Message::new_scalar(Opcode::ConnMgrStartStop.to_usize().unwrap(), 3, 0,0, 0) + ).map(|_| ()) + } } impl Drop for NetManager { fn drop(&mut self) { diff --git a/services/net/src/main.rs b/services/net/src/main.rs index d5a557c77..b772691c5 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -2118,6 +2118,34 @@ fn main() -> ! { ), ) .expect("couldn't send stop message"); + } else if code == 2 { + send_message( + cm_cid, + Message::new_scalar( + connection_manager::ConnectionManagerOpcode::DisconnectAndStop + .to_usize() + .unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't send disconnect and stop message"); + } else if code == 3 { + send_message( + cm_cid, + Message::new_scalar( + connection_manager::ConnectionManagerOpcode::WifiOnAndRun + .to_usize() + .unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't send disconnect and stop message"); } else { log::error!("Got incorrect start/stop code: {}", code); } diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 7083f8f3f..30c4b7c89 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -65,6 +65,12 @@ "zh": "没有连接", "en-tts": "Not connected" }, + "stats.wifi_off": { + "ja": "WiFiオフ", + "en": "WiFi off", + "zh": "WiFi关闭", + "en-tts": "WiFi off" + }, "stats.uptime": { "translator-note": "This needs to be a very short string, 2 chars max. Trailing space is necessary for English due to proportional font.", "ja": "稼働", diff --git a/services/status/src/main.rs b/services/status/src/main.rs index b5c681290..a0de16afe 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -733,11 +733,19 @@ fn wrapped_main() -> ! { ssid.rssi, ).unwrap(); } else { - write!( - &mut battstats_tv, - "{}", - t!("stats.disconnected", xous::LANG) - ).unwrap(); + if wifi_status.link_state == com_rs_ref::LinkState::ResetHold { + write!( + &mut battstats_tv, + "{}", + t!("stats.wifi_off", xous::LANG) + ).unwrap(); + } else { + write!( + &mut battstats_tv, + "{}", + t!("stats.disconnected", xous::LANG) + ).unwrap(); + } } } } diff --git a/services/status/src/wifi.rs b/services/status/src/wifi.rs index 0f0458b24..fa5d6fc0b 100644 --- a/services/status/src/wifi.rs +++ b/services/status/src/wifi.rs @@ -105,13 +105,11 @@ impl WLANMan { match state { true => { // on - self.com.wlan_set_on()?; - self.netmgr.connection_manager_run()?; + self.netmgr.connection_manager_wifi_on_and_run()?; } false => { // off - self.netmgr.connection_manager_stop()?; - self.com.wlan_set_off()?; + self.netmgr.connection_manager_wifi_off_and_stop()?; } };