Merge pull request #191 from gsora/gsora/backlight-on-keypress

Automatic backlight on keypress
This commit is contained in:
bunnie 2022-06-17 23:55:44 +08:00 committed by GitHub
commit 6d2531804b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 270 additions and 4 deletions

View file

@ -3,3 +3,6 @@ xtask = "run --package xtask --"
# [net]
# offline = true # do not access the network
[build]
rustflags = ["--cfg", "crossbeam_no_atomic_64"]

25
Cargo.lock generated
View file

@ -614,6 +614,20 @@ dependencies = [
"riscv 0.7.0",
]
[[package]]
name = "crossbeam"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae5588f6b3c3cb05239e90bd110f257254aecd01e4635400391aeae07497845"
dependencies = [
"cfg-if 1.0.0",
"crossbeam-channel",
"crossbeam-deque",
"crossbeam-epoch",
"crossbeam-queue",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.4"
@ -649,6 +663,16 @@ dependencies = [
"scopeguard",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f25d8400f4a7a5778f0e4e52384a48cbd9b5c495d110786187fc750075277a2"
dependencies = [
"cfg-if 1.0.0",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.8"
@ -3264,6 +3288,7 @@ dependencies = [
"chrono",
"com",
"content-plugin-api",
"crossbeam",
"gam",
"graphics-server",
"keyboard",

View file

@ -60,6 +60,9 @@ pub(crate) enum Opcode {
/// request for raw keyups/downs
RegisterRawListener = 3,
/// request for updates for *when* keyboard is pressed
RegisterKeyObserver = 12,
/// set repeat delay, rate; both in ms
SetRepeat = 4, //(u32, u32),

View file

@ -41,6 +41,16 @@ impl Keyboard {
.expect("couldn't register listener");
}
pub fn register_observer(&self, server_name: &str, action_opcode: usize) {
let kr = KeyboardRegistration {
server_name: String::<64>::from_str(server_name),
listener_op_id: action_opcode
};
let buf = Buffer::into_buf(kr).unwrap();
buf.lend(self.conn, Opcode::RegisterKeyObserver.to_u32().unwrap())
.expect("couldn't register listener");
}
pub fn set_vibe(&self, enable: bool) -> Result<(), xous::Error> {
let ena =
if enable { 1 }

View file

@ -760,6 +760,8 @@ fn main() -> ! {
let mut listener_op: Option<usize> = None;
let mut raw_listener_conn: Option<CID> = None;
let mut raw_listener_op: Option<u32> = None;
let mut observer_conn: Option<CID> = None;
let mut observer_op: Option<usize> = None;
let mut vibe = false;
let llio = llio::Llio::new(&xns);
@ -834,6 +836,21 @@ fn main() -> ! {
}
}
},
Some(Opcode::RegisterKeyObserver) => {
let buffer = unsafe{Buffer::from_memory_message(msg.body.memory_message().unwrap())};
let kr = buffer.as_flat::<KeyboardRegistration, _>().unwrap();
match xns.request_connection_blocking(kr.server_name.as_str()) {
Ok(cid) => {
observer_conn = Some(cid);
observer_op = Some(kr.listener_op_id as usize);
}
Err(e) => {
log::error!("couldn't connect to observer: {:?}", e);
observer_conn = None;
observer_op = None;
}
}
},
Some(Opcode::SelectKeyMap) => msg_scalar_unpack!(msg, km, _, _, _, {
kbd.set_map(KeyMap::from(km))
}),
@ -942,6 +959,20 @@ fn main() -> ! {
).unwrap();
}
}
if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key");
xous::send_message(observer_conn.unwrap(),
xous::Message::new_scalar(
observer_op.unwrap(),
0,
0,
0,
0,
)
).expect("couldn't send key codes to listener");
}
#[cfg(all(feature="debuginject", not(feature="rawserial")))]
for listener in blocking_listener.drain(..) {
// we must unblock anyways once the key is hit; even if the key is invalid,
@ -970,6 +1001,19 @@ fn main() -> ! {
buf.lend(raw_listener_conn.unwrap(), raw_listener_op.unwrap()).expect("couldn't send raw scancodes");
}
if observer_conn.is_some() && observer_op.is_some() {
log::trace!("sending observer key");
xous::send_message(observer_conn.unwrap(),
xous::Message::new_scalar(
observer_op.unwrap(),
0,
0,
0,
0,
)
).expect("couldn't send key codes to listener");
}
// interpret scancodes
// the track_* functions track the keyup/keydowns to modify keys with shift, hold, and chord state
let kc: Vec<char> = match kbd.get_map() {

View file

@ -34,6 +34,7 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics
chrono = {version = "0.4.19", default-features = false, features = ["std"]}
sntpc = {version = "0.3.1"} #, features = ["log"]
crossbeam = "0.8.1"
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = {path = "../../utralib"}

View file

@ -90,6 +90,14 @@
"zh": "背光关闭",
"en-tts": "🔇"
},
"mainmenu.autobacklighton": {
"en": "Automatic backlight on",
"en-tts": "🔇"
},
"mainmenu.autobacklightoff": {
"en": "Automatic backlight off",
"en-tts": "🔇"
},
"mainmenu.init_keys": {
"en": "Initialize root keys",
"ja": "ルートキーの初期化",

View file

@ -19,6 +19,7 @@ use graphics_server::api::GlyphStyle;
use locales::t;
use gam::{GamObjectList, GamObjectType};
use chrono::prelude::*;
use crossbeam::channel::{at, select, unbounded, Receiver, Sender};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@ -31,6 +32,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
const SERVER_NAME_STATUS_GID: &str = "_Status bar GID receiver_";
const SERVER_NAME_STATUS: &str = "_Status_";
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum StatusOpcode {
@ -56,6 +58,17 @@ pub(crate) enum StatusOpcode {
/// Set the keyboard map
SetKeyboard,
/// Tells keyboard watching thread that a new keypress happened.
Keypress,
/// Turns backlight off.
TurnLightsOff,
/// Turns backlight on.
TurnLightsOn,
/// Enables automatic backlight handling.
EnableAutomaticBacklight,
/// Disables automatic backlight handling.
DisableAutomaticBacklight,
/// Suspend handler from the main menu
TrySuspend,
/// Ship mode handler for the main menu
@ -149,7 +162,8 @@ fn wrapped_main() -> ! {
log::debug!("|status: registering GAM|status thread");
let status_sid = xous::create_server().unwrap(); // completely private to this crate
// allow only one connection, from keyboard to us.
let status_sid = xns.register_name(SERVER_NAME_STATUS, Some(1)).unwrap();
// create a connection for callback hooks
let cb_cid = xous::connect(status_sid).unwrap();
unsafe { CB_TO_MAIN_CONN = Some(cb_cid) };
@ -345,7 +359,9 @@ fn wrapped_main() -> ! {
let modals = modals::Modals::new(&xns).unwrap();
log::debug!("starting main menu thread");
create_main_menu(keys.clone(), xous::connect(status_sid).unwrap(), &com, time_cid);
let main_menu_sid = xous::create_server().unwrap();
let status_cid = xous::connect(status_sid).unwrap();
let menu_manager = create_main_menu(keys.clone(), main_menu_sid, status_cid, &com, time_cid);
create_app_menu(xous::connect(status_sid).unwrap());
let kbd_mgr = xous::create_server().unwrap();
let kbd_menumatic = create_kbd_menu(xous::connect(status_sid).unwrap(), kbd_mgr);
@ -371,11 +387,77 @@ fn wrapped_main() -> ! {
#[cfg(any(target_os = "none", target_os = "xous"))]
llio.clear_wakeup_alarm().unwrap(); // this is here to clear any wake-up alarms that were set by a prior coldboot command
// Automatic backlight-related variables.
kbd.register_observer(
SERVER_NAME_STATUS,
StatusOpcode::Keypress.to_u32().unwrap() as usize,
);
let enabled = Arc::new(Mutex::new(false));
let (tx, rx): (Sender<BacklightThreadOps>, Receiver<BacklightThreadOps>) = unbounded();
let rx = Box::new(rx);
let thread_already_running = Arc::new(Mutex::new(false));
let thread_conn = xous::connect(status_sid).unwrap();
pump_run.store(true, Ordering::Relaxed); // start status thread updating
loop {
let msg = xous::receive_message(status_sid).unwrap();
log::trace!("|status: Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
// TODO: handle tts
Some(StatusOpcode::EnableAutomaticBacklight) => {
*enabled.lock().unwrap() = true;
// second: delete the first three elements off the menu
menu_manager.delete_item(t!("mainmenu.backlighton", xous::LANG));
menu_manager.delete_item(t!("mainmenu.backlightoff", xous::LANG));
menu_manager.delete_item(t!("mainmenu.autobacklighton", xous::LANG));
// third: add a "disable automatic backlight element"
menu_manager.insert_item(gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)),
action_conn: Some(status_cid),
action_opcode: StatusOpcode::DisableAutomaticBacklight.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
}, 0);
}
Some(StatusOpcode::DisableAutomaticBacklight) => {
*enabled.lock().unwrap() = false;
tx.send(BacklightThreadOps::Stop).unwrap();
// second: delete the first element off the menu.
menu_manager.delete_item(t!("mainmenu.autobacklightoff", xous::LANG));
// third: construct an array of the new elements to add to the menu.
let new_elems = [
gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.backlighton", xous::LANG)),
action_conn: Some(com.conn()),
action_opcode: com.getop_backlight(),
action_payload: gam::MenuPayload::Scalar([191 >> 3, 191 >> 3, 0, 0]),
close_on_select: true,
},
gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.backlightoff", xous::LANG)),
action_conn: Some(com.conn()),
action_opcode: com.getop_backlight(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
},
gam::MenuItem {
name: xous_ipc::String::from_str(t!("mainmenu.autobacklighton", xous::LANG)),
action_conn: Some(status_cid),
action_opcode: StatusOpcode::EnableAutomaticBacklight.to_u32().unwrap(),
action_payload: gam::MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
}
];
new_elems.iter().enumerate().for_each(|(index, element)| {let _ = menu_manager.insert_item(*element, index);});
}
Some(StatusOpcode::BattStats) => msg_scalar_unpack!(msg, lo, hi, _, _, {
stats = [lo, hi].into();
battstats_tv.clear_str();
@ -672,6 +754,40 @@ fn wrapped_main() -> ! {
com.power_off_soc().unwrap();
}
},
Some(StatusOpcode::Keypress) => {
if !*enabled.lock().unwrap() {
log::trace!("ignoring keypress, automatic backlight is disabled");
continue
}
let mut run_lock = thread_already_running.lock().unwrap();
match *run_lock {
true => {
log::trace!("renewing backlight timer");
tx.send(BacklightThreadOps::Renew).unwrap();
continue
},
false => {
*run_lock = true;
com.set_backlight(255, 128).expect("cannot set backlight on");
std::thread::spawn({
let rx = rx.clone();
move || turn_lights_on(rx, thread_conn)
});
},
}
}
Some(StatusOpcode::TurnLightsOn) => {
log::trace!("turning lights on");
com.set_backlight(255, 128).expect("cannot set backlight on");
},
Some(StatusOpcode::TurnLightsOff) => {
log::trace!("turning lights off");
let mut run_lock = thread_already_running.lock().unwrap();
*run_lock = false;
com.set_backlight(0, 0).expect("cannot set backlight off");
},
Some(StatusOpcode::Quit) => {
break;
}
@ -695,3 +811,41 @@ fn wrapped_main() -> ! {
xous::terminate_process(0)
}
enum BacklightThreadOps {
/// Renew renews the backlight timer for another instance of standard_duration.
Renew,
/// Stop stops the background backlight thread.
Stop,
}
fn turn_lights_on(rx: Box<Receiver<BacklightThreadOps>>, cid: xous::CID) {
let standard_duration = std::time::Duration::from_secs(10);
let mut timeout = std::time::Instant::now() + standard_duration;
let mut total_waited = 0;
loop {
select! {
recv(rx) -> op => {
match op.unwrap() {
BacklightThreadOps::Renew => {
timeout = std::time::Instant::now() + standard_duration;
total_waited += 1;
},
BacklightThreadOps::Stop => {
log::trace!("received Stop op, killing background backlight thread");
xous::send_message(cid, xous::Message::new_scalar(StatusOpcode::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap();
return;
},
}
},
recv(at(timeout)) -> _ => {
log::trace!("timeout finished, total re-waited {}, returning!", total_waited);
xous::send_message(cid, xous::Message::new_scalar(StatusOpcode::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap();
break;
}
};
}
}

View file

@ -8,7 +8,7 @@ use num_traits::*;
use crate::StatusOpcode;
#[allow(unused_variables)] // quiets a warning about unused com that is emitted in tts config. Would be nice to make this more targeted...
pub fn create_main_menu(keys: Arc<Mutex<RootKeys>>, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID) {
pub fn create_main_menu(keys: Arc<Mutex<RootKeys>>, menu_management_sid: xous::SID, status_conn: xous::CID, com: &com::Com, time_ux_conn: xous::CID) -> MenuMatic {
let key_conn = keys.lock().unwrap().conn();
let mut menuitems = Vec::<MenuItem>::new();
@ -32,6 +32,24 @@ pub fn create_main_menu(keys: Arc<Mutex<RootKeys>>, status_conn: xous::CID, com:
close_on_select: true,
});
#[cfg(not(feature="tts"))]
menuitems.push(MenuItem {
name: String::from_str(t!("mainmenu.autobacklighton", xous::LANG)),
action_conn: Some(status_conn),
action_opcode: StatusOpcode::EnableAutomaticBacklight.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
// #[cfg(not(feature="tts"))]
// menuitems.push(MenuItem {
// name: String::from_str(t!("mainmenu.autobacklightoff", xous::LANG)),
// action_conn: Some(kbb.cid()),
// action_opcode: KbbOps::DisableAutomaticBacklight.to_u32().unwrap(),
// action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
// close_on_select: true,
// });
menuitems.push(MenuItem {
name: String::from_str(t!("mainmenu.sleep", xous::LANG)),
action_conn: Some(status_conn),
@ -128,5 +146,5 @@ pub fn create_main_menu(keys: Arc<Mutex<RootKeys>>, status_conn: xous::CID, com:
close_on_select: true,
});
menu_matic(menuitems, MAIN_MENU_NAME, None);
menu_matic(menuitems, MAIN_MENU_NAME, Some(menu_management_sid)).unwrap()
}