diff --git a/Cargo.lock b/Cargo.lock index d92ca31bf..c5868b0a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2229,6 +2229,7 @@ dependencies = [ "log", "log-server", "modals", + "net", "num-derive", "num-traits", "pddb", diff --git a/services/com/src/api.rs b/services/com/src/api.rs index 5e8bfdc50..ccc286f17 100644 --- a/services/com/src/api.rs +++ b/services/com/src/api.rs @@ -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, 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), diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 2c0d7a22c..193d65e3d 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -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 { let status = WlanStatusIpc::default(); let mut buf = Buffer::into_buf(status).or(Err(xous::Error::InternalError))?; diff --git a/services/gam/src/main.rs b/services/gam/src/main.rs index 86cffa37e..95fb39e43 100644 --- a/services/gam/src/main.rs +++ b/services/gam/src/main.rs @@ -550,15 +550,9 @@ fn xmain() -> ! { let mut canvases: HashMap = 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); diff --git a/services/graphics-server/src/api/shapes.rs b/services/graphics-server/src/api/shapes.rs index efb720f78..5340ba5a8 100644 --- a/services/graphics-server/src/api/shapes.rs +++ b/services/graphics-server/src/api/shapes.rs @@ -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; diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index af7ad568c..7890b379d 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -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 { diff --git a/services/net/src/api.rs b/services/net/src/api.rs index 88ca1f434..a4f66b353 100644 --- a/services/net/src/api.rs +++ b/services/net/src/api.rs @@ -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, diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index af7f98ffd..7476d3fbc 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -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) { let tt = ticktimer_server::Ticktimer::new().unwrap(); @@ -25,7 +24,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc msg_scalar_unpack!(msg, _, _, _, _, { @@ -58,19 +58,19 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc { + 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, _, _, _, _, { diff --git a/services/net/src/lib.rs b/services/net/src/lib.rs index 85bd78ddc..4c61d74cd 100644 --- a/services/net/src/lib.rs +++ b/services/net/src/lib.rs @@ -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 { + 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::().unwrap(); + Ok(com::WlanStatus::from_ipc(response)) + } } \ No newline at end of file diff --git a/services/net/src/main.rs b/services/net/src/main.rs index ce615b77d..c1ea9b0f2 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -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()); diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index f55d55439..a0027adfd 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -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} diff --git a/services/status/src/main.rs b/services/status/src/main.rs index cdd9dfd20..82ff3173f 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -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); }