move more crates to standardized formatting

This commit is contained in:
bunnie 2021-08-20 00:19:16 +08:00
parent 3f679bd1e9
commit d801749e18
4 changed files with 314 additions and 151 deletions

View file

@ -3,13 +3,11 @@ ignore = [
"services/aes",
"services/codec",
"services/com",
"services/content-plugin-api",
"services/engine-25519",
"services/engine-sha512",
"services/gam",
"services/graphics-server",
"services/ime-frontend",
"services/ime-plugin-api",
"services/ime-plugin-shell",
"services/jtag",
"services/keyboard",
@ -18,6 +16,5 @@ ignore = [
"services/rtc",
"services/shellchat",
"services/spinor",
"services/status",
"services/susres",
]

16
services/content-plugin-api/src/lib.rs Normal file → Executable file
View file

@ -1,6 +1,6 @@
#![cfg_attr(target_os = "none", no_std)]
use xous::{CID, send_message, Message, ScalarMessage};
use xous::{send_message, Message, ScalarMessage, CID};
#[derive(Debug)]
pub enum Opcode {
@ -8,9 +8,9 @@ pub enum Opcode {
Redraw,
}
impl core::convert::TryFrom<& Message> for Opcode {
impl core::convert::TryFrom<&Message> for Opcode {
type Error = &'static str;
fn try_from(message: & Message) -> Result<Self, Self::Error> {
fn try_from(message: &Message) -> Result<Self, Self::Error> {
match message {
Message::Scalar(m) => match m.id {
0 => Ok(Opcode::Redraw),
@ -25,7 +25,11 @@ impl Into<Message> for Opcode {
fn into(self) -> Message {
match self {
Opcode::Redraw => Message::Scalar(ScalarMessage {
id: 0, arg1: 0, arg2: 0, arg3: 0, arg4: 0,
id: 0,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
// _ => panic!("SHCH api: Opcode type not handled by Into(), refer to helper method"),
}
@ -45,8 +49,7 @@ impl ContentCanvasApi for ContentCanvasConnection {
fn redraw_canvas(&self) -> Result<(), xous::Error> {
if let Some(id) = self.redraw_id {
match self.connection {
Some(cid) => send_message(cid,
Message::new_scalar(id, 0, 0, 0, 0)).map(|_| ()),
Some(cid) => send_message(cid, Message::new_scalar(id, 0, 0, 0, 0)).map(|_| ()),
_ => Err(xous::Error::UseBeforeInit),
}
} else {
@ -54,4 +57,3 @@ impl ContentCanvasApi for ContentCanvasConnection {
}
}
}

158
services/ime-plugin-api/src/lib.rs Normal file → Executable file
View file

@ -1,14 +1,14 @@
#![cfg_attr(target_os = "none", no_std)]
use xous::{Message, CID, send_message};
use num_traits::{FromPrimitive, ToPrimitive};
use xous::{send_message, Message, CID};
use xous_ipc::{Buffer, String};
use num_traits::{ToPrimitive, FromPrimitive};
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct Prediction {
pub index: u32,
pub valid: bool,
pub string: String::<1000>,
pub string: String<1000>,
}
#[derive(Debug, Default, Copy, Clone)]
@ -24,9 +24,15 @@ pub struct PredictionTriggers {
impl Into<usize> for PredictionTriggers {
fn into(self) -> usize {
let mut ret: usize = 0;
if self.newline { ret |= 0x1; }
if self.punctuation { ret |= 0x2; }
if self.whitespace { ret |= 0x4; }
if self.newline {
ret |= 0x1;
}
if self.punctuation {
ret |= 0x2;
}
if self.whitespace {
ret |= 0x4;
}
ret
}
}
@ -87,14 +93,22 @@ impl PredictionApi for PredictionPlugin {
fn get_prediction_triggers(&self) -> Result<PredictionTriggers, xous::Error> {
match self.connection {
Some(cid) => {
let response = send_message(cid,
Message::new_blocking_scalar(Opcode::GetPredictionTriggers.to_usize().unwrap(), 0, 0, 0, 0))?;
let response = send_message(
cid,
Message::new_blocking_scalar(
Opcode::GetPredictionTriggers.to_usize().unwrap(),
0,
0,
0,
0,
),
)?;
if let xous::Result::Scalar1(code) = response {
Ok(code.into())
} else {
Err(xous::Error::InternalError)
}
},
}
_ => Err(xous::Error::UseBeforeInit),
}
}
@ -102,11 +116,13 @@ impl PredictionApi for PredictionPlugin {
fn unpick(&self) -> Result<(), xous::Error> {
match self.connection {
Some(cid) => {
send_message(cid,
Message::new_scalar(Opcode::Unpick.to_usize().unwrap(), 0, 0, 0, 0))?;
send_message(
cid,
Message::new_scalar(Opcode::Unpick.to_usize().unwrap(), 0, 0, 0, 0),
)?;
Ok(())
},
_ => Err(xous::Error::UseBeforeInit)
}
_ => Err(xous::Error::UseBeforeInit),
}
}
@ -114,9 +130,10 @@ impl PredictionApi for PredictionPlugin {
match self.connection {
Some(cid) => {
let buf = Buffer::into_buf(s).or(Err(xous::Error::InternalError))?;
buf.lend(cid, Opcode::Input.to_u32().unwrap()).expect("|API: set_input operation failure");
buf.lend(cid, Opcode::Input.to_u32().unwrap())
.expect("|API: set_input operation failure");
Ok(())
},
}
_ => Err(xous::Error::UseBeforeInit),
}
}
@ -125,9 +142,10 @@ impl PredictionApi for PredictionPlugin {
match self.connection {
Some(cid) => {
let buf = Buffer::into_buf(s).or(Err(xous::Error::InternalError))?;
buf.lend(cid, Opcode::Picked.to_u32().unwrap()).expect("|API: feedback_picked operation failure");
buf.lend(cid, Opcode::Picked.to_u32().unwrap())
.expect("|API: feedback_picked operation failure");
Ok(())
},
}
_ => Err(xous::Error::UseBeforeInit),
}
}
@ -141,7 +159,8 @@ impl PredictionApi for PredictionPlugin {
valid: false,
};
let mut buf = Buffer::into_buf(prediction).or(Err(xous::Error::InternalError))?;
buf.lend_mut(cid, Opcode::Prediction.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
buf.lend_mut(cid, Opcode::Prediction.to_u32().unwrap())
.or(Err(xous::Error::InternalError))?;
log::trace!("IME|API: returned from get_prediction");
@ -162,13 +181,12 @@ impl PredictionApi for PredictionPlugin {
Err(xous::Error::InternalError)
}
}
},
}
_ => Err(xous::Error::UseBeforeInit),
}
}
}
//////////////////////////////////////////////////////
//////////////////// FRONT END API
//////////////////////////////////////////////////////
@ -202,13 +220,13 @@ pub enum ImefCallback {
pub struct ImefDescriptor {
pub input_canvas: Option<graphics_server::Gid>,
pub prediction_canvas: Option<graphics_server::Gid>,
pub predictor: Option<String::<64>>,
pub predictor: Option<String<64>>,
pub token: [u32; 4], // token used to lookup our connected app inside the GAM
}
pub trait ImeFrontEndApi {
fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<(), xous::Error>;
fn hook_listener_callback(&mut self, cb: fn(String::<4000>)) -> Result<(), xous::Error>;
fn hook_listener_callback(&mut self, cb: fn(String<4000>)) -> Result<(), xous::Error>;
fn redraw(&self, force_all: bool) -> Result<(), xous::Error>;
fn send_keyevent(&self, keys: [char; 4]) -> Result<(), xous::Error>;
fn conn(&self) -> xous::CID;
@ -216,7 +234,7 @@ pub trait ImeFrontEndApi {
}
pub const SERVER_NAME_IME_FRONT: &str = "_IME front end_";
static mut INPUT_CB: Option<fn(String::<4000>)> = None;
static mut INPUT_CB: Option<fn(String<4000>)> = None;
pub struct ImeFrontEnd {
cid: CID,
@ -225,11 +243,13 @@ pub struct ImeFrontEnd {
impl ImeFrontEnd {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(SERVER_NAME_IME_FRONT).expect("Can't connect to IMEF");
let conn = xns
.request_connection_blocking(SERVER_NAME_IME_FRONT)
.expect("Can't connect to IMEF");
Ok(ImeFrontEnd {
cid: conn,
callback_sid: None,
})
})
}
}
use core::sync::atomic::{AtomicU32, Ordering};
@ -242,61 +262,90 @@ impl Drop for ImeFrontEnd {
// tell my handler thread to quit
let cid = xous::connect(sid).unwrap();
xous::send_message(cid,
Message::new_blocking_scalar(ImefCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
unsafe{xous::disconnect(cid).unwrap();}
xous::send_message(
cid,
Message::new_blocking_scalar(ImefCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0),
)
.unwrap();
unsafe {
xous::disconnect(cid).unwrap();
}
xous::destroy_server(sid).unwrap();
}
if REFCOUNT.load(Ordering::Relaxed) == 0 {
unsafe{xous::disconnect(self.cid).unwrap();}
unsafe {
xous::disconnect(self.cid).unwrap();
}
}
}
}
impl ImeFrontEndApi for ImeFrontEnd {
fn conn(&self) -> xous::CID { self.cid }
fn conn(&self) -> xous::CID {
self.cid
}
fn getop_process_keys(&self) -> u32 {
ImefOpcode::ProcessKeys.to_u32().unwrap()
}
fn connect_backend(&self, descriptor: ImefDescriptor) -> Result<(), xous::Error> {
let buf = Buffer::into_buf(descriptor).or(Err(xous::Error::InternalError))?;
buf.lend(self.cid, ImefOpcode::ConnectBackend.to_u32().unwrap()).or(Err(xous::Error::InternalError)).map(|_| ())
buf.lend(self.cid, ImefOpcode::ConnectBackend.to_u32().unwrap())
.or(Err(xous::Error::InternalError))
.map(|_| ())
}
fn send_keyevent(&self, keys: [char; 4]) -> Result<(), xous::Error> {
log::trace!("sending keys: {:?}", keys);
xous::send_message(self.cid,
xous::Message::new_scalar(ImefOpcode::ProcessKeys.to_usize().unwrap(),
keys[0] as u32 as usize,
keys[1] as u32 as usize,
keys[2] as u32 as usize,
keys[3] as u32 as usize,
)).map(|_|())
xous::send_message(
self.cid,
xous::Message::new_scalar(
ImefOpcode::ProcessKeys.to_usize().unwrap(),
keys[0] as u32 as usize,
keys[1] as u32 as usize,
keys[2] as u32 as usize,
keys[3] as u32 as usize,
),
)
.map(|_| ())
}
fn hook_listener_callback(&mut self, cb: fn(String::<4000>)) -> Result<(), xous::Error> {
if unsafe{INPUT_CB}.is_some() {
return Err(xous::Error::MemoryInUse) // can't hook it twice
fn hook_listener_callback(&mut self, cb: fn(String<4000>)) -> Result<(), xous::Error> {
if unsafe { INPUT_CB }.is_some() {
return Err(xous::Error::MemoryInUse); // can't hook it twice
}
unsafe{INPUT_CB = Some(cb)};
unsafe { INPUT_CB = Some(cb) };
if self.callback_sid.is_none() {
let sid = xous::create_server().unwrap();
self.callback_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(callback_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
xous::send_message(self.cid,
Message::new_scalar(ImefOpcode::RegisterListener.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
xous::create_thread_4(
callback_server,
sid_tuple.0 as usize,
sid_tuple.1 as usize,
sid_tuple.2 as usize,
sid_tuple.3 as usize,
)
.unwrap();
xous::send_message(
self.cid,
Message::new_scalar(
ImefOpcode::RegisterListener.to_usize().unwrap(),
sid_tuple.0 as usize,
sid_tuple.1 as usize,
sid_tuple.2 as usize,
sid_tuple.3 as usize,
),
)
.unwrap();
}
Ok(())
}
fn redraw(&self, force_all: bool) -> Result<(), xous::Error> {
let arg = if force_all { 1 } else { 0 };
send_message(self.cid,
Message::new_scalar(ImefOpcode::Redraw.to_usize().unwrap(),
arg, 0, 0, 0)
send_message(
self.cid,
Message::new_scalar(ImefOpcode::Redraw.to_usize().unwrap(), arg, 0, 0, 0),
)?;
Ok(())
}
@ -309,18 +358,19 @@ fn callback_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(ImefCallback::GotInputLine) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let inputline = buffer.to_original::<String::<4000>, _>().unwrap();
let buffer =
unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let inputline = buffer.to_original::<String<4000>, _>().unwrap();
unsafe {
if let Some(cb) = INPUT_CB {
cb(inputline)
}
}
},
}
Some(ImefCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
}
}

288
services/status/src/main.rs Normal file → Executable file
View file

@ -1,27 +1,30 @@
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
use log::info;
use com::api::BattStats;
use log::info;
use core::fmt::Write;
use blitstr_ref as blitstr;
use xous::{send_message, CID, Message, msg_scalar_unpack};
use xous_ipc::String;
use num_traits::*;
use xous::{msg_scalar_unpack, send_message, Message, CID};
use xous_ipc::String;
use graphics_server::*;
use locales::t;
use std::sync::{Arc, Mutex};
#[cfg_attr(not(any(target_os = "none", target_os = "xous")), allow(unused_imports))]
use std::thread;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[cfg_attr(
not(any(target_os = "none", target_os = "xous")),
allow(unused_imports)
)]
use std::thread;
const SERVER_NAME_STATUS: &str = "_Status bar manager_";
const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_";
const SERVER_NAME_STATUS: &str = "_Status bar manager_";
const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_";
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
enum StatusOpcode {
@ -37,32 +40,43 @@ enum StatusOpcode {
static mut CB_TO_MAIN_CONN: Option<CID> = None;
fn battstats_cb(stats: BattStats) {
if let Some(cb_to_main_conn) = unsafe{CB_TO_MAIN_CONN} {
if let Some(cb_to_main_conn) = unsafe { CB_TO_MAIN_CONN } {
let rawstats: [usize; 2] = stats.into();
send_message(cb_to_main_conn,
xous::Message::new_scalar(StatusOpcode::BattStats.to_usize().unwrap(),
rawstats[0], rawstats[1], 0, 0
)).unwrap();
send_message(
cb_to_main_conn,
xous::Message::new_scalar(
StatusOpcode::BattStats.to_usize().unwrap(),
rawstats[0],
rawstats[1],
0,
0,
),
)
.unwrap();
}
}
pub fn dt_callback(dt: rtc::DateTime) {
//log::info!("dt_callback received with {:?}", dt);
if let Some(cb_to_main_conn) = unsafe{CB_TO_MAIN_CONN} {
let buf = xous_ipc::Buffer::into_buf(dt).or(Err(xous::Error::InternalError)).unwrap();
buf.send(cb_to_main_conn, StatusOpcode::DateTime.to_u32().unwrap()).unwrap();
if let Some(cb_to_main_conn) = unsafe { CB_TO_MAIN_CONN } {
let buf = xous_ipc::Buffer::into_buf(dt)
.or(Err(xous::Error::InternalError))
.unwrap();
buf.send(cb_to_main_conn, StatusOpcode::DateTime.to_u32().unwrap())
.unwrap();
}
}
pub fn pump_thread(conn: usize) {
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
loop {
match send_message(conn as u32,
Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0)
match send_message(
conn as u32,
Message::new_scalar(StatusOpcode::Pump.to_usize().unwrap(), 0, 0, 0, 0),
) {
Err(xous::Error::ServerNotFound) => break,
Ok(xous::Result::Ok) => {},
_ => panic!("unhandled error in status pump thread")
Ok(xous::Result::Ok) => {}
_ => panic!("unhandled error in status pump thread"),
}
ticktimer.sleep_ms(1000).unwrap();
}
@ -75,16 +89,18 @@ fn xmain() -> ! {
let xns = xous_names::XousNames::new().unwrap();
// 1 connection exactly -- from the GAM to set our canvas GID
let status_gam_getter = xns.register_name(SERVER_NAME_STATUS_GID, Some(1)).expect("can't register server");
let status_gam_getter = xns
.register_name(SERVER_NAME_STATUS_GID, Some(1))
.expect("can't register server");
let mut canvas_gid: [u32; 4] = [0; 4];
// wait unil we're assigned a GID -- this is a one-time message from the GAM
let msg = xous::receive_message(status_gam_getter).unwrap();
log::trace!("GID assignment message: {:?}", msg);
xous::msg_scalar_unpack!(msg, g0, g1, g2, g3, {
canvas_gid[0] = g0 as u32;
canvas_gid[1] = g1 as u32;
canvas_gid[2] = g2 as u32;
canvas_gid[3] = g3 as u32;
canvas_gid[0] = g0 as u32;
canvas_gid[1] = g1 as u32;
canvas_gid[2] = g2 as u32;
canvas_gid[3] = g3 as u32;
});
match xns.unregister_server(status_gam_getter) {
Err(e) => {
@ -100,9 +116,11 @@ fn xmain() -> ! {
log::trace!("|status: registering GAM|status thread");
// we have one connection, from the status main loop; but we make it with a local call, not using xns. so there's 0 in xns.
let status_sid = xns.register_name(SERVER_NAME_STATUS, Some(0)).expect("|status: can't register server");
let status_sid = xns
.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())};
unsafe { CB_TO_MAIN_CONN = Some(xous::connect(status_sid).unwrap()) };
let pump_conn = xous::connect(status_sid).unwrap();
xous::create_thread_1(pump_thread, pump_conn as _).expect("couldn't create pump thread");
@ -111,30 +129,42 @@ fn xmain() -> ! {
let mut com = com::Com::new(&xns).expect("|status: can't connect to COM");
log::trace!("|status: getting screen size");
let screensize = gam.get_canvas_bounds(status_gid).expect("|status: Couldn't get canvas size");
let screensize = gam
.get_canvas_bounds(status_gid)
.expect("|status: Couldn't get canvas size");
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 - 1))));
let mut uptime_tv = TextView::new(
status_gid,
TextBounds::BoundingBox(Rectangle::new(
Point::new(0, 0),
Point::new(screensize.x / 2, screensize.y / 2 - 1),
)),
);
uptime_tv.untrusted = false;
uptime_tv.style = blitstr::GlyphStyle::Small;
uptime_tv.draw_border = false;
uptime_tv.margin = Point::new(3, 0);
write!(uptime_tv, "Booting up...").expect("|status: couldn't init uptime text");
gam.post_textview(&mut uptime_tv).expect("|status: can't draw battery stats");
gam.post_textview(&mut uptime_tv)
.expect("|status: can't draw battery stats");
log::trace!("|status: screensize as reported: {:?}", screensize);
log::trace!("|status: uptime initialized to '{:?}'", uptime_tv);
// 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 - 1))));
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 - 1),
)),
);
battstats_tv.style = blitstr::GlyphStyle::Small;
battstats_tv.draw_border = false;
battstats_tv.margin = Point::new(0, 0);
gam.post_textview(&mut battstats_tv).expect("|status: can't draw battery stats");
gam.post_textview(&mut battstats_tv)
.expect("|status: can't draw battery stats");
// initialize to some "sane" mid-point defaults, so we don't trigger errors later on before the first real battstat reading comes
let mut stats = BattStats {
@ -145,15 +175,21 @@ fn xmain() -> ! {
};
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");
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");
com.hook_batt_stats(battstats_cb).expect("|status: couldn't hook callback for events from COM");
com.hook_batt_stats(battstats_cb)
.expect("|status: couldn't hook callback for events from COM");
// prime the loop
com.req_batt_stats().expect("Can't get battery stats from COM");
com.req_batt_stats()
.expect("Can't get battery stats from COM");
log::debug!("initializing RTC...");
let mut rtc = rtc::Rtc::new(&xns).unwrap();
@ -169,9 +205,13 @@ fn xmain() -> ! {
let (dl, _) = llio.debug_usb(None).unwrap();
let mut debug_locked = dl;
// build security status textview
let mut security_tv = TextView::new(status_gid,
TextBounds::BoundingBox(Rectangle::new(Point::new(0,screensize.y / 2),
Point::new(screensize.x, screensize.y - 1))));
let mut security_tv = TextView::new(
status_gid,
TextBounds::BoundingBox(Rectangle::new(
Point::new(0, screensize.y / 2),
Point::new(screensize.x, screensize.y - 1),
)),
);
security_tv.style = blitstr::GlyphStyle::Small;
security_tv.draw_border = false;
security_tv.margin = Point::new(0, 0);
@ -180,32 +220,53 @@ fn xmain() -> ! {
security_tv.invert = true;
write!(&mut security_tv, "{}", t!("secnote.startup", xous::LANG)).unwrap();
gam.post_textview(&mut security_tv).unwrap();
gam.redraw().unwrap(); // initial boot redraw
gam.redraw().unwrap(); // initial boot redraw
let sec_notes = Arc::new(Mutex::new(HashMap::new()));
let mut last_sec_note_index = 0;
let mut last_sec_note_size = 0;
if !debug_locked {
sec_notes.lock().unwrap().insert("secnote.usb_unlock".to_string(), t!("secnote.usb_unlock", xous::LANG).to_string());
sec_notes.lock().unwrap().insert(
"secnote.usb_unlock".to_string(),
t!("secnote.usb_unlock", xous::LANG).to_string(),
);
}
let keys = Arc::new(Mutex::new(root_keys::RootKeys::new(&xns, None).expect("couldn't connect to root_keys to query initialization state")));
let keys = Arc::new(Mutex::new(
root_keys::RootKeys::new(&xns, None)
.expect("couldn't connect to root_keys to query initialization state"),
));
if !keys.lock().unwrap().is_initialized().unwrap() {
sec_notes.lock().unwrap().insert("secnotes.no_keys".to_string(), t!("secnote.no_keys", xous::LANG).to_string());
sec_notes.lock().unwrap().insert(
"secnotes.no_keys".to_string(),
t!("secnote.no_keys", xous::LANG).to_string(),
);
} else {
log::info!("checking gateware signature...");
#[cfg(any(target_os = "none", target_os = "xous"))] // for now, threads don't work in hosted mode, but the result of this isn't important in hosted mode right now
#[cfg(any(target_os = "none", target_os = "xous"))]
// for now, threads don't work in hosted mode, but the result of this isn't important in hosted mode right now
thread::spawn({
let clone = Arc::clone(&sec_notes);
let keys = Arc::clone(&keys);
move || {
if let Some(pass) = keys.lock().unwrap().check_gateware_signature().expect("couldn't issue gateware check call") {
if let Some(pass) = keys
.lock()
.unwrap()
.check_gateware_signature()
.expect("couldn't issue gateware check call")
{
if !pass {
let mut sn = clone.lock().unwrap();
sn.insert("secnotes.gateware_fail".to_string(), t!("secnote.gateware_fail", xous::LANG).to_string());
sn.insert(
"secnotes.gateware_fail".to_string(),
t!("secnote.gateware_fail", xous::LANG).to_string(),
);
}
} else {
let mut sn = clone.lock().unwrap();
sn.insert("secnotes.state_fail".to_string(), t!("secnote.state_fail", xous::LANG).to_string());
sn.insert(
"secnotes.state_fail".to_string(),
t!("secnote.state_fail", xous::LANG).to_string(),
);
}
}
});
@ -242,8 +303,14 @@ fn xmain() -> ! {
keys_op = keys.lock().unwrap().get_try_init_keys_op();
}
let sign_op = keys.lock().unwrap().get_try_selfsign_op();
xous::create_thread_4(main_menu_thread, keys_init, keys.lock().unwrap().conn() as usize, keys_op as usize, sign_op as usize)
.expect("couldn't create menu thread");
xous::create_thread_4(
main_menu_thread,
keys_init,
keys.lock().unwrap().conn() as usize,
keys_op as usize,
sign_op as usize,
)
.expect("couldn't create menu thread");
info!("|status: starting main loop");
loop {
@ -255,24 +322,40 @@ fn xmain() -> ! {
battstats_tv.clear_str();
// 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).expect("|status: can't write string");
write!(&mut battstats_tv, "{}mV {}mA", stats.voltage, stats.current)
.expect("|status: can't write string");
} else {
write!(&mut battstats_tv, "{}mAh {}%", stats.remaining_capacity, stats.soc).expect("|status: can't write string");
write!(
&mut battstats_tv,
"{}mAh {}%",
stats.remaining_capacity, stats.soc
)
.expect("|status: can't write string");
}
gam.post_textview(&mut battstats_tv).expect("|status: can't draw battery stats");
gam.post_textview(&mut battstats_tv)
.expect("|status: can't draw battery stats");
battstats_phase = !battstats_phase;
needs_redraw = true;
}),
Some(StatusOpcode::Pump) => {
let (is_locked, force_update) = llio.debug_usb(None).unwrap();
if (debug_locked != is_locked) || force_update
|| sec_notes.lock().unwrap().len() != last_sec_note_size
|| (sec_notes.lock().unwrap().len() > 1) && ((stats_phase % secnotes_interval) == 0) {
if (debug_locked != is_locked)
|| force_update
|| sec_notes.lock().unwrap().len() != last_sec_note_size
|| (sec_notes.lock().unwrap().len() > 1)
&& ((stats_phase % secnotes_interval) == 0)
{
if debug_locked != is_locked {
if debug_locked {
sec_notes.lock().unwrap().remove(&"secnotes.usb_unlock".to_string());
sec_notes
.lock()
.unwrap()
.remove(&"secnotes.usb_unlock".to_string());
} else {
sec_notes.lock().unwrap().insert("secnotes.usb_unlock".to_string(), t!("secnote.usb_unlock", xous::LANG).to_string());
sec_notes.lock().unwrap().insert(
"secnotes.usb_unlock".to_string(),
t!("secnote.usb_unlock", xous::LANG).to_string(),
);
}
debug_locked = is_locked;
}
@ -289,7 +372,8 @@ fn xmain() -> ! {
for (index, v) in sec_notes.lock().unwrap().values().enumerate() {
if index == last_sec_note_index {
write!(&mut security_tv, "{}", v.as_str()).unwrap();
last_sec_note_index = (last_sec_note_index + 1) % last_sec_note_size;
last_sec_note_index =
(last_sec_note_index + 1) % last_sec_note_size;
break;
}
}
@ -302,25 +386,31 @@ fn xmain() -> ! {
needs_redraw = true;
}
if (stats_phase % batt_interval) == (batt_interval - 1) {
com.req_batt_stats().expect("Can't get battery stats from COM");
com.req_batt_stats()
.expect("Can't get battery stats from COM");
}
if (stats_phase % charger_pump_interval) == 1 { // stagger periodic tasks
if (stats_phase % charger_pump_interval) == 1 {
// stagger periodic tasks
// confirm that the charger is in the right state.
if stats.soc < 95 || stats.remaining_capacity < 1000 { // only request if we aren't fully charged, either by SOC or capacity metrics
if (llio.adc_vbus().unwrap() as f64) * 0.005033 > 4.45 { // 4.45V is our threshold for deciding if a cable is present
if stats.soc < 95 || stats.remaining_capacity < 1000 {
// only request if we aren't fully charged, either by SOC or capacity metrics
if (llio.adc_vbus().unwrap() as f64) * 0.005033 > 4.45 {
// 4.45V is our threshold for deciding if a cable is present
// charging cable is present
if !com.is_charging().expect("couldn't check charging state") {
// not charging, but cable is present
log::debug!("Charger present, but not currently charging. Automatically requesting charge start.");
com.request_charging().expect("couldn't send charge request");
com.request_charging()
.expect("couldn't send charge request");
}
}
}
}
if (stats_phase % dt_pump_interval) == 2 {
#[cfg(any(target_os = "none", target_os = "xous"))]
rtc.request_datetime().expect("|status: can't request datetime from RTC");
rtc.request_datetime()
.expect("|status: can't request datetime from RTC");
#[cfg(not(any(target_os = "none", target_os = "xous")))]
{
log::trace!("hosted request of date time - short circuiting server call");
@ -348,7 +438,11 @@ 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() {
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 {
rtc::Weekday::Monday => "Mon",
@ -360,19 +454,33 @@ fn xmain() -> ! {
rtc::Weekday::Sunday => "Sun",
};
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");
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");
let (latest_activity, period) = llio
.activity_instantaneous()
.expect("couldn't get CPU activity");
// 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}%",
(elapsed_time / 3_600_000), (elapsed_time / 60_000) % 60, (elapsed_time / 1000) % 60,
write!(
&mut uptime_tv,
"Up {}:{:02}:{:02} {:.0}%",
(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");
)
.expect("|status: can't write string");
gam.post_textview(&mut uptime_tv)
.expect("|status: can't draw uptime");
needs_redraw = true;
}
if needs_redraw {
@ -384,23 +492,29 @@ fn xmain() -> ! {
}
Some(StatusOpcode::DateTime) => {
//log::info!("got DateTime update");
let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let buffer = unsafe {
xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap())
};
let dt = buffer.to_original::<rtc::DateTime, _>().unwrap();
datetime = Some(dt);
}
Some(StatusOpcode::Quit) => {
break;
}
None => {log::error!("|status: received unknown Opcode");}
None => {
log::error!("|status: received unknown Opcode");
}
}
}
log::trace!("status thread exit, destroying servers");
unsafe{
if let Some(cb)= CB_TO_MAIN_CONN {
unsafe {
if let Some(cb) = CB_TO_MAIN_CONN {
xous::disconnect(cb).unwrap();
}
}
unsafe{xous::disconnect(pump_conn).unwrap();}
unsafe {
xous::disconnect(pump_conn).unwrap();
}
xns.unregister_server(status_sid).unwrap();
xous::destroy_server(status_sid).unwrap();
log::trace!("status thread quitting");
@ -498,7 +612,7 @@ pub fn main_menu_thread(keys_init: usize, key_conn: usize, key_op: usize, selfsi
match FromPrimitive::from_usize(msg.body.id()) {
Some(MenuOpcode::Redraw) => {
menu.redraw();
},
}
Some(MenuOpcode::Rawkeys) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
if let Some(a) = core::char::from_u32(k1 as u32) {
@ -526,7 +640,7 @@ pub fn main_menu_thread(keys_init: usize, key_conn: usize, key_op: usize, selfsi
}),
Some(MenuOpcode::Quit) => {
break;
},
}
None => {
log::error!("unknown opcode {:?}", msg.body.id());
}
@ -535,4 +649,4 @@ pub fn main_menu_thread(keys_init: usize, key_conn: usize, key_op: usize, selfsi
log::trace!("menu thread exit, destroying servers");
// do we want to add a deregister_ux call to the system?
xous::destroy_server(menu.sid).unwrap();
}
}