add also the new files associated with the vault

This commit is contained in:
bunnie 2022-05-28 01:20:05 +08:00
parent 81f823ff34
commit 389ea55b00
6 changed files with 777 additions and 0 deletions

23
apps/vault/Cargo.toml Normal file
View file

@ -0,0 +1,23 @@
[package]
name = "vault"
version = "0.1.0"
edition = "2018"
[dependencies]
log = "0.4.14"
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
xous = { path = "../../xous-rs" }
xous-ipc = { path = "../../xous-ipc" }
log-server = { path = "../../services/log-server" }
xous-names = { path = "../../services/xous-names" }
gam = {path = "../../services/gam" }
graphics-server = {path = "../../services/graphics-server" }
locales = {path = "../../locales"}
tts-frontend = {path="../../services/tts"}
usb-device-xous = {path="../../services/usb-device-xous"}
usbd-human-interface-device = {git="https://github.com/betrusted-io/usbd-human-interface-device.git", branch="main"}
[features]
tts = []
default = []

View file

@ -0,0 +1,8 @@
{
"helloworld.hello": {
"en": "Hello World!",
"ja": "Hello World!",
"zh": "大家好!",
"en-tts": "Hello World!"
}
}

219
apps/vault/src/cmds.rs Normal file
View file

@ -0,0 +1,219 @@
use xous::{MessageEnvelope};
use xous_ipc::String;
use core::fmt::Write;
use std::collections::HashMap;
/////////////////////////// Common items to all commands
pub trait ShellCmdApi<'a> {
// user implemented:
// called to process the command with the remainder of the string attached
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error>;
// called to process incoming messages that may have been origniated by the most recently issued command
fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
log::info!("received unhandled message {:?}", msg);
Ok(None)
}
// created with cmd_api! macro
// checks if the command matches the current verb in question
fn matches(&self, verb: &str) -> bool;
// returns my verb
fn verb(&self) -> &'static str;
}
// the argument to this macro is the command verb
macro_rules! cmd_api {
($verb:expr) => {
fn verb(&self) -> &'static str {
stringify!($verb)
}
fn matches(&self, verb: &str) -> bool {
if verb == stringify!($verb) {
true
} else {
false
}
}
};
}
use trng::*;
/////////////////////////// Command shell integration
#[derive(Debug)]
#[allow(dead_code)] // there's more in the envornment right now than we need for the demo
pub struct CommonEnv {
llio: llio::Llio,
com: com::Com,
codec: codec::Codec,
ticktimer: ticktimer_server::Ticktimer,
gam: gam::Gam,
cb_registrations: HashMap::<u32, String::<256>>,
trng: Trng,
xns: xous_names::XousNames,
}
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);
key
}
}
/*
To add a new command:
0. ensure that the command implements the ShellCmdApi (above)
1. mod/use the new command
2. create an entry for the command's storage in the CmdEnv structure
3. initialize the persistant storage here
4. add it to the "commands" array in the dispatch() routine below
Side note: if your command doesn't require persistent storage, you could,
technically, generate the command dynamically every time it's called.
*/
///// 1. add your module here, and pull its namespace into the local crate
mod audio; use audio::*;
pub struct CmdEnv {
common_env: CommonEnv,
lastverb: String::<256>,
///// 2. declare storage for your command here.
audio_cmd: Audio,
}
impl CmdEnv {
pub fn new(xns: &xous_names::XousNames) -> CmdEnv {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
log::info!("creating CommonEnv");
let common = CommonEnv {
llio: llio::Llio::new(&xns),
com: com::Com::new(&xns).expect("could't connect to COM"),
codec: codec::Codec::new(&xns).expect("couldn't connect to CODEC"),
ticktimer,
gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"),
cb_registrations: HashMap::new(),
trng: Trng::new(&xns).unwrap(),
xns: xous_names::XousNames::new().unwrap(),
};
log::info!("done creating CommonEnv");
CmdEnv {
common_env: common,
lastverb: String::<256>::new(),
///// 3. initialize your storage, by calling new()
audio_cmd: Audio::new(&xns),
}
}
pub fn dispatch(&mut self, maybe_cmdline: Option<&mut String::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result<Option<String::<1024>>, xous::Error> {
let mut ret = String::<1024>::new();
let commands: &mut [& mut dyn ShellCmdApi] = &mut [
///// 4. add your command to this array, so that it can be looked up and dispatched
&mut self.audio_cmd,
];
if let Some(cmdline) = maybe_cmdline {
let maybe_verb = tokenize(cmdline);
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None);
if let Some(verb_string) = maybe_verb {
let verb = verb_string.to_str();
// search through the list of commands linearly until one matches,
// then run it.
let mut match_found = false;
for cmd in commands.iter_mut() {
if cmd.matches(verb) {
match_found = true;
cmd_ret = cmd.process(*cmdline, &mut self.common_env);
self.lastverb.clear();
write!(self.lastverb, "{}", verb).expect("couldn't record last verb");
};
}
// if none match, create a list of available commands
if !match_found {
let mut first = true;
write!(ret, "Commands: ").unwrap();
for cmd in commands.iter() {
if !first {
ret.append(", ")?;
}
ret.append(cmd.verb())?;
first = false;
}
Ok(Some(ret))
} else {
cmd_ret
}
} else {
Ok(None)
}
} else if let Some(callback) = maybe_callback {
let mut cmd_ret: Result<Option<String::<1024>>, xous::Error> = Ok(None);
// first check and see if we have a callback registration; if not, just map to the last verb
let verb = match self.common_env.cb_registrations.get(&(callback.body.id() as u32)) {
Some(verb) => {
verb.to_str()
},
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
} else {
Ok(None)
}
} else {
Ok(None)
}
}
}
/// extract the first token, as delimited by spaces
/// modifies the incoming line by removing the token and returning the remainder
/// returns the found token
pub fn tokenize(line: &mut String::<1024>) -> Option<String::<1024>> {
let mut token = String::<1024>::new();
let mut retline = String::<1024>::new();
let lineiter = line.as_str().unwrap().chars();
let mut foundspace = false;
let mut foundrest = false;
for ch in lineiter {
if ch != ' ' && !foundspace {
token.push(ch).unwrap();
} else if foundspace && foundrest {
retline.push(ch).unwrap();
} else if foundspace && ch != ' ' {
// handle case of multiple spaces in a row
foundrest = true;
retline.push(ch).unwrap();
} else {
foundspace = true;
// consume the space
}
}
line.clear();
write!(line, "{}", retline.as_str().unwrap()).unwrap();
if token.len() > 0 {
Some(token)
} else {
None
}
}

