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>
17 #if defined(__OpenBSD__)
18 #include <sys/types.h>
19 #include <sys/ioctl.h>
20 #include <sys/fcntl.h>
21 #include <machine/apmvar.h>
24 #if defined(__NetBSD__)
26 #include <prop/proplib.h>
27 #include <sys/envsys.h>
31 * Get battery information from /sys. Note that it uses the design capacity to
32 * calculate the percentage, not the last full capacity, so you can see how
33 * worn off your battery is.
36 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_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) {
41 char percentagebuf[16];
42 char remainingbuf[256];
43 char emptytimebuf[256];
44 char consumptionbuf[256];
45 const char *walk, *last;
46 char *outwalk = buffer;
47 bool watt_as_unit = false;
48 bool colorful_output = false;
53 charging_status_t status = CS_DISCHARGING;
55 memset(statusbuf, '\0', sizeof(statusbuf));
56 memset(percentagebuf, '\0', sizeof(percentagebuf));
57 memset(remainingbuf, '\0', sizeof(remainingbuf));
58 memset(emptytimebuf, '\0', sizeof(emptytimebuf));
59 memset(consumptionbuf, '\0', sizeof(consumptionbuf));
61 static char batpath[512];
62 sprintf(batpath, path, number);
65 #define BATT_STATUS_NAME(status) \
66 (status == CS_CHARGING ? status_chr : (status == CS_DISCHARGING ? status_bat : status_full))
69 if (!slurp(batpath, buf, sizeof(buf))) {
70 OUTPUT_FULL_TEXT(format_down);
74 for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
83 if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW")) {
85 remaining = atoi(walk + 1);
86 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW")) {
88 remaining = atoi(walk + 1);
89 } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
90 present_rate = abs(atoi(walk + 1));
91 else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW"))
92 voltage = abs(atoi(walk + 1));
93 /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
94 * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
95 * unit instead of μAh. We will calculate it as we need it
97 else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW"))
98 present_rate = abs(atoi(walk + 1));
99 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
100 status = CS_CHARGING;
101 else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
104 /* The only thing left is the full capacity */
105 if (last_full_capacity) {
106 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
107 !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
110 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
111 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
115 full_design = atoi(walk + 1);
119 /* the difference between POWER_SUPPLY_ENERGY_NOW and
120 * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
121 * given in mWh, the charge in mAh. So calculate every value given in
124 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
127 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
128 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
132 if ((full_design == -1) || (remaining == -1)) {
133 OUTPUT_FULL_TEXT(format_down);
137 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
139 float percentage_remaining = (((float)remaining / (float)full_design) * 100);
140 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
141 * charged, even though that’s plainly wrong. For people who chose to see
142 * the percentage calculated based on the last full capacity, we clamp the
143 * value to 100%, as that makes more sense.
144 * See http://bugs.debian.org/785398 */
145 if (last_full_capacity && percentage_remaining > 100) {
146 percentage_remaining = 100;
148 if (integer_battery_capacity) {
149 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00f%%", percentage_remaining);
151 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.02f%%", percentage_remaining);
154 if (present_rate > 0) {
155 float remaining_time;
156 int seconds, hours, minutes, seconds_remaining;
157 if (status == CS_CHARGING)
158 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
159 else if (status == CS_DISCHARGING)
160 remaining_time = ((float)remaining / (float)present_rate);
164 seconds_remaining = (int)(remaining_time * 3600.0);
166 hours = seconds_remaining / 3600;
167 seconds = seconds_remaining - (hours * 3600);
168 minutes = seconds / 60;
169 seconds -= (minutes * 60);
171 if (status == CS_DISCHARGING && low_threshold > 0) {
172 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
173 START_COLOR("color_bad");
174 colorful_output = true;
175 } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) {
176 START_COLOR("color_bad");
177 colorful_output = true;
179 colorful_output = false;
184 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
185 max(hours, 0), max(minutes, 0));
187 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
188 max(hours, 0), max(minutes, 0), max(seconds, 0));
190 empty_time = time(NULL);
191 empty_time += seconds_remaining;
192 empty_tm = localtime(&empty_time);
195 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
196 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
198 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
199 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
201 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
202 ((float)present_rate / 1000.0 / 1000.0));
204 /* On some systems, present_rate may not exist. Still, make sure
205 * we colorize the output if threshold_type is set to percentage
206 * (since we don't have any information on remaining time). */
207 if (status == CS_DISCHARGING && low_threshold > 0) {
208 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
209 START_COLOR("color_bad");
210 colorful_output = true;
214 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
217 size_t sysctl_size = sizeof(sysctl_rslt);
219 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
220 OUTPUT_FULL_TEXT(format_down);
224 present_rate = sysctl_rslt;
225 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
226 OUTPUT_FULL_TEXT(format_down);
230 remaining = sysctl_rslt;
231 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
232 OUTPUT_FULL_TEXT(format_down);
237 if (state == 0 && present_rate == 100)
239 else if (state == 0 && present_rate < 100)
240 status = CS_CHARGING;
242 status = CS_DISCHARGING;
244 full_design = sysctl_rslt;
246 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
248 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%02d%%",
254 hours = minutes / 60;
255 minutes -= (hours * 60);
256 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
257 max(hours, 0), max(minutes, 0));
258 if (strcasecmp(threshold_type, "percentage") == 0 && present_rate < low_threshold) {
259 START_COLOR("color_bad");
260 colorful_output = true;
261 } else if (strcasecmp(threshold_type, "time") == 0 && remaining < (u_int)low_threshold) {
262 START_COLOR("color_bad");
263 colorful_output = true;
266 #elif defined(__OpenBSD__)
268 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
269 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
270 * probing acpi(4) devices.
272 struct apm_power_info apm_info;
275 apm_fd = open("/dev/apm", O_RDONLY);
277 OUTPUT_FULL_TEXT("can't open /dev/apm");
280 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
281 OUTPUT_FULL_TEXT("can't read power info");
285 /* Don't bother to go further if there's no battery present. */
286 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
287 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
288 OUTPUT_FULL_TEXT(format_down);
292 switch (apm_info.ac_state) {
294 status = CS_DISCHARGING;
297 status = CS_CHARGING;
300 /* If we don't know what's going on, just assume we're discharging. */
301 status = CS_DISCHARGING;
305 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
306 /* integer_battery_capacity is implied as battery_life is already in whole numbers. */
307 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00d%%", apm_info.battery_life);
309 if (status == CS_DISCHARGING && low_threshold > 0) {
310 if (strcasecmp(threshold_type, "percentage") == 0 && apm_info.battery_life < low_threshold) {
311 START_COLOR("color_bad");
312 colorful_output = true;
313 } else if (strcasecmp(threshold_type, "time") == 0 && apm_info.minutes_left < (u_int)low_threshold) {
314 START_COLOR("color_bad");
315 colorful_output = true;
319 /* Can't give a meaningful value for remaining minutes if we're charging. */
320 if (status != CS_CHARGING) {
321 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", apm_info.minutes_left / 60, apm_info.minutes_left % 60);
323 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%s", "(CHR)");
328 #elif defined(__NetBSD__)
330 * Using envsys(4) via sysmon(4).
332 int fd, rval, last_full_cap;
333 bool is_found = false;
335 bool is_full = false;
337 prop_dictionary_t dict;
339 prop_object_iterator_t iter;
340 prop_object_iterator_t iter2;
341 prop_object_t obj, obj2, obj3, obj4, obj5;
343 asprintf(&sensor_desc, "acpibat%d", number);
345 fd = open("/dev/sysmon", O_RDONLY);
347 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
351 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
357 if (prop_dictionary_count(dict) == 0) {
358 prop_object_release(dict);
363 iter = prop_dictionary_iterator(dict);
365 prop_object_release(dict);
369 /* iterate over the dictionary returned by the kernel */
370 while ((obj = prop_object_iterator_next(iter)) != NULL) {
371 /* skip this dict if it's not what we're looking for */
372 if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) &&
373 (strncmp(sensor_desc,
374 prop_dictionary_keysym_cstring_nocopy(obj),
375 strlen(sensor_desc)) != 0))
380 array = prop_dictionary_get_keysym(dict, obj);
381 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
382 prop_object_iterator_release(iter);
383 prop_object_release(dict);
388 iter2 = prop_array_iterator(array);
390 prop_object_iterator_release(iter);
391 prop_object_release(dict);
396 /* iterate over array of dicts specific to target battery */
397 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
398 obj3 = prop_dictionary_get(obj2, "description");
401 strlen(prop_string_cstring_nocopy(obj3)) == 8 &&
403 prop_string_cstring_nocopy(obj3),
405 obj3 = prop_dictionary_get(obj2, "cur-value");
407 if (prop_number_integer_value(obj3))
408 status = CS_CHARGING;
410 status = CS_DISCHARGING;
416 strlen(prop_string_cstring_nocopy(obj3)) == 6 &&
418 prop_string_cstring_nocopy(obj3),
420 obj3 = prop_dictionary_get(obj2, "cur-value");
421 obj4 = prop_dictionary_get(obj2, "max-value");
422 obj5 = prop_dictionary_get(obj2, "type");
424 remaining = prop_number_integer_value(obj3);
425 full_design = prop_number_integer_value(obj4);
427 if (remaining == full_design)
430 if (strncmp("Ampere hour",
431 prop_string_cstring_nocopy(obj5),
433 watt_as_unit = false;
441 strlen(prop_string_cstring_nocopy(obj3)) == 14 &&
442 strncmp("discharge rate",
443 prop_string_cstring_nocopy(obj3),
445 obj3 = prop_dictionary_get(obj2, "cur-value");
446 present_rate = prop_number_integer_value(obj3);
451 strlen(prop_string_cstring_nocopy(obj3)) == 13 &&
452 strncmp("last full cap",
453 prop_string_cstring_nocopy(obj3),
455 obj3 = prop_dictionary_get(obj2, "cur-value");
456 last_full_cap = prop_number_integer_value(obj3);
461 strlen(prop_string_cstring_nocopy(obj3)) == 7 &&
463 prop_string_cstring_nocopy(obj3),
465 obj3 = prop_dictionary_get(obj2, "cur-value");
466 voltage = prop_number_integer_value(obj3);
470 prop_object_iterator_release(iter2);
473 prop_object_iterator_release(iter);
474 prop_object_release(dict);
478 OUTPUT_FULL_TEXT(format_down);
482 if (last_full_capacity)
483 full_design = last_full_cap;
486 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
487 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
488 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
491 float percentage_remaining =
492 (((float)remaining / (float)full_design) * 100);
494 if (integer_battery_capacity)
495 (void)snprintf(percentagebuf,
496 sizeof(percentagebuf),
498 (int)percentage_remaining);
500 (void)snprintf(percentagebuf,
501 sizeof(percentagebuf),
503 percentage_remaining);
506 * Handle percentage low_threshold here, and time low_threshold when
509 if (status == CS_DISCHARGING && low_threshold > 0) {
510 if (strcasecmp(threshold_type, "percentage") == 0 && (((float)remaining / (float)full_design) * 100) < low_threshold) {
511 START_COLOR("color_bad");
512 colorful_output = true;
517 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(CS_FULL));
519 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
522 * The envsys(4) ACPI routines do not appear to provide a 'time
523 * remaining' figure, so we must deduce it.
525 float remaining_time;
526 int seconds, hours, minutes, seconds_remaining;
528 if (status == CS_CHARGING)
529 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
530 else if (status == CS_DISCHARGING)
531 remaining_time = ((float)remaining / (float)present_rate);
535 seconds_remaining = (int)(remaining_time * 3600.0);
537 hours = seconds_remaining / 3600;
538 seconds = seconds_remaining - (hours * 3600);
539 minutes = seconds / 60;
540 seconds -= (minutes * 60);
542 if (status != CS_CHARGING) {
544 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
545 max(hours, 0), max(minutes, 0));
547 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
548 max(hours, 0), max(minutes, 0), max(seconds, 0));
550 if (low_threshold > 0) {
551 if (strcasecmp(threshold_type, "time") == 0 && ((float)seconds_remaining / 60.0) < (u_int)low_threshold) {
552 START_COLOR("color_bad");
553 colorful_output = true;
558 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d until full)",
559 max(hours, 0), max(minutes, 0));
561 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d:%02d until full)",
562 max(hours, 0), max(minutes, 0), max(seconds, 0));
565 empty_time = time(NULL);
566 empty_time += seconds_remaining;
567 empty_tm = localtime(&empty_time);
569 /* No need to show empty time if battery is charging */
570 if (status != CS_CHARGING) {
572 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
573 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
575 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
576 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
579 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
580 ((float)present_rate / 1000.0 / 1000.0));
583 #define EAT_SPACE_FROM_OUTPUT_IF_EMPTY(_buf) \
585 if (strlen(_buf) == 0) { \
586 if (outwalk > buffer && isspace(outwalk[-1])) \
588 else if (isspace(*(walk + 1))) \
593 for (walk = format; *walk != '\0'; walk++) {
595 *(outwalk++) = *walk;
599 if (BEGINS_WITH(walk + 1, "status")) {
600 outwalk += sprintf(outwalk, "%s", statusbuf);
601 walk += strlen("status");
602 } else if (BEGINS_WITH(walk + 1, "percentage")) {
603 outwalk += sprintf(outwalk, "%s", percentagebuf);
604 walk += strlen("percentage");
605 } else if (BEGINS_WITH(walk + 1, "remaining")) {
606 outwalk += sprintf(outwalk, "%s", remainingbuf);
607 walk += strlen("remaining");
608 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(remainingbuf);
609 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
610 outwalk += sprintf(outwalk, "%s", emptytimebuf);
611 walk += strlen("emptytime");
612 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(emptytimebuf);
613 } else if (BEGINS_WITH(walk + 1, "consumption")) {
614 outwalk += sprintf(outwalk, "%s", consumptionbuf);
615 walk += strlen("consumption");
616 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(consumptionbuf);
623 OUTPUT_FULL_TEXT(buffer);