diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2023-08-10 03:01:18 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2023-08-10 03:01:18 +0300 |
commit | ccebe78c6caa4f05dcb24cba4f146fc6c95ab487 (patch) | |
tree | 107ba1c543f866c1cf11f65621a4b84a7863ded3 /intel_backlight_ctl.c | |
parent | fa38d589b878530565d11ad5e7e3267544be52c3 (diff) |
rename source file
Diffstat (limited to 'intel_backlight_ctl.c')
-rw-r--r-- | intel_backlight_ctl.c | 137 |
1 files changed, 137 insertions, 0 deletions
diff --git a/intel_backlight_ctl.c b/intel_backlight_ctl.c new file mode 100644 index 0000000..70f6822 --- /dev/null +++ b/intel_backlight_ctl.c @@ -0,0 +1,137 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ + +#include <stdio.h> +#include <math.h> +#include <string.h> +#include <stdbool.h> + +#define CUR_PATH "/sys/class/backlight/intel_backlight/brightness" +#define MAX_PATH "/sys/class/backlight/intel_backlight/max_brightness" +#define STEP 10 + +struct brightness { + int max_raw; + int raw; + int percents; +}; + + + +int readval(const char *path, int *dst) +{ + FILE *f = fopen(path, "r"); + int retval = 1; + + if (f == NULL) { + perror(path); + goto end; + } + + int raw; + if (fscanf(f, "%d", &raw) != 1) { + perror(path); + goto end; + } + + *dst = raw; + retval = 0; + +end: + if (f != NULL) + fclose(f); + return retval; +} + + +int get(struct brightness *dst) +{ + int retval = 1; + if (readval(CUR_PATH, &dst->raw)) + goto end; + if (readval(MAX_PATH, &dst->max_raw)) + goto end; + + dst->percents = (int)round((double)dst->raw*100/dst->max_raw); + retval = 0; + +end: + return retval; +} + +int set(struct brightness *src) +{ + int retval = 1; + FILE *f = fopen(CUR_PATH, "w"); + if (!f) { + perror(CUR_PATH); + goto end; + } + + fprintf(f, "%d", src->raw); + retval = 0; + +end: + if (f != NULL) + fclose(f); + return retval; +} + +void adjust(struct brightness *b, int value) +{ + b->percents += value; + if (b->percents > 100) + b->percents = 100; + else if (b->percents < 0) + b->percents = 0; + b->raw = (int)ceil((double)b->percents*b->max_raw/100); +} + + +void dump(struct brightness *b) +{ + printf("%d (%d%%)\n", b->raw, b->percents); +} + + +int main(int argc, char** argv) +{ + int retval = 0; + struct brightness b; + int adjust_val = STEP; + bool decr = false; + + if (argc > 1 && strcmp(argv[1], "-h") == 0) { + printf("usage: %s [-h] [+/-]\n", argv[0]); + goto end; + } + + if (get(&b)) + goto end; + + if (argc <= 1) { + dump(&b); + goto end; + } + + if (strcmp(argv[1], "-") == 0) + decr = true; + else if (strcmp(argv[1], "+") != 0) { + fprintf(stderr, "%s: unknown argument\n", argv[1]); + retval = 1; + goto end; + } + + if (decr) + adjust_val *= -1; + + adjust(&b, adjust_val); + if (set(&b)) { + retval = 1; + goto end; + } + + dump(&b); + +end: + return retval; +} |