1 // vim:ts=4:sw=4:expandtab
7 #include <yajl/yajl_gen.h>
8 #include <yajl/yajl_version.h>
12 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
13 #include <sys/types.h>
14 #include <sys/sysctl.h>
15 #include <dev/acpica/acpiio.h>
18 #if defined(__OpenBSD__)
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 #include <sys/fcntl.h>
22 #include <machine/apmvar.h>
25 #if defined(__NetBSD__)
27 #include <prop/proplib.h>
28 #include <sys/envsys.h>
32 * Get battery information from /sys. Note that it uses the design capacity to
33 * calculate the percentage, not the last full capacity, so you can see how
34 * worn off your battery is.
37 void print_battery_info(yajl_gen json_gen, char *buffer, int number, const char *path, const char *format, const char *format_down, const char *status_chr, const char *status_bat, const char *status_unk, const char *status_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) {
42 char percentagebuf[16];
43 char remainingbuf[256];
44 char emptytimebuf[256];
45 char consumptionbuf[256];
46 const char *walk, *last;
47 char *outwalk = buffer;
48 bool watt_as_unit = false;
49 bool colorful_output = false;
54 charging_status_t status = CS_DISCHARGING;
56 memset(statusbuf, '\0', sizeof(statusbuf));
57 memset(percentagebuf, '\0', sizeof(percentagebuf));
58 memset(remainingbuf, '\0', sizeof(remainingbuf));
59 memset(emptytimebuf, '\0', sizeof(emptytimebuf));
60 memset(consumptionbuf, '\0', sizeof(consumptionbuf));
62 static char batpath[512];
63 sprintf(batpath, path, number);
66 #define BATT_STATUS_NAME(status) \
67 (status == CS_CHARGING ? status_chr : (status == CS_DISCHARGING ? status_bat : (status == CS_UNKNOWN ? status_unk : status_full)))
70 if (!slurp(batpath, buf, sizeof(buf))) {
71 OUTPUT_FULL_TEXT(format_down);
75 for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
84 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW")) {
86 remaining = atoi(walk + 1);
87 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW")) {
89 remaining = atoi(walk + 1);
90 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
91 present_rate = abs(atoi(walk + 1));
92 else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW"))
93 voltage = abs(atoi(walk + 1));
94 /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
95 * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
96 * unit instead of μAh. We will calculate it as we need it
98 else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW"))
99 present_rate = abs(atoi(walk + 1));
100 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
101 status = CS_CHARGING;
102 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
104 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging"))
105 status = CS_DISCHARGING;
106 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
109 /* The only thing left is the full capacity */
110 if (last_full_capacity) {
111 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
112 !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
115 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
116 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
120 full_design = atoi(walk + 1);
124 /* the difference between POWER_SUPPLY_ENERGY_NOW and
125 * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
126 * given in mWh, the charge in mAh. So calculate every value given in
129 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
132 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
133 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
137 if ((full_design == -1) || (remaining == -1)) {
138 OUTPUT_FULL_TEXT(format_down);
142 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
144 float percentage_remaining = (((float)remaining / (float)full_design) * 100);
145 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
146 * charged, even though that’s plainly wrong. For people who chose to see
147 * the percentage calculated based on the last full capacity, we clamp the
148 * value to 100%, as that makes more sense.
149 * See http://bugs.debian.org/785398 */
150 if (last_full_capacity && percentage_remaining > 100) {
151 percentage_remaining = 100;
153 if (integer_battery_capacity) {
154 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00f%s", percentage_remaining, pct_mark);
156 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.02f%s", percentage_remaining, pct_mark);
159 if (present_rate > 0 && status != CS_FULL) {
160 float remaining_time;
161 int seconds, hours, minutes, seconds_remaining;
162 if (status == CS_CHARGING)
163 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
164 else if (status == CS_DISCHARGING)
165 remaining_time = ((float)remaining / (float)present_rate);
169 seconds_remaining = (int)(remaining_time * 3600.0);
171 hours = seconds_remaining / 3600;
172 seconds = seconds_remaining - (hours * 3600);
173 minutes = seconds / 60;
174 seconds -= (minutes * 60);
176 if (status == CS_DISCHARGING && low_threshold > 0) {
177 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
178 START_COLOR("color_bad");
179 colorful_output = true;
180 } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) {
181 START_COLOR("color_bad");
182 colorful_output = true;
184 colorful_output = false;
189 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
190 max(hours, 0), max(minutes, 0));
192 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
193 max(hours, 0), max(minutes, 0), max(seconds, 0));
195 empty_time = time(NULL);
196 empty_time += seconds_remaining;
197 empty_tm = localtime(&empty_time);
200 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
201 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
203 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
204 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
206 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
207 ((float)present_rate / 1000.0 / 1000.0));
209 /* On some systems, present_rate may not exist. Still, make sure
210 * we colorize the output if threshold_type is set to percentage
211 * (since we don't have any information on remaining time). */
212 if (status == CS_DISCHARGING && low_threshold > 0) {
213 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
214 START_COLOR("color_bad");
215 colorful_output = true;
219 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
222 size_t sysctl_size = sizeof(sysctl_rslt);
224 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
225 OUTPUT_FULL_TEXT(format_down);
229 present_rate = sysctl_rslt;
230 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
231 OUTPUT_FULL_TEXT(format_down);
235 remaining = sysctl_rslt;
236 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
237 OUTPUT_FULL_TEXT(format_down);
242 if (state == 0 && present_rate == 100)
244 else if ((state & ACPI_BATT_STAT_CHARGING) && present_rate < 100)
245 status = CS_CHARGING;
247 status = CS_DISCHARGING;
249 full_design = sysctl_rslt;
251 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
253 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%02d%s",
254 present_rate, pct_mark);
256 if (state == ACPI_BATT_STAT_DISCHARG) {
259 hours = minutes / 60;
260 minutes -= (hours * 60);
261 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
262 max(hours, 0), max(minutes, 0));
263 if (strcasecmp(threshold_type, "percentage") == 0 && present_rate < low_threshold) {
264 START_COLOR("color_bad");
265 colorful_output = true;
266 } else if (strcasecmp(threshold_type, "time") == 0 && remaining < (u_int)low_threshold) {
267 START_COLOR("color_bad");
268 colorful_output = true;
271 #elif defined(__OpenBSD__)
273 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
274 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
275 * probing acpi(4) devices.
277 struct apm_power_info apm_info;
280 apm_fd = open("/dev/apm", O_RDONLY);
282 OUTPUT_FULL_TEXT("can't open /dev/apm");
285 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
286 OUTPUT_FULL_TEXT("can't read power info");
290 /* Don't bother to go further if there's no battery present. */
291 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
292 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
293 OUTPUT_FULL_TEXT(format_down);
297 switch (apm_info.ac_state) {
299 status = CS_DISCHARGING;
302 status = CS_CHARGING;
305 /* If we don't know what's going on, just assume we're discharging. */
306 status = CS_DISCHARGING;
310 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
311 /* integer_battery_capacity is implied as battery_life is already in whole numbers. */
312 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00d%s", apm_info.battery_life, pct_mark);
314 if (status == CS_DISCHARGING && low_threshold > 0) {
315 if (strcasecmp(threshold_type, "percentage") == 0 && apm_info.battery_life < low_threshold) {
316 START_COLOR("color_bad");
317 colorful_output = true;
318 } else if (strcasecmp(threshold_type, "time") == 0 && apm_info.minutes_left < (u_int)low_threshold) {
319 START_COLOR("color_bad");
320 colorful_output = true;
324 /* Can't give a meaningful value for remaining minutes if we're charging. */
325 if (status != CS_CHARGING) {
326 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", apm_info.minutes_left / 60, apm_info.minutes_left % 60);
328 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%s", "(CHR)");
333 #elif defined(__NetBSD__)
335 * Using envsys(4) via sysmon(4).
337 int fd, rval, last_full_cap;
338 bool is_found = false;
340 bool is_full = false;
342 prop_dictionary_t dict;
344 prop_object_iterator_t iter;
345 prop_object_iterator_t iter2;
346 prop_object_t obj, obj2, obj3, obj4, obj5;
348 asprintf(&sensor_desc, "acpibat%d", number);
350 fd = open("/dev/sysmon", O_RDONLY);
352 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
356 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
362 if (prop_dictionary_count(dict) == 0) {
363 prop_object_release(dict);
368 iter = prop_dictionary_iterator(dict);
370 prop_object_release(dict);
374 /* iterate over the dictionary returned by the kernel */
375 while ((obj = prop_object_iterator_next(iter)) != NULL) {
376 /* skip this dict if it's not what we're looking for */
377 if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) &&
378 (strncmp(sensor_desc,
379 prop_dictionary_keysym_cstring_nocopy(obj),
380 strlen(sensor_desc)) != 0))
385 array = prop_dictionary_get_keysym(dict, obj);
386 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
387 prop_object_iterator_release(iter);
388 prop_object_release(dict);
393 iter2 = prop_array_iterator(array);
395 prop_object_iterator_release(iter);
396 prop_object_release(dict);
401 /* iterate over array of dicts specific to target battery */
402 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
403 obj3 = prop_dictionary_get(obj2, "description");
406 strlen(prop_string_cstring_nocopy(obj3)) == 8 &&
408 prop_string_cstring_nocopy(obj3),
410 obj3 = prop_dictionary_get(obj2, "cur-value");
412 if (prop_number_integer_value(obj3))
413 status = CS_CHARGING;
415 status = CS_DISCHARGING;
421 strlen(prop_string_cstring_nocopy(obj3)) == 6 &&
423 prop_string_cstring_nocopy(obj3),
425 obj3 = prop_dictionary_get(obj2, "cur-value");
426 obj4 = prop_dictionary_get(obj2, "max-value");
427 obj5 = prop_dictionary_get(obj2, "type");
429 remaining = prop_number_integer_value(obj3);
430 full_design = prop_number_integer_value(obj4);
432 if (remaining == full_design)
435 if (strncmp("Ampere hour",
436 prop_string_cstring_nocopy(obj5),
438 watt_as_unit = false;
446 strlen(prop_string_cstring_nocopy(obj3)) == 14 &&
447 strncmp("discharge rate",
448 prop_string_cstring_nocopy(obj3),
450 obj3 = prop_dictionary_get(obj2, "cur-value");
451 present_rate = prop_number_integer_value(obj3);
456 strlen(prop_string_cstring_nocopy(obj3)) == 13 &&
457 strncmp("last full cap",
458 prop_string_cstring_nocopy(obj3),
460 obj3 = prop_dictionary_get(obj2, "cur-value");
461 last_full_cap = prop_number_integer_value(obj3);
466 strlen(prop_string_cstring_nocopy(obj3)) == 7 &&
468 prop_string_cstring_nocopy(obj3),
470 obj3 = prop_dictionary_get(obj2, "cur-value");
471 voltage = prop_number_integer_value(obj3);
475 prop_object_iterator_release(iter2);
478 prop_object_iterator_release(iter);
479 prop_object_release(dict);
483 OUTPUT_FULL_TEXT(format_down);
487 if (last_full_capacity)
488 full_design = last_full_cap;
491 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
492 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
493 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
496 float percentage_remaining =
497 (((float)remaining / (float)full_design) * 100);
499 if (integer_battery_capacity)
500 (void)snprintf(percentagebuf,
501 sizeof(percentagebuf),
503 (int)percentage_remaining, pct_mark);
505 (void)snprintf(percentagebuf,
506 sizeof(percentagebuf),
508 percentage_remaining, pct_mark);
511 * Handle percentage low_threshold here, and time low_threshold when
514 if (status == CS_DISCHARGING && low_threshold > 0) {
515 if (strcasecmp(threshold_type, "percentage") == 0 && (((float)remaining / (float)full_design) * 100) < low_threshold) {
516 START_COLOR("color_bad");
517 colorful_output = true;
522 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(CS_FULL));
524 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
527 * The envsys(4) ACPI routines do not appear to provide a 'time
528 * remaining' figure, so we must deduce it.
530 float remaining_time;
531 int seconds, hours, minutes, seconds_remaining;
533 if (status == CS_CHARGING)
534 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
535 else if (status == CS_DISCHARGING)
536 remaining_time = ((float)remaining / (float)present_rate);
540 seconds_remaining = (int)(remaining_time * 3600.0);
542 hours = seconds_remaining / 3600;
543 seconds = seconds_remaining - (hours * 3600);
544 minutes = seconds / 60;
545 seconds -= (minutes * 60);
547 if (status != CS_CHARGING) {
549 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
550 max(hours, 0), max(minutes, 0));
552 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
553 max(hours, 0), max(minutes, 0), max(seconds, 0));
555 if (low_threshold > 0) {
556 if (strcasecmp(threshold_type, "time") == 0 && ((float)seconds_remaining / 60.0) < (u_int)low_threshold) {
557 START_COLOR("color_bad");
558 colorful_output = true;
563 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d until full)",
564 max(hours, 0), max(minutes, 0));
566 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d:%02d until full)",
567 max(hours, 0), max(minutes, 0), max(seconds, 0));
570 empty_time = time(NULL);
571 empty_time += seconds_remaining;
572 empty_tm = localtime(&empty_time);
574 /* No need to show empty time if battery is charging */
575 if (status != CS_CHARGING) {
577 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
578 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
580 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
581 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
584 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
585 ((float)present_rate / 1000.0 / 1000.0));
588 #define EAT_SPACE_FROM_OUTPUT_IF_EMPTY(_buf) \
590 if (strlen(_buf) == 0) { \
591 if (outwalk > buffer && isspace(outwalk[-1])) \
593 else if (isspace(*(walk + 1))) \
598 for (walk = format; *walk != '\0'; walk++) {
600 *(outwalk++) = *walk;
604 if (BEGINS_WITH(walk + 1, "status")) {
605 outwalk += sprintf(outwalk, "%s", statusbuf);
606 walk += strlen("status");
607 } else if (BEGINS_WITH(walk + 1, "percentage")) {
608 outwalk += sprintf(outwalk, "%s", percentagebuf);
609 walk += strlen("percentage");
610 } else if (BEGINS_WITH(walk + 1, "remaining")) {
611 outwalk += sprintf(outwalk, "%s", remainingbuf);
612 walk += strlen("remaining");
613 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(remainingbuf);
614 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
615 outwalk += sprintf(outwalk, "%s", emptytimebuf);
616 walk += strlen("emptytime");
617 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(emptytimebuf);
618 } else if (BEGINS_WITH(walk + 1, "consumption")) {
619 outwalk += sprintf(outwalk, "%s", consumptionbuf);
620 walk += strlen("consumption");
621 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(consumptionbuf);
628 OUTPUT_FULL_TEXT(buffer);