Xinqi Bao's Git
1 /* See LICENSE file for copyright and license details. */
13 pick(const char *bat
, const char *f1
, const char *f2
, char *path
,
16 if (esnprintf(path
, length
, f1
, bat
) > 0 &&
17 access(path
, R_OK
) == 0) {
21 if (esnprintf(path
, length
, f2
, bat
) > 0 &&
22 access(path
, R_OK
) == 0) {
30 battery_perc(const char *bat
)
35 if (esnprintf(path
, sizeof(path
),
36 "/sys/class/power_supply/%s/capacity",
40 if (pscanf(path
, "%d", &perc
) != 1) {
44 return bprintf("%d", perc
);
48 battery_state(const char *bat
)
55 { "Discharging", "-" },
58 char path
[PATH_MAX
], state
[12];
60 if (esnprintf(path
, sizeof(path
),
61 "/sys/class/power_supply/%s/status",
65 if (pscanf(path
, "%12s", state
) != 1) {
69 for (i
= 0; i
< LEN(map
); i
++) {
70 if (!strcmp(map
[i
].state
, state
)) {
74 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
78 battery_remaining(const char *bat
)
80 uintmax_t charge_now
, current_now
, m
, h
;
82 char path
[PATH_MAX
], state
[12];
84 if (esnprintf(path
, sizeof(path
),
85 "/sys/class/power_supply/%s/status",
89 if (pscanf(path
, "%12s", state
) != 1) {
93 if (!pick(bat
, "/sys/class/power_supply/%s/charge_now",
94 "/sys/class/power_supply/%s/energy_now",
95 path
, sizeof(path
)) ||
96 pscanf(path
, "%" PRIuMAX
, &charge_now
) < 0) {
100 if (!strcmp(state
, "Discharging")) {
101 if (!pick(bat
, "/sys/class/power_supply/%s/current_now",
102 "/sys/class/power_supply/%s/power_now", path
,
104 pscanf(path
, "%" PRIuMAX
, ¤t_now
) < 0) {
108 if (current_now
== 0) {
112 timeleft
= (double)charge_now
/ (double)current_now
;
114 m
= (timeleft
- (double)h
) * 60;
116 return bprintf("%" PRIuMAX
"h %" PRIuMAX
"m", h
, m
);
121 #elif defined(__OpenBSD__)
123 #include <machine/apmvar.h>
124 #include <sys/ioctl.h>
128 load_apm_power_info(struct apm_power_info
*apm_info
)
132 fd
= open("/dev/apm", O_RDONLY
);
134 warn("open '/dev/apm':");
138 memset(apm_info
, 0, sizeof(struct apm_power_info
));
139 if (ioctl(fd
, APM_IOC_GETPOWER
, apm_info
) < 0) {
140 warn("ioctl 'APM_IOC_GETPOWER':");
148 battery_perc(const char *unused
)
150 struct apm_power_info apm_info
;
152 if (load_apm_power_info(&apm_info
)) {
153 return bprintf("%d", apm_info
.battery_life
);
160 battery_state(const char *unused
)
169 struct apm_power_info apm_info
;
172 if (load_apm_power_info(&apm_info
)) {
173 for (i
= 0; i
< LEN(map
); i
++) {
174 if (map
[i
].state
== apm_info
.ac_state
) {
178 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
185 battery_remaining(const char *unused
)
187 struct apm_power_info apm_info
;
189 if (load_apm_power_info(&apm_info
)) {
190 if (apm_info
.ac_state
!= APM_AC_ON
) {
191 return bprintf("%uh %02um",
192 apm_info
.minutes_left
/ 60,
193 apm_info
.minutes_left
% 60);