Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add supprt for [als.cmd] to read brightness from external script #98 #99

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ The `config.toml` in repository represents default config values. To change them

### ALS

Choose whether to use a real IIO-based ambient light sensor (`[als.iio]`), a webcam-based simulation (`[als.webcam]`), a time-based simulation (`[als.time]`) or disable it altogether (`[als.none]`).
Choose whether to use a real IIO-based ambient light sensor (`[als.iio]`), a webcam-based simulation (`[als.webcam]`), a time-based simulation (`[als.time]`), reading from the output of a command (`[als.cmd]`), or disable it altogether (`[als.none]`).

Each of them contains a `thresholds` field, which comes with good default values. It is there to convert generally exponential lux values into a linear scale to improve the prediction algorithm in `wluma`. Keys are the raw values from ambient light sensor (maximal value depends on the implementation), values are arbitrary "profiles". `wluma` will predict the best screen brightness according to the data learned within the same ALS profile.

Expand Down
4 changes: 4 additions & 0 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ thresholds = { 0 = "night", 20 = "dark", 80 = "dim", 250 = "normal", 500 = "brig
# [als.time]
# thresholds = { 0 = "night", 7 = "dark", 9 = "dim", 11 = "normal", 13 = "bright", 16 = "normal", 18 = "dark", 20 = "night" }

# [als.cmd]
# command = my_brightness_script
# thresholds = { 0 = "night", 15 = "dark", 30 = "dim", 45 = "normal", 60 = "bright", 75 = "outdoors" }

# [als.none]

[[output.backlight]]
Expand Down
141 changes: 141 additions & 0 deletions src/als/cmd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use std::cell::RefCell;
use std::collections::HashMap;
use std::error::Error;
use std::process::{Command, Output};
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use std::time::Duration;

const DEFAULT_LUX: u64 = 100;
const WAITING_SLEEP_MS: u64 = 2000;

pub struct Cmd {
cmd_tx: Sender<u64>,
command: String,
}

impl Cmd {
pub fn new(cmd_tx: Sender<u64>, command: String) -> Self {
Self { cmd_tx, command }
}

pub fn run(&mut self) {
loop {
self.step();
}
}

fn step(&mut self) {
if let Ok(lux) = self.output() {
self.cmd_tx
.send(lux)
.expect("Unable to send new webcam lux value, channel is dead");
};

thread::sleep(Duration::from_millis(WAITING_SLEEP_MS));
}

fn output(&mut self) -> Result<u64, Box<dyn Error>> {
let Output { status, stdout, .. } =
Command::new("sh").arg("-c").arg(&self.command).output()?;

if !status.success() {
let cmd = &self.command;
log::warn!("Command {cmd:?} failed: {status}");
Err(format!("Command {cmd:?} failed: {status}"))?;
}

let lux = String::from_utf8(stdout)?.parse()?;

Ok(lux)
}
}

pub struct Als {
cmd_rx: Receiver<u64>,
thresholds: HashMap<u64, String>,
lux: RefCell<u64>,
}

impl Als {
pub fn new(cmd_rx: Receiver<u64>, thresholds: HashMap<u64, String>) -> Self {
Self {
cmd_rx,
thresholds,
lux: RefCell::new(DEFAULT_LUX),
}
}

fn get_raw(&self) -> Result<u64, Box<dyn Error>> {
let new_value = self.cmd_rx.try_iter().last().unwrap_or(*self.lux.borrow());
*self.lux.borrow_mut() = new_value;
Ok(new_value)
}
}

impl super::Als for Als {
fn get(&self) -> Result<String, Box<dyn Error>> {
let raw = self.get_raw()?;
let profile = super::find_profile(raw, &self.thresholds);

log::trace!("ALS (cmd): {} ({})", profile, raw);
Ok(profile)
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc;

fn setup() -> (Als, Sender<u64>) {
let (cmd_tx, cmd_rx) = mpsc::channel();
let als = Als::new(cmd_rx, HashMap::default());
(als, cmd_tx)
}

#[test]
fn test_get_raw_returns_default_value_when_no_data_from_command() -> Result<(), Box<dyn Error>>
{
let (als, _) = setup();

assert_eq!(DEFAULT_LUX, als.get_raw()?);
Ok(())
}

#[test]
fn test_get_raw_returns_value_from_command() -> Result<(), Box<dyn Error>> {
let (als, cmd_tx) = setup();

cmd_tx.send(42)?;

assert_eq!(42, als.get_raw()?);
Ok(())
}

#[test]
fn test_get_raw_returns_most_recent_value_from_command() -> Result<(), Box<dyn Error>> {
let (als, cmd_tx) = setup();

cmd_tx.send(42)?;
cmd_tx.send(43)?;
cmd_tx.send(44)?;

assert_eq!(44, als.get_raw()?);
Ok(())
}

#[test]
fn test_get_raw_returns_last_known_value_from_command_when_no_new_data(
) -> Result<(), Box<dyn Error>> {
let (als, cmd_tx) = setup();

cmd_tx.send(42)?;
cmd_tx.send(43)?;

assert_eq!(43, als.get_raw()?);
assert_eq!(43, als.get_raw()?);
assert_eq!(43, als.get_raw()?);
Ok(())
}
}
1 change: 1 addition & 0 deletions src/als/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use itertools::Itertools;
use std::collections::HashMap;
use std::error::Error;

pub mod cmd;
pub mod controller;
pub mod iio;
pub mod none;
Expand Down
4 changes: 4 additions & 0 deletions src/config/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ pub enum Als {
video: usize,
thresholds: HashMap<u64, String>,
},
Cmd {
command: String,
thresholds: HashMap<u64, String>,
},
None,
}

Expand Down
4 changes: 4 additions & 0 deletions src/config/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ pub enum Als {
video: usize,
thresholds: HashMap<String, String>,
},
Cmd {
command: String,
thresholds: HashMap<String, String>,
},
None,
}

Expand Down
7 changes: 7 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ fn parse() -> Result<app::Config, toml::de::Error> {
video,
thresholds: parse_als_thresholds(thresholds),
},
file::Als::Cmd {
command,
thresholds,
} => app::Als::Cmd {
command,
thresholds: parse_als_thresholds(thresholds),
},
file::Als::Time { thresholds } => app::Als::Time {
thresholds: parse_als_thresholds(thresholds),
},
Expand Down
13 changes: 13 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,19 @@ fn main() {
.expect("Unable to start thread: als-webcam");
als::webcam::Als::new(webcam_rx, thresholds)
}),
config::Als::Cmd {
command,
thresholds,
} => Box::new({
let (cmd_tx, cmd_rx) = mpsc::channel();
std::thread::Builder::new()
.name("als-cmd".to_string())
.spawn(move || {
als::cmd::Cmd::new(cmd_tx, command).run();
})
.expect("Unable to start thread: als-cmd");
als::cmd::Als::new(cmd_rx, thresholds)
}),
config::Als::None => Box::<als::none::Als>::default(),
};

Expand Down
Loading