COM refactor of callbacks

This commit is contained in:
bunnie 2021-04-02 16:40:17 +08:00
parent 190ca6a29d
commit d6fd42b593
9 changed files with 61 additions and 170 deletions

2
Cargo.lock generated
View file

@ -1080,11 +1080,13 @@ dependencies = [
name = "rkyv-test-client"
version = "0.1.0"
dependencies = [
"com",
"log",
"log-server",
"rkyv-test-server",
"ticktimer-server",
"xous",
"xous-names",
]
[[package]]

View file

@ -104,140 +104,9 @@ pub(crate) enum Opcode {
/// These enums indicate what kind of callback type we're sending.
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum CallbackType {
pub(crate) enum Callback {
/// Battery status
BattStats,
/// Server is quitting, drop connections
Drop,
}
/*
impl core::convert::TryFrom<&Message> for Opcode {
type Error = &'static str;
fn try_from(message: &Message) -> Result<Self, Self::Error> {
match message {
Message::Scalar(m) => {
if m.id as u16 == ComState::CHG_BOOST_ON.verb {
Ok(Opcode::BoostOn)
} else if m.id as u16 == ComState::CHG_BOOST_OFF.verb {
Ok(Opcode::BoostOff)
} else if m.id as u16 == ComState::POWER_SHIPMODE.verb {
Ok(Opcode::ShipMode)
} else if m.id as u16 == ComState::POWER_OFF.verb {
Ok(Opcode::PowerOffSoc)
} else if m.id as u16 == ComState::STAT.verb {
Ok(Opcode::BattStatsNb)
} else if m.id == xous::names::GID_COM_BATTSTATS_EVENT {
let raw_stats: [usize; 2] = [m.arg1, m.arg2];
Ok(Opcode::BattStatsEvent(raw_stats.into()))
} else if m.id as u16 == ComState::WFX_RXSTAT_GET.verb {
Ok(Opcode::RxStatsAgent)
} else {
Err("unrecognized command")
}
}
Message::BlockingScalar(m) => {
if m.id as u16 == ComState::STAT.verb {
Ok(Opcode::BattStats)
} else if m.id as u16 == ComState::GYRO_READ.verb {
Ok(Opcode::ImuAccelRead)
} else if m.id as u16 == ComState::WFX_FW_REV_GET.verb {
Ok(Opcode::Wf200Rev)
} else if m.id as u16 == ComState::EC_GIT_REV.verb {
Ok(Opcode::EcGitRev)
} else {
Err("unrecognized opcode")
}
}
_ => Err("unhandled message type"),
}let registration_name = buffer.as_flat::<
}
}
impl Into<Message> for Opcode {
fn into(self) -> Message {
match self {
Opcode::BoostOn => Message::Scalar(ScalarMessage {
id: ComState::CHG_BOOST_ON.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::BoostOff => Message::Scalar(ScalarMessage {
id: ComState::CHG_BOOST_OFF.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::ShipMode => Message::Scalar(ScalarMessage {
id: ComState::POWER_SHIPMODE.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::PowerOffSoc => Message::Scalar(ScalarMessage {
id: ComState::POWER_OFF.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::BattStats => Message::BlockingScalar(ScalarMessage {
id: ComState::STAT.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::BattStatsNb => Message::Scalar(ScalarMessage {
id: ComState::STAT.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::ImuAccelRead => Message::BlockingScalar(ScalarMessage {
id: ComState::GYRO_READ.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::BattStatsEvent(stats) => {
let raw_stats: [usize; 2] = stats.into();
Message::Scalar(ScalarMessage {
id: xous::names::GID_COM_BATTSTATS_EVENT as usize,
arg1: raw_stats[0],
arg2: raw_stats[1],
arg3: 0,
arg4: 0,
})
}
Opcode::Wf200Rev => Message::BlockingScalar(ScalarMessage {
id: ComState::WFX_FW_REV_GET.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
Opcode::EcGitRev => Message::BlockingScalar(ScalarMessage {
id: ComState::EC_GIT_REV.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
// Wf200PdsLine() uses the direct string "lend" API
Opcode::RxStatsAgent => Message::Scalar(ScalarMessage {
id: ComState::WFX_RXSTAT_GET.verb as _,
arg1: 0,
arg2: 0,
arg3: 0,
arg4: 0,
}),
_ => panic!("opcode not handled -- maybe you meant to use one of the direct APIs"),
}
}
}
*/

View file

@ -6,8 +6,8 @@ use core::convert::TryInto;
/// are calling these functions inside a different process.
pub mod api;
use api::BattStats;
use api::Opcode;
pub use api::BattStats;
use api::{Callback, Opcode};
use xous::{send_message, Error, CID, Message, msg_scalar_unpack};
use xous_ipc::{String, Buffer};
use num_traits::{ToPrimitive, FromPrimitive};
@ -23,7 +23,7 @@ fn battstats_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(api::CallbackType::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, {
Some(api::Callback::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, {
let bs: BattStats = [lo, hi].into();
unsafe {
if let Some(cb) = BATTSTATS_CB {
@ -31,7 +31,10 @@ fn battstats_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
}
}
}),
_ => (),
Some(api::Callback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
}
@ -55,28 +58,6 @@ impl Com {
).map(|_| ())
}
pub fn hook_batt_stats(&mut self, cb: fn(BattStats)) -> Result<(), xous::Error> {
if unsafe{BATTSTATS_CB}.is_some() {
return Err(xous::Error::MemoryInUse)
}
unsafe{BATTSTATS_CB = Some(cb)};
if self.battstats_sid.is_none() {
let sid = xous::create_server().unwrap();
self.battstats_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(battstats_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.conn,
Message::new_scalar(Opcode::RegisterBattStatsListener.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(())
}
pub fn get_batt_stats_nb(&self) -> Result<(), xous::Error> {
send_message(self.conn, Message::new_scalar(Opcode::BattStatsNb.to_usize().unwrap(), 0, 0, 0, 0,)).map(|_| ())
}
pub fn get_wf200_fw_rev(&self) -> Result<(u8, u8, u8), xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::Wf200Rev.to_usize().unwrap(), 0, 0, 0, 0))?;
@ -115,12 +96,38 @@ impl Com {
).map(|_| ())
}
// event relay request API
pub fn request_battstat_events(&self, name: &str) -> Result<xous::Result, xous::Error> {
let s = String::<64>::from_str(name);
let buf = Buffer::into_buf(s).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::RegisterBattStatsListener.to_u32().unwrap())
/// this kicks off an async callback for battery status at some later time
pub fn req_batt_stats(&self) -> Result<(), xous::Error> {
send_message(self.conn, Message::new_scalar(Opcode::BattStatsNb.to_usize().unwrap(), 0, 0, 0, 0,)).map(|_| ())
}
/// this allows the caller to provide a hook to handle the callback
pub fn hook_batt_stats(&mut self, cb: fn(BattStats)) -> Result<(), xous::Error> {
if unsafe{BATTSTATS_CB}.is_some() {
return Err(xous::Error::MemoryInUse)
}
unsafe{BATTSTATS_CB = Some(cb)};
if self.battstats_sid.is_none() {
let sid = xous::create_server().unwrap();
self.battstats_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(battstats_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.conn,
Message::new_scalar(Opcode::RegisterBattStatsListener.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(())
}
// note to future self: add other event listener registrations (such as network events) here
}
impl Drop for Com {
fn drop(&mut self) {
// tell my handler thread to quit
xous::send_message(self.conn,
Message::new_scalar(api::Callback::Drop.to_usize().unwrap(), 0, 0, 0, 0)).unwrap();
// now de-allocate myself
self.battstats_sid = None;
}
}

View file

@ -25,7 +25,7 @@ pub struct WorkRequest {
fn return_battstats(cid: CID, stats: api::BattStats) -> Result<(), xous::Error> {
let rawstats: [usize; 2] = stats.into();
xous::send_message(cid,
xous::Message::new_scalar(api::CallbackType::BattStats.to_usize().unwrap(),
xous::Message::new_scalar(api::Callback::BattStats.to_usize().unwrap(),
rawstats[0], rawstats[1], 0, 0)
).map(|_| ())
}

View file

@ -60,7 +60,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
com::request_battstat_events(xous::names::SERVER_NAME_STATUS, com_conn).expect("GAM|status: couldn't request events from COM");
// prime the loop
com::get_batt_stats_nb(com_conn).expect("Can't get battery stats from COM");
com::req_batt_stats(com_conn).expect("Can't get battery stats from COM");
last_seconds = last_seconds - 1; // this will force the uptime to redraw
info!("GAM|status: starting main loop");
loop {
@ -109,7 +109,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
//info!("GAM|status: size of TextView type: {} bytes", core::mem::size_of::<TextView>());
if debug1{info!("GAM|status: periodic tasks: updating uptime, requesting battstats");}
last_time = elapsed_time;
com::get_batt_stats_nb(com_conn).expect("Can't get battery stats from COM");
com::req_batt_stats(com_conn).expect("Can't get battery stats from COM");
}
} else {
error!("error requesting ticktimer!")

View file

@ -11,6 +11,8 @@ log-server = {path = "../log-server"}
rkyv-test-server = {path = "../rkyv-test-server"}
ticktimer-server = {path = "../ticktimer-server"}
xous = {path = "../../xous-rs"}
com = {path = "../com"}
xous-names = {path="../xous-names"}
[features]
default = []

View file

@ -11,6 +11,10 @@ fn print_log_messages(log_message: &str, prefix: &str) {
);
}
fn handle_battstats(bs: com::BattStats) {
log::info!("battstats: {:?}", bs);
}
#[xous::xous_main]
fn rkyv_test_client() -> ! {
log_server::init_wait().unwrap();
@ -30,6 +34,11 @@ fn rkyv_test_client() -> ! {
let mut double_src = xous::String::<256>::new();
let mut message_string = xous::String::<64>::new();
let xns = xous_names::XousNames::new().unwrap();
let mut com = com::Com::new(xns).unwrap();
com.hook_batt_stats(handle_battstats);
loop {
log::info!("2 + {} = {}", idx, rkyv_test_server::add(2, idx).unwrap());
ticktimer.sleep_ms(500).ok();
@ -48,6 +57,8 @@ fn rkyv_test_client() -> ! {
log::info!("Sending a string \"{}\"", sent_str);
rkyv_test_server::log_message("prefix", sent_str);
com.req_batt_stats();
idx += 1;
}
}

View file

@ -382,7 +382,7 @@ fn shell_main() -> ! {
if let Ok(elapsed_time) = ticktimer.elapsed_ms() {
if elapsed_time - last_time > 500 {
last_time = elapsed_time;
get_batt_stats_nb(com_conn).expect("Can't get battery stats from COM");
req_batt_stats(com_conn).expect("Can't get battery stats from COM");
}
} else {
error!("error requesting ticktimer!")

View file

@ -95,7 +95,7 @@ fn try_main() -> Result<(), DynError> {
],
)?,
Some("renode-image-debug") => renode_image(true, &hw_pkgs)?,
Some("run") => run(false, &minimal_pkgs)?,
Some("run") => run(false, &hw_pkgs)?,
Some("hw-image") => build_hw_image(false, env::args().nth(2), &hw_pkgs)?,
Some("benchmark") => build_hw_image(false, env::args().nth(2), &benchmark_pkgs)?,
Some("fcc-agent") => build_hw_image(false, env::args().nth(2), &fcc_pkgs)?,