1 // vim:ts=4:sw=4:expandtab
8 #include <yajl/yajl_gen.h>
9 #include <yajl/yajl_version.h>
13 #if defined(__linux__)
16 #include <sys/types.h>
19 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
20 #include <dev/acpica/acpiio.h>
21 #include <sys/sysctl.h>
22 #include <sys/types.h>
25 #if defined(__DragonFly__)
26 #include <sys/fcntl.h>
29 #if defined(__OpenBSD__)
30 #include <machine/apmvar.h>
31 #include <sys/fcntl.h>
32 #include <sys/ioctl.h>
33 #include <sys/types.h>
36 #if defined(__NetBSD__)
38 #include <prop/proplib.h>
39 #include <sys/envsys.h>
49 /* A description of the state of one or more batteries. */
51 /* measured properties */
52 int full_design; /* in uAh */
53 int full_last; /* in uAh */
54 int remaining; /* in uAh */
55 int present_rate; /* in uA, always non-negative */
57 /* derived properties */
58 int seconds_remaining;
59 float percentage_remaining;
60 charging_status_t status;
63 #if defined(__DragonFly__)
64 #define ACPIDEV "/dev/acpi"
67 static bool acpi_init(void) {
69 acpifd = open(ACPIDEV, O_RDWR);
71 acpifd = open(ACPIDEV, O_RDONLY);
79 #if defined(__linux__) || defined(__NetBSD__)
81 * Add batt_info data to acc.
83 static void add_battery_info(struct battery_info *acc, const struct battery_info *batt_info) {
84 if (acc->remaining < 0) {
85 /* initialize accumulator so we can add to it */
89 acc->present_rate = 0;
92 acc->full_design += batt_info->full_design;
93 acc->full_last += batt_info->full_last;
94 acc->remaining += batt_info->remaining;
96 /* make present_rate negative for discharging and positive for charging */
97 int present_rate = (acc->status == CS_DISCHARGING ? -1 : 1) * acc->present_rate;
98 present_rate += (batt_info->status == CS_DISCHARGING ? -1 : 1) * batt_info->present_rate;
101 switch (acc->status) {
103 acc->status = batt_info->status;
107 if (present_rate > 0)
108 acc->status = CS_CHARGING;
109 /* else if batt_info is DISCHARGING: no conflict
110 * else if batt_info is CHARGING: present_rate should indicate that
111 * else if batt_info is FULL: but something else is discharging */
115 if (present_rate < 0)
116 acc->status = CS_DISCHARGING;
117 /* else if batt_info is DISCHARGING: present_rate should indicate that
118 * else if batt_info is CHARGING: no conflict
119 * else if batt_info is FULL: but something else is charging */
123 if (batt_info->status != CS_UNKNOWN)
124 acc->status = batt_info->status;
125 /* else: retain FULL, since it is more specific than UNKNOWN */
129 acc->present_rate = abs(present_rate);
133 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) {
134 char *outwalk = buffer;
136 #if defined(__linux__)
138 const char *walk, *last;
139 bool watt_as_unit = false;
142 sprintf(batpath, path, number);
145 if (!slurp(batpath, buf, sizeof(buf))) {
146 OUTPUT_FULL_TEXT(format_down);
150 for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
159 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW=")) {
161 batt_info->remaining = atoi(walk + 1);
162 batt_info->percentage_remaining = -1;
163 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW=")) {
164 watt_as_unit = false;
165 batt_info->remaining = atoi(walk + 1);
166 batt_info->percentage_remaining = -1;
167 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CAPACITY=") && batt_info->remaining == -1) {
168 batt_info->percentage_remaining = atoi(walk + 1);
169 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW="))
170 batt_info->present_rate = abs(atoi(walk + 1));
171 else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW="))
172 voltage = abs(atoi(walk + 1));
173 /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
174 * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
175 * unit instead of μAh. We will calculate it as we need it
177 else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW="))
178 batt_info->present_rate = abs(atoi(walk + 1));
179 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
180 batt_info->status = CS_CHARGING;
181 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
182 batt_info->status = CS_FULL;
183 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging") || BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Not charging"))
184 batt_info->status = CS_DISCHARGING;
185 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
186 batt_info->status = CS_UNKNOWN;
187 else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN=") ||
188 BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN="))
189 batt_info->full_design = atoi(walk + 1);
190 else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL=") ||
191 BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL="))
192 batt_info->full_last = atoi(walk + 1);
195 /* the difference between POWER_SUPPLY_ENERGY_NOW and
196 * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
197 * given in mWh, the charge in mAh. So calculate every value given in
199 if (!watt_as_unit && voltage >= 0) {
200 if (batt_info->present_rate > 0) {
201 batt_info->present_rate = (((float)voltage / 1000.0) * ((float)batt_info->present_rate / 1000.0));
203 if (batt_info->remaining > 0) {
204 batt_info->remaining = (((float)voltage / 1000.0) * ((float)batt_info->remaining / 1000.0));
206 if (batt_info->full_design > 0) {
207 batt_info->full_design = (((float)voltage / 1000.0) * ((float)batt_info->full_design / 1000.0));
209 if (batt_info->full_last > 0) {
210 batt_info->full_last = (((float)voltage / 1000.0) * ((float)batt_info->full_last / 1000.0));
213 #elif defined(__DragonFly__)
214 union acpi_battery_ioctl_arg battio;
216 battio.unit = number;
217 ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio);
218 batt_info->full_design = battio.bif.dcap;
219 batt_info->full_last = battio.bif.lfcap;
220 battio.unit = number;
221 ioctl(acpifd, ACPIIO_BATT_GET_BATTINFO, &battio);
222 batt_info->percentage_remaining = battio.battinfo.cap;
223 batt_info->present_rate = battio.battinfo.rate;
224 batt_info->seconds_remaining = battio.battinfo.min * 60;
225 switch (battio.battinfo.state) {
227 batt_info->status = CS_FULL;
229 case ACPI_BATT_STAT_CHARGING:
230 batt_info->status = CS_CHARGING;
232 case ACPI_BATT_STAT_DISCHARG:
233 batt_info->status = CS_DISCHARGING;
236 batt_info->status = CS_UNKNOWN;
238 OUTPUT_FULL_TEXT(format_down);
240 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
243 size_t sysctl_size = sizeof(sysctl_rslt);
245 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
246 OUTPUT_FULL_TEXT(format_down);
250 batt_info->percentage_remaining = sysctl_rslt;
251 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
252 OUTPUT_FULL_TEXT(format_down);
256 batt_info->seconds_remaining = sysctl_rslt * 60;
257 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
258 OUTPUT_FULL_TEXT(format_down);
263 if (state == 0 && batt_info->percentage_remaining == 100)
264 batt_info->status = CS_FULL;
265 else if ((state & ACPI_BATT_STAT_CHARGING) && batt_info->percentage_remaining < 100)
266 batt_info->status = CS_CHARGING;
268 batt_info->status = CS_DISCHARGING;
269 #elif defined(__OpenBSD__)
271 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
272 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
273 * probing acpi(4) devices.
275 struct apm_power_info apm_info;
278 apm_fd = open("/dev/apm", O_RDONLY);
280 OUTPUT_FULL_TEXT("can't open /dev/apm");
283 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
284 OUTPUT_FULL_TEXT("can't read power info");
288 /* Don't bother to go further if there's no battery present. */
289 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
290 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
291 OUTPUT_FULL_TEXT(format_down);
295 switch (apm_info.ac_state) {
297 batt_info->status = CS_DISCHARGING;
300 batt_info->status = CS_CHARGING;
303 /* If we don't know what's going on, just assume we're discharging. */
304 batt_info->status = CS_DISCHARGING;
308 batt_info->percentage_remaining = apm_info.battery_life;
310 /* Can't give a meaningful value for remaining minutes if we're charging. */
311 if (batt_info->status != CS_CHARGING) {
312 batt_info->seconds_remaining = apm_info.minutes_left * 60;
314 #elif defined(__NetBSD__)
316 * Using envsys(4) via sysmon(4).
319 bool is_found = false;
320 char sensor_desc[16];
322 prop_dictionary_t dict;
324 prop_object_iterator_t iter;
325 prop_object_iterator_t iter2;
326 prop_object_t obj, obj2, obj3, obj4, obj5;
329 (void)snprintf(sensor_desc, sizeof(sensor_desc), "acpibat%d", number);
331 fd = open("/dev/sysmon", O_RDONLY);
333 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
337 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
343 if (prop_dictionary_count(dict) == 0) {
344 prop_object_release(dict);
349 iter = prop_dictionary_iterator(dict);
351 prop_object_release(dict);
355 /* iterate over the dictionary returned by the kernel */
356 while ((obj = prop_object_iterator_next(iter)) != NULL) {
357 /* skip this dict if it's not what we're looking for */
359 /* we want all batteries */
360 if (!BEGINS_WITH(prop_dictionary_keysym_cstring_nocopy(obj),
364 /* we want a specific battery */
365 if (strcmp(sensor_desc,
366 prop_dictionary_keysym_cstring_nocopy(obj)) != 0)
372 array = prop_dictionary_get_keysym(dict, obj);
373 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
374 prop_object_iterator_release(iter);
375 prop_object_release(dict);
380 iter2 = prop_array_iterator(array);
382 prop_object_iterator_release(iter);
383 prop_object_release(dict);
388 struct battery_info batt_buf = {
393 .status = CS_UNKNOWN,
396 bool watt_as_unit = false;
398 /* iterate over array of dicts specific to target battery */
399 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
400 obj3 = prop_dictionary_get(obj2, "description");
405 if (strcmp("charging", prop_string_cstring_nocopy(obj3)) == 0) {
406 obj3 = prop_dictionary_get(obj2, "cur-value");
408 if (prop_number_integer_value(obj3))
409 batt_buf.status = CS_CHARGING;
411 batt_buf.status = CS_DISCHARGING;
412 } else if (strcmp("charge", prop_string_cstring_nocopy(obj3)) == 0) {
413 obj3 = prop_dictionary_get(obj2, "cur-value");
414 obj4 = prop_dictionary_get(obj2, "max-value");
415 obj5 = prop_dictionary_get(obj2, "type");
417 batt_buf.remaining = prop_number_integer_value(obj3);
418 batt_buf.full_design = prop_number_integer_value(obj4);
420 if (strcmp("Ampere hour", prop_string_cstring_nocopy(obj5)) == 0)
421 watt_as_unit = false;
424 } else if (strcmp("discharge rate", prop_string_cstring_nocopy(obj3)) == 0) {
425 obj3 = prop_dictionary_get(obj2, "cur-value");
426 batt_buf.present_rate = prop_number_integer_value(obj3);
427 } else if (strcmp("charge rate", prop_string_cstring_nocopy(obj3)) == 0) {
428 obj3 = prop_dictionary_get(obj2, "cur-value");
429 batt_info->present_rate = prop_number_integer_value(obj3);
430 } else if (strcmp("last full cap", prop_string_cstring_nocopy(obj3)) == 0) {
431 obj3 = prop_dictionary_get(obj2, "cur-value");
432 batt_buf.full_last = prop_number_integer_value(obj3);
433 } else if (strcmp("voltage", prop_string_cstring_nocopy(obj3)) == 0) {
434 obj3 = prop_dictionary_get(obj2, "cur-value");
435 voltage = prop_number_integer_value(obj3);
438 prop_object_iterator_release(iter2);
440 if (!watt_as_unit && voltage != -1) {
441 batt_buf.present_rate = (((float)voltage / 1000.0) * ((float)batt_buf.present_rate / 1000.0));
442 batt_buf.remaining = (((float)voltage / 1000.0) * ((float)batt_buf.remaining / 1000.0));
443 batt_buf.full_design = (((float)voltage / 1000.0) * ((float)batt_buf.full_design / 1000.0));
444 batt_buf.full_last = (((float)voltage / 1000.0) * ((float)batt_buf.full_last / 1000.0));
447 if (batt_buf.remaining == batt_buf.full_design)
448 batt_buf.status = CS_FULL;
450 add_battery_info(batt_info, &batt_buf);
453 prop_object_iterator_release(iter);
454 prop_object_release(dict);
458 OUTPUT_FULL_TEXT(format_down);
462 batt_info->present_rate = abs(batt_info->present_rate);
469 * Populate batt_info with aggregate information about all batteries.
470 * Returns false on error, and an error message will have been written.
472 static bool slurp_all_batteries(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, const char *path, const char *format_down) {
473 #if defined(__linux__)
474 char *outwalk = buffer;
475 bool is_found = false;
478 char *globpath = sstrdup(path);
479 if ((placeholder = strstr(path, "%d")) != NULL) {
480 char *globplaceholder = globpath + (placeholder - path);
481 *globplaceholder = '*';
482 strcpy(globplaceholder + 1, placeholder + 2);
485 if (!strcmp(globpath, path)) {
486 OUTPUT_FULL_TEXT("no '%d' in battery path");
491 if (glob(globpath, 0, NULL, &globbuf) == 0) {
492 for (size_t i = 0; i < globbuf.gl_pathc; i++) {
493 /* Probe to see if there is such a battery. */
494 struct battery_info batt_buf = {
499 .status = CS_UNKNOWN,
501 if (!slurp_battery_info(&batt_buf, json_gen, buffer, i, globbuf.gl_pathv[i], format_down)) {
508 add_battery_info(batt_info, &batt_buf);
515 OUTPUT_FULL_TEXT(format_down);
519 batt_info->present_rate = abs(batt_info->present_rate);
521 /* FreeBSD and OpenBSD only report aggregates. NetBSD always
522 * iterates through all batteries, so it's more efficient to
523 * aggregate in slurp_battery_info. */
524 return slurp_battery_info(batt_info, json_gen, buffer, -1, path, format_down);
530 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) {
532 char *outwalk = buffer;
533 struct battery_info batt_info = {
538 .seconds_remaining = -1,
539 .percentage_remaining = -1,
540 .status = CS_UNKNOWN,
542 bool colorful_output = false;
544 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
545 /* These OSes report battery stats in whole percent. */
546 integer_battery_capacity = true;
548 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
549 /* These OSes report battery time in minutes. */
554 if (!slurp_all_batteries(&batt_info, json_gen, buffer, path, format_down))
557 if (!slurp_battery_info(&batt_info, json_gen, buffer, number, path, format_down))
561 // *Choose* a measure of the 'full' battery. It is whichever is better of
562 // the battery's (hardware-given) design capacity (batt_info.full_design)
563 // and the battery's last known good charge (batt_info.full_last).
564 // We prefer the design capacity, but use the last capacity if we don't have it,
565 // or if we are asked to (last_full_capacity == true); but similarly we use
566 // the design capacity if we don't have the last capacity.
567 // If we don't have either then both full_design and full_last <= 0,
568 // which implies full <= 0, which bails out on the following line.
569 int full = batt_info.full_design;
570 if (full <= 0 || (last_full_capacity && batt_info.full_last > 0)) {
571 full = batt_info.full_last;
573 if (full <= 0 && batt_info.remaining < 0 && batt_info.percentage_remaining < 0) {
574 /* We have no physical measurements and no estimates. Nothing
575 * much we can report, then. */
576 OUTPUT_FULL_TEXT(format_down);
580 if (batt_info.percentage_remaining < 0) {
581 batt_info.percentage_remaining = (((float)batt_info.remaining / (float)full) * 100);
582 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
583 * charged, even though that’s plainly wrong. For people who chose to see
584 * the percentage calculated based on the last full capacity, we clamp the
585 * value to 100%, as that makes more sense.
586 * See http://bugs.debian.org/785398 */
587 if (last_full_capacity && batt_info.percentage_remaining > 100) {
588 batt_info.percentage_remaining = 100;
592 if (batt_info.seconds_remaining < 0 && batt_info.present_rate > 0 && batt_info.status != CS_FULL) {
593 if (batt_info.status == CS_CHARGING)
594 batt_info.seconds_remaining = 3600.0 * (full - batt_info.remaining) / batt_info.present_rate;
595 else if (batt_info.status == CS_DISCHARGING)
596 batt_info.seconds_remaining = 3600.0 * batt_info.remaining / batt_info.present_rate;
598 batt_info.seconds_remaining = 0;
601 if (batt_info.status == CS_DISCHARGING && low_threshold > 0) {
602 if (batt_info.percentage_remaining >= 0 && strcasecmp(threshold_type, "percentage") == 0 && batt_info.percentage_remaining < low_threshold) {
603 START_COLOR("color_bad");
604 colorful_output = true;
605 } else if (batt_info.seconds_remaining >= 0 && strcasecmp(threshold_type, "time") == 0 && batt_info.seconds_remaining < 60 * low_threshold) {
606 START_COLOR("color_bad");
607 colorful_output = true;
611 #define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT() \
613 if (outwalk == prevoutwalk) { \
614 if (outwalk > buffer && isspace((int)outwalk[-1])) \
616 else if (isspace((int)*(walk + 1))) \
621 for (walk = format; *walk != '\0'; walk++) {
622 char *prevoutwalk = outwalk;
625 *(outwalk++) = *walk;
627 } else if (BEGINS_WITH(walk + 1, "status")) {
628 const char *statusstr;
629 switch (batt_info.status) {
631 statusstr = status_chr;
634 statusstr = status_bat;
637 statusstr = status_full;
640 statusstr = status_unk;
643 outwalk += sprintf(outwalk, "%s", statusstr);
644 walk += strlen("status");
646 } else if (BEGINS_WITH(walk + 1, "percentage")) {
647 if (integer_battery_capacity) {
648 outwalk += sprintf(outwalk, "%.00f%s", batt_info.percentage_remaining, pct_mark);
650 outwalk += sprintf(outwalk, "%.02f%s", batt_info.percentage_remaining, pct_mark);
652 walk += strlen("percentage");
654 } else if (BEGINS_WITH(walk + 1, "remaining")) {
655 if (batt_info.seconds_remaining >= 0) {
656 int seconds, hours, minutes;
658 hours = batt_info.seconds_remaining / 3600;
659 seconds = batt_info.seconds_remaining - (hours * 3600);
660 minutes = seconds / 60;
661 seconds -= (minutes * 60);
664 outwalk += sprintf(outwalk, "%02d:%02d",
665 max(hours, 0), max(minutes, 0));
667 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
668 max(hours, 0), max(minutes, 0), max(seconds, 0));
670 walk += strlen("remaining");
671 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
673 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
674 if (batt_info.seconds_remaining >= 0) {
675 time_t empty_time = time(NULL) + batt_info.seconds_remaining;
676 set_timezone(NULL); /* Use local time. */
677 struct tm *empty_tm = localtime(&empty_time);
680 outwalk += sprintf(outwalk, "%02d:%02d",
681 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
683 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
684 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
686 walk += strlen("emptytime");
687 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
689 } else if (BEGINS_WITH(walk + 1, "consumption")) {
690 if (batt_info.present_rate >= 0)
691 outwalk += sprintf(outwalk, "%1.2fW", batt_info.present_rate / 1e6);
693 walk += strlen("consumption");
694 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
704 OUTPUT_FULL_TEXT(buffer);