extend shellchat to allow for multiple callback registrations

This commit is contained in:
bunnie 2021-05-07 16:22:06 +08:00
parent b3a60faec2
commit 46fa8fa01e
6 changed files with 61 additions and 46 deletions

3
Cargo.lock generated
View file

@ -1402,7 +1402,7 @@ dependencies = [
"content-plugin-api", "content-plugin-api",
"gam", "gam",
"graphics-server", "graphics-server",
"heapless 0.5.6", "heapless 0.7.0",
"ime-plugin-api", "ime-plugin-api",
"keyboard", "keyboard",
"llio", "llio",
@ -1414,6 +1414,7 @@ dependencies = [
"rtc", "rtc",
"susres", "susres",
"ticktimer-server", "ticktimer-server",
"trng",
"utralib", "utralib",
"xous", "xous",
"xous-ipc", "xous-ipc",

View file

@ -10,7 +10,6 @@ com = {path = "../com"}
content-plugin-api = {path = "../content-plugin-api"}# all content canvas providers must provide this API content-plugin-api = {path = "../content-plugin-api"}# all content canvas providers must provide this API
gam = {path = "../gam"} gam = {path = "../gam"}
graphics-server = {path = "../graphics-server"} graphics-server = {path = "../graphics-server"}
heapless = "0.5.6"
ime-plugin-api = {path = "../ime-plugin-api"} ime-plugin-api = {path = "../ime-plugin-api"}
llio = {path = "../llio"} llio = {path = "../llio"}
rtc = {path = "../rtc"} rtc = {path = "../rtc"}
@ -24,6 +23,9 @@ keyboard = {path = "../keyboard"}
susres = {path = "../susres"} susres = {path = "../susres"}
codec = {path = "../codec"} codec = {path = "../codec"}
heapless = "0.7.0"
trng = {path = "../trng"}
num-derive = {version = "0.3", default-features = false} num-derive = {version = "0.3", default-features = false}
num-traits = {version = "0.2", default-features = false} num-traits = {version = "0.2", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}

View file

@ -1,6 +1,8 @@
use xous::{MessageEnvelope}; use xous::{MessageEnvelope};
use xous_ipc::String; use xous_ipc::String;
use core::fmt::Write; use core::fmt::Write;
use heapless::FnvIndexMap;
/////////////////////////// Common items to all commands /////////////////////////// Common items to all commands
pub trait ShellCmdApi<'a> { pub trait ShellCmdApi<'a> {
// user implemented: // user implemented:
@ -42,6 +44,22 @@ pub struct CommonEnv {
com: com::Com, com: com::Com,
ticktimer: ticktimer_server::Ticktimer, ticktimer: ticktimer_server::Ticktimer,
gam: gam::Gam, gam: gam::Gam,
cb_registrations: heapless::FnvIndexMap::<u32, String::<256>, 8>,
trng: trng::Trng,
}
impl CommonEnv {
pub fn register_handler(&mut self, verb: String::<256>) -> u32 {
let mut key: u32;
loop {
key = self.trng.get_u32().unwrap();
// reserve the bottom 1000 IDs for the main loop enums.
if !self.cb_registrations.contains_key(&key) && (key > 1000) {
break;
}
}
self.cb_registrations.insert(key, verb).unwrap();
key
}
} }
/* /*
@ -97,6 +115,8 @@ impl CmdEnv {
com: com::Com::new(&xns).expect("could't connect to COM"), com: com::Com::new(&xns).expect("could't connect to COM"),
ticktimer: ticktimer, ticktimer: ticktimer,
gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"), gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"),
cb_registrations: FnvIndexMap::new(),
trng: trng::Trng::new(&xns).unwrap(),
}, },
lastverb: String::<256>::new(), lastverb: String::<256>::new(),
///// 3. initialize your storage, by calling new() ///// 3. initialize your storage, by calling new()
@ -173,14 +193,25 @@ impl CmdEnv {
} }
} else if let Some(callback) = maybe_callback { } else if let Some(callback) = maybe_callback {
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None); let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None);
if self.lastverb.len() > 0 { // first check and see if we have a callback registration; if not, just map to the last verb
let verb = self.lastverb.to_str(); let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) {
for cmd in commands.iter_mut() { Some(verb) => {
if cmd.matches(verb) { verb.to_str()
cmd_ret = cmd.callback(callback, &mut self.common_env); },
break; None => {
}; self.lastverb.to_str()
} }
};
// now dispatch
let mut verbfound = false;
for cmd in commands.iter_mut() {
if cmd.matches(verb) {
cmd_ret = cmd.callback(callback, &mut self.common_env);
verbfound = true;
break;
};
}
if verbfound {
cmd_ret cmd_ret
} else { } else {
Ok(None) Ok(None)

View file

@ -14,6 +14,8 @@ pub struct Audio {
raw_len_bytes: u32, raw_len_bytes: u32,
play_ptr_bytes: usize, play_ptr_bytes: usize,
framecount: u32, framecount: u32,
callback_id: Option<u32>,
callback_conn: u32,
} }
impl Audio { impl Audio {
pub fn new(xns: &xous_names::XousNames) -> Self { pub fn new(xns: &xous_names::XousNames) -> Self {
@ -30,15 +32,10 @@ impl Audio {
unsafe{ raw_header[i] = (*samples)[i] }; unsafe{ raw_header[i] = (*samples)[i] };
} }
log::trace!("setting up audio stream"); log::trace!("setting up codec hardware parameters");
codec.setup_8k_stream().expect("couldn't set the CODEC to expected defaults"); codec.setup_8k_stream().expect("couldn't set the CODEC to expected defaults");
log::trace!("getting a callback ID");
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap();
log::trace!("hooking frame callback");
codec.hook_frame_callback(0xDEAD_BEEF, callback_conn).unwrap(); // any non-handled IDs get routed to our callback port
log::trace!("returning from setup");
let mut audio = Audio { let audio = Audio {
codec, codec,
sample, sample,
header: Header::from(raw_header), header: Header::from(raw_header),
@ -46,33 +43,10 @@ impl Audio {
raw_len_bytes: unsafe{*(sample.as_ptr().add(40) as *const u32)}, raw_len_bytes: unsafe{*(sample.as_ptr().add(40) as *const u32)},
play_ptr_bytes: 0, play_ptr_bytes: 0,
framecount: 0, framecount: 0,
}; callback_id: None,
/* callback_conn: xns.request_connection_blocking(crate::SERVER_NAME_SHELLCHAT).unwrap(),
// load the initial sample data
let (play_free, _) = audio.codec.free_frames().unwrap();
let mut frames: FrameRing = FrameRing::new();
let frames_to_push = if frames.writeable_count() < play_free {
frames.writeable_count()
} else {
play_free
}; };
log::debug!("loading up {} frames", frames_to_push);
audio.framecount += frames_to_push as u32;
for i in 0..frames_to_push {
let mut frame: [u32; codec::FIFO_DEPTH] = [codec::ZERO_PCM as u32 | (codec::ZERO_PCM as u32) << 16; codec::FIFO_DEPTH];
for sample in frame.iter_mut() {
*sample = unsafe{audio.raw_data.add(i).read_volatile()};
}
audio.play_ptr_bytes += codec::FIFO_DEPTH * 4;
frames.nq_frame(frame).unwrap();
}
log::debug!("pushing frames");
audio.codec.swap_frames(&mut frames).unwrap();
// start the playing
log::debug!("starting playback");
audio.codec.resume().unwrap();
*/
audio audio
} }
} }
@ -80,7 +54,7 @@ impl Audio {
impl<'a> ShellCmdApi<'a> for Audio { impl<'a> ShellCmdApi<'a> for Audio {
cmd_api!(audio); cmd_api!(audio);
fn process(&mut self, args: String::<1024>, _env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> { fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
use core::fmt::Write; use core::fmt::Write;
let mut ret = String::<1024>::new(); let mut ret = String::<1024>::new();
@ -91,6 +65,13 @@ impl<'a> ShellCmdApi<'a> for Audio {
if let Some(sub_cmd) = tokens.next() { if let Some(sub_cmd) = tokens.next() {
match sub_cmd { match sub_cmd {
"play" => { "play" => {
if self.callback_id.is_none() {
let cb_id = env.register_handler(String::<256>::from_str(self.verb()));
log::trace!("hooking frame callback with ID {}", cb_id);
self.codec.hook_frame_callback(cb_id, self.callback_conn).unwrap(); // any non-handled IDs get routed to our callback port
self.callback_id = Some(cb_id);
}
write!(ret, "Playing sample...").unwrap(); write!(ret, "Playing sample...").unwrap();
// load the initial sample data // load the initial sample data
let (play_free, _) = self.codec.free_frames().unwrap(); let (play_free, _) = self.codec.free_frames().unwrap();

View file

@ -11,7 +11,6 @@ use xous::MessageEnvelope;
use xous_ipc::{String, Buffer}; use xous_ipc::{String, Buffer};
use heapless::spsc::Queue; use heapless::spsc::Queue;
use heapless::consts::U16;
mod cmds; mod cmds;
use cmds::*; use cmds::*;
@ -33,7 +32,7 @@ struct Repl {
msg: Option<MessageEnvelope>, msg: Option<MessageEnvelope>,
// record our input history // record our input history
history: Queue<History, U16>, history: Queue::<History, 16>,
content: Gid, content: Gid,
gam: gam::Gam, gam: gam::Gam,
@ -227,7 +226,7 @@ use num_traits::{ToPrimitive, FromPrimitive};
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
enum ShellOpcode { enum ShellOpcode {
/// a line of text has arrived /// a line of text has arrived
Line, Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks
/// redraw our UI /// redraw our UI
Redraw, Redraw,
/// exit the application /// exit the application
@ -259,7 +258,7 @@ pub(crate) const SERVER_NAME_SHELLCHAT: &str = "_Shell chat application_";
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Debug);
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();

View file

@ -4,6 +4,7 @@ pub mod api;
use xous::{CID, send_message}; use xous::{CID, send_message};
use num_traits::ToPrimitive; use num_traits::ToPrimitive;
#[derive(Debug)]
pub struct Trng { pub struct Trng {
conn: CID, conn: CID,
} }