You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.5 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. static char *argv0 = "./led";
  6. static char *led_file_template = "/sys/class/leds/%s:%s/brightness";
  7. void print_usage()
  8. {
  9. printf("usage: %s COMMAND COLOR [VALUE]\n", argv0);
  10. printf(" COMMAND = {get, set}\n");
  11. printf(" get ... prints LED level\n");
  12. printf(" set ... sets LED level to VALUE\n");
  13. printf(" COLOR = {red, green, blue, flash}\n");
  14. printf(" red ... red:indicator LED\n");
  15. printf(" green ... green:indicator LED\n");
  16. printf(" blue ... blue:indicator LED\n");
  17. printf(" flash ... white:flash LED\n");
  18. printf(" VALUE = [0..255] ... light level\n");
  19. }
  20. void print_usage_and_fail()
  21. {
  22. print_usage();
  23. exit(EXIT_FAILURE);
  24. }
  25. void command_get(char *filepath)
  26. {
  27. FILE *fp = fopen(filepath, "r");
  28. if (fp == NULL) {
  29. fprintf(stderr, "Cannot open file '%s' for reading.\n", filepath);
  30. exit(EXIT_FAILURE);
  31. }
  32. int buffer_length = 255;
  33. char buffer[buffer_length];
  34. while (fgets(buffer, buffer_length, fp)) {
  35. printf("%s", buffer);
  36. }
  37. fclose(fp);
  38. }
  39. void command_set(char *filepath, int value)
  40. {
  41. if (setuid(0)) {
  42. fprintf(stderr, "Cannot set root permissions via setuid(0).\n");
  43. exit(EXIT_FAILURE);
  44. }
  45. FILE *fp = fopen(filepath, "w+");
  46. if (fp == NULL) {
  47. fprintf(stderr, "Cannot open file '%s' for writing.\n", filepath);
  48. exit(EXIT_FAILURE);
  49. }
  50. fprintf(fp, "%d\n", value);
  51. fclose(fp);
  52. }
  53. int main(int argc, char *argv[])
  54. {
  55. if (argc < 1) {
  56. print_usage_and_fail();
  57. }
  58. argv0 = argv[0];
  59. if (argc < 3) {
  60. print_usage_and_fail();
  61. }
  62. char *command = argv[1];
  63. char *led = argv[2];
  64. if (strcmp(led, "red") != 0
  65. && strcmp(led, "blue") != 0
  66. && strcmp(led, "green") != 0
  67. && strcmp(led, "flash")) {
  68. print_usage_and_fail();
  69. }
  70. char *type = "indicator";
  71. if (strcmp(led, "flash") == 0) {
  72. led = "white";
  73. type = "flash";
  74. }
  75. char filename[255];
  76. sprintf(filename, led_file_template, led, type);
  77. if ((strcmp(command, "get") == 0) && (argc == 3)) {
  78. command_get(filename);
  79. } else if ((strcmp(command, "set") == 0) && (argc == 4)) {
  80. int value = atoi(argv[3]);
  81. if (value < 0 || value > 255) {
  82. print_usage_and_fail();
  83. }
  84. command_set(filename, value);
  85. } else {
  86. print_usage_and_fail();
  87. }
  88. exit(EXIT_SUCCESS);
  89. }