chore: move automatic backlight in status crate

Let's not use a precious process just for some a backlight effect :-)
This commit is contained in:
Gianguido Sorà 2022-06-13 16:33:44 +02:00
parent ee29998534
commit d7eb53664e
9 changed files with 104 additions and 264 deletions

23
Cargo.lock generated
View file

@ -1813,27 +1813,6 @@ dependencies = [
"xous-names",
]
[[package]]
name = "keyboard-backlight"
version = "0.1.0"
dependencies = [
"com",
"crossbeam",
"keyboard",
"log",
"log-server",
"net",
"num-derive",
"num-traits",
"rkyv",
"ticktimer-server",
"trng",
"utralib",
"xous",
"xous-ipc 0.9.7",
"xous-names",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
@ -3270,10 +3249,10 @@ dependencies = [
"chrono",
"com",
"content-plugin-api",
"crossbeam",
"gam",
"graphics-server",
"keyboard",
"keyboard-backlight",
"llio",
"locales",
"log",

View file

@ -5,7 +5,6 @@ default-members = [
"services/ticktimer-server",
"services/xous-names",
"services/keyboard",
"services/keyboard-backlight",
"services/com",
"services/trng",
"services/gam",
@ -35,7 +34,6 @@ members = [
"xous-ipc",
"xous-rs",
"tools",
"services/keyboard-backlight",
"services/aes-test",
"services/graphics-server",
"services/log-server",

View file

@ -1,27 +0,0 @@
[package]
name = "keyboard-backlight"
version = "0.1.0"
edition = "2021"
# Dependency policy: fully specify dependencies to the minor version number
[dependencies]
xous = { path = "../../xous-rs" }
log-server = { path = "../log-server" }
ticktimer-server = { path = "../ticktimer-server" }
xous-names = { path = "../xous-names" }
log = "0.4.14"
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
net = {path = "../net"}
xous-ipc = {path="../../xous-ipc"}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
trng = {path = "../trng"}
keyboard = {path = "../keyboard"}
com = {path = "../com"}
crossbeam = "0.8.1"
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}
[features]
default = []

View file

@ -1,11 +0,0 @@
pub const KBB_SERVER_NAME: &str = "_Keyboard backlight_";
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub enum KbbOps {
Keypress,
TurnLightsOff,
TurnLightsOn,
EnableAutomaticBacklight,
DisableAutomaticBacklight,
Status,
}

View file

@ -1,66 +0,0 @@
pub mod api;
use api::*;
use num_traits::*;
#[derive(Debug)]
pub struct KeyboardBacklight {
conn: xous::CID,
}
impl KeyboardBacklight {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
let conn = xns.request_connection_blocking(api::KBB_SERVER_NAME).expect("Can't connect to KBD");
Ok(KeyboardBacklight {
conn,
})
}
pub fn cid(&self) -> xous::CID {
self.conn
}
pub fn enable(&self) {
xous::send_message(self.conn,
xous::Message::new_scalar(KbbOps::EnableAutomaticBacklight.to_usize().unwrap(),
0,
0,
0,
0
)
).map(|_|()).unwrap();
}
pub fn disable(&self) {
xous::send_message(self.conn,
xous::Message::new_scalar(KbbOps::DisableAutomaticBacklight.to_usize().unwrap(),
0,
0,
0,
0
)
).map(|_|()).unwrap();
}
pub fn enabled(&self) -> Result<bool, xous::Error> {
match xous::send_message(self.conn,
xous::Message::new_blocking_scalar(KbbOps::Status.to_usize().unwrap(),
0,
0,
0,
0
)
) {
Ok(xous::Result::Scalar1(last_state)) => {
if last_state == 1 {
Ok(true)
} else {
Ok(false)
}
}
_ => {
Err(xous::Error::InternalError)
}
}
}
}

View file

@ -1,123 +0,0 @@
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
mod api;
use api::*;
use crossbeam::channel::{at, select, unbounded, Receiver, Sender};
use num_traits::*;
use std::sync::Arc;
use std::sync::Mutex;
enum ThreadOps {
Renew,
Stop,
}
fn main() -> ! {
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();
let kbb_sid = xns
.register_name(api::KBB_SERVER_NAME, Some(2))
.expect("can't register server");
// connect to com
let com = com::Com::new(&xns).expect("cannot connect to com");
let keyboard = keyboard::Keyboard::new(&xns).expect("cannot connect to keyboard server");
keyboard.register_observer(
"_Keyboard backlight_",
KbbOps::Keypress.to_u32().unwrap() as usize,
);
let enabled = Arc::new(Mutex::new(false));
let (tx, rx): (Sender<ThreadOps>, Receiver<ThreadOps>) = unbounded();
let rx = Box::new(rx);
let thread_already_running = Arc::new(Mutex::new(false));
let thread_conn = xous::connect(kbb_sid).unwrap();
loop {
let msg = xous::receive_message(kbb_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(KbbOps::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(ThreadOps::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(KbbOps::TurnLightsOn) => {
log::trace!("turning lights on");
com.set_backlight(255, 128).expect("cannot set backlight on");
},
Some(KbbOps::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(KbbOps::EnableAutomaticBacklight) => {
*enabled.lock().unwrap() = true;
}
Some(KbbOps::DisableAutomaticBacklight) => {
*enabled.lock().unwrap() = false;
tx.send(ThreadOps::Stop).unwrap();
}
Some(KbbOps::Status) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let status = *enabled.lock().unwrap();
xous::return_scalar(msg.sender, status.into()).unwrap();
}),
_ => {}
}
}
}
fn turn_lights_on(rx: Box<Receiver<ThreadOps>>, 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() {
ThreadOps::Renew => {
timeout = std::time::Instant::now() + standard_duration;
total_waited += 1;
},
ThreadOps::Stop => {
log::trace!("received Stop op, killing background backlight thread");
return;
},
}
},
recv(at(timeout)) -> _ => {
log::trace!("timeout finished, total re-waited {}, returning!", total_waited);
xous::send_message(cid, xous::Message::new_scalar(KbbOps::TurnLightsOff.to_usize().unwrap(), 0,0,0,0)).unwrap();
break;
}
};
}
}

