Xinqi Bao's Git

327d5765c66991408f2e668e05934894a22702ed
[slstatus.git] / components / battery.c
1 /* See LICENSE file for copyright and license details. */
2 #include <errno.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 #include "../util.h"
7
8 #if defined(__linux__)
9 #include <limits.h>
10
11 const char *
12 battery_perc(const char *bat)
13 {
14 int perc;
15 char path[PATH_MAX];
16
17 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
18 bat, "/capacity");
19 return (pscanf(path, "%i", &perc) == 1) ?
20 bprintf("%d", perc) : NULL;
21 }
22
23 const char *
24 battery_power(const char *bat)
25 {
26 int watts;
27 char path[PATH_MAX];
28
29 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
30 bat, "/power_now");
31 return (pscanf(path, "%i", &watts) == 1) ?
32 bprintf("%d", (watts + 500000) / 1000000) : NULL;
33 }
34
35 const char *
36 battery_state(const char *bat)
37 {
38 struct {
39 char *state;
40 char *symbol;
41 } map[] = {
42 { "Charging", "+" },
43 { "Discharging", "-" },
44 { "Full", "=" },
45 { "Unknown", "/" },
46 };
47 size_t i;
48 char path[PATH_MAX], state[12];
49
50 snprintf(path, sizeof(path), "%s%s%s", "/sys/class/power_supply/",
51 bat, "/status");
52 if (pscanf(path, "%12s", state) != 1) {
53 return NULL;
54 }
55
56 for (i = 0; i < LEN(map); i++) {
57 if (!strcmp(map[i].state, state)) {
58 break;
59 }
60 }
61 return (i == LEN(map)) ? "?" : map[i].symbol;
62 }
63 #elif defined(__OpenBSD__)
64 #include <fcntl.h>
65 #include <machine/apmvar.h>
66 #include <sys/ioctl.h>
67 #include <unistd.h>
68
69 const char *
70 battery_perc(const char *null)
71 {
72 struct apm_power_info apm_info;
73 int fd;
74
75 fd = open("/dev/apm", O_RDONLY);
76 if (fd < 0) {
77 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
78 return NULL;
79 }
80
81 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
82 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
83 strerror(errno));
84 close(fd);
85 return NULL;
86 }
87 close(fd);
88
89 return bprintf("%d", apm_info.battery_life);
90 }
91
92 const char *
93 battery_state(const char *bat)
94 {
95 int fd;
96 size_t i;
97 struct apm_power_info apm_info;
98 struct {
99 unsigned int state;
100 char *symbol;
101 } map[] = {
102 { APM_AC_ON, "+" },
103 { APM_AC_OFF, "-" },
104 { APM_AC_UNKNOWN, "/" },
105 };
106
107 fd = open("/dev/apm", O_RDONLY);
108 if (fd < 0) {
109 fprintf(stderr, "open '/dev/apm': %s\n", strerror(errno));
110 return NULL;
111 }
112
113 if (ioctl(fd, APM_IOC_GETPOWER, &apm_info) < 0) {
114 fprintf(stderr, "ioctl 'APM_IOC_GETPOWER': %s\n",
115 strerror(errno));
116 close(fd);
117 return NULL;
118 }
119 close(fd);
120
121 for (i = 0; i < LEN(map); i++) {
122 if (map[i].state == apm_info.ac_state) {
123 break;
124 }
125 }
126 return (i == LEN(map)) ? "?" : map[i].symbol;
127 }
128 #endif