Xinqi Bao's Git
fa525be15b5d035c8a5118c8707d4bde2213bda3
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 timeleft
= (double)charge_now
/ (double)current_now
;
112 m
= (timeleft
- (double)h
) * 60;
114 return bprintf("%dh %dm", h
, m
);
119 #elif defined(__OpenBSD__)
121 #include <machine/apmvar.h>
122 #include <sys/ioctl.h>
126 load_apm_power_info(struct apm_power_info
*apm_info
)
130 fd
= open("/dev/apm", O_RDONLY
);
132 warn("open '/dev/apm':");
136 memset(apm_info
, 0, sizeof(struct apm_power_info
));
137 if (ioctl(fd
, APM_IOC_GETPOWER
, apm_info
) < 0) {
138 warn("ioctl 'APM_IOC_GETPOWER':");
146 battery_perc(const char *unused
)
148 struct apm_power_info apm_info
;
150 if (load_apm_power_info(&apm_info
)) {
151 return bprintf("%d", apm_info
.battery_life
);
158 battery_state(const char *unused
)
167 struct apm_power_info apm_info
;
170 if (load_apm_power_info(&apm_info
)) {
171 for (i
= 0; i
< LEN(map
); i
++) {
172 if (map
[i
].state
== apm_info
.ac_state
) {
176 return (i
== LEN(map
)) ? "?" : map
[i
].symbol
;
183 battery_remaining(const char *unused
)
185 struct apm_power_info apm_info
;
187 if (load_apm_power_info(&apm_info
)) {
188 if (apm_info
.ac_state
!= APM_AC_ON
) {
189 return bprintf("%uh %02um",
190 apm_info
.minutes_left
/ 60,
191 apm_info
.minutes_left
% 60);