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