Skip to content

Instantly share code, notes, and snippets.

@nbyouri
Last active November 21, 2022 04:07
Show Gist options
  • Save nbyouri/f369b8064a0e8d5d15fa63c503041244 to your computer and use it in GitHub Desktop.
Save nbyouri/f369b8064a0e8d5d15fa63c503041244 to your computer and use it in GitHub Desktop.
Get/Set screen brightness value on NetBSD
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/sysctl.h>
#include <inttypes.h>
bool device_enabled(char *);
char *find_device(void);
int get_brightness(char *);
void set_brightness(char *, unsigned int);
int usage(void);
bool device_enabled(char *device) {
size_t size = sizeof(int);
int buf = 0;
int res = 0;
char *name = malloc(BUFSIZ);
snprintf(name, BUFSIZ, "hw.acpi.%s.bios_switch", device);
if (sysctlbyname(name, &buf, &size, NULL, 0) == -1) {
if (errno != ENOENT)
fprintf(stderr, "Sysctl failed: %s\n", strerror(errno));
} else {
res = buf;
}
free(name);
name = NULL;
return (res == 1);
}
char *find_device(void) {
char *vga = "acpivga";
char *device = NULL;
device = malloc(BUFSIZ);
/* get first enabled device */
for (int num_dev = 0; num_dev < 10; num_dev++) {
snprintf(device, BUFSIZ, "%s%d", vga, num_dev);
if (device_enabled(device)) {
snprintf(device, BUFSIZ, "acpiout%d", num_dev);
return device;
}
}
free(device);
device = NULL;
return NULL;
}
int get_brightness(char *device_name) {
size_t size = sizeof(int);
int buf = 0;
int res = 0;
char *name = malloc(BUFSIZ);
sprintf(name, "hw.acpi.%s.brightness", device_name);
if (sysctlbyname(name, &buf, &size, NULL, 0) == -1)
printf("%s\n", strerror(errno));
else
res = buf;
free(name);
name = NULL;
return res;
}
void set_brightness(char *device_name, unsigned int level) {
size_t size = sizeof(level);
char *name = malloc(BUFSIZ);
sprintf(name, "hw.acpi.%s.brightness", device_name);
if (sysctlbyname(name, NULL, NULL, &level, size) == -1)
printf("%s\n", strerror(errno));
free(name);
name = NULL;
}
int usage(void) {
const char *progname = getprogname();
fprintf(stderr, "usage: %s get\n", progname);
fprintf(stderr, "usage: %s set [0:100]\n", progname);
return EXIT_FAILURE;
}
int main(int argc, char **argv) {
if (argc < 2)
return usage();
if (strncmp(argv[1], "set", 4) == 0) {
if (argc != 3)
return usage();
char *buf = strndup(argv[2], BUFSIZ);
int e;
intmax_t lval = strtoi(buf, NULL, 10, 0, 100, &e);
free(buf);
buf = NULL;
if (e)
return usage();
char *device = find_device();
set_brightness(device, lval);
free(device);
device = NULL;
} else if (strncmp(argv[1], "get", 4) == 0) {
char *device = find_device();
if (device == NULL) {
printf("No devices found.\n");
return EXIT_FAILURE;
} else {
printf("current brightness for %s = %u\n",
device, get_brightness(device));
free(device);
device = NULL;
}
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment