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.
This commit is contained in:
bunnie 2022-09-20 19:36:55 +08:00
parent ec8a16f3d7
commit 035bdaf986
8 changed files with 179 additions and 27 deletions

View file

@ -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<xous::Result, xous::Error> { pub fn wlan_set_on(&mut self) -> Result<xous::Result, xous::Error> {
send_message( send_message(
self.conn, 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. /// 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 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. /// this information making the status check lighter-weight overall.
pub fn wlan_status(&mut self) -> Result<WlanStatus, xous::Error> { pub fn wlan_status(&self) -> Result<WlanStatus, xous::Error> {
let status = WlanStatusIpc::default(); let status = WlanStatusIpc::default();
let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?; 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))?; 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) Err(xous::Error::InternalError)
} }
} }
pub fn wlan_is_reset_hold(&self) -> Result<bool, xous::Error> {
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]) { pub fn ints_enable(&self, int_list: &[ComIntSources]) {
let mut mask_val: u16 = 0; let mut mask_val: u16 = 0;

View file

@ -891,11 +891,37 @@ fn main() -> ! {
buffer.replace(ssid_ret).unwrap(); buffer.replace(ssid_ret).unwrap();
} }
Some(Opcode::WlanOn) => { Some(Opcode::WlanOn) => {
info!("TODO: implement WlanOn");
com.txrx(ComState::WLAN_ON.verb); 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) => { Some(Opcode::WlanOff) => {
info!("TODO: implement WlanOff");
com.txrx(ComState::WLAN_OFF.verb); com.txrx(ComState::WLAN_OFF.verb);
} }
Some(Opcode::WlanRssi) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(Opcode::WlanRssi) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {

View file

@ -24,6 +24,8 @@ pub(crate) enum ConnectionManagerOpcode {
Run, Run,
Poll, Poll,
Stop, Stop,
DisconnectAndStop,
WifiOnAndRun,
SubscribeWifiStats, SubscribeWifiStats,
UnsubWifiStats, UnsubWifiStats,
FetchSsidList, FetchSsidList,
@ -48,6 +50,7 @@ enum WifiState {
InvalidAuth, InvalidAuth,
Connected, Connected,
Disconnected, Disconnected,
Off,
Error Error
} }
#[derive(Eq, PartialEq)] #[derive(Eq, PartialEq)]
@ -191,6 +194,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
} }
wifi_state = WifiState::Error; wifi_state = WifiState::Error;
} }
LinkState::ResetHold => {
// wifi was manually forced "off", leave it off; presume connection manager is also stopped.
wifi_state = WifiState::Off;
}
_ => { // should approximately be a "disconnected" state. _ => { // should approximately be a "disconnected" state.
match wifi_state { match wifi_state {
WifiState::Connected => { WifiState::Connected => {
@ -239,10 +246,14 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
} }
ComIntSources::Disconnect => { ComIntSources::Disconnect => {
log::info!("{:?}", source); log::info!("{:?}", source);
ssid_list.clear(); // clear the ssid list because a likely cause of disconnect is we've moved out of range if wifi_state != WifiState::Off {
com.set_ssid_scanning(true).unwrap(); ssid_list.clear(); // clear the ssid list because a likely cause of disconnect is we've moved out of range
scan_state = SsidScanState::Scanning; com.set_ssid_scanning(true).unwrap();
wifi_state = WifiState::Disconnected; scan_state = SsidScanState::Scanning;
wifi_state = WifiState::Disconnected;
} else {
log::info!("Wifi intent is off. Ignoring disconnect interrupt.");
}
}, },
ComIntSources::WlanSsidScanUpdate => { ComIntSources::WlanSsidScanUpdate => {
log::info!("{:?}", source); log::info!("{:?}", source);
@ -273,18 +284,22 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
activity_interval.store(0, Ordering::SeqCst); activity_interval.store(0, Ordering::SeqCst);
// this is the "first" path -- it's hit immediately on connect. // this is the "first" path -- it's hit immediately on connect.
// relay status updates to any subscribers that want to know if a state has changed // relay status updates to any subscribers that want to know if a state has changed
wifi_stats_cache = com.wlan_status().unwrap(); if wifi_state != WifiState::Off {
log::debug!("stats update: {:?}", wifi_stats_cache); wifi_stats_cache = com.wlan_status().unwrap();
for &sub in status_subscribers.keys() { log::debug!("stats update: {:?}", wifi_stats_cache);
let buf = Buffer::into_buf(com::WlanStatusIpc::from_status(wifi_stats_cache)).or(Err(xous::Error::InternalError)).unwrap(); for &sub in status_subscribers.keys() {
buf.send(sub, WifiStateCallback::Update.to_u32().unwrap()).or(Err(xous::Error::InternalError)).unwrap(); 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 wifi_stats_cache.ipv4.dhcp == com_rs_ref::DhcpState::Bound { }
wifi_state = WifiState::Connected; if wifi_stats_cache.ipv4.dhcp == com_rs_ref::DhcpState::Bound {
wifi_state = WifiState::Connected;
} else {
wifi_state = WifiState::WaitDhcp;
}
log::debug!("comint new wifi state: {:?}", wifi_state);
} else { } else {
wifi_state = WifiState::WaitDhcp; log::info!("Wifi intent is off, skipping wlan status query update.");
} }
log::debug!("comint new wifi state: {:?}", wifi_state);
} }
ComIntSources::WfxErr => { ComIntSources::WfxErr => {
log::info!("{:?}", source); log::info!("{:?}", source);
@ -392,6 +407,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
buf.send(sub, WifiStateCallback::Update.to_u32().unwrap()).or(Err(xous::Error::InternalError)).unwrap(); buf.send(sub, WifiStateCallback::Update.to_u32().unwrap()).or(Err(xous::Error::InternalError)).unwrap();
} }
} }
WifiState::Off => {
// 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<AtomicU3
Some(ConnectionManagerOpcode::Stop) => msg_scalar_unpack!(msg, _, _, _, _, { Some(ConnectionManagerOpcode::Stop) => msg_scalar_unpack!(msg, _, _, _, _, {
run.store(false, Ordering::SeqCst); 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, _, _, _, _, { 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. // 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) // (e.g. an update)

View file

@ -170,6 +170,16 @@ impl NetManager {
Message::new_scalar(Opcode::ConnMgrStartStop.to_usize().unwrap(), 1, 0,0, 0) Message::new_scalar(Opcode::ConnMgrStartStop.to_usize().unwrap(), 1, 0,0, 0)
).map(|_| ()) ).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 { impl Drop for NetManager {
fn drop(&mut self) { fn drop(&mut self) {

View file

@ -2118,6 +2118,34 @@ fn main() -> ! {
), ),
) )
.expect("couldn't send stop message"); .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 { } else {
log::error!("Got incorrect start/stop code: {}", code); log::error!("Got incorrect start/stop code: {}", code);
} }

View file

@ -65,6 +65,12 @@
"zh": "没有连接", "zh": "没有连接",
"en-tts": "Not connected" "en-tts": "Not connected"
}, },
"stats.wifi_off": {
"ja": "WiFiオフ",
"en": "WiFi off",
"zh": "WiFi关闭",
"en-tts": "WiFi off"
},
"stats.uptime": { "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.", "translator-note": "This needs to be a very short string, 2 chars max. Trailing space is necessary for English due to proportional font.",
"ja": "稼働", "ja": "稼働",

View file

@ -733,11 +733,19 @@ fn wrapped_main() -> ! {
ssid.rssi, ssid.rssi,
).unwrap(); ).unwrap();
} else { } else {
write!( if wifi_status.link_state == com_rs_ref::LinkState::ResetHold {
&mut battstats_tv, write!(
"{}", &mut battstats_tv,
t!("stats.disconnected", xous::LANG) "{}",
).unwrap(); t!("stats.wifi_off", xous::LANG)
).unwrap();
} else {
write!(
&mut battstats_tv,
"{}",
t!("stats.disconnected", xous::LANG)
).unwrap();
}
} }
} }
} }

View file

@ -105,13 +105,11 @@ impl WLANMan {
match state { match state {
true => { true => {
// on // on
self.com.wlan_set_on()?; self.netmgr.connection_manager_wifi_on_and_run()?;
self.netmgr.connection_manager_run()?;
} }
false => { false => {
// off // off
self.netmgr.connection_manager_stop()?; self.netmgr.connection_manager_wifi_off_and_stop()?;
self.com.wlan_set_off()?;
} }
}; };