View file

@ -0,0 +1,154 @@
use crate::{ShellCmdApi,CommonEnv};
use xous_ipc::String;
use xous::{MessageEnvelope, Message};
use codec::*;
use core::fmt::Write;
use locales::t;
#[derive(Debug)]
pub struct Audio {
callback_id: Option<u32>,
callback_conn: u32,
framecount: u32,
play_sample: f32, // count of play samples generated. in f32 to avoid int<->f32 conversions
freq: f32,
}
impl Audio {
pub fn new(xns: &xous_names::XousNames) -> Self {
let callback_conn = xns.request_connection_blocking(crate::SERVER_NAME_REPL).unwrap();
Audio {
callback_id: None,
callback_conn,
framecount: 0,
play_sample: 0.0,
freq: 440.0,
}
}
}
const STOP_ID: usize = 1;
const SAMPLE_RATE_HZ: f32 = 8000.0;
// note to self: A4 = 440.0, E4 = 329.63, C4 = 261.63
impl<'a> ShellCmdApi<'a> for Audio {
cmd_api!(audio);
fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
let mut ret = String::<1024>::new();
let helpstring = t!("replapp.audio.help", xous::LANG);
let mut tokens = args.as_str().unwrap().split(' ');
if let Some(sub_cmd) = tokens.next() {
match sub_cmd {
"tone" => {
self.freq = if let Some(freq_str) = tokens.next() {
match freq_str.parse::<f32>() {
Ok(f) => f,
Err(_) => 440.0,
}
} else {
440.0
};
let mut duration: f32 = if let Some(duration_str) = tokens.next() {
duration_str.parse::<f32>().unwrap_or(0.5)
} else {
0.5
};
if duration > 10.0 {
duration = 10.0; // sanity check the duration so we don't go nuts
}
env.codec.setup_8k_stream().expect("couldn't set the CODEC to expected defaults");
env.ticktimer.sleep_ms(50).unwrap();
env.codec.set_speaker_volume(VolumeOps::RestoreDefault, None).unwrap();
env.codec.set_headphone_volume(VolumeOps::RestoreDefault, None).unwrap();
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);
env.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);
}
self.play_sample = 0.0;
env.codec.resume().unwrap();
// kick off a thread that stops the playback, after the designated delay
std::thread::spawn({
let cb_id = self.callback_id.unwrap().clone();
let conn = self.callback_conn.clone();
let duration = duration.clone();
move || {
let ticktimer = ticktimer_server::Ticktimer::new().unwrap();
ticktimer.sleep_ms((duration * 1000.0) as usize).unwrap();
xous::send_message(conn, Message::new_scalar(cb_id as usize, 0, 0, 0, STOP_ID)).unwrap();
}
});
write!(ret, "{}", t!("replapp.audio.start", xous::LANG)).unwrap();
}
_ => {
write!(ret, "{}", helpstring).unwrap();
}
}
}
Ok(Some(ret))
}
fn callback(&mut self, msg: &MessageEnvelope, env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
const AMPLITUDE: f32 = 0.8;
match &msg.body {
Message::Scalar(xous::ScalarMessage{id: _, arg1: free_play, arg2: _avail_rec, arg3: _, arg4: routing_id}) => {
if *routing_id == codec::AUDIO_CB_ROUTING_ID {
let mut frames: FrameRing = FrameRing::new();
let frames_to_push = if frames.writeable_count() < *free_play {
frames.writeable_count()
} else {
*free_play
};
self.framecount += frames_to_push as u32;
log::debug!("f{} p{}", self.framecount, frames_to_push);
for _ in 0..frames_to_push {
let mut frame: [u32; codec::FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; codec::FIFO_DEPTH];
// put the "expensive" f32 comparison outside the cosine wave table computation loop
let omega = self.freq * 2.0 * std::f32::consts::PI / SAMPLE_RATE_HZ;
for sample in frame.iter_mut() {
let raw_sine: i16 = (AMPLITUDE * f32::cos( self.play_sample * omega ) * i16::MAX as f32) as i16;
let left = raw_sine as u16;
let right = raw_sine as u16;
*sample = right as u32 | (left as u32) << 16;
self.play_sample += 1.0;
}
frames.nq_frame(frame).unwrap();
}
env.codec.swap_frames(&mut frames).unwrap();
} else if *routing_id == STOP_ID {
let mut ret = String::<1024>::new();
env.codec.abort().unwrap(); // this should stop callbacks from occurring too.
write!(ret, "{} {} {}.",
t!("replapp.audio.completion_a", xous::LANG),
self.framecount,
t!("replapp.audio.completion_b", xous::LANG),
).unwrap();
self.framecount = 0;
self.play_sample = 0.0;
env.codec.power_off().unwrap();
return Ok(Some(ret));
}
},
Message::Move(_mm) => {
log::error!("received memory message when not expected")
},
_ => {
log::error!("received unknown callback type")
}
}
Ok(None)
}
}

