Led_Sysfs.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. Copyright (C) 2017 Mathieu Othacehe. All rights reserved.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include "Led_Sysfs.h"
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <inttypes.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. #include <AP_HAL/AP_HAL.h>
  22. static const AP_HAL::HAL &hal = AP_HAL::get_HAL();
  23. namespace Linux {
  24. Led_Sysfs::Led_Sysfs(const char *led_name)
  25. : _led_name(led_name)
  26. {
  27. }
  28. Led_Sysfs::~Led_Sysfs()
  29. {
  30. if (_brightness_fd >= 0) {
  31. close(_brightness_fd);
  32. }
  33. }
  34. bool Led_Sysfs::init()
  35. {
  36. char *br_path;
  37. char *max_br_path;
  38. if (asprintf(&br_path, "/sys/class/leds/%s/brightness", _led_name) == -1) {
  39. AP_HAL::panic("LinuxLed_Sysfs : Couldn't allocate brightness path");
  40. }
  41. _brightness_fd = open(br_path, O_WRONLY | O_CLOEXEC);
  42. if (_brightness_fd < 0) {
  43. printf("LinuxLed_Sysfs: Unable to open file %s\n", br_path);
  44. free(br_path);
  45. return false;
  46. }
  47. if (asprintf(&max_br_path, "/sys/class/leds/%s/max_brightness", _led_name) == -1) {
  48. AP_HAL::panic("LinuxLed_Sysfs : Couldn't allocate max_brightness path");
  49. }
  50. if (Util::from(hal.util)->read_file(max_br_path, "%u", &_max_brightness) < 0) {
  51. AP_HAL::panic("LinuxLed_Sysfs : Unable to read max_brightness in %s",
  52. max_br_path);
  53. }
  54. free(max_br_path);
  55. free(br_path);
  56. return true;
  57. }
  58. bool Led_Sysfs::set_brightness(uint8_t brightness)
  59. {
  60. if (_brightness_fd < 0) {
  61. return false;
  62. }
  63. unsigned int br = brightness * _max_brightness / UINT8_MAX;
  64. /* Don't log fails since this could spam the console */
  65. if (dprintf(_brightness_fd, "%u", br) < 0) {
  66. return false;
  67. }
  68. return true;
  69. }
  70. }