1 // vim:ts=4:sw=4:expandtab
7 #include <yajl/yajl_gen.h>
8 #include <yajl/yajl_version.h>
15 #include <sys/types.h>
18 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
19 #include <sys/types.h>
20 #include <sys/sysctl.h>
21 #include <dev/acpica/acpiio.h>
24 #if defined(__OpenBSD__)
25 #include <sys/types.h>
26 #include <sys/ioctl.h>
27 #include <sys/fcntl.h>
28 #include <machine/apmvar.h>
31 #if defined(__NetBSD__)
33 #include <prop/proplib.h>
34 #include <sys/envsys.h>
44 /* A description of the state of one or more batteries. */
46 /* measured properties */
47 int full_design; /* in uAh */
48 int full_last; /* in uAh */
49 int remaining; /* in uAh */
50 int present_rate; /* in uA, always non-negative */
52 /* derived properties */
53 int seconds_remaining;
54 float percentage_remaining;
55 charging_status_t status;
58 #if defined(LINUX) || defined(__NetBSD__)
60 * Add batt_info data to acc.
62 static void add_battery_info(struct battery_info *acc, const struct battery_info *batt_info) {
63 if (acc->remaining < 0) {
64 /* initialize accumulator so we can add to it */
68 acc->present_rate = 0;
71 acc->full_design += batt_info->full_design;
72 acc->full_last += batt_info->full_last;
73 acc->remaining += batt_info->remaining;
75 /* make present_rate negative for discharging and positive for charging */
76 int present_rate = (acc->status == CS_DISCHARGING ? -1 : 1) * acc->present_rate;
77 present_rate += (batt_info->status == CS_DISCHARGING ? -1 : 1) * batt_info->present_rate;
80 switch (acc->status) {
82 acc->status = batt_info->status;
87 acc->status = CS_CHARGING;
88 /* else if batt_info is DISCHARGING: no conflict
89 * else if batt_info is CHARGING: present_rate should indicate that
90 * else if batt_info is FULL: but something else is discharging */
95 acc->status = CS_DISCHARGING;
96 /* else if batt_info is DISCHARGING: present_rate should indicate that
97 * else if batt_info is CHARGING: no conflict
98 * else if batt_info is FULL: but something else is charging */
102 if (batt_info->status != CS_UNKNOWN)
103 acc->status = batt_info->status;
104 /* else: retain FULL, since it is more specific than UNKNOWN */
108 acc->present_rate = abs(present_rate);
112 static bool slurp_battery_info(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, int number, const char *path, const char *format_down) {
113 char *outwalk = buffer;
117 const char *walk, *last;
118 bool watt_as_unit = false;
121 sprintf(batpath, path, number);
124 if (!slurp(batpath, buf, sizeof(buf))) {
125 OUTPUT_FULL_TEXT(format_down);
129 for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
138 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW=")) {
140 batt_info->remaining = atoi(walk + 1);
141 batt_info->percentage_remaining = -1;
142 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW=")) {
143 watt_as_unit = false;
144 batt_info->remaining = atoi(walk + 1);
145 batt_info->percentage_remaining = -1;
146 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CAPACITY=") && batt_info->remaining == -1) {
147 batt_info->percentage_remaining = atoi(walk + 1);
148 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW="))
149 batt_info->present_rate = abs(atoi(walk + 1));
150 else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW="))
151 voltage = abs(atoi(walk + 1));
152 /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
153 * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
154 * unit instead of μAh. We will calculate it as we need it
156 else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW="))
157 batt_info->present_rate = abs(atoi(walk + 1));
158 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
159 batt_info->status = CS_CHARGING;
160 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
161 batt_info->status = CS_FULL;
162 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging"))
163 batt_info->status = CS_DISCHARGING;
164 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
165 batt_info->status = CS_UNKNOWN;
166 else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN=") ||
167 BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN="))
168 batt_info->full_design = atoi(walk + 1);
169 else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL=") ||
170 BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL="))
171 batt_info->full_last = atoi(walk + 1);
174 /* the difference between POWER_SUPPLY_ENERGY_NOW and
175 * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
176 * given in mWh, the charge in mAh. So calculate every value given in
178 if (!watt_as_unit && voltage >= 0) {
179 if (batt_info->present_rate > 0) {
180 batt_info->present_rate = (((float)voltage / 1000.0) * ((float)batt_info->present_rate / 1000.0));
182 if (batt_info->remaining > 0) {
183 batt_info->remaining = (((float)voltage / 1000.0) * ((float)batt_info->remaining / 1000.0));
185 if (batt_info->full_design > 0) {
186 batt_info->full_design = (((float)voltage / 1000.0) * ((float)batt_info->full_design / 1000.0));
188 if (batt_info->full_last > 0) {
189 batt_info->full_last = (((float)voltage / 1000.0) * ((float)batt_info->full_last / 1000.0));
192 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
195 size_t sysctl_size = sizeof(sysctl_rslt);
197 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
198 OUTPUT_FULL_TEXT(format_down);
202 batt_info->percentage_remaining = sysctl_rslt;
203 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
204 OUTPUT_FULL_TEXT(format_down);
208 batt_info->seconds_remaining = sysctl_rslt * 60;
209 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
210 OUTPUT_FULL_TEXT(format_down);
215 if (state == 0 && batt_info->percentage_remaining == 100)
216 batt_info->status = CS_FULL;
217 else if ((state & ACPI_BATT_STAT_CHARGING) && batt_info->percentage_remaining < 100)
218 batt_info->status = CS_CHARGING;
220 batt_info->status = CS_DISCHARGING;
221 #elif defined(__OpenBSD__)
223 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
224 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
225 * probing acpi(4) devices.
227 struct apm_power_info apm_info;
230 apm_fd = open("/dev/apm", O_RDONLY);
232 OUTPUT_FULL_TEXT("can't open /dev/apm");
235 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
236 OUTPUT_FULL_TEXT("can't read power info");
240 /* Don't bother to go further if there's no battery present. */
241 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
242 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
243 OUTPUT_FULL_TEXT(format_down);
247 switch (apm_info.ac_state) {
249 batt_info->status = CS_DISCHARGING;
252 batt_info->status = CS_CHARGING;
255 /* If we don't know what's going on, just assume we're discharging. */
256 batt_info->status = CS_DISCHARGING;
260 batt_info->percentage_remaining = apm_info.battery_life;
262 /* Can't give a meaningful value for remaining minutes if we're charging. */
263 if (batt_info->status != CS_CHARGING) {
264 batt_info->seconds_remaining = apm_info.minutes_left * 60;
266 #elif defined(__NetBSD__)
268 * Using envsys(4) via sysmon(4).
271 bool is_found = false;
272 char sensor_desc[16];
274 prop_dictionary_t dict;
276 prop_object_iterator_t iter;
277 prop_object_iterator_t iter2;
278 prop_object_t obj, obj2, obj3, obj4, obj5;
281 (void)snprintf(sensor_desc, sizeof(sensor_desc), "acpibat%d", number);
283 fd = open("/dev/sysmon", O_RDONLY);
285 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
289 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
295 if (prop_dictionary_count(dict) == 0) {
296 prop_object_release(dict);
301 iter = prop_dictionary_iterator(dict);
303 prop_object_release(dict);
307 /* iterate over the dictionary returned by the kernel */
308 while ((obj = prop_object_iterator_next(iter)) != NULL) {
309 /* skip this dict if it's not what we're looking for */
311 /* we want all batteries */
312 if (!BEGINS_WITH(prop_dictionary_keysym_cstring_nocopy(obj),
316 /* we want a specific battery */
317 if (strcmp(sensor_desc,
318 prop_dictionary_keysym_cstring_nocopy(obj)) != 0)
324 array = prop_dictionary_get_keysym(dict, obj);
325 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
326 prop_object_iterator_release(iter);
327 prop_object_release(dict);
332 iter2 = prop_array_iterator(array);
334 prop_object_iterator_release(iter);
335 prop_object_release(dict);
340 struct battery_info batt_buf = {
345 .status = CS_UNKNOWN,
348 bool watt_as_unit = false;
350 /* iterate over array of dicts specific to target battery */
351 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
352 obj3 = prop_dictionary_get(obj2, "description");
357 if (strcmp("charging", prop_string_cstring_nocopy(obj3)) == 0) {
358 obj3 = prop_dictionary_get(obj2, "cur-value");
360 if (prop_number_integer_value(obj3))
361 batt_buf.status = CS_CHARGING;
363 batt_buf.status = CS_DISCHARGING;
364 } else if (strcmp("charge", prop_string_cstring_nocopy(obj3)) == 0) {
365 obj3 = prop_dictionary_get(obj2, "cur-value");
366 obj4 = prop_dictionary_get(obj2, "max-value");
367 obj5 = prop_dictionary_get(obj2, "type");
369 batt_buf.remaining = prop_number_integer_value(obj3);
370 batt_buf.full_design = prop_number_integer_value(obj4);
372 if (strcmp("Ampere hour", prop_string_cstring_nocopy(obj5)) == 0)
373 watt_as_unit = false;
376 } else if (strcmp("discharge rate", prop_string_cstring_nocopy(obj3)) == 0) {
377 obj3 = prop_dictionary_get(obj2, "cur-value");
378 batt_buf.present_rate = prop_number_integer_value(obj3);
379 } else if (strcmp("charge rate", prop_string_cstring_nocopy(obj3)) == 0) {
380 obj3 = prop_dictionary_get(obj2, "cur-value");
381 batt_info->present_rate = prop_number_integer_value(obj3);
382 } else if (strcmp("last full cap", prop_string_cstring_nocopy(obj3)) == 0) {
383 obj3 = prop_dictionary_get(obj2, "cur-value");
384 batt_buf.full_last = prop_number_integer_value(obj3);
385 } else if (strcmp("voltage", prop_string_cstring_nocopy(obj3)) == 0) {
386 obj3 = prop_dictionary_get(obj2, "cur-value");
387 voltage = prop_number_integer_value(obj3);
390 prop_object_iterator_release(iter2);
392 if (!watt_as_unit && voltage != -1) {
393 batt_buf.present_rate = (((float)voltage / 1000.0) * ((float)batt_buf.present_rate / 1000.0));
394 batt_buf.remaining = (((float)voltage / 1000.0) * ((float)batt_buf.remaining / 1000.0));
395 batt_buf.full_design = (((float)voltage / 1000.0) * ((float)batt_buf.full_design / 1000.0));
396 batt_buf.full_last = (((float)voltage / 1000.0) * ((float)batt_buf.full_last / 1000.0));
399 if (batt_buf.remaining == batt_buf.full_design)
400 batt_buf.status = CS_FULL;
402 add_battery_info(batt_info, &batt_buf);
405 prop_object_iterator_release(iter);
406 prop_object_release(dict);
410 OUTPUT_FULL_TEXT(format_down);
414 batt_info->present_rate = abs(batt_info->present_rate);
421 * Populate batt_info with aggregate information about all batteries.
422 * Returns false on error, and an error message will have been written.
424 static bool slurp_all_batteries(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, const char *path, const char *format_down) {
426 char *outwalk = buffer;
427 bool is_found = false;
430 char *globpath = sstrdup(path);
431 if ((placeholder = strstr(path, "%d")) != NULL) {
432 char *globplaceholder = globpath + (placeholder - path);
433 *globplaceholder = '*';
434 strcpy(globplaceholder + 1, placeholder + 2);
437 if (!strcmp(globpath, path)) {
438 OUTPUT_FULL_TEXT("no '%d' in battery path");
443 if (glob(globpath, 0, NULL, &globbuf) == 0) {
444 for (size_t i = 0; i < globbuf.gl_pathc; i++) {
445 /* Probe to see if there is such a battery. */
446 struct battery_info batt_buf = {
451 .status = CS_UNKNOWN,
453 if (!slurp_battery_info(&batt_buf, json_gen, buffer, i, globbuf.gl_pathv[i], format_down))
457 add_battery_info(batt_info, &batt_buf);
464 OUTPUT_FULL_TEXT(format_down);
468 batt_info->present_rate = abs(batt_info->present_rate);
470 /* FreeBSD and OpenBSD only report aggregates. NetBSD always
471 * iterates through all batteries, so it's more efficient to
472 * aggregate in slurp_battery_info. */
473 return slurp_battery_info(batt_info, json_gen, buffer, -1, path, format_down);
479 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) {
481 char *outwalk = buffer;
482 struct battery_info batt_info = {
487 .seconds_remaining = -1,
488 .percentage_remaining = -1,
489 .status = CS_UNKNOWN,
491 bool colorful_output = false;
493 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
494 /* These OSes report battery stats in whole percent. */
495 integer_battery_capacity = true;
497 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
498 /* These OSes report battery time in minutes. */
503 if (!slurp_all_batteries(&batt_info, json_gen, buffer, path, format_down))
506 if (!slurp_battery_info(&batt_info, json_gen, buffer, number, path, format_down))
510 // *Choose* a measure of the 'full' battery. It is whichever is better of
511 // the battery's (hardware-given) design capacity (batt_info.full_design)
512 // and the battery's last known good charge (batt_info.full_last).
513 // We prefer the design capacity, but use the last capacity if we don't have it,
514 // or if we are asked to (last_full_capacity == true); but similarly we use
515 // the design capacity if we don't have the last capacity.
516 // If we don't have either then both full_design and full_last <= 0,
517 // which implies full <= 0, which bails out on the following line.
518 int full = batt_info.full_design;
519 if (full <= 0 || (last_full_capacity && batt_info.full_last > 0)) {
520 full = batt_info.full_last;
522 if (full <= 0 && batt_info.remaining < 0 && batt_info.percentage_remaining < 0) {
523 /* We have no physical measurements and no estimates. Nothing
524 * much we can report, then. */
525 OUTPUT_FULL_TEXT(format_down);
529 if (batt_info.percentage_remaining < 0) {
530 batt_info.percentage_remaining = (((float)batt_info.remaining / (float)full) * 100);
531 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
532 * charged, even though that’s plainly wrong. For people who chose to see
533 * the percentage calculated based on the last full capacity, we clamp the
534 * value to 100%, as that makes more sense.
535 * See http://bugs.debian.org/785398 */
536 if (last_full_capacity && batt_info.percentage_remaining > 100) {
537 batt_info.percentage_remaining = 100;
541 if (batt_info.seconds_remaining < 0 && batt_info.present_rate > 0 && batt_info.status != CS_FULL) {
542 if (batt_info.status == CS_CHARGING)
543 batt_info.seconds_remaining = 3600.0 * (full - batt_info.remaining) / batt_info.present_rate;
544 else if (batt_info.status == CS_DISCHARGING)
545 batt_info.seconds_remaining = 3600.0 * batt_info.remaining / batt_info.present_rate;
547 batt_info.seconds_remaining = 0;
550 if (batt_info.status == CS_DISCHARGING && low_threshold > 0) {
551 if (batt_info.percentage_remaining >= 0 && strcasecmp(threshold_type, "percentage") == 0 && batt_info.percentage_remaining < low_threshold) {
552 START_COLOR("color_bad");
553 colorful_output = true;
554 } else if (batt_info.seconds_remaining >= 0 && strcasecmp(threshold_type, "time") == 0 && batt_info.seconds_remaining < 60 * low_threshold) {
555 START_COLOR("color_bad");
556 colorful_output = true;
560 #define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT() \
562 if (outwalk == prevoutwalk) { \
563 if (outwalk > buffer && isspace((int)outwalk[-1])) \
565 else if (isspace((int)*(walk + 1))) \
570 for (walk = format; *walk != '\0'; walk++) {
571 char *prevoutwalk = outwalk;
574 *(outwalk++) = *walk;
578 if (BEGINS_WITH(walk + 1, "status")) {
579 const char *statusstr;
580 switch (batt_info.status) {
582 statusstr = status_chr;
585 statusstr = status_bat;
588 statusstr = status_full;
591 statusstr = status_unk;
594 outwalk += sprintf(outwalk, "%s", statusstr);
595 walk += strlen("status");
596 } else if (BEGINS_WITH(walk + 1, "percentage")) {
597 if (integer_battery_capacity) {
598 outwalk += sprintf(outwalk, "%.00f%s", batt_info.percentage_remaining, pct_mark);
600 outwalk += sprintf(outwalk, "%.02f%s", batt_info.percentage_remaining, pct_mark);
602 walk += strlen("percentage");
603 } else if (BEGINS_WITH(walk + 1, "remaining")) {
604 if (batt_info.seconds_remaining >= 0) {
605 int seconds, hours, minutes;
607 hours = batt_info.seconds_remaining / 3600;
608 seconds = batt_info.seconds_remaining - (hours * 3600);
609 minutes = seconds / 60;
610 seconds -= (minutes * 60);
613 outwalk += sprintf(outwalk, "%02d:%02d",
614 max(hours, 0), max(minutes, 0));
616 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
617 max(hours, 0), max(minutes, 0), max(seconds, 0));
619 walk += strlen("remaining");
620 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
621 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
622 if (batt_info.seconds_remaining >= 0) {
623 time_t empty_time = time(NULL) + batt_info.seconds_remaining;
624 set_timezone(NULL); /* Use local time. */
625 struct tm *empty_tm = localtime(&empty_time);
628 outwalk += sprintf(outwalk, "%02d:%02d",
629 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
631 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
632 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
634 walk += strlen("emptytime");
635 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
636 } else if (BEGINS_WITH(walk + 1, "consumption")) {
637 if (batt_info.present_rate >= 0)
638 outwalk += sprintf(outwalk, "%1.2fW", batt_info.present_rate / 1e6);
640 walk += strlen("consumption");
641 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
648 OUTPUT_FULL_TEXT(buffer);