mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-15 08:30:02 +00:00
Adds app mtxcli
Initial version of mtxcli is simply a copy of repl with the requisite manifest changes to make the app unique. Signed-off-by: Tom Marble <tmarble@info9.net>
This commit is contained in:
parent
be239f9812
commit
21908e9d01
12 changed files with 880 additions and 1 deletions
24
Cargo.lock
generated
24
Cargo.lock
generated
|
|
@ -2210,6 +2210,30 @@ dependencies = [
|
|||
"xous-ipc 0.9.13 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mtxcli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"codec",
|
||||
"com",
|
||||
"content-plugin-api",
|
||||
"gam",
|
||||
"graphics-server",
|
||||
"ime-plugin-api",
|
||||
"ime-plugin-shell",
|
||||
"llio",
|
||||
"locales",
|
||||
"log",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"trng",
|
||||
"xous 0.9.13 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"xous-api-log",
|
||||
"xous-api-names",
|
||||
"xous-api-ticktimer",
|
||||
"xous-ipc 0.9.13 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nb"
|
||||
version = "0.1.3"
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ default-members = [
|
|||
"services/dns",
|
||||
"services/modals",
|
||||
"services/usb-device-xous",
|
||||
"apps/mtxcli",
|
||||
]
|
||||
members = [
|
||||
"xous-ipc",
|
||||
|
|
@ -72,6 +73,7 @@ members = [
|
|||
"services/modals",
|
||||
"apps/ball",
|
||||
"apps/hello",
|
||||
"apps/mtxcli",
|
||||
"apps/repl",
|
||||
"apps/vault",
|
||||
"apps/vault/tools/vaultbackup-rs",
|
||||
|
|
@ -156,4 +158,4 @@ rev="36e419d05ce1d6957a3cc25092f2d68feba8e9a3" # use the commitref because we're
|
|||
#branch="0.16.20-cleanup"
|
||||
|
||||
# [patch.crates-io.xous]
|
||||
# path = "./xous-rs"
|
||||
# path = "./xous-rs"
|
||||
|
|
|
|||
|
|
@ -43,5 +43,16 @@
|
|||
"en-tts": "Basic REPL demo"
|
||||
}
|
||||
}
|
||||
},
|
||||
"mtxcli": {
|
||||
"context_name": "Matrix chat",
|
||||
"menu_name": {
|
||||
"appmenu.repl": {
|
||||
"en": "Matrix chat",
|
||||
"ja": "シンプルなMATRIXデモ",
|
||||
"zh": "基本 MATRIX 演示",
|
||||
"en-tts": "Basic MATRIX demo"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
30
apps/mtxcli/Cargo.toml
Normal file
30
apps/mtxcli/Cargo.toml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
[package]
|
||||
name = "mtxcli"
|
||||
version = "0.1.0"
|
||||
authors = ["bunnie <bunnie@kosagi.com>"]
|
||||
edition = "2018"
|
||||
description = "Matrix chat"
|
||||
|
||||
# Dependency versions enforced by Cargo.lock.
|
||||
[dependencies]
|
||||
log = "0.4.14"
|
||||
num-derive = {version = "0.3.3", default-features = false}
|
||||
num-traits = {version = "0.2.14", default-features = false}
|
||||
xous = "0.9.13"
|
||||
xous-ipc = "0.9.13"
|
||||
log-server = { package = "xous-api-log", version = "0.1.7" }
|
||||
ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.5" }
|
||||
xous-names = { package = "xous-api-names", version = "0.9.8" }
|
||||
gam = {path = "../../services/gam" }
|
||||
graphics-server = {path = "../../services/graphics-server" }
|
||||
trng = {path = "../../services/trng"}
|
||||
locales = {path = "../../locales"}
|
||||
ime-plugin-api = {path = "../../services/ime-plugin-api"}
|
||||
ime-plugin-shell = {path = "../../services/ime-plugin-shell"}
|
||||
content-plugin-api = {path = "../../services/content-plugin-api"} # all content canvas providers must provide this API
|
||||
com = {path = "../../services/com"}
|
||||
llio = {path = "../../services/llio"}
|
||||
codec = {path = "../../services/codec"}
|
||||
|
||||
[features]
|
||||
default = []
|
||||
68
apps/mtxcli/README.md
Normal file
68
apps/mtxcli/README.md
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
# MTXCLI
|
||||
|
||||
This is a new Matrix chat application which will be derived from REPL.
|
||||
|
||||
# Inherited from REPL
|
||||
|
||||
A simple demo application that provides a bare-bones REPL framework.
|
||||
## Copying This Demo to a New App
|
||||
|
||||
1. Copy this demo application, and rename the relevant structures in its `Cargo.toml` and `main.rs`.
|
||||
2. Add it to the Workspace `default-members` and `members` arrays by editing `./Cargo.toml`
|
||||
3. Edit the `manifest.json` file as documented in its [README](../README.md)
|
||||
4. Build using `cargo xtask app-image you_new_app` to create a flashable Xous image with your app in it.
|
||||
## Details
|
||||
|
||||

|
||||
|
||||
`repl` is a baseline demo application for Xous. It uses a chat-client
|
||||
style interface (stacking bubbles of text, with user input right-aligned
|
||||
and shell feedback left-aligned) to facilitate interactions.
|
||||
|
||||
It implements the basic envisioned structure of a Xous application, namely:
|
||||
|
||||
- Text input comes via the `ime-frontend`
|
||||
- Graphical output is rendered via the `gam`
|
||||
|
||||
[Push Events and Listeners](https://github.com/betrusted-io/xous-core/wiki/Push-Events-and-Listeners) provides an overview of the flow of
|
||||
messages between an Xous application and the Xous Services.
|
||||
|
||||
The one demo command provisioned in the `repl` app plays a tone via
|
||||
the `codec` service. This was chosen because it is about one of the most complicated
|
||||
and comprehensive things you can do in the `repl` environment, as it requires
|
||||
real-time callbacks to fill the audio buffer with new samples. If you have
|
||||
specific questions about how the callbacks work, we encourage you to open
|
||||
an issue in this repo and ask your question. Your questions will help us
|
||||
direct effort toward building the documentation base.
|
||||
|
||||
To make your own command, copy the `audio.rs` template
|
||||
in the `apps/repl/src/cmds/` directory, or use this very basic `echo`
|
||||
template:
|
||||
|
||||
```Rust
|
||||
use crate::{ShellCmdApi, CommonEnv};
|
||||
use xous_ipc::String;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Echo {
|
||||
}
|
||||
|
||||
impl<'a> ShellCmdApi<'a> for Echo {
|
||||
cmd_api!(echo); // inserts boilerplate for command API
|
||||
|
||||
fn process(&mut self, args: String::<1024>, _env: &mut CommonEnv) -> Result<Option<String::<1024>>, xous::Error> {
|
||||
Ok(Some(rest))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The "verb" is the name of your command, and it is the argument to the `cmd_api!()` macro.
|
||||
|
||||
`process()` is your "main" function, and `args` is a string which contains the
|
||||
rest of the line that was typed into the chat, minus the verb used to identify
|
||||
your command (e.g. the arguments, but not tokenized or parsed in
|
||||
any way). `env` contains some items in a common environment, for example, connections
|
||||
to the GAM, LLIO server or other resources required by your implementation.
|
||||
|
||||
Once you've added your command to the directory, go to the `cmds.rs` file, and follow
|
||||
the four-step instructions embedded within the file, starting around line 40.
|
||||
32
apps/mtxcli/locales/i18n.json
Normal file
32
apps/mtxcli/locales/i18n.json
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"mtxcli.greeting": {
|
||||
"en": "Welcome to the simple MTXCLI demo.",
|
||||
"ja": "シンプルなMTXCLIデモへようこそ",
|
||||
"zh": "简单的 mtxcli 演示活动",
|
||||
"en-tts": "Welcome to the simple MTXCLI demo."
|
||||
},
|
||||
"mtxcli.audio.start": {
|
||||
"en": "tone started...",
|
||||
"ja": "トーン開始…",
|
||||
"zh": "哔声开始...",
|
||||
"en-tts": "tone started..."
|
||||
},
|
||||
"mtxcli.audio.help": {
|
||||
"en": "audio [tone [freq [duration]]]",
|
||||
"ja": "オーディオ [ トーン [ 周波数 [ 間隔 ]]]",
|
||||
"zh": "audio [tone [音频 [时长]]]",
|
||||
"en-tts": "audio tone, then optional frequency plus optional duration."
|
||||
},
|
||||
"mtxcli.audio.completion_a": {
|
||||
"en": "Playback stopped at",
|
||||
"ja": "再生停止位置: ",
|
||||
"zh": "播放停止在",
|
||||
"en-tts": "Playback stopped at"
|
||||
},
|
||||
"mtxcli.audio.completion_b": {
|
||||
"en": "frames",
|
||||
"ja": "フレーム",
|
||||
"zh": "帧",
|
||||
"en-tts": "frames"
|
||||
}
|
||||
}
|
||||
BIN
apps/mtxcli/mtxcli_screenshot.png
Normal file
BIN
apps/mtxcli/mtxcli_screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.6 KiB |
219
apps/mtxcli/src/cmds.rs
Normal file
219
apps/mtxcli/src/cmds.rs
Normal 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
|
||||
}
|
||||
}
|
||||
185
apps/mtxcli/src/cmds/audio.rs
Normal file
185
apps/mtxcli/src/cmds/audio.rs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
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_MTXCLI).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
|
||||
|
||||
use std::num::ParseIntError;
|
||||
/// this will parse a simple decimal into an i32, multiplied by 1000
|
||||
/// we do this because the full f32 parsing stuff is pretty heavy, some
|
||||
/// 28kiB of code
|
||||
#[inline(never)]
|
||||
fn simple_kilofloat_parse(input: &str) -> core::result::Result<i32, ParseIntError> {
|
||||
if let Some((integer, fraction)) = input.split_once('.') {
|
||||
let mut result = integer.parse::<i32>()? * 1000;
|
||||
let mut significance = 100i32;
|
||||
for (place, digit) in fraction.chars().enumerate() {
|
||||
if place >= 3 {
|
||||
break;
|
||||
}
|
||||
if let Some(d) = digit.to_digit(10) {
|
||||
if result >= 0 {
|
||||
result += (d as i32) * significance;
|
||||
} else {
|
||||
result -= (d as i32) * significance;
|
||||
}
|
||||
significance /= 10;
|
||||
} else {
|
||||
return "z".parse::<i32>() // you can't create a ParseIntError any other way
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
let base = input.parse::<i32>()?;
|
||||
Ok(base * 1000)
|
||||
}
|
||||
}
|
||||
|
||||
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!("mtxcli.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 simple_kilofloat_parse(freq_str) {
|
||||
Ok(f) => (f as f32) / 1000.0,
|
||||
Err(_) => 440.0,
|
||||
}
|
||||
} else {
|
||||
440.0
|
||||
};
|
||||
let mut duration: f32 = if let Some(duration_str) = tokens.next() {
|
||||
simple_kilofloat_parse(duration_str).unwrap_or(500) as f32 / 1000.0
|
||||
} 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!("mtxcli.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!("mtxcli.audio.completion_a", xous::LANG),
|
||||
self.framecount,
|
||||
t!("mtxcli.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)
|
||||
}
|
||||
}
|
||||
91
apps/mtxcli/src/main.rs
Normal file
91
apps/mtxcli/src/main.rs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
#![cfg_attr(target_os = "none", no_std)]
|
||||
#![cfg_attr(target_os = "none", no_main)]
|
||||
|
||||
mod mtxcli;
|
||||
use mtxcli::*;
|
||||
mod cmds;
|
||||
use cmds::*;
|
||||
use num_traits::*;
|
||||
use xous_ipc::Buffer;
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
pub(crate) enum MtxcliOp {
|
||||
/// 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_MTXCLI: &str = "_Matrix chat_";
|
||||
|
||||
fn main() -> ! {
|
||||
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_MTXCLI, None).expect("can't register server");
|
||||
// log::trace!("registered with NS -- {:?}", sid);
|
||||
|
||||
let mut mtxcli = Mtxcli::new(&xns, sid);
|
||||
let mut update_mtxcli = 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(MtxcliOp::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!("mtxcli got input line: {}", s.as_str());
|
||||
mtxcli.input(s.as_str()).expect("MTXCLI couldn't accept input string");
|
||||
update_mtxcli = true; // set a flag, instead of calling here, so message can drop and calling server is released
|
||||
was_callback = false;
|
||||
}
|
||||
Some(MtxcliOp::Redraw) => {
|
||||
if allow_redraw {
|
||||
mtxcli.redraw().expect("MTXCLI couldn't redraw");
|
||||
}
|
||||
}
|
||||
Some(MtxcliOp::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(MtxcliOp::Quit) => {
|
||||
log::error!("got Quit");
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
log::trace!("got unknown message, treating as callback");
|
||||
mtxcli.msg(msg);
|
||||
update_mtxcli = true;
|
||||
was_callback = true;
|
||||
}
|
||||
}
|
||||
if update_mtxcli {
|
||||
mtxcli.update(was_callback).expect("MTXCLI had problems updating");
|
||||
update_mtxcli = 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)
|
||||
}
|
||||
215
apps/mtxcli/src/mtxcli.rs
Normal file
215
apps/mtxcli/src/mtxcli.rs
Normal 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 Mtxcli {
|
||||
// optional structures that indicate new input to the Mtxcli 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 Mtxcli{
|
||||
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_MTXCLI),
|
||||
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: MtxcliOp::Redraw.to_u32().unwrap(),
|
||||
gotinput_id: Some(MtxcliOp::Line.to_u32().unwrap()),
|
||||
audioframe_id: None,
|
||||
rawkeys_id: None,
|
||||
focuschange_id: Some(MtxcliOp::ChangeFocus.to_u32().unwrap()),
|
||||
}).expect("couldn't register Ux context for mtxcli");
|
||||
|
||||
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");
|
||||
Mtxcli {
|
||||
input: None,
|
||||
msg: None,
|
||||
history: vec![History{text: String::from(t!("mtxcli.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!("mtxcli app redraw##");
|
||||
self.gam.redraw().expect("couldn't redraw screen");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -43,6 +43,7 @@ pub const APP_NAME_SHELLCHAT: &'static str = "shellchat";
|
|||
pub const APP_MENU_NAME: &'static str = "app menu";
|
||||
pub const KBD_MENU_NAME: &'static str = "keyboard menu";
|
||||
pub const WIFI_MENU_NAME: &'static str = "WLAN menu";
|
||||
pub const APP_NAME_MTXCLI: &'static str = "mtxcli";
|
||||
|
||||
/// UX context registry. Names here are authorized by the GAM to have Canvases.
|
||||
pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[
|
||||
|
|
@ -57,6 +58,7 @@ pub const EXPECTED_BOOT_CONTEXTS: &[&'static str] = &[
|
|||
APP_MENU_NAME,
|
||||
KBD_MENU_NAME,
|
||||
WIFI_MENU_NAME,
|
||||
APP_NAME_MTXCLI,
|
||||
];
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
|
|
|
|||
Loading…
Reference in a new issue