From c7140f898b3bfdc194c095d3201bbdca8010af45 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Sat, 30 May 2020 17:23:08 +0200 Subject: [PATCH] Add backlight --- README.md | 13 +++++++++ meson.build | 2 ++ src/backlight.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 README.md create mode 100644 meson.build create mode 100644 src/backlight.c diff --git a/README.md b/README.md new file mode 100644 index 0000000..b6ec507 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# PinePhone Toolkit +A collection of tools and utility apps for the PINE64 PinePhone. + +## Components +### backlight +Get / Set backlight brightness. + +## Building +``` +$ meson build +$ cd build +$ ninja +``` diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..4b2ca4a --- /dev/null +++ b/meson.build @@ -0,0 +1,2 @@ +project('PinePhone Toolkit', 'c') +executable('pptk-backlight', ['src/backlight.c']) diff --git a/src/backlight.c b/src/backlight.c new file mode 100644 index 0000000..70c1864 --- /dev/null +++ b/src/backlight.c @@ -0,0 +1,77 @@ +#include +#include +#include +#include + +static char *argv0 = "./backlight"; +static char *backlight_file = "/sys/devices/platform/backlight/backlight/backlight/brightness"; + +void print_usage() +{ + printf("usage: %s COMMAND [VALUE]\n", argv0); + printf(" COMMAND = {get, set}\n"); + printf(" get ... prints current backlight level\n"); + printf(" set ... sets backlight level to VALUE\n"); + printf(" VALUE = [0..10] ... backlight amount\n"); +} + +void print_usage_and_fail() +{ + print_usage(); + exit(EXIT_FAILURE); +} + +void command_get() +{ + FILE *fp = fopen(backlight_file, "r"); + if (fp == NULL) { + fprintf(stderr, "Cannot open file '%s' for reading.\n", backlight_file); + exit(EXIT_FAILURE); + } + int buffer_length = 255; + char buffer[buffer_length]; + while (fgets(buffer, buffer_length, fp)) { + printf("%s", buffer); + } + fclose(fp); +} + +void command_set(int value) +{ + if (setuid(0)) { + fprintf(stderr, "Cannot set root permissions via setuid(0).\n"); + exit(EXIT_FAILURE); + } + + FILE *fp = fopen(backlight_file, "w+"); + if (fp == NULL) { + fprintf(stderr, "Cannot open file '%s' for writing.\n", backlight_file); + exit(EXIT_FAILURE); + } + fprintf(fp, "%d\n", value); + fclose(fp); +} + +int main(int argc, char *argv[]) +{ + if (argc < 1) { + print_usage_and_fail(); + } + argv0 = argv[0]; + if (argc < 2) { + print_usage_and_fail(); + } + char *command = argv[1]; + if ((strcmp(command, "get") == 0) && (argc == 2)) { + command_get(); + } else if ((strcmp(command, "set") == 0) && (argc == 3)) { + int value = atoi(argv[2]); + if (value < 0 || value > 10) { + print_usage_and_fail(); + } + command_set(value); + } else { + print_usage_and_fail(); + } + exit(EXIT_SUCCESS); +}