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_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_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"))
105 /* The only thing left is the full capacity */
106 if (last_full_capacity) {
107 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
108 !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
111 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
112 !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
116 full_design = atoi(walk + 1);
120 /* the difference between POWER_SUPPLY_ENERGY_NOW and
121 * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
122 * given in mWh, the charge in mAh. So calculate every value given in
125 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
128 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
129 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
133 if ((full_design == -1) || (remaining == -1)) {
134 OUTPUT_FULL_TEXT(format_down);
138 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
140 float percentage_remaining = (((float)remaining / (float)full_design) * 100);
141 /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
142 * charged, even though that’s plainly wrong. For people who chose to see
143 * the percentage calculated based on the last full capacity, we clamp the
144 * value to 100%, as that makes more sense.
145 * See http://bugs.debian.org/785398 */
146 if (last_full_capacity && percentage_remaining > 100) {
147 percentage_remaining = 100;
149 if (integer_battery_capacity) {
150 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00f%s", percentage_remaining, pct_mark);
152 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.02f%s", percentage_remaining, pct_mark);
155 if (present_rate > 0) {
156 float remaining_time;
157 int seconds, hours, minutes, seconds_remaining;
158 if (status == CS_CHARGING)
159 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
160 else if (status == CS_DISCHARGING)
161 remaining_time = ((float)remaining / (float)present_rate);
165 seconds_remaining = (int)(remaining_time * 3600.0);
167 hours = seconds_remaining / 3600;
168 seconds = seconds_remaining - (hours * 3600);
169 minutes = seconds / 60;
170 seconds -= (minutes * 60);
172 if (status == CS_DISCHARGING && low_threshold > 0) {
173 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
174 START_COLOR("color_bad");
175 colorful_output = true;
176 } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) {
177 START_COLOR("color_bad");
178 colorful_output = true;
180 colorful_output = false;
185 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
186 max(hours, 0), max(minutes, 0));
188 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
189 max(hours, 0), max(minutes, 0), max(seconds, 0));
191 empty_time = time(NULL);
192 empty_time += seconds_remaining;
193 empty_tm = localtime(&empty_time);
196 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
197 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
199 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
200 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
202 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
203 ((float)present_rate / 1000.0 / 1000.0));
205 /* On some systems, present_rate may not exist. Still, make sure
206 * we colorize the output if threshold_type is set to percentage
207 * (since we don't have any information on remaining time). */
208 if (status == CS_DISCHARGING && low_threshold > 0) {
209 if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
210 START_COLOR("color_bad");
211 colorful_output = true;
215 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
218 size_t sysctl_size = sizeof(sysctl_rslt);
220 if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
221 OUTPUT_FULL_TEXT(format_down);
225 present_rate = sysctl_rslt;
226 if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
227 OUTPUT_FULL_TEXT(format_down);
231 remaining = sysctl_rslt;
232 if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
233 OUTPUT_FULL_TEXT(format_down);
238 if (state == 0 && present_rate == 100)
240 else if ((state & ACPI_BATT_STAT_CHARGING) && present_rate < 100)
241 status = CS_CHARGING;
243 status = CS_DISCHARGING;
245 full_design = sysctl_rslt;
247 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
249 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%02d%s",
250 present_rate, pct_mark);
252 if (state == ACPI_BATT_STAT_DISCHARG) {
255 hours = minutes / 60;
256 minutes -= (hours * 60);
257 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
258 max(hours, 0), max(minutes, 0));
259 if (strcasecmp(threshold_type, "percentage") == 0 && present_rate < low_threshold) {
260 START_COLOR("color_bad");
261 colorful_output = true;
262 } else if (strcasecmp(threshold_type, "time") == 0 && remaining < (u_int)low_threshold) {
263 START_COLOR("color_bad");
264 colorful_output = true;
267 #elif defined(__OpenBSD__)
269 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
270 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
271 * probing acpi(4) devices.
273 struct apm_power_info apm_info;
276 apm_fd = open("/dev/apm", O_RDONLY);
278 OUTPUT_FULL_TEXT("can't open /dev/apm");
281 if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
282 OUTPUT_FULL_TEXT("can't read power info");
286 /* Don't bother to go further if there's no battery present. */
287 if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
288 (apm_info.battery_state == APM_BATT_UNKNOWN)) {
289 OUTPUT_FULL_TEXT(format_down);
293 switch (apm_info.ac_state) {
295 status = CS_DISCHARGING;
298 status = CS_CHARGING;
301 /* If we don't know what's going on, just assume we're discharging. */
302 status = CS_DISCHARGING;
306 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
307 /* integer_battery_capacity is implied as battery_life is already in whole numbers. */
308 (void)snprintf(percentagebuf, sizeof(percentagebuf), "%.00d%s", apm_info.battery_life, pct_mark);
310 if (status == CS_DISCHARGING && low_threshold > 0) {
311 if (strcasecmp(threshold_type, "percentage") == 0 && apm_info.battery_life < low_threshold) {
312 START_COLOR("color_bad");
313 colorful_output = true;
314 } else if (strcasecmp(threshold_type, "time") == 0 && apm_info.minutes_left < (u_int)low_threshold) {
315 START_COLOR("color_bad");
316 colorful_output = true;
320 /* Can't give a meaningful value for remaining minutes if we're charging. */
321 if (status != CS_CHARGING) {
322 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d", apm_info.minutes_left / 60, apm_info.minutes_left % 60);
324 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%s", "(CHR)");
329 #elif defined(__NetBSD__)
331 * Using envsys(4) via sysmon(4).
333 int fd, rval, last_full_cap;
334 bool is_found = false;
336 bool is_full = false;
338 prop_dictionary_t dict;
340 prop_object_iterator_t iter;
341 prop_object_iterator_t iter2;
342 prop_object_t obj, obj2, obj3, obj4, obj5;
344 asprintf(&sensor_desc, "acpibat%d", number);
346 fd = open("/dev/sysmon", O_RDONLY);
348 OUTPUT_FULL_TEXT("can't open /dev/sysmon");
352 rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
358 if (prop_dictionary_count(dict) == 0) {
359 prop_object_release(dict);
364 iter = prop_dictionary_iterator(dict);
366 prop_object_release(dict);
370 /* iterate over the dictionary returned by the kernel */
371 while ((obj = prop_object_iterator_next(iter)) != NULL) {
372 /* skip this dict if it's not what we're looking for */
373 if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) &&
374 (strncmp(sensor_desc,
375 prop_dictionary_keysym_cstring_nocopy(obj),
376 strlen(sensor_desc)) != 0))
381 array = prop_dictionary_get_keysym(dict, obj);
382 if (prop_object_type(array) != PROP_TYPE_ARRAY) {
383 prop_object_iterator_release(iter);
384 prop_object_release(dict);
389 iter2 = prop_array_iterator(array);
391 prop_object_iterator_release(iter);
392 prop_object_release(dict);
397 /* iterate over array of dicts specific to target battery */
398 while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
399 obj3 = prop_dictionary_get(obj2, "description");
402 strlen(prop_string_cstring_nocopy(obj3)) == 8 &&
404 prop_string_cstring_nocopy(obj3),
406 obj3 = prop_dictionary_get(obj2, "cur-value");
408 if (prop_number_integer_value(obj3))
409 status = CS_CHARGING;
411 status = CS_DISCHARGING;
417 strlen(prop_string_cstring_nocopy(obj3)) == 6 &&
419 prop_string_cstring_nocopy(obj3),
421 obj3 = prop_dictionary_get(obj2, "cur-value");
422 obj4 = prop_dictionary_get(obj2, "max-value");
423 obj5 = prop_dictionary_get(obj2, "type");
425 remaining = prop_number_integer_value(obj3);
426 full_design = prop_number_integer_value(obj4);
428 if (remaining == full_design)
431 if (strncmp("Ampere hour",
432 prop_string_cstring_nocopy(obj5),
434 watt_as_unit = false;
442 strlen(prop_string_cstring_nocopy(obj3)) == 14 &&
443 strncmp("discharge rate",
444 prop_string_cstring_nocopy(obj3),
446 obj3 = prop_dictionary_get(obj2, "cur-value");
447 present_rate = prop_number_integer_value(obj3);
452 strlen(prop_string_cstring_nocopy(obj3)) == 13 &&
453 strncmp("last full cap",
454 prop_string_cstring_nocopy(obj3),
456 obj3 = prop_dictionary_get(obj2, "cur-value");
457 last_full_cap = prop_number_integer_value(obj3);
462 strlen(prop_string_cstring_nocopy(obj3)) == 7 &&
464 prop_string_cstring_nocopy(obj3),
466 obj3 = prop_dictionary_get(obj2, "cur-value");
467 voltage = prop_number_integer_value(obj3);
471 prop_object_iterator_release(iter2);
474 prop_object_iterator_release(iter);
475 prop_object_release(dict);
479 OUTPUT_FULL_TEXT(format_down);
483 if (last_full_capacity)
484 full_design = last_full_cap;
487 present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
488 remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
489 full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
492 float percentage_remaining =
493 (((float)remaining / (float)full_design) * 100);
495 if (integer_battery_capacity)
496 (void)snprintf(percentagebuf,
497 sizeof(percentagebuf),
499 (int)percentage_remaining, pct_mark);
501 (void)snprintf(percentagebuf,
502 sizeof(percentagebuf),
504 percentage_remaining, pct_mark);
507 * Handle percentage low_threshold here, and time low_threshold when
510 if (status == CS_DISCHARGING && low_threshold > 0) {
511 if (strcasecmp(threshold_type, "percentage") == 0 && (((float)remaining / (float)full_design) * 100) < low_threshold) {
512 START_COLOR("color_bad");
513 colorful_output = true;
518 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(CS_FULL));
520 (void)snprintf(statusbuf, sizeof(statusbuf), "%s", BATT_STATUS_NAME(status));
523 * The envsys(4) ACPI routines do not appear to provide a 'time
524 * remaining' figure, so we must deduce it.
526 float remaining_time;
527 int seconds, hours, minutes, seconds_remaining;
529 if (status == CS_CHARGING)
530 remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
531 else if (status == CS_DISCHARGING)
532 remaining_time = ((float)remaining / (float)present_rate);
536 seconds_remaining = (int)(remaining_time * 3600.0);
538 hours = seconds_remaining / 3600;
539 seconds = seconds_remaining - (hours * 3600);
540 minutes = seconds / 60;
541 seconds -= (minutes * 60);
543 if (status != CS_CHARGING) {
545 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d",
546 max(hours, 0), max(minutes, 0));
548 (void)snprintf(remainingbuf, sizeof(remainingbuf), "%02d:%02d:%02d",
549 max(hours, 0), max(minutes, 0), max(seconds, 0));
551 if (low_threshold > 0) {
552 if (strcasecmp(threshold_type, "time") == 0 && ((float)seconds_remaining / 60.0) < (u_int)low_threshold) {
553 START_COLOR("color_bad");
554 colorful_output = true;
559 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d until full)",
560 max(hours, 0), max(minutes, 0));
562 (void)snprintf(remainingbuf, sizeof(remainingbuf), "(%02d:%02d:%02d until full)",
563 max(hours, 0), max(minutes, 0), max(seconds, 0));
566 empty_time = time(NULL);
567 empty_time += seconds_remaining;
568 empty_tm = localtime(&empty_time);
570 /* No need to show empty time if battery is charging */
571 if (status != CS_CHARGING) {
573 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
574 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
576 (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
577 max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
580 (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
581 ((float)present_rate / 1000.0 / 1000.0));
584 #define EAT_SPACE_FROM_OUTPUT_IF_EMPTY(_buf) \
586 if (strlen(_buf) == 0) { \
587 if (outwalk > buffer && isspace(outwalk[-1])) \
589 else if (isspace(*(walk + 1))) \
594 for (walk = format; *walk != '\0'; walk++) {
596 *(outwalk++) = *walk;
600 if (BEGINS_WITH(walk + 1, "status")) {
601 outwalk += sprintf(outwalk, "%s", statusbuf);
602 walk += strlen("status");
603 } else if (BEGINS_WITH(walk + 1, "percentage")) {
604 outwalk += sprintf(outwalk, "%s", percentagebuf);
605 walk += strlen("percentage");
606 } else if (BEGINS_WITH(walk + 1, "remaining")) {
607 outwalk += sprintf(outwalk, "%s", remainingbuf);
608 walk += strlen("remaining");
609 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(remainingbuf);
610 } else if (BEGINS_WITH(walk + 1, "emptytime")) {
611 outwalk += sprintf(outwalk, "%s", emptytimebuf);
612 walk += strlen("emptytime");
613 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(emptytimebuf);
614 } else if (BEGINS_WITH(walk + 1, "consumption")) {
615 outwalk += sprintf(outwalk, "%s", consumptionbuf);
616 walk += strlen("consumption");
617 EAT_SPACE_FROM_OUTPUT_IF_EMPTY(consumptionbuf);
624 OUTPUT_FULL_TEXT(buffer);