brightness.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "brightness.h" /* struct brightness_data */
  2. #include "../lib/util.h" /* see functions description here */
  3. #include "../aslstatus.h"
  4. #define SYSFS_CLASS "/sys/class/backlight"
  5. static void brightness_cleanup(void *ptr);
  6. void
  7. brightness(char *out,
  8. const char *device,
  9. uint32_t __unused _i,
  10. static_data_t *static_data)
  11. {
  12. /*
  13. * `static_data_t` used to have static data per thread
  14. *
  15. * `static` keyword will save data staticly for function,
  16. * but not for thread
  17. */
  18. struct brightness_data *data = static_data->data;
  19. char buf[INT_STR_SIZE]; /* buffer for reading data from file */
  20. uint8_t err = 0; /* is error occurred */
  21. int max_fd = -1; /* fd of max_brightness */
  22. __typeof__(data->max_brightness) brightness;
  23. /* add cleanup function */
  24. if (!static_data->cleanup) static_data->cleanup = brightness_cleanup;
  25. if (!data->max_brightness) {
  26. /* open file */
  27. if ((max_fd = sysfs_fd(SYSFS_CLASS, device, "max_brightness"))
  28. == -1)
  29. ERRRET(out);
  30. /* read data to buffer */
  31. if (!eread(max_fd, WITH_LEN(buf))) err = !0;
  32. /* close file after reading */
  33. eclose(max_fd);
  34. if (err) ERRRET(out);
  35. if (!esscanf(1, buf, "%u", &data->max_brightness)) ERRRET(out);
  36. }
  37. /* open `brightness` file */
  38. if (!sysfs_fd_or_rewind(&data->fd, SYSFS_CLASS, device, "brightness"))
  39. ERRRET(out);
  40. if (!eread(data->fd, WITH_LEN(buf))) ERRRET(out);
  41. if (!esscanf(1, buf, "%u", &brightness)) ERRRET(out);
  42. bprintf(out,
  43. "%" PRIperc,
  44. (percent_t)(100 * brightness / data->max_brightness));
  45. /*
  46. * NOTE: `brightness` file not closed
  47. * it will be closed at cleanup
  48. */
  49. }
  50. static inline void
  51. brightness_cleanup(void *ptr)
  52. {
  53. /* close `brightness` fd at exit */
  54. eclose(((struct brightness_data *)ptr)->fd);
  55. }