make wlan status checks asynchronous

the synchronous method would lead to stutter in the animation
of the status bar during netork congestion.
This commit is contained in:
bunnie 2022-01-23 00:24:45 +08:00
parent 0cafd10e28
commit 94a8a4736f
5 changed files with 167 additions and 55 deletions

View file

@ -12,12 +12,6 @@ use std::fmt;
use std::fmt::Debug;
use std::io::Write;
#[allow(dead_code)]
pub(crate) const BOOT_POLL_INTERVAL_MS: usize = 5_758; // a slightly faster poll during boot so we acquire wifi faster once PDDB is mounted
/// this is shared externally so other functions (e.g. in status bar) that want to query the net manager know how long to back off, otherwise the status query will block
#[allow(dead_code)]
pub const POLL_INTERVAL_MS: usize = 20_151; // stagger slightly off of an integer-seconds interval to even out loads
// republish this so we can decode the icmpv4 error codes
pub use smoltcp::wire::Icmpv4DstUnreachable;
@ -58,7 +52,8 @@ pub(crate) enum Opcode {
/// Link Management,
GetIpv4Config,
Reset,
GetWifiStats,
SubscribeWifiStats,
UnsubWifiStats,
/// [Internal] com llio interrupt callback
ComInterrupt,
@ -91,6 +86,17 @@ pub(crate) enum PrivateDnsOp {
Quit,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum WifiStateCallback {
Update,
Drop,
}
#[derive(Debug, Archive, Serialize, Deserialize, Copy, Clone)]
pub(crate) struct WifiStateSubscription {
pub sid: [u32; 4],
pub opcode: u32,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum NetCallback {
Ping,

View file

@ -7,13 +7,21 @@ use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message}
use xous_ipc::Buffer;
use num_traits::*;
use std::io::Read;
use std::collections::HashMap;
#[allow(dead_code)]
const BOOT_POLL_INTERVAL_MS: usize = 5_758; // a slightly faster poll during boot so we acquire wifi faster once PDDB is mounted
/// this is shared externally so other functions (e.g. in status bar) that want to query the net manager know how long to back off, otherwise the status query will block
#[allow(dead_code)]
const POLL_INTERVAL_MS: usize = 20_151; // stagger slightly off of an integer-seconds interval to even out loads
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum ConnectionManagerOpcode {
Run,
Poll,
Stop,
WifiStatus,
SubscribeWifiStats,
UnsubWifiStats,
Quit,
}
@ -40,9 +48,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
let mut mounted = false;
let mut current_interval = BOOT_POLL_INTERVAL_MS;
let mut wifi_stats_cache: WlanStatus = WlanStatus::from_ipc(WlanStatusIpc::default());
let mut status_subscribers = HashMap::<xous::CID, WifiStateSubscription>::new();
send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), current_interval, 0, 0, 0)).expect("couldn't kick off next poll");
loop {
let mut msg = xous::receive_message(sid).unwrap();
let msg = xous::receive_message(sid).unwrap();
log::debug!("got msg: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(ConnectionManagerOpcode::Run) => msg_scalar_unpack!(msg, _, _, _, _, {
@ -58,7 +67,17 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
if pddb.is_mounted() && rev_ok {
mounted = true;
// the status check code is going to get refactored, so this is a "bare minimum" check
wifi_stats_cache = com.wlan_status().unwrap();
let new_state = com.wlan_status().unwrap();
if wifi_stats_cache.link_state != new_state.link_state ||
wifi_stats_cache.ssid.unwrap_or(com::SsidRecord::default()).name != new_state.ssid.unwrap_or(com::SsidRecord::default()).name ||
wifi_stats_cache.ssid.unwrap_or(com::SsidRecord::default()).rssi != new_state.ssid.unwrap_or(com::SsidRecord::default()).rssi
{
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();
}
}
wifi_stats_cache = new_state;
let config = netmgr.get_ipv4_config();
if wifi_stats_cache.link_state == com_rs_ref::LinkState::WFXError {
com.wlan_leave().expect("couldn't issue leave command"); // this may not be received by the wf200, *but* it will also re-init the DHCP stack on the EC
@ -104,6 +123,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
break;
}
}
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();
}
} else {
log::warn!("Connection manager couldn't access {}, but continuing to poll.", AP_DICT_NAME);
}
@ -123,12 +146,29 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
send_message(self_cid, Message::new_scalar(ConnectionManagerOpcode::Poll.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't kick off next poll");
}
}),
Some(ConnectionManagerOpcode::WifiStatus) => {
let mut buffer = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
Some(ConnectionManagerOpcode::SubscribeWifiStats) => {
let buffer = unsafe {
Buffer::from_memory_message(msg.body.memory_message().unwrap())
};
buffer.replace(com::WlanStatusIpc::from_status(wifi_stats_cache)).unwrap();
let sub = buffer.to_original::<WifiStateSubscription, _>().unwrap();
let sub_cid = xous::connect(xous::SID::from_array(sub.sid)).expect("couldn't connect to wifi subscriber callback");
status_subscribers.insert(sub_cid, sub);
},
Some(ConnectionManagerOpcode::UnsubWifiStats) => msg_blocking_scalar_unpack!(msg, s0, s1, s2, s3, {
// note: this routine largely untested, could have some errors around the ordering of the blocking return vs the disconnect call.
let sid = [s0 as u32, s1 as u32, s2 as u32, s3 as u32];
let mut valid_sid: Option<xous::CID> = None;
for (&cid, &sub) in status_subscribers.iter() {
if sub.sid == sid {
valid_sid = Some(cid)
}
}
xous::return_scalar(msg.sender, 1).expect("couldn't ack unsub");
if let Some(cid) = valid_sid {
status_subscribers.remove(&cid);
unsafe{xous::disconnect(cid).expect("couldn't remove wifi status subscriber from our CID list that is limited to 32 items total. Suspect issue with ordering of disconnect vs blocking return...");}
}
}),
// stop is blocking because we need to ensure the previous poll has finished before moving on, otherwise,
// we could get a double-run condition
Some(ConnectionManagerOpcode::Stop) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {

View file

@ -48,11 +48,15 @@ impl Drop for NetConn {
pub struct NetManager {
netconn: NetConn,
wifi_state_cid: Option<CID>,
wifi_state_sid: Option<xous::SID>,
}
impl NetManager {
pub fn new() -> NetManager {
NetManager {
netconn: NetConn::new(&xous_names::XousNames::new().unwrap()).expect("can't connect to Net Server"),
wifi_state_cid: None,
wifi_state_sid: None,
}
}
pub fn get_ipv4_config(&self) -> Option<Ipv4Conf> {
@ -76,11 +80,75 @@ impl NetManager {
/// This is the function that the system should be using to check the wifi state -- it will read
/// the cached value from the connection manager. The direct call to the COM could cause too much
/// congestion.
pub fn read_wifi_state(&self) -> Result<com::WlanStatus, xous::Error> {
let status = com::WlanStatusIpc::default();
let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.netconn.conn(), Opcode::GetWifiStats.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let response = buf.to_original::<com::WlanStatusIpc, _>().unwrap();
Ok(com::WlanStatus::from_ipc(response))
pub fn wifi_state_subscribe(&mut self, return_cid: CID, opcode: u32) -> Result<(), xous::Error> {
if self.wifi_state_cid.is_none() {
let onetime_sid = xous::create_server().unwrap();
let sub = WifiStateSubscription {
sid: onetime_sid.to_array(),
opcode
};
let buf = Buffer::into_buf(sub).or(Err(xous::Error::InternalError))?;
buf.send(self.netconn.conn(), Opcode::SubscribeWifiStats.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
self.wifi_state_cid = Some(xous::connect(onetime_sid).unwrap());
self.wifi_state_sid = Some(onetime_sid);
let _ = std::thread::spawn({
let onetime_sid = onetime_sid.clone();
let opcode = opcode.clone();
move || {
loop {
let msg = xous::receive_message(onetime_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(WifiStateCallback::Update) => {
let buffer = unsafe {
Buffer::from_memory_message(msg.body.memory_message().unwrap())
};
log::debug!("got state_subscribe callback {} {}", return_cid, opcode);
// have to transform it through the local memory space because you can't re-lend pages
let sub = buffer.to_original::<com::WlanStatusIpc, _>().unwrap();
let buf = Buffer::into_buf(sub).expect("couldn't convert to memory message");
buf.lend(return_cid, opcode).expect("couldn't forward state update");
}
Some(WifiStateCallback::Drop) => {
xous::return_scalar(msg.sender, 1).unwrap();
break;
}
_ => {
log::error!("got unknown opcode: {:?}", msg);
}
}
}
log::info!("destroying callback server");
xous::destroy_server(onetime_sid).unwrap();
}
});
Ok(())
} else {
// you can only hook this once per object
Err(xous::Error::ServerExists)
}
}
}
/// If we're not already subscribed, returns without error.
pub fn wifi_state_unsubscribe(&mut self) -> Result<(), xous::Error> {
if let Some(handler) = self.wifi_state_cid.take() {
if let Some(sid) = self.wifi_state_sid.take() {
let s = sid.to_array();
send_message(self.netconn.conn(),
Message::new_blocking_scalar(Opcode::UnsubWifiStats.to_usize().unwrap(),
s[0] as usize,
s[1] as usize,
s[2] as usize,
s[3] as usize,
)
).expect("couldn't unsubscribe");
}
send_message(handler, Message::new_blocking_scalar(WifiStateCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).ok();
unsafe{xous::disconnect(handler).ok()};
}
Ok(())
}
}
impl Drop for NetManager {
fn drop(&mut self) {
self.wifi_state_unsubscribe().unwrap();
}
}

View file

@ -963,13 +963,27 @@ fn xmain() -> ! {
};
buffer.replace(ser).expect("couldn't return config");
},
Some(Opcode::GetWifiStats) => {
let mut buffer = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
Some(Opcode::SubscribeWifiStats) => {
let buffer = unsafe {
Buffer::from_memory_message(msg.body.memory_message().unwrap())
};
buffer.lend_mut(cm_cid, connection_manager::ConnectionManagerOpcode::WifiStatus.to_u32().unwrap()).expect("couldn't retrieve stats cache");
// no need to call replace, because it's already been mutated by the caller
// have to transform it through the local memory space because you can't re-lend pages
let sub = buffer.to_original::<WifiStateSubscription, _>().unwrap();
let buf = Buffer::into_buf(sub).expect("couldn't convert to memory message");
buf.send(cm_cid, connection_manager::ConnectionManagerOpcode::SubscribeWifiStats.to_u32().unwrap()).expect("couldn't forward subscription request");
},
Some(Opcode::UnsubWifiStats) => msg_blocking_scalar_unpack!(msg, s0, s1, s2, s3, {
// now do something with the unsubscription
let response = xous::send_message(cm_cid, Message::new_blocking_scalar(
connection_manager::ConnectionManagerOpcode::UnsubWifiStats.to_usize().unwrap(),
s0, s1, s2, s3
)).expect("couldn't send unsub message");
if let xous::Result::Scalar1(val) = response {
xous::return_scalar(msg.sender, val).unwrap();
} else {
xous::return_scalar(msg.sender, 0).unwrap();
}
}),
Some(Opcode::Reset) => {
net_config = None;
let neighbor_cache = NeighborCache::new(BTreeMap::new());

View file

@ -5,13 +5,9 @@ mod mainmenu;
use mainmenu::*;
use com::api::*;
use log::info;
use core::fmt::Write;
use num_traits::*;
use xous::{msg_scalar_unpack, send_message, Message, CID};
use graphics_server::*;
use graphics_server::api::GlyphStyle;
use locales::t;
@ -47,6 +43,8 @@ enum StatusOpcode {
SubmenuPddb,
/// Suspend handler from the main menu
TrySuspend,
/// for returning wifi stats
WifiStats,
Quit,
}
@ -134,7 +132,8 @@ fn xmain() -> ! {
.register_name(SERVER_NAME_STATUS, Some(0))
.expect("|status: can't register server");
// create a connection for callback hooks
unsafe { CB_TO_MAIN_CONN = Some(xous::connect(status_sid).unwrap()) };
let cb_cid = xous::connect(status_sid).unwrap();
unsafe { CB_TO_MAIN_CONN = Some(cb_cid) };
let pump_run = Arc::new(AtomicBool::new(true));
let pump_conn = xous::connect(status_sid).unwrap();
let _ = thread::spawn({
@ -148,7 +147,7 @@ fn xmain() -> ! {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
let mut com = com::Com::new(&xns).expect("|status: can't connect to COM");
let susres = susres::Susres::new_without_hook(&xns).unwrap();
let netmgr = net::NetManager::new();
let mut netmgr = net::NetManager::new();
let screensize = gam
.get_canvas_bounds(status_gid)
@ -207,19 +206,6 @@ fn xmain() -> ! {
remaining_capacity: 650,
};
/*
let style_dark = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1);
gam.draw_line(
status_gid,
Line::new_with_style(
Point::new(0, screensize.y),
Point::new(screensize.x, screensize.y),
style_dark,
),
)
.expect("|status: Can't draw border line");
*/
// the EC gets reset by the Net crate on boot to ensure that the state machines are synced up
// this takes a few seconds, so we have a dead-wait here. This is a good spot for it because
// the status bar reads "booting up..." during this period.
@ -313,16 +299,13 @@ fn xmain() -> ! {
let dt_pump_interval = 15;
let charger_pump_interval = 180;
let stats_interval;
let batt_interval;
let secnotes_interval;
if cfg!(feature = "braille") {
// lower the status output rate for braille mode, debugging, etc.
stats_interval = 30;
batt_interval = 60;
secnotes_interval = 30;
} else {
stats_interval = 4;
batt_interval = 4;
secnotes_interval = 4;
}
@ -342,9 +325,9 @@ fn xmain() -> ! {
t!("rtc.saturday", xous::LANG),
t!("rtc.sunday", xous::LANG),
];
netmgr.wifi_state_subscribe(cb_cid, StatusOpcode::WifiStats.to_u32().unwrap()).unwrap();
let mut wifi_status: WlanStatus = WlanStatus::from_ipc(WlanStatusIpc::default());
info!("|status: starting main loop"); // don't change this -- factory test looks for this exact string
log::info!("|status: starting main loop"); // don't change this -- factory test looks for this exact string
loop {
let msg = xous::receive_message(status_sid).unwrap();
log::trace!("|status: Message: {:?}", msg);
@ -378,6 +361,12 @@ fn xmain() -> ! {
.expect("|status: can't draw battery stats");
battstats_phase = !battstats_phase;
}),
Some(StatusOpcode::WifiStats) => {
let buffer = unsafe {
xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap())
};
wifi_status = WlanStatus::from_ipc(buffer.to_original::<com::WlanStatusIpc, _>().unwrap());
},
Some(StatusOpcode::Pump) => {
let elapsed_time = ticktimer.elapsed_ms();
let (is_locked, force_update) = llio.debug_usb(None).unwrap();
@ -430,11 +419,6 @@ fn xmain() -> ! {
com.req_batt_stats()
.expect("Can't get battery stats from COM");
}
if (stats_phase % stats_interval) == 2 {
if elapsed_time > net::POLL_INTERVAL_MS as u64 { // The EC has to come out of reset, etc before the net connection manager can unblock.
wifi_status = netmgr.read_wifi_state().expect("couldn't get wifi state");
}
}
if (stats_phase % charger_pump_interval) == 1 {
// stagger periodic tasks
// confirm that the charger is in the right state.