158
apps/vault/src/main.rs Normal file
View file

@ -0,0 +1,158 @@
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
mod repl;
use repl::*;
mod cmds;
use cmds::*;
use num_traits::*;
use xous_ipc::Buffer;
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum VaultOp {
/// a line of text has arrived
Line = 0, // make sure we occupy opcodes with discriminants < 1000, as the rest are used for callbacks
/// redraw our UI
Redraw,
/// change focus
ChangeFocus,
/// exit the application
Quit,
}
// This name should be (1) unique (2) under 64 characters long and (3) ideally descriptive.
pub(crate) const SERVER_NAME_VAULT: &str = "Authentication Vault";
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
// unlimited connections allowed, this is a user app and it's up to the app to decide its policy
let sid = xns.register_name(SERVER_NAME_VAULT, None).expect("can't register server");
// log::trace!("registered with NS -- {:?}", sid);
let mut repl = Repl::new(&xns, sid);
let mut update_repl = true;
let mut was_callback = false;
let mut allow_redraw = false;
loop {
let msg = xous::receive_message(sid).unwrap();
log::debug!("got message {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(VaultOp::Line) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let s = buffer.as_flat::<xous_ipc::String<4000>, _>().unwrap();
log::trace!("repl got input line: {}", s.as_str());
repl.input(s.as_str()).expect("Vault couldn't accept input string");
update_repl = true; // set a flag, instead of calling here, so message can drop and calling server is released
was_callback = false;
}
Some(VaultOp::Redraw) => {
if allow_redraw {
repl.redraw().expect("Vault couldn't redraw");
}
}
Some(VaultOp::ChangeFocus) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, {
let new_state = gam::FocusState::convert_focus_change(new_state_code);
match new_state {
gam::FocusState::Background => {
allow_redraw = false;
}
gam::FocusState::Foreground => {
allow_redraw = true;
}
}
}),
Some(VaultOp::Quit) => {
log::error!("got Quit");
break;
}
_ => {
log::trace!("got unknown message, treating as callback");
repl.msg(msg);
update_repl = true;
was_callback = true;
}
}
if update_repl {
repl.update(was_callback).expect("Vault had problems updating");
update_repl = false;
}
log::trace!("reached bottom of main loop");
}
// clean up our program
log::error!("main loop exit, destroying servers");
xns.unregister_server(sid).unwrap();
xous::destroy_server(sid).unwrap();
log::trace!("quitting");
xous::terminate_process(0)
}
/*
mod api;
use api::*;
mod ctap;
use ctap::hid::{ChannelID, CtapHid, KeepaliveStatus, ProcessedPacket};
use ctap::status_code::Ctap2StatusCode;
use ctap::CtapState;
use num_traits::*;
use std::thread;
use usbd_human_interface_device::device::fido::*;
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Trace);
log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
// TODO: figure out what, if any, should be the limit of connections to the U2F server?
let u2f_sid = xns.register_name(api::SERVER_NAME_U2F, None).expect("can't register server");
log::trace!("registered with NS -- {:?}", u2f_sid);
let _ = thread::spawn({
move || {
let usb = usb_device_xous::UsbHid::new();
loop {
match usb.u2f_wait_incoming() {
Ok(msg) => {
log::info!("FIDO listener got message: {:?}", msg);
}
Err(e) => {
log::warn!("FIDO listener got an error: {:?}", e);
}
}
}
}
});
let mut ctap_state = CtapState::new(&mut rng, check_user_presence, boot_time);
let mut ctap_hid = CtapHid::new();
loop {
let msg = xous::receive_message(u2f_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::Quit) => {
log::warn!("Quit received, goodbye world!");
break;
},
None => {
log::error!("couldn't convert opcode: {:?}", msg);
}
}
}
// clean up our program
log::trace!("main loop exit, destroying servers");
xns.unregister_server(u2f_sid).unwrap();
xous::destroy_server(u2f_sid).unwrap();
log::trace!("quitting");
xous::terminate_process(0)
}
*/

