From 9ba6ed6136a9671ed91a0a78a3bd09e620c4d4f6 Mon Sep 17 00:00:00 2001 From: Alessandro Mauri Date: Tue, 29 Oct 2024 13:22:11 +0100 Subject: [PATCH] smooth brightness changes --- ambientd.c3 | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/ambientd.c3 b/ambientd.c3 index 26a04f6..f923461 100644 --- a/ambientd.c3 +++ b/ambientd.c3 @@ -18,7 +18,9 @@ const int MAX_LUMINANCE = 700; // minimum display brightness in percent const float MIN_BRIGHTNESS_PERCENT = 0.05; -const int SLEEP_DELAY = 3000; +const int SLEEP_DELAY = 2500; +const int SMOOTH_DURATION = 500; +const int SMOOTH_SAMPLES = 20; macro abs(x) { return x < 0 ? -x : x; } macro clamp(x, l, h) { return max(min(x, h), l); } @@ -154,11 +156,25 @@ fn int main() 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); - if (catch excuse = write_int(BRIGHTNESS_DEV, brightness_adjusted)) { - io::eprintfn("Error writing brightness: %s", excuse); - } + + // 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-1); + for (int i; i < SMOOTH_SAMPLES-1; i++) { + anyfault e = @catch(write_int(BRIGHTNESS_DEV, brightness_now + step*i)); + if (e) { + io::eprintfn("Error writing brightness: %s", e); + } + thread::sleep_ms(SMOOTH_DURATION/SMOOTH_SAMPLES); + } + anyfault e = @catch(write_int(BRIGHTNESS_DEV, brightness_adjusted)); + if (e) { + io::eprintfn("Error writing brightness: %s", e); + } + |}; thread::sleep_ms(SLEEP_DELAY); @@ -182,6 +198,6 @@ fn int main() } // TODO: option to turn off logging - io::printfn("brightness {target=%d, adjusted=%d}, offset=%d, luminance=%d (%.5f%%)", brightness_target, brightness_adjusted, user_offset, luminance_median, luminance_percent); + io::printfn("brightness {target=%d, adjusted=%d}, offset=%d, luminance=%d (%.5f%%)", brightness_target, brightness_adjusted, user_offset, luminance_median, luminance_percent*100); } }