rewritten, much simpler with config file now
This commit is contained in:
parent
3efc3b1974
commit
36c4aff457
2 changed files with 225 additions and 177 deletions
14
TODO
14
TODO
|
|
@ -1,14 +0,0 @@
|
||||||
[ ] Add a config file
|
|
||||||
[ ] Use a better filter than a simple median, maybe a kalman filter
|
|
||||||
[x] Add a way to customise the brightness curve
|
|
||||||
Percieved brightness is not linear, on low light you need a slightly higher
|
|
||||||
brightness and on high light you can get away with a lower brightness
|
|
||||||
than the max, the goal is to find the right curve for the screen
|
|
||||||
[ ] Automatically detect backlight device, or at least make it configurable
|
|
||||||
[ ] Add signal handlers
|
|
||||||
[ ] SIGUSR1 to reset the user offset
|
|
||||||
[x] Handle kill by closing all file descriptors
|
|
||||||
(every read is done by only keeping the file open for as long as it is needed)
|
|
||||||
[ ] Handle suspend and resume, usually suspending means that the screen is
|
|
||||||
turned off so do not apply user offset
|
|
||||||
[ ] Account for DPMS and do not apply offset in that case
|
|
||||||
388
ambientd.c3
388
ambientd.c3
|
|
@ -1,206 +1,268 @@
|
||||||
|
module ambientd;
|
||||||
|
|
||||||
import std::io;
|
import std::io;
|
||||||
import std::io::file;
|
import std::io::path;
|
||||||
|
import std::os::env;
|
||||||
|
import std::os::posix;
|
||||||
|
import std::collections::list;
|
||||||
|
import std::collections::object;
|
||||||
|
import std::encoding::ini;
|
||||||
import std::thread;
|
import std::thread;
|
||||||
|
import std::time;
|
||||||
|
import std::math;
|
||||||
|
import libc;
|
||||||
|
|
||||||
// import some functions from the C standard library
|
|
||||||
extern fn long strtol(char *buffer, char **endptr, int base);
|
|
||||||
|
|
||||||
const String LUMINANCE_DEV = "/sys/bus/iio/devices/iio:device0/in_illuminance_raw";
|
alias StrList = List{String};
|
||||||
const String MAX_BRIGHTNESS_DEV = "/sys/class/backlight/intel_backlight/max_brightness";
|
|
||||||
const String BRIGHTNESS_DEV = "/sys/class/backlight/intel_backlight/brightness";
|
|
||||||
const String ACTUAL_BRIGHTNESS_DEV = "/sys/class/backlight/intel_backlight/actual_brightness";
|
|
||||||
|
|
||||||
char[128] str_buffer;
|
|
||||||
|
|
||||||
// max luminance that the display can output
|
const String DEF_LIGHT_SENSOR_PATH = "/sys/bus/iio/devices/iio:device0/in_illuminance_raw";
|
||||||
const int MAX_LUMINANCE = 700;
|
const String DEF_BACKLIGHT_PATH = "/sys/class/backlight/intel_backlight";
|
||||||
|
const float DEF_SCREEN_NIT = 400.0;
|
||||||
|
const float DEF_SENSOR_K = 0.98;
|
||||||
|
const int DEF_UPDATE_INTERVAL_MS = 200;
|
||||||
|
|
||||||
// minimum display brightness in percent
|
const String[*] CONFIG_PATHS = {
|
||||||
const float MIN_BRIGHTNESS_PERCENT = 0.05;
|
"$XDG_CONFIG_HOME/ambientd/ambientd.ini",
|
||||||
|
"$HOME/.config/ambientd/ambientd.ini",
|
||||||
|
"/etc/ambientd/ambientd.ini",
|
||||||
|
};
|
||||||
|
|
||||||
const int SLEEP_DELAY = 2500;
|
|
||||||
const int SMOOTH_DURATION = 500;
|
|
||||||
const int SMOOTH_SAMPLES = 20;
|
|
||||||
|
|
||||||
macro abs(x) { return x < 0 ? -x : x; }
|
String light_sensor_path = DEF_LIGHT_SENSOR_PATH;
|
||||||
macro clamp(x, l, h) { return max(min(x, h), l); }
|
String backlight_path = DEF_BACKLIGHT_PATH;
|
||||||
|
float backlight_max_luminance = DEF_SCREEN_NIT;
|
||||||
|
float light_sensor_k = DEF_SENSOR_K;
|
||||||
|
int update_interval_ms = DEF_UPDATE_INTERVAL_MS;
|
||||||
|
|
||||||
/**
|
|
||||||
* read a string to the buffer up until the end of the buffer or the first '\n'
|
struct LuminanceFilter {
|
||||||
* @require fp != null
|
float x; // estimate
|
||||||
**/
|
float p; // error
|
||||||
fn void! io::File.gets(&self, char[] buffer)
|
float r; // mesurement noise
|
||||||
|
float q; // process noise
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fn float LuminanceFilter.update(&self, int reading, float dt)
|
||||||
{
|
{
|
||||||
usz i = 0;
|
float x_1 = self.x;
|
||||||
char !c;
|
float p_1 = self.p + self.q * dt;
|
||||||
for (; i < buffer.len-1; i++) {
|
|
||||||
c = self.read_byte();
|
float k = p_1 / (p_1 + self.r);
|
||||||
if (catch excuse = c) {
|
|
||||||
if (excuse == io::IoError.EOF) {
|
self.x = x_1 + k * ((float)reading - x_1);
|
||||||
|
self.p = (1.0 - k) * p_1;
|
||||||
|
|
||||||
|
return self.x;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fn void LuminanceFilter.init(&self, int reading)
|
||||||
|
{
|
||||||
|
self.p = 0.0;
|
||||||
|
self.x = (float)reading;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// TODO: this should be configurable
|
||||||
|
LuminanceFilter filter = {.r = 5.0, .q = 0.1};
|
||||||
|
|
||||||
|
|
||||||
|
fn String? String.to_expanded_path(&str, Allocator allocator, String[] extra_env = {})
|
||||||
|
{
|
||||||
|
@pool() {
|
||||||
|
StrList l;
|
||||||
|
l.tinit();
|
||||||
|
Path str_path = str.to_tpath()!;
|
||||||
|
|
||||||
|
l.push(str_path.basename());
|
||||||
|
Path? p = str_path.parent();
|
||||||
|
while (true) {
|
||||||
|
Path? x;
|
||||||
|
if (try p) {
|
||||||
|
String n = p.basename();
|
||||||
|
l.push("/");
|
||||||
|
|
||||||
|
// env variable
|
||||||
|
if (n.starts_with("$")) {
|
||||||
|
String? e = env::tget_var(n[1..]);
|
||||||
|
if (catch e) {
|
||||||
|
// var is not in regular environment, check extra_env
|
||||||
|
bool in_extra = false;
|
||||||
|
foreach_r (j: extra_env) {
|
||||||
|
if (j.starts_with(n[1..])) {
|
||||||
|
l.push(j.strip_suffix(n[1..])[1..]);
|
||||||
|
in_extra = true;
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!in_extra) {
|
||||||
|
return NOT_FOUND~;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
return excuse?;
|
l.push(e);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
l.push(n);
|
||||||
}
|
}
|
||||||
buffer[i] = c;
|
|
||||||
|
x = p.parent();
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
buffer[i] = '\0';
|
p = x;
|
||||||
|
}
|
||||||
|
l.reverse();
|
||||||
|
String path;
|
||||||
|
path = string::tjoin(l.array_view(), path);
|
||||||
|
|
||||||
|
return (String)path::new(allocator, path);
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* read a string from a file and convert it to int, should only be used for
|
fn void update_config()
|
||||||
* positive numbers since negative numbers mean an error
|
|
||||||
* @ensure return > 0, return < 1000000
|
|
||||||
**/
|
|
||||||
fn int! read_int(String path)
|
|
||||||
{
|
{
|
||||||
static io::File! fp;
|
bool config_found = false;
|
||||||
fp = io::file::open((String)path, "r")!;
|
foreach (c: CONFIG_PATHS) {
|
||||||
defer (void)fp.close();
|
String? p = c.to_expanded_path(tmem);
|
||||||
|
if (catch e = p) {
|
||||||
|
io::eprintfn("Error expanding path %s: %s", c, e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!file::exists(p)) {
|
||||||
|
io::printfn("%s not present", p);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
fp.gets(str_buffer[..])!;
|
// Read file
|
||||||
int r = (int)strtol(&str_buffer, null, 10);
|
File f = file::open(p, "r")!!;
|
||||||
return r;
|
Object*? o = ini::load_temp(&f).get(ini::GLOBAL);
|
||||||
}
|
if (catch e = o) {
|
||||||
|
io::eprintfn("Error reading config file %s: %s", p, e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// write an intger value to a file as a string
|
// Read backlight device folder
|
||||||
fn void! write_int(String path, int value)
|
String? backlight = o.get_string("backlight");
|
||||||
{
|
if (catch e = backlight) {
|
||||||
static io::File! fp;
|
io::eprintfn("Error reading backlight path from config: %s", e);
|
||||||
fp = io::file::open(path, "w")!;
|
continue;
|
||||||
defer (void)fp.close();
|
}
|
||||||
|
if (!file::is_dir(backlight)) {
|
||||||
|
io::eprintfn("Error setting the backlight path: path should be a directory");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
backlight_path = backlight;
|
||||||
|
|
||||||
char[] b = io::bprintf(str_buffer[..], "%d\n", value)!;
|
// Read light sensor device path
|
||||||
fp.write(b)!;
|
String? sensor = o.get_string("sensor");
|
||||||
}
|
if (catch e = sensor) {
|
||||||
|
io::eprintfn("Error reading luminance sensor path from config: %s", e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
light_sensor_path = sensor;
|
||||||
|
|
||||||
// returns the raw luminance value
|
// Optional configurations
|
||||||
macro get_luminance_raw() { return read_int(LUMINANCE_DEV); }
|
|
||||||
|
|
||||||
// write the brightness value, on fail log on stderr
|
// Read the max screen brightness
|
||||||
macro write_brightness(int b)
|
if (try x = o.get_string("max_brightness").to_float()) {
|
||||||
{
|
backlight_max_luminance = (float)x;
|
||||||
anyfault e = @catch(write_int(BRIGHTNESS_DEV, b));
|
}
|
||||||
if (e) {
|
|
||||||
io::eprintfn("Error writing brightness: %s", e);
|
// Read the light sensor factor
|
||||||
|
if (try x = o.get_string("sensor_factor").to_float()) {
|
||||||
|
light_sensor_k = (float)x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the light sensor factor
|
||||||
|
if (try x = o.get_string("update_interval").to_int()) {
|
||||||
|
update_interval_ms = x;
|
||||||
|
}
|
||||||
|
|
||||||
|
config_found = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config_found) {
|
||||||
|
io::eprintfn("Keping previous configuration");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn float bezier(float t)
|
|
||||||
|
macro float @bezier(float t)
|
||||||
{
|
{
|
||||||
const float B = 0.66;
|
const float B = 0.66;
|
||||||
const float D = 0.28;
|
const float D = 0.28;
|
||||||
return 3*B*t+(3*D-6*B)*t*t+(1+3*B-3*D)*t*t*t;
|
return 3*B*t+(3*D-6*B)*t*t+(1+3*B-3*D)*t*t*t;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: add some command line options like:
|
|
||||||
// -v: verbose/logging
|
// https://docs.kernel.org/admin-guide/abi-stable-files.html#abi-file-stable-sysfs-class-backlight
|
||||||
// -c file; specify a config file
|
macro int @read_int_from_file(String path) => ((String)file::load_temp(path)[..^2]).to_int() ?? 0;
|
||||||
fn int main()
|
macro void @write_int_to_file(String path, int i) => (void)file::save(path, string::tformat("%d\n", i));
|
||||||
|
macro int @get_luminance() => @read_int_from_file(light_sensor_path);
|
||||||
|
macro int @get_max_backlight() => @read_int_from_file(backlight_path.tconcat("/max_brightness"));
|
||||||
|
macro int @get_backlight() => @read_int_from_file(backlight_path.tconcat("/brightness"));
|
||||||
|
macro void @set_backlight(int v) => @write_int_to_file(backlight_path.tconcat("/brightness"), v);
|
||||||
|
macro bool @is_screen_on() => @read_int_from_file(backlight_path.tconcat("/bl_power")) == 0;
|
||||||
|
|
||||||
|
|
||||||
|
fn void sigusr1_handler(CInt sig, void* act, void* oldact)
|
||||||
{
|
{
|
||||||
// open the luminance device and try reading from it
|
(void)sig;
|
||||||
if (catch excuse = get_luminance_raw()) {
|
(void)act;
|
||||||
io::eprintfn("Error on initial opening of %s: %s", LUMINANCE_DEV, excuse);
|
(void)oldact;
|
||||||
thread::exit(1);
|
update_config();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// TODO: add command line arguments, like -h, -v and -d
|
||||||
|
// TODO: daemonization
|
||||||
|
// TODO: override config file with arguments
|
||||||
|
fn void main(String[] args)
|
||||||
|
{
|
||||||
|
update_config();
|
||||||
|
|
||||||
|
posix::install_signal_handler(libc::SIGUSR1, &sigusr1_handler);
|
||||||
|
|
||||||
|
filter.init(@get_luminance());
|
||||||
|
float luminance_old = filter.update(@get_luminance(), 0.0);
|
||||||
|
int brightness_set = @get_backlight();
|
||||||
|
int user_offset = 0;
|
||||||
|
int backlight_max = @get_max_backlight();
|
||||||
|
Time start = time::now();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
if (!@is_screen_on()) {
|
||||||
|
thread::sleep_ms(5000);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// get the max brightness
|
Time now = time::now();
|
||||||
int max_brightness;
|
Time dt = (Time)(now - start);
|
||||||
int min_brightness;
|
|
||||||
int! opt = read_int(MAX_BRIGHTNESS_DEV);
|
|
||||||
if (try unwrapped = opt) {
|
|
||||||
max_brightness = unwrapped;
|
|
||||||
} if (catch excuse = opt) {
|
|
||||||
io::eprintfn("Error reading max brightness on %s: %s", MAX_BRIGHTNESS_DEV, excuse);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
min_brightness = (int)(max_brightness * MIN_BRIGHTNESS_PERCENT);
|
|
||||||
|
|
||||||
// try writing to brightness device
|
// Check user offset
|
||||||
int! br = read_int(BRIGHTNESS_DEV);
|
user_offset = @get_backlight() - brightness_set;
|
||||||
if (catch excuse = br) {
|
|
||||||
io::eprintfn("Error reading from %s: %s", BRIGHTNESS_DEV, excuse);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
if (catch excuse = write_int(BRIGHTNESS_DEV, br)) {
|
|
||||||
io::eprintfn("Error writing to brightness device %s: %s", BRIGHTNESS_DEV, excuse);
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// try reading from the actual brightness device
|
// Filtered luminance, depends heavily on the type of sensor, for the CF-SV7
|
||||||
if (catch excuse = read_int(ACTUAL_BRIGHTNESS_DEV)) {
|
// seems to be in lux
|
||||||
io::eprintfn("Error reading from %s: %s", ACTUAL_BRIGHTNESS_DEV, excuse);
|
float luminance = filter.update(@get_luminance(), (float)dt.to_seconds()) * light_sensor_k;
|
||||||
return 1;
|
// Percent of the luminance received compared to what the panel can output
|
||||||
}
|
float p = min((luminance/backlight_max_luminance), 1.0f);
|
||||||
|
|
||||||
int x = get_luminance_raw() ?? MAX_LUMINANCE;
|
// int new_brightness = (int)(@bezier(p)*backlight_max);
|
||||||
int[<4>] luminance_samples = x;
|
// The panel should output slightly more light than the ambient, moreover the
|
||||||
usz idx;
|
// relationship between a percent increase in the backlight power and the
|
||||||
int user_offset;
|
// perceived luminance is non-linear, I think the inverse square law is correct
|
||||||
int brightness_target = min_brightness;
|
int new_brightness = (int)(math::pow(p*1.1f, 0.5f)*backlight_max);
|
||||||
int brightness_old = min_brightness;
|
brightness_set = new_brightness;
|
||||||
int brightness_adjusted = min_brightness;
|
@set_backlight(brightness_set + user_offset);
|
||||||
int brightness_delta;
|
|
||||||
float luminance_median;
|
|
||||||
float luminance_percent;
|
|
||||||
while (1) {
|
|
||||||
int! tmp = get_luminance_raw();
|
|
||||||
if (catch excuse = tmp) {
|
|
||||||
io::eprintfn("Error reading luminance: %s", excuse);
|
|
||||||
} else {
|
|
||||||
luminance_samples[idx] = tmp;
|
|
||||||
idx = (idx + 1) % luminance_samples.len;
|
|
||||||
}
|
|
||||||
|
|
||||||
luminance_median = (float)luminance_samples.sum() / luminance_samples.len;
|
// io::printfn("%f, %d, %d", luminance, brightness_set, user_offset);
|
||||||
luminance_percent = bezier(clamp(luminance_median/MAX_LUMINANCE, 0.0f, 1.0f));
|
|
||||||
|
|
||||||
brightness_old = brightness_target;
|
start = now;
|
||||||
brightness_target = max((int)(luminance_percent * max_brightness), min_brightness);
|
thread::sleep_ms(update_interval_ms);
|
||||||
brightness_delta = (int)abs((float)(brightness_target - brightness_old)/brightness_old);
|
|
||||||
|
|
||||||
// if the brightness changes by more than 10% reduce the user offset, scaling
|
|
||||||
// with the delta, this accounts for large changes in brightness no longer
|
|
||||||
// corresponding to the adjustments that the user made to the brightness
|
|
||||||
if (brightness_delta > 0.1) {
|
|
||||||
user_offset = (int)(user_offset * clamp(1-(int)(brightness_delta*1.2), 0, 1));
|
|
||||||
}
|
|
||||||
brightness_adjusted = clamp(brightness_target + user_offset, min_brightness, max_brightness);
|
|
||||||
|
|
||||||
// animate the transition to the brightness target
|
|
||||||
{|
|
|
||||||
int brightness_now = read_int(ACTUAL_BRIGHTNESS_DEV) ?? brightness_adjusted;
|
|
||||||
if (brightness_now == brightness_adjusted) { return; }
|
|
||||||
int step = (brightness_adjusted-brightness_now)/(SMOOTH_SAMPLES);
|
|
||||||
for (int i; i < SMOOTH_SAMPLES; i++) {
|
|
||||||
write_brightness(brightness_now + step*i);
|
|
||||||
thread::sleep_ms(SMOOTH_DURATION/SMOOTH_SAMPLES);
|
|
||||||
}
|
|
||||||
write_brightness(brightness_adjusted);
|
|
||||||
|};
|
|
||||||
|
|
||||||
thread::sleep_ms(SLEEP_DELAY);
|
|
||||||
|
|
||||||
// read actual brightness to get the user offset
|
|
||||||
int actual_brightness;
|
|
||||||
int off;
|
|
||||||
tmp = read_int(ACTUAL_BRIGHTNESS_DEV);
|
|
||||||
actual_brightness = tmp ?? brightness_adjusted;
|
|
||||||
if (catch excuse = tmp) {
|
|
||||||
io::eprintfn("Error reading actual brightness: %s", excuse);
|
|
||||||
}
|
|
||||||
|
|
||||||
// if the actual brightness is zero, it means that the screen is turned
|
|
||||||
// off for some reason, usually DPMS. As such it should not count for user
|
|
||||||
// offset. Look at the TODO file.
|
|
||||||
if (actual_brightness != 0) {
|
|
||||||
off = actual_brightness - brightness_target;
|
|
||||||
if (brightness_target != max_brightness || off < 0){
|
|
||||||
user_offset = off;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: option to turn off logging
|
|
||||||
io::printfn("brightness {target=%d, adjusted=%d}, offset=%d, luminance=%d (%.1f%%)", brightness_target, brightness_adjusted, user_offset, luminance_median, luminance_percent*100);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue