refactor status bar to take advantage of the new fonts

This commit is contained in:
bunnie 2022-01-22 18:25:39 +08:00
parent 747891eaad
commit 0cafd10e28
12 changed files with 160 additions and 83 deletions

1
Cargo.lock generated
View file

@ -2229,6 +2229,7 @@ dependencies = [
"log",
"log-server",
"modals",
"net",
"num-derive",
"num-traits",
"pddb",

View file

@ -87,11 +87,21 @@ impl Default for SsidReturn {
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct WlanStatusIpc {
pub struct WlanStatusIpc {
pub ssid: Option<SsidRecord>,
pub link_state: u16, // this is slung around as a u16 to avoid pulling rkyv into the EC dependency tree
pub ipv4: [u16; com_rs_ref::ComState::WLAN_GET_IPV4_CONF.r_words as usize],
}
impl WlanStatusIpc {
#[allow(dead_code)]
pub fn from_status(status: WlanStatus) -> Self {
WlanStatusIpc {
ssid: status.ssid,
link_state: status.link_state as u16,
ipv4: status.ipv4.encode_u16(),
}
}
}
impl Default for WlanStatusIpc {
fn default() -> Self {
WlanStatusIpc {
@ -109,7 +119,7 @@ pub struct WlanStatus {
}
impl WlanStatus {
#[allow(dead_code)]
pub(crate) fn from_ipc(status: WlanStatusIpc) -> Self {
pub fn from_ipc(status: WlanStatusIpc) -> Self {
WlanStatus {
ssid: status.ssid,
link_state: com_rs_ref::LinkState::decode_u16(status.link_state),

View file

@ -449,7 +449,9 @@ impl Com {
Message::new_scalar(Opcode::WlanLeave.to_usize().unwrap(), 0, 0, 0, 0),
)
}
/// 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<WlanStatus, xous::Error> {
let status = WlanStatusIpc::default();
let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?;

View file

@ -550,15 +550,9 @@ fn xmain() -> ! {
let mut canvases: HashMap<Gid, Canvas> = HashMap::new();
let screensize = gfx.screen_size().expect("Couldn't get screen size");
let small_height: i16 = if xous::LANG != "zh" {
gfx.glyph_height_hint(GlyphStyle::Small).expect("couldn't get glyph height") as i16
} else {
gfx.glyph_height_hint(GlyphStyle::Regular).expect("couldn't get glyph height") as i16
};
// the status canvas is special -- there can only be one, and it is ultimately trusted
let status_canvas = Canvas::new(
Rectangle::new_coords(0, 0, screensize.x, small_height * 2),
Rectangle::new_coords(0, 0, screensize.x, gfx.glyph_height_hint(GlyphStyle::Regular).expect("couldn't get glyph height") as i16 * 2),
255, &trng, None
).expect("couldn't create status canvas");
canvases.insert(status_canvas.gid(), status_canvas);

View file

@ -177,6 +177,12 @@ impl Rectangle {
pub fn y1(&self) -> u32 {
self.br.y as u32
}
pub fn width(&self) -> u32 {
(self.br.x - self.tl.x) as u32
}
pub fn height(&self) -> u32 {
(self.br.y - self.tl.y) as u32
}
pub fn translate(&mut self, offset: Point) {
self.tl.x += offset.x;
self.br.x += offset.x;

View file

@ -578,6 +578,7 @@ mod implementation {
}
pub fn debug_wakeup(&mut self, _ena: bool) {
}
#[allow(dead_code)]
pub fn activity_get_period(&mut self) -> u32 {
12_000_000
}
@ -957,9 +958,19 @@ fn xmain() -> ! {
latest_activity = activity as u32;
}),
Some(Opcode::GetActivity) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let period = llio.activity_get_period() as u32;
log::debug!("activity/period: {}/{}, {:.2}%", latest_activity, period, (latest_activity as f32 / period as f32) * 100.0);
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity");
#[cfg(any(target_os = "none", target_os = "xous"))]
{
let period = llio.activity_get_period() as u32;
// log::debug!("activity/period: {}/{}, {:.2}%", latest_activity, period, (latest_activity as f32 / period as f32) * 100.0);
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity");
}
#[cfg(not(any(target_os = "none", target_os = "xous")))] // fake an activity
{
let period = 12_000;
xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity");
latest_activity += period / 20;
latest_activity %= period;
}
}),
Some(Opcode::DebugUsbOp) => msg_blocking_scalar_unpack!(msg, update_req, new_state, _, _, {
if update_req != 0 {

View file

@ -12,6 +12,12 @@ 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;
@ -52,6 +58,7 @@ pub(crate) enum Opcode {
/// Link Management,
GetIpv4Config,
Reset,
GetWifiStats,
/// [Internal] com llio interrupt callback
ComInterrupt,

View file

@ -1,8 +1,10 @@
use crate::api::*;
use std::sync::Arc;
use core::sync::atomic::{AtomicU32, Ordering};
use com::{WlanStatus, WlanStatusIpc};
use net::MIN_EC_REV;
use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack, send_message, Message};
use xous_ipc::Buffer;
use num_traits::*;
use std::io::Read;
@ -11,12 +13,9 @@ pub(crate) enum ConnectionManagerOpcode {
Run,
Poll,
Stop,
WifiStatus,
Quit,
}
#[allow(dead_code)]
const POLL_INTERVAL_MS: usize = 20_151; // stagger slightly off of an integer-seconds interval to even out loads
#[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
pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU32>) {
let tt = ticktimer_server::Ticktimer::new().unwrap();
@ -25,7 +24,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
let netmgr = net::NetManager::new();
let mut pddb = pddb::Pddb::new();
let self_cid = xous::connect(sid).unwrap();
// give the system some time to boot before trying to run this
// give the system some time to boot before trying to run a check on the EC minimum version, as it is in reset on boot
tt.sleep_ms(POLL_INTERVAL_MS).unwrap();
// check that the EC rev meets the minimum version for this service to function
@ -40,9 +39,10 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
let mut run = rev_ok;
let mut mounted = false;
let mut current_interval = BOOT_POLL_INTERVAL_MS;
let mut wifi_stats_cache: WlanStatus = WlanStatus::from_ipc(WlanStatusIpc::default());
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 msg = xous::receive_message(sid).unwrap();
let mut 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,19 +58,19 @@ 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
let status = com.wlan_status().unwrap();
wifi_stats_cache = com.wlan_status().unwrap();
let config = netmgr.get_ipv4_config();
if status.link_state == com_rs_ref::LinkState::WFXError {
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
netmgr.reset(); // this will clear our internal net state
// the wfx chip is wedged. kick it. This call has a built-in 2 second delay.
com.wifi_reset().expect("couldn't reset the wf200 chip");
}
let needs_reconnect =
if status.link_state == com_rs_ref::LinkState::Connected {
if wifi_stats_cache.link_state == com_rs_ref::LinkState::Connected {
if let Some(config) = config { // check that the EC's view of the world is synchronized with our view
// is it enough to just check that the address is the same?
if config.addr != status.ipv4.addr {
if config.addr != wifi_stats_cache.ipv4.addr {
true
} else {
false
@ -99,7 +99,8 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
}
// this needs to not be a dead-wait loop, but for now the WLAN API doesn't support anything better
tt.sleep_ms(5_000).unwrap();
if com.wlan_status().unwrap().link_state == com_rs_ref::LinkState::Connected {
wifi_stats_cache = com.wlan_status().unwrap();
if wifi_stats_cache.link_state == com_rs_ref::LinkState::Connected {
break;
}
}
@ -122,6 +123,12 @@ 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())
};
buffer.replace(com::WlanStatusIpc::from_status(wifi_stats_cache)).unwrap();
},
// 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

@ -73,4 +73,14 @@ impl NetManager {
Message::new_blocking_scalar(Opcode::Reset.to_usize().unwrap(), 0, 0, 0, 0),
).expect("couldn't send reset");
}
/// 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))
}
}

View file

@ -963,6 +963,13 @@ 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())
};
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
},
Some(Opcode::Reset) => {
net_config = None;
let neighbor_cache = NeighborCache::new(BTreeMap::new());

View file

@ -25,6 +25,7 @@ susres = {path = "../susres"}
root-keys = {path = "../root-keys"}
modals = {path = "../modals"}
pddb = {path = "../pddb"}
net = {path = "../net"}
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}

View file

@ -4,7 +4,7 @@
mod mainmenu;
use mainmenu::*;
use com::api::BattStats;
use com::api::*;
use log::info;
use core::fmt::Write;
@ -148,20 +148,35 @@ 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();
log::trace!("|status: getting screen size");
let screensize = gam
.get_canvas_bounds(status_gid)
.expect("|status: Couldn't get canvas size");
// layout: 336 px wide
// 0 150 150 200
// Feb 05 15:00 (00:06:23) xxxx 3.72V/-100mA/99%
const CPU_BAR_WIDTH: i16 = 50;
let time_rect = Rectangle::new(
Point::new(0, 0),
Point::new(screensize.x / 2 - CPU_BAR_WIDTH / 2, screensize.y / 2 - 1)
);
let cpuload_rect = Rectangle::new_with_style(
Point::new(screensize.x / 2 - CPU_BAR_WIDTH / 2, 0),
Point::new(screensize.x / 2 + CPU_BAR_WIDTH / 2, screensize.y / 2 + 1),
DrawStyle::new(PixelColor::Light, PixelColor::Dark, 1),
);
let stats_rect = Rectangle::new_with_style(
Point::new(screensize.x / 2 - CPU_BAR_WIDTH / 2, 0),
Point::new(screensize.x, screensize.y / 2 - 1),
DrawStyle::new(PixelColor::Light, PixelColor::Light, 0),
);
log::trace!("|status: building textview objects");
// build uptime text view: left half of status bar
let mut uptime_tv = TextView::new(
status_gid,
TextBounds::BoundingBox(Rectangle::new(
Point::new(0, 0),
Point::new(screensize.x / 2, screensize.y / 2),
)),
TextBounds::GrowableFromTl(time_rect.tl(), time_rect.width() as _),
);
uptime_tv.untrusted = false;
uptime_tv.style = GlyphStyle::Regular;
@ -176,10 +191,7 @@ fn xmain() -> ! {
// build battstats text view: right half of status bar
let mut battstats_tv = TextView::new(
status_gid,
TextBounds::BoundingBox(Rectangle::new(
Point::new(screensize.x / 2, 0),
Point::new(screensize.x, screensize.y / 2),
)),
TextBounds::GrowableFromTr(stats_rect.tr(), stats_rect.width() as _),
);
battstats_tv.style = GlyphStyle::Regular;
battstats_tv.draw_border = false;
@ -195,6 +207,7 @@ fn xmain() -> ! {
remaining_capacity: 650,
};
/*
let style_dark = DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 1);
gam.draw_line(
status_gid,
@ -205,6 +218,7 @@ fn xmain() -> ! {
),
)
.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
@ -233,7 +247,7 @@ fn xmain() -> ! {
let mut security_tv = TextView::new(
status_gid,
TextBounds::BoundingBox(Rectangle::new(
Point::new(0, screensize.y / 2),
Point::new(0, screensize.y / 2 + 1),
Point::new(screensize.x, screensize.y),
)),
);
@ -313,7 +327,6 @@ fn xmain() -> ! {
secnotes_interval = 4;
}
let mut battstats_phase = true;
let mut needs_redraw = false;
log::debug!("starting main menu thread");
create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com);
@ -330,6 +343,7 @@ fn xmain() -> ! {
t!("rtc.sunday", xous::LANG),
];
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
loop {
let msg = xous::receive_message(status_sid).unwrap();
@ -338,24 +352,34 @@ fn xmain() -> ! {
Some(StatusOpcode::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, {
stats = [lo, hi].into();
battstats_tv.clear_str();
gam.draw_rectangle(status_gid, stats_rect).ok();
// toggle between two views of the data every time we have a status update
if battstats_phase {
write!(&mut battstats_tv, "{}mV {}mA", stats.voltage, stats.current)
write!(&mut battstats_tv, "{}mA {:.2}V {}%", stats.current, stats.voltage as f32 / 1000.0, stats.soc)
.expect("|status: can't write string");
} else {
write!(
&mut battstats_tv,
"{}mAh {}%",
stats.remaining_capacity, stats.soc
)
.expect("|status: can't write string");
if let Some(ssid) = wifi_status.ssid {
write!(
&mut battstats_tv,
"{} -{}dBm",
ssid.name.as_str().unwrap_or("UTF-8 Erorr"),
ssid.rssi,
)
.expect("|status: can't write string");
} else {
write!(
&mut battstats_tv,
"Not connected"
)
.expect("|status: can't write string");
}
}
gam.post_textview(&mut battstats_tv)
.expect("|status: can't draw battery stats");
battstats_phase = !battstats_phase;
needs_redraw = true;
}),
Some(StatusOpcode::Pump) => {
let elapsed_time = ticktimer.elapsed_ms();
let (is_locked, force_update) = llio.debug_usb(None).unwrap();
if (debug_locked != is_locked)
|| force_update
@ -401,13 +425,16 @@ fn xmain() -> ! {
// only post the view if something has actually changed
gam.post_textview(&mut security_tv).unwrap();
needs_redraw = true;
}
if (stats_phase % batt_interval) == (batt_interval - 1) {
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.
@ -455,56 +482,50 @@ fn xmain() -> ! {
});
}
}
// date/time only redraws once every stats_interval period; but if needs_redraw is triggered (e.g. due to resume), force a redraw
if (needs_redraw
|| ((stats_phase % stats_interval == 0)
&& ((stats_phase % (stats_interval * 2)) == stats_interval)))
&& datetime.is_some()
{
let dt = datetime.unwrap();
let day = match dt.weekday {
llio::Weekday::Monday => "Mon",
llio::Weekday::Tuesday => "Tue",
llio::Weekday::Wednesday => "Wed",
llio::Weekday::Thursday => "Thu",
llio::Weekday::Friday => "Fri",
llio::Weekday::Saturday => "Sat",
llio::Weekday::Sunday => "Sun",
};
{ // update the time field
uptime_tv.clear_str();
write!(
&mut uptime_tv,
"{:02}:{:02} {} {}/{}",
dt.hours, dt.minutes, day, dt.months, dt.days
)
.unwrap();
gam.post_textview(&mut uptime_tv)
.expect("|status: can't draw uptime");
needs_redraw = true;
} else if (stats_phase % (stats_interval * 2)) < stats_interval {
uptime_tv.clear_str();
let (latest_activity, period) = llio
.activity_instantaneous()
.expect("couldn't get CPU activity");
if let Some(dt) = datetime {
write!(
&mut uptime_tv,
"{:02}:{:02} {}/{}",
dt.hours, dt.minutes, dt.months, dt.days
)
.unwrap();
} else {
write!(
&mut uptime_tv,
"Invalid RTC"
).unwrap();
}
// use ticktimer, not stats_phase, because stats_phase encodes some phase drift due to task-switching overhead
let elapsed_time = ticktimer.elapsed_ms();
write!(
&mut uptime_tv,
"Up {}:{:02}:{:02} {:.0}%",
" Up {}:{:02}:{:02}",
(elapsed_time / 3_600_000),
(elapsed_time / 60_000) % 60,
(elapsed_time / 1000) % 60,
((latest_activity as f32) / (period as f32)) * 100.0
)
.expect("|status: can't write string");
gam.post_textview(&mut uptime_tv)
.expect("|status: can't draw uptime");
needs_redraw = true;
}
if needs_redraw {
gam.redraw().expect("|status: couldn't redraw");
needs_redraw = false;
{ // update the CPU load bar
gam.draw_rectangle(status_gid, cpuload_rect).ok();
let (latest_activity, period) = llio
.activity_instantaneous()
.expect("couldn't get CPU activity");
let activity_to_width = ((latest_activity as f32) / (period as f32)) * (cpuload_rect.width() - 4) as f32;
gam.draw_rectangle(status_gid,
Rectangle::new_coords_with_style(
cpuload_rect.tl().x + 2,
cpuload_rect.tl().y + 2,
cpuload_rect.tl().x + 2 + activity_to_width as i16,
cpuload_rect.br().y - 2,
DrawStyle::new(PixelColor::Dark, PixelColor::Dark, 0))
).ok();
}
gam.redraw().expect("|status: couldn't redraw");
stats_phase = stats_phase.wrapping_add(1);
}