215
apps/vault/src/repl.rs Normal file
View file

@ -0,0 +1,215 @@
use super::*;
use gam::UxRegistration;
use graphics_server::{Gid, Point, Rectangle, TextBounds, TextView, DrawStyle, PixelColor};
use graphics_server::api::GlyphStyle;
use xous::MessageEnvelope;
use core::fmt::Write;
use locales::t;
#[derive(Debug)]
struct History {
// the history record
pub text: String,
// if true, this was input from the user; if false, it's a response from the shell
pub is_input: bool,
}
#[allow(dead_code)]
pub(crate) struct Repl {
// optional structures that indicate new input to the Repl loop per iteration
// an input string
input: Option<String>,
// messages from other servers
msg: Option<MessageEnvelope>,
// record our input history
history: Vec::<History>,
history_len: usize,
content: Gid,
gam: gam::Gam,
// variables that define our graphical attributes
screensize: Point,
bubble_width: u16,
margin: Point, // margin to edge of canvas
bubble_margin: Point, // margin of text in bubbles
bubble_radius: u16,
bubble_space: i16, // spacing between text bubbles
// command environment
env: CmdEnv,
// our security token for making changes to our record on the GAM
token: [u32; 4],
}
impl Repl{
pub(crate) fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self {
let gam = gam::Gam::new(xns).expect("can't connect to GAM");
let token = gam.register_ux(UxRegistration {
app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_REPL),
ux_type: gam::UxType::Chat,
predictor: Some(xous_ipc::String::<64>::from_str(ime_plugin_shell::SERVER_NAME_IME_PLUGIN_SHELL)),
listener: sid.to_array(), // note disclosure of our SID to the GAM -- the secret is now shared with the GAM!
redraw_id: ReplOp::Redraw.to_u32().unwrap(),
gotinput_id: Some(ReplOp::Line.to_u32().unwrap()),
audioframe_id: None,
rawkeys_id: None,
focuschange_id: Some(ReplOp::ChangeFocus.to_u32().unwrap()),
}).expect("couldn't register Ux context for repl");
let content = gam.request_content_canvas(token.unwrap()).expect("couldn't get content canvas");
let screensize = gam.get_canvas_bounds(content).expect("couldn't get dimensions of content canvas");
Repl {
input: None,
msg: None,
history: vec![History{text: String::from(t!("replapp.greeting", xous::LANG)), is_input: false}],
history_len: 10,
content,
gam,
screensize,
bubble_width: ((screensize.x / 5) * 4) as u16, // 80% width for the text bubbles
margin: Point::new(4, 4),
bubble_margin: Point::new(4, 4),
bubble_radius: 4,
bubble_space: 4,
env: CmdEnv::new(xns),
token: token.unwrap(),
}
}
/// accept a new input string
pub(crate) fn input(&mut self, line: &str) -> Result<(), xous::Error> {
self.input = Some(String::from(line));
Ok(())
}
pub(crate) fn msg(&mut self, message: MessageEnvelope) {
self.msg = Some(message);
}
fn circular_push(&mut self, item: History) {
if self.history.len() >= self.history_len {
self.history.remove(0);
}
self.history.push(item);
}
/// update the loop, in response to various inputs
pub(crate) fn update(&mut self, was_callback: bool) -> Result<(), xous::Error> {
// if we had an input string, do something
if let Some(local) = &self.input {
let input_history = History {
text: local.to_string(),
is_input: true,
};
self.circular_push(input_history);
}
// AT THIS POINT: if we have other inputs, update accordingly
// other inputs might be, for example, events that came in from other servers that would
// side effect our commands
// redraw UI once upon accepting all input
if !was_callback { // don't need to redraw on a callback, save some cycles
self.redraw().expect("can't redraw");
}
let mut dirty = true;
// take the input and pass it on to the various command parsers, and attach result
if let Some(local) = &self.input {
if let Some(res) = self.env.dispatch(Some(&mut xous_ipc::String::<1024>::from_str(&local)), None).expect("command dispatch failed") {
let output_history = History {
text: String::from(res.as_str().unwrap_or("UTF-8 Error")),
is_input: false
};
self.circular_push(output_history);
} else {
dirty = false;
}
} else if let Some(msg) = &self.msg {
if let Some(res) = self.env.dispatch(None, Some(msg)).expect("callback failed") {
let output_history = History {
text: String::from(res.as_str().unwrap_or("UTF-8 Error")),
is_input: false
};
self.circular_push(output_history);
} else {
dirty = false;
}
}
// clear all the inputs to the loop, so we don't process them twice
self.input = None;
self.msg = None;
// redraw UI now that we've responded
if dirty {
self.redraw().expect("can't redraw");
}
Ok(())
}
fn clear_area(&self) {
self.gam.draw_rectangle(self.content,
Rectangle::new_with_style(Point::new(0, 0), self.screensize,
DrawStyle {
fill_color: Some(PixelColor::Light),
stroke_color: None,
stroke_width: 0
}
)).expect("can't clear content area");
}
pub(crate) fn redraw(&mut self) -> Result<(), xous::Error> {
self.clear_area();
// this defines the bottom border of the text bubbles as they stack up wards
let mut bubble_baseline = self.screensize.y - self.margin.y;
// iterator returns from oldest to newest
// .rev() iterator is from newest to oldest
for h in self.history.iter().rev() {
let mut bubble_tv =
if h.is_input {
TextView::new(self.content,
TextBounds::GrowableFromBr(
Point::new(self.screensize.x - self.margin.x, bubble_baseline),
self.bubble_width))
} else {
TextView::new(self.content,
TextBounds::GrowableFromBl(
Point::new(self.margin.x, bubble_baseline),
self.bubble_width))
};
if h.is_input {
bubble_tv.border_width = 1;
} else {
bubble_tv.border_width = 2;
}
bubble_tv.draw_border = true;
bubble_tv.clear_area = true;
bubble_tv.rounded_border = Some(self.bubble_radius);
bubble_tv.style = GlyphStyle::Regular;
bubble_tv.margin = self.bubble_margin;
bubble_tv.ellipsis = false; bubble_tv.insertion = None;
write!(bubble_tv.text, "{}", h.text.as_str()).expect("couldn't write history text to TextView");
self.gam.post_textview(&mut bubble_tv).expect("couldn't render bubble textview");
if let Some(bounds) = bubble_tv.bounds_computed {
// we only subtract 1x of the margin because the bounds were computed from a "bottom right" that already counted
// the margin once.
bubble_baseline -= (bounds.br.y - bounds.tl.y) + self.bubble_space + self.bubble_margin.y;
if bubble_baseline <= 0 {
// don't draw history that overflows the top of the screen
break;
}
} else {
break; // we get None on the bounds computed if the text view fell off the top of the screen
}
}
log::trace!("repl app redraw##");
self.gam.redraw().expect("couldn't redraw screen");
Ok(())
}
}