led_hw_brightness_mon.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * led_hw_brightness_mon.c
  4. *
  5. * This program monitors LED brightness level changes having its origin
  6. * in hardware/firmware, i.e. outside of kernel control.
  7. * A timestamp and brightness value is printed each time the brightness changes.
  8. *
  9. * Usage: led_hw_brightness_mon <device-name>
  10. *
  11. * <device-name> is the name of the LED class device to be monitored. Pressing
  12. * CTRL+C will exit.
  13. */
  14. #include <errno.h>
  15. #include <fcntl.h>
  16. #include <poll.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <linux/uleds.h>
  23. int main(int argc, char const *argv[])
  24. {
  25. int fd, ret;
  26. char brightness_file_path[LED_MAX_NAME_SIZE + 11];
  27. struct pollfd pollfd;
  28. struct timespec ts;
  29. char buf[11];
  30. if (argc != 2) {
  31. fprintf(stderr, "Requires <device-name> argument\n");
  32. return 1;
  33. }
  34. snprintf(brightness_file_path, LED_MAX_NAME_SIZE,
  35. "/sys/class/leds/%s/brightness_hw_changed", argv[1]);
  36. fd = open(brightness_file_path, O_RDONLY);
  37. if (fd == -1) {
  38. printf("Failed to open %s file\n", brightness_file_path);
  39. return 1;
  40. }
  41. /*
  42. * read may fail if no hw brightness change has occurred so far,
  43. * but it is required to avoid spurious poll notifications in
  44. * the opposite case.
  45. */
  46. read(fd, buf, sizeof(buf));
  47. pollfd.fd = fd;
  48. pollfd.events = POLLPRI;
  49. while (1) {
  50. ret = poll(&pollfd, 1, -1);
  51. if (ret == -1) {
  52. printf("Failed to poll %s file (%d)\n",
  53. brightness_file_path, ret);
  54. ret = 1;
  55. break;
  56. }
  57. clock_gettime(CLOCK_MONOTONIC, &ts);
  58. ret = read(fd, buf, sizeof(buf));
  59. if (ret < 0)
  60. break;
  61. ret = lseek(pollfd.fd, 0, SEEK_SET);
  62. if (ret < 0) {
  63. printf("lseek failed (%d)\n", ret);
  64. break;
  65. }
  66. printf("[%ld.%09ld] %d\n", ts.tv_sec, ts.tv_nsec, atoi(buf));
  67. }
  68. close(fd);
  69. return ret;
  70. }