View file

@ -27,7 +27,6 @@ pddb = {path = "../pddb"}
net = {path = "../net"}
keyboard = {path = "../keyboard"}
usb-device-xous = {path="../usb-device-xous"}
keyboard-backlight = {path = "../keyboard-backlight"}
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
@ -35,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

@ -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,10 +58,15 @@ pub(crate) enum StatusOpcode {
/// Set the keyboard map
SetKeyboard,
/// Sets automatic backlight on
/// Tells keyboard watching thread that a new keypress happened.
Keypress,
/// Turns backlight off.
TurnLightsOff,
/// Turns backlight on.
TurnLightsOn,
/// Enables automatic backlight handling.
EnableAutomaticBacklight,
/// Sets automatic backlight off
/// Disables automatic backlight handling.
DisableAutomaticBacklight,
/// Suspend handler from the main menu
@ -143,7 +150,8 @@ fn 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) };
@ -338,8 +346,6 @@ fn main() -> ! {
// used to show notifications, e.g. can't sleep while power is engaged.
let modals = modals::Modals::new(&xns).unwrap();
let keyboard_backlight = keyboard_backlight::KeyboardBacklight::new(&xns).unwrap();
log::debug!("starting main menu thread");
let main_menu_sid = xous::create_server().unwrap();
let status_cid = xous::connect(status_sid).unwrap();
@ -369,15 +375,28 @@ fn 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) => {
// first: enable automatic backlight.
keyboard_backlight.enable();
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));
@ -394,8 +413,8 @@ fn main() -> ! {
}, 0);
}
Some(StatusOpcode::DisableAutomaticBacklight) => {
// first: disable automatic backlight.
keyboard_backlight.disable();
*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));
@ -719,6 +738,40 @@ fn 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;
}
@ -742,3 +795,41 @@ fn 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

@ -58,7 +58,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"com",
"xous-names",
"keyboard",
"keyboard-backlight",
"trng",
"llio",
"susres",