From 3254f7091245b3f0f6ccfb71e839276ce3238c26 Mon Sep 17 00:00:00 2001 From: Aaron Ball Date: Wed, 22 Jul 2020 11:00:28 -0600 Subject: Add toggle support This adds the -t,--toggle switch, which will toggle brightness between the current set value, 0, and back. Note that this writes a state file to /tmp/luminous.state to track the the original brightness when dimming to nothing. --- src/main.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/main.c b/src/main.c index 9ee733f..d78a40d 100644 --- a/src/main.c +++ b/src/main.c @@ -22,6 +22,7 @@ #include "config.h" #define CONF "/etc/luminous.conf" +#define STATE "/tmp/luminous.state" // For string macros #define xstr(s) str(s) @@ -84,6 +85,25 @@ int fgeti(char* path) { } +/** + * write_state: + * Writes the current brightness level to a text file. + * + * @path Path to the file to contain the current brightness + */ +int write_state(char* path, int cur) { + FILE* fd; + fd = fopen(path, "w"); + + if(!fd) + return errno; + + fprintf(fd, "%d", cur); + fclose(fd); + return 0; +} + + /** * fade: * @props Props struct containing runtime parameters @@ -141,6 +161,9 @@ int fade(struct props* props) { props->cur += step * direction; steps--; } + // The step loop got us very close to the destination brightness, just finish + // things off since the math rarely works evenly. + fprintf(fd, "%d\n", props->lvl); fclose(fd); return 0; } @@ -200,6 +223,21 @@ int parseargs(struct props* out, int argc, char* argv[]) { i++; out->duration = atoi(argv[i]); + } else if(strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--toggle") == 0) { + FILE* fd = fopen(STATE, "r"); + // If somehow we are at zero and there is no statefile, set brightness to + // half max. + if(out->cur < out->max * .02) { + // If 0, we increase brightness which means reading from statefile + if(!fd) + write_state(STATE, out->lvl = out->max / 2); + else + out->lvl = fgeti(STATE); + } else { + write_state(STATE, out->cur); + out->lvl = 0; + } + } else if(strcmp(argv[i], "-l") == 0 || strcmp(argv[i], "--level") == 0) { i++; // Account for relative and absolute increments and decrements -- cgit v1.2.3