battery.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /* See LICENSE file for copyright and license details. */
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "../util.h"
  6. #if defined(__linux__)
  7. #include <limits.h>
  8. const char *
  9. battery_perc(const char *bat)
  10. {
  11. int perc;
  12. char path[PATH_MAX];
  13. snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
  14. bat, "/capacity");
  15. return (pscanf(path, "%i", &perc) == 1) ? bprintf("%d", perc) : NULL;
  16. }
  17. const char *
  18. battery_state(const char *bat)
  19. {
  20. struct {
  21. char *state;
  22. char *symbol;
  23. } map[] = {
  24. { "Charging", "+" },
  25. { "Discharging", "-" },
  26. };
  27. size_t i;
  28. char path[PATH_MAX], state[12];
  29. snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
  30. bat, "/status");
  31. if (pscanf(path, "%12s", state) != 1) {
  32. return NULL;
  33. }
  34. for (i = 0; i < LEN(map); i++) {
  35. if (!strcmp(map[i].state, state)) {
  36. break;
  37. }
  38. }
  39. return (i == LEN(map)) ? "?" : map[i].symbol;
  40. }
  41. #elif defined(__OpenBSD__)
  42. #include <fcntl.h>
  43. #include <machine/apmvar.h>
  44. #include <sys/ioctl.h>
  45. #include <unistd.h>
  46. const char *
  47. battery_perc(const char *bat)
  48. {
  49. struct apm_power_info apm_info;
  50. int fd;
  51. UNUSED(bat); /* no way to specify battery on OpenBSD */
  52. fd = open("/dev/apm", O_RDONLY);
  53. if (fd < 0) {
  54. fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
  55. return NULL;
  56. }
  57. if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
  58. fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
  59. strerror(errno));
  60. close(fd);
  61. return NULL;
  62. }
  63. close(fd);
  64. return bprintf("%d", apm_info.battery_life);
  65. }
  66. const char *
  67. battery_state(const char *bat)
  68. {
  69. int fd;
  70. size_t i;
  71. struct apm_power_info apm_info;
  72. struct {
  73. unsigned int state;
  74. char *symbol;
  75. } map[] = {
  76. { APM_AC_ON, "+" },
  77. { APM_AC_OFF, "-" },
  78. };
  79. UNUSED(bat); /* no way to specify battery on OpenBSD */
  80. fd = open("/dev/apm", O_RDONLY);
  81. if (fd < 0) {
  82. fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
  83. return NULL;
  84. }
  85. if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
  86. fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
  87. strerror(errno));
  88. close(fd);
  89. return NULL;
  90. }
  91. close(fd);
  92. for (i = 0; i < LEN(map); i++) {
  93. if (map[i].state == apm_info.ac_state) {
  94. break;
  95. }
  96. }
  97. return (i == LEN(map)) ? "?" : map[i].symbol;
  98. }
  99. #endif