Xinqi Bao's Git
1 /* See LICENSE file for copyright and license details. */
12 #define CHARGE_NOW "/sys/class/power_supply/%s/charge_now"
13 #define ENERGY_NOW "/sys/class/power_supply/%s/energy_now"
14 #define CURRENT_NOW "/sys/class/power_supply/%s/current_now"
15 #define POWER_NOW "/sys/class/power_supply/%s/power_now"
18 pick(const char *bat
, const char *f1
, const char *f2
, char *path
,
21 if (esnprintf(path
, length
, f1
, bat
) > 0 &&
22 access(path
, R_OK
) == 0) {
26 if (esnprintf(path
, length
, f2
, bat
) > 0 &&
27 access(path
, R_OK
) == 0) {
35 battery_perc(const char *bat
)
40 if (esnprintf(path
, sizeof(path
),
41 "/sys/class/power_supply/%s/capacity",
45 if (pscanf(path
, "%d", &perc
) != 1) {
49 return bprintf("%d", perc
);
53 battery_state(const char *bat
)
60 { "Discharging", "-" },
63 char path
[PATH_MAX
], state
[12];
65 if (esnprintf(path
, sizeof(path
),
66 "/sys/class/power_supply/%s/status",
70 if (pscanf(path
, "%12s", state
) != 1) {
74 for (i
= 0; i
< LEN(map
); i
++) {
75 if (!strcmp(map
[i
].state
, state
)) {
79 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
83 battery_remaining(const char *bat
)
85 int charge_now
, current_now
, m
, h
;
87 char path
[PATH_MAX
], state
[12];
89 if (esnprintf(path
, sizeof(path
),
90 "/sys/class/power_supply/%s/status",
94 if (pscanf(path
, "%12s", state
) != 1) {
98 if (!pick(bat
, CHARGE_NOW
, ENERGY_NOW
, path
, sizeof(path
)) ||
99 pscanf(path
, "%d", &charge_now
) < 0) {
103 if (!strcmp(state
, "Discharging")) {
104 if (!pick(bat
, CURRENT_NOW
, POWER_NOW
, path
,
106 pscanf(path
, "%d", ¤t_now
) < 0) {
110 if (current_now
== 0) {
114 timeleft
= (double)charge_now
/ (double)current_now
;
116 m
= (timeleft
- (double)h
) * 60;
118 return bprintf("%dh %dm", h
, m
);
123 #elif defined(__OpenBSD__)
125 #include <machine/apmvar.h>
126 #include <sys/ioctl.h>
130 load_apm_power_info(struct apm_power_info
*apm_info
)
134 fd
= open("/dev/apm", O_RDONLY
);
136 warn("open '/dev/apm':");
140 memset(apm_info
, 0, sizeof(struct apm_power_info
));
141 if (ioctl(fd
, APM_IOC_GETPOWER
, apm_info
) < 0) {
142 warn("ioctl 'APM_IOC_GETPOWER':");
150 battery_perc(const char *unused
)
152 struct apm_power_info apm_info
;
154 if (load_apm_power_info(&apm_info
)) {
155 return bprintf("%d", apm_info
.battery_life
);
162 battery_state(const char *unused
)
171 struct apm_power_info apm_info
;
174 if (load_apm_power_info(&apm_info
)) {
175 for (i
= 0; i
< LEN(map
); i
++) {
176 if (map
[i
].state
== apm_info
.ac_state
) {
180 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
187 battery_remaining(const char *unused
)
189 struct apm_power_info apm_info
;
191 if (load_apm_power_info(&apm_info
)) {
192 if (apm_info
.ac_state
!= APM_AC_ON
) {
193 return bprintf("%uh %02um",
194 apm_info
.minutes_left
/ 60,
195 apm_info
.minutes_left
% 60);