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 != -1) {
179 batt_info->present_rate = (((float)voltage / 1000.0) * ((float)batt_info->present_rate / 1000.0));
180 batt_info->remaining = (((float)voltage / 1000.0) * ((float)batt_info->remaining / 1000.0));
181 batt_info->full_design = (((float)voltage / 1000.0) * ((float)batt_info->full_design / 1000.0));
182 batt_info->full_last = (((float)voltage / 1000.0) * ((float)batt_info->full_last / 1000.0));
184 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
187 size_t sysctl_size = sizeof(sysctl_rslt);
189 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
190 OUTPUT_FULL_TEXT(format_down);
194 batt_info->percentage_remaining = sysctl_rslt;
195 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
196 OUTPUT_FULL_TEXT(format_down);
200 batt_info->seconds_remaining = sysctl_rslt * 60;
201 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
202 OUTPUT_FULL_TEXT(format_down);
207 if (state == 0 && batt_info->percentage_remaining == 100)
208 batt_info->status = CS_FULL;
209 else if ((state & ACPI_BATT_STAT_CHARGING) && batt_info->percentage_remaining < 100)
210 batt_info->status = CS_CHARGING;
212 batt_info->status = CS_DISCHARGING;
213 #elif defined(__OpenBSD__)
215 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
216 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
217 * probing acpi(4) devices.
219 struct apm_power_info apm_info;
222 apm_fd = open("/dev/apm", O_RDONLY);
224 OUTPUT_FULL_TEXT("can't open /dev/apm");
227 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
228 OUTPUT_FULL_TEXT("can't read power info");
232 /* Don't bother to go further if there's no battery present. */
233 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
234 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
235 OUTPUT_FULL_TEXT(format_down);
239 switch (apm_info.ac_state) {
241 batt_info->status = CS_DISCHARGING;
244 batt_info->status = CS_CHARGING;
247 /* If we don't know what's going on, just assume we're discharging. */
248 batt_info->status = CS_DISCHARGING;
252 batt_info->percentage_remaining = apm_info.battery_life;
254 /* Can't give a meaningful value for remaining minutes if we're charging. */
255 if (batt_info->status != CS_CHARGING) {
256 batt_info->seconds_remaining = apm_info.minutes_left * 60;
258 #elif defined(__NetBSD__)
260 * Using envsys(4) via sysmon(4).
263 bool is_found = false;
264 char sensor_desc[16];
266 prop_dictionary_t dict;
268 prop_object_iterator_t iter;
269 prop_object_iterator_t iter2;
270 prop_object_t obj, obj2, obj3, obj4, obj5;
273 (void)snprintf(sensor_desc, sizeof(sensor_desc), "acpibat%d", number);
275 fd = open("/dev/sysmon", O_RDONLY);
277 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
281 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
287 if (prop_dictionary_count(dict) == 0) {
288 prop_object_release(dict);
293 iter = prop_dictionary_iterator(dict);
295 prop_object_release(dict);
299 /* iterate over the dictionary returned by the kernel */
300 while ((obj = prop_object_iterator_next(iter)) != NULL) {
301 /* skip this dict if it's not what we're looking for */
303 /* we want all batteries */
304 if (!BEGINS_WITH(prop_dictionary_keysym_cstring_nocopy(obj),
308 /* we want a specific battery */
309 if (strcmp(sensor_desc,
310 prop_dictionary_keysym_cstring_nocopy(obj)) != 0)
316 array = prop_dictionary_get_keysym(dict, obj);
317 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
318 prop_object_iterator_release(iter);
319 prop_object_release(dict);
324 iter2 = prop_array_iterator(array);
326 prop_object_iterator_release(iter);
327 prop_object_release(dict);
332 struct battery_info batt_buf = {
337 .status = CS_UNKNOWN,
340 bool watt_as_unit = false;
342 /* iterate over array of dicts specific to target battery */
343 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
344 obj3 = prop_dictionary_get(obj2, "description");
349 if (strcmp("charging", prop_string_cstring_nocopy(obj3)) == 0) {
350 obj3 = prop_dictionary_get(obj2, "cur-value");
352 if (prop_number_integer_value(obj3))
353 batt_buf.status = CS_CHARGING;
355 batt_buf.status = CS_DISCHARGING;
356 } else if (strcmp("charge", prop_string_cstring_nocopy(obj3)) == 0) {
357 obj3 = prop_dictionary_get(obj2, "cur-value");
358 obj4 = prop_dictionary_get(obj2, "max-value");
359 obj5 = prop_dictionary_get(obj2, "type");
361 batt_buf.remaining = prop_number_integer_value(obj3);
362 batt_buf.full_design = prop_number_integer_value(obj4);
364 if (strcmp("Ampere hour", prop_string_cstring_nocopy(obj5)) == 0)
365 watt_as_unit = false;
368 } else if (strcmp("discharge rate", prop_string_cstring_nocopy(obj3)) == 0) {
369 obj3 = prop_dictionary_get(obj2, "cur-value");
370 batt_buf.present_rate = prop_number_integer_value(obj3);
371 } else if (strcmp("charge rate", prop_string_cstring_nocopy(obj3)) == 0) {
372 obj3 = prop_dictionary_get(obj2, "cur-value");
373 batt_info->present_rate = prop_number_integer_value(obj3);
374 } else if (strcmp("last full cap", prop_string_cstring_nocopy(obj3)) == 0) {
375 obj3 = prop_dictionary_get(obj2, "cur-value");
376 batt_buf.full_last = prop_number_integer_value(obj3);
377 } else if (strcmp("voltage", prop_string_cstring_nocopy(obj3)) == 0) {
378 obj3 = prop_dictionary_get(obj2, "cur-value");
379 voltage = prop_number_integer_value(obj3);
382 prop_object_iterator_release(iter2);
384 if (!watt_as_unit && voltage != -1) {
385 batt_buf.present_rate = (((float)voltage / 1000.0) * ((float)batt_buf.present_rate / 1000.0));
386 batt_buf.remaining = (((float)voltage / 1000.0) * ((float)batt_buf.remaining / 1000.0));
387 batt_buf.full_design = (((float)voltage / 1000.0) * ((float)batt_buf.full_design / 1000.0));
388 batt_buf.full_last = (((float)voltage / 1000.0) * ((float)batt_buf.full_last / 1000.0));
391 if (batt_buf.remaining == batt_buf.full_design)
392 batt_buf.status = CS_FULL;
394 add_battery_info(batt_info, &batt_buf);
397 prop_object_iterator_release(iter);
398 prop_object_release(dict);
402 OUTPUT_FULL_TEXT(format_down);
406 batt_info->present_rate = abs(batt_info->present_rate);
413 * Populate batt_info with aggregate information about all batteries.
414 * Returns false on error, and an error message will have been written.
416 static bool slurp_all_batteries(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, const char *path, const char *format_down) {
418 char *outwalk = buffer;
419 bool is_found = false;
422 char *globpath = sstrdup(path);
423 if ((placeholder = strstr(path, "%d")) != NULL) {
424 char *globplaceholder = globpath + (placeholder - path);
425 *globplaceholder = '*';
426 strcpy(globplaceholder + 1, placeholder + 2);
429 if (!strcmp(globpath, path)) {
430 OUTPUT_FULL_TEXT("no '%d' in battery path");
435 if (glob(globpath, 0, NULL, &globbuf) == 0) {
436 for (size_t i = 0; i < globbuf.gl_pathc; i++) {
437 /* Probe to see if there is such a battery. */
438 struct battery_info batt_buf = {
443 .status = CS_UNKNOWN,
445 if (!slurp_battery_info(&batt_buf, json_gen, buffer, i, globbuf.gl_pathv[i], format_down))
449 add_battery_info(batt_info, &batt_buf);
456 OUTPUT_FULL_TEXT(format_down);
460 batt_info->present_rate = abs(batt_info->present_rate);
462 /* FreeBSD and OpenBSD only report aggregates. NetBSD always
463 * iterates through all batteries, so it's more efficient to
464 * aggregate in slurp_battery_info. */
465 return slurp_battery_info(batt_info, json_gen, buffer, -1, path, format_down);
471 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) {
473 char *outwalk = buffer;
474 struct battery_info batt_info = {
479 .seconds_remaining = -1,
480 .percentage_remaining = -1,
481 .status = CS_UNKNOWN,
483 bool colorful_output = false;
485 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
486 /* These OSes report battery stats in whole percent. */
487 integer_battery_capacity = true;
489 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
490 /* These OSes report battery time in minutes. */
495 if (!slurp_all_batteries(&batt_info, json_gen, buffer, path, format_down))
498 if (!slurp_battery_info(&batt_info, json_gen, buffer, number, path, format_down))
502 int full = (last_full_capacity ? batt_info.full_last : batt_info.full_design);
503 if (full < 0 && batt_info.percentage_remaining < 0) {
504 /* We have no physical measurements and no estimates. Nothing
505 * much we can report, then. */
506 OUTPUT_FULL_TEXT(format_down);
510 if (batt_info.percentage_remaining < 0) {
511 batt_info.percentage_remaining = (((float)batt_info.remaining / (float)full) * 100);
512 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
513 * charged, even though that’s plainly wrong. For people who chose to see
514 * the percentage calculated based on the last full capacity, we clamp the
515 * value to 100%, as that makes more sense.
516 * See http://bugs.debian.org/785398 */
517 if (last_full_capacity && batt_info.percentage_remaining > 100) {
518 batt_info.percentage_remaining = 100;
522 if (batt_info.seconds_remaining < 0 && batt_info.present_rate > 0 && batt_info.status != CS_FULL) {
523 if (batt_info.status == CS_CHARGING)
524 batt_info.seconds_remaining = 3600.0 * (full - batt_info.remaining) / batt_info.present_rate;
525 else if (batt_info.status == CS_DISCHARGING)
526 batt_info.seconds_remaining = 3600.0 * batt_info.remaining / batt_info.present_rate;
528 batt_info.seconds_remaining = 0;
531 if (batt_info.status == CS_DISCHARGING && low_threshold > 0) {
532 if (batt_info.percentage_remaining >= 0 && strcasecmp(threshold_type, "percentage") == 0 && batt_info.percentage_remaining < low_threshold) {
533 START_COLOR("color_bad");
534 colorful_output = true;
535 } else if (batt_info.seconds_remaining >= 0 && strcasecmp(threshold_type, "time") == 0 && batt_info.seconds_remaining < 60 * low_threshold) {
536 START_COLOR("color_bad");
537 colorful_output = true;
541 #define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT() \
543 if (outwalk == prevoutwalk) { \
544 if (outwalk > buffer && isspace((int)outwalk[-1])) \
546 else if (isspace((int)*(walk + 1))) \
551 for (walk = format; *walk != '\0'; walk++) {
552 char *prevoutwalk = outwalk;
555 *(outwalk++) = *walk;
559 if (BEGINS_WITH(walk + 1, "status")) {
560 const char *statusstr;
561 switch (batt_info.status) {
563 statusstr = status_chr;
566 statusstr = status_bat;
569 statusstr = status_full;
572 statusstr = status_unk;
575 outwalk += sprintf(outwalk, "%s", statusstr);
576 walk += strlen("status");
577 } else if (BEGINS_WITH(walk + 1, "percentage")) {
578 if (integer_battery_capacity) {
579 outwalk += sprintf(outwalk, "%.00f%s", batt_info.percentage_remaining, pct_mark);
581 outwalk += sprintf(outwalk, "%.02f%s", batt_info.percentage_remaining, pct_mark);
583 walk += strlen("percentage");
584 } else if (BEGINS_WITH(walk + 1, "remaining")) {
585 if (batt_info.seconds_remaining >= 0) {
586 int seconds, hours, minutes;
588 hours = batt_info.seconds_remaining / 3600;
589 seconds = batt_info.seconds_remaining - (hours * 3600);
590 minutes = seconds / 60;
591 seconds -= (minutes * 60);
594 outwalk += sprintf(outwalk, "%02d:%02d",
595 max(hours, 0), max(minutes, 0));
597 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
598 max(hours, 0), max(minutes, 0), max(seconds, 0));
600 walk += strlen("remaining");
601 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
602 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
603 if (batt_info.seconds_remaining >= 0) {
604 time_t empty_time = time(NULL) + batt_info.seconds_remaining;
605 struct tm *empty_tm = localtime(&empty_time);
608 outwalk += sprintf(outwalk, "%02d:%02d",
609 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
611 outwalk += sprintf(outwalk, "%02d:%02d:%02d",
612 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
614 walk += strlen("emptytime");
615 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
616 } else if (BEGINS_WITH(walk + 1, "consumption")) {
617 if (batt_info.present_rate >= 0)
618 outwalk += sprintf(outwalk, "%1.2fW", batt_info.present_rate / 1e6);
620 walk += strlen("consumption");
621 EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
628 OUTPUT_FULL_TEXT(buffer);