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", bat
) < 0) {
39 if (pscanf(path
, "%d", &perc
) != 1) {
43 return bprintf("%d", perc
);
47 battery_state(const char *bat
)
54 { "Discharging", "-" },
57 char path
[PATH_MAX
], state
[12];
59 if (esnprintf(path
, sizeof(path
),
60 "/sys/class/power_supply/%s/status", bat
) < 0) {
63 if (pscanf(path
, "%12s", state
) != 1) {
67 for (i
= 0; i
< LEN(map
); i
++) {
68 if (!strcmp(map
[i
].state
, state
)) {
72 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
76 battery_remaining(const char *bat
)
78 uintmax_t charge_now
, current_now
, m
, h
;
80 char path
[PATH_MAX
], state
[12];
82 if (esnprintf(path
, sizeof(path
),
83 "/sys/class/power_supply/%s/status", bat
) < 0) {
86 if (pscanf(path
, "%12s", state
) != 1) {
90 if (!pick(bat
, "/sys/class/power_supply/%s/charge_now",
91 "/sys/class/power_supply/%s/energy_now", path
,
93 pscanf(path
, "%ju", &charge_now
) < 0) {
97 if (!strcmp(state
, "Discharging")) {
98 if (!pick(bat
, "/sys/class/power_supply/%s/current_now",
99 "/sys/class/power_supply/%s/power_now", path
,
101 pscanf(path
, "%ju", ¤t_now
) < 0) {
105 if (current_now
== 0) {
109 timeleft
= (double)charge_now
/ (double)current_now
;
111 m
= (timeleft
- (double)h
) * 60;
113 return bprintf("%juh %jum", h
, m
);
118 #elif defined(__OpenBSD__)
120 #include <machine/apmvar.h>
121 #include <sys/ioctl.h>
125 load_apm_power_info(struct apm_power_info
*apm_info
)
129 fd
= open("/dev/apm", O_RDONLY
);
131 warn("open '/dev/apm':");
135 memset(apm_info
, 0, sizeof(struct apm_power_info
));
136 if (ioctl(fd
, APM_IOC_GETPOWER
, apm_info
) < 0) {
137 warn("ioctl 'APM_IOC_GETPOWER':");
145 battery_perc(const char *unused
)
147 struct apm_power_info apm_info
;
149 if (load_apm_power_info(&apm_info
)) {
150 return bprintf("%d", apm_info
.battery_life
);
157 battery_state(const char *unused
)
166 struct apm_power_info apm_info
;
169 if (load_apm_power_info(&apm_info
)) {
170 for (i
= 0; i
< LEN(map
); i
++) {
171 if (map
[i
].state
== apm_info
.ac_state
) {
175 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
182 battery_remaining(const char *unused
)
184 struct apm_power_info apm_info
;
186 if (load_apm_power_info(&apm_info
)) {
187 if (apm_info
.ac_state
!= APM_AC_ON
) {
188 return bprintf("%uh %02um",
189 apm_info
.minutes_left
/ 60,
190 apm_info
.minutes_left
% 60);