]> git.sur5r.net Git - i3/i3status/blob - src/print_battery_info.c
Merge pull request #142 from tommie/incremental_multibatt
[i3/i3status] / src / print_battery_info.c
1 // vim:ts=4:sw=4:expandtab
2 #include <ctype.h>
3 #include <time.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <yajl/yajl_gen.h>
8 #include <yajl/yajl_version.h>
9
10 #include "i3status.h"
11
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>
16 #endif
17
18 #if defined(__OpenBSD__)
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 #include <sys/fcntl.h>
22 #include <machine/apmvar.h>
23 #endif
24
25 #if defined(__NetBSD__)
26 #include <fcntl.h>
27 #include <prop/proplib.h>
28 #include <sys/envsys.h>
29 #endif
30
31 /*
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.
35  *
36  */
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_unk, const char *status_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) {
38     time_t empty_time;
39     struct tm *empty_tm;
40     char buf[1024];
41     char emptytimebuf[256];
42     char consumptionbuf[256];
43     const char *walk, *last;
44     char *outwalk = buffer;
45     bool watt_as_unit = false;
46     bool colorful_output = false;
47     int full_design = -1,
48         remaining = -1,
49         present_rate = -1,
50         voltage = -1,
51         seconds_remaining = -1;
52     float percentage_remaining = -1;
53     charging_status_t status = CS_DISCHARGING;
54
55     memset(emptytimebuf, '\0', sizeof(emptytimebuf));
56     memset(consumptionbuf, '\0', sizeof(consumptionbuf));
57
58     static char batpath[512];
59     sprintf(batpath, path, number);
60     INSTANCE(batpath);
61
62 #if defined(LINUX)
63     if (!slurp(batpath, buf, sizeof(buf))) {
64         OUTPUT_FULL_TEXT(format_down);
65         return;
66     }
67
68     for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
69         if (*walk == '\n') {
70             last = walk + 1;
71             continue;
72         }
73
74         if (*walk != '=')
75             continue;
76
77         if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW")) {
78             watt_as_unit = true;
79             remaining = atoi(walk + 1);
80         } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW")) {
81             watt_as_unit = false;
82             remaining = atoi(walk + 1);
83         } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW"))
84             present_rate = abs(atoi(walk + 1));
85         else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW"))
86             voltage = abs(atoi(walk + 1));
87         /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
88          * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
89          * unit instead of μAh. We will calculate it as we need it
90          * later. */
91         else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW"))
92             present_rate = abs(atoi(walk + 1));
93         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
94             status = CS_CHARGING;
95         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
96             status = CS_FULL;
97         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging"))
98             status = CS_DISCHARGING;
99         else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
100             status = CS_UNKNOWN;
101         else {
102             /* The only thing left is the full capacity */
103             if (last_full_capacity) {
104                 if (!BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL") &&
105                     !BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL"))
106                     continue;
107             } else {
108                 if (!BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN") &&
109                     !BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN"))
110                     continue;
111             }
112
113             full_design = atoi(walk + 1);
114         }
115     }
116
117     /* the difference between POWER_SUPPLY_ENERGY_NOW and
118      * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
119      * given in mWh, the charge in mAh. So calculate every value given in
120      * ampere to watt */
121     if (!watt_as_unit) {
122         present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
123
124         if (voltage != -1) {
125             remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
126             full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
127         }
128     }
129
130     if ((full_design == -1) || (remaining == -1)) {
131         OUTPUT_FULL_TEXT(format_down);
132         return;
133     }
134
135     percentage_remaining = (((float)remaining / (float)full_design) * 100);
136     /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
137      * charged, even though that’s plainly wrong. For people who chose to see
138      * the percentage calculated based on the last full capacity, we clamp the
139      * value to 100%, as that makes more sense.
140      * See http://bugs.debian.org/785398 */
141     if (last_full_capacity && percentage_remaining > 100) {
142         percentage_remaining = 100;
143     }
144
145     if (present_rate > 0 && status != CS_FULL) {
146         float remaining_time;
147         if (status == CS_CHARGING)
148             remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
149         else if (status == CS_DISCHARGING)
150             remaining_time = ((float)remaining / (float)present_rate);
151         else
152             remaining_time = 0;
153
154         seconds_remaining = (int)(remaining_time * 3600.0);
155
156         if (status == CS_DISCHARGING && low_threshold > 0) {
157             if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
158                 START_COLOR("color_bad");
159                 colorful_output = true;
160             } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) {
161                 START_COLOR("color_bad");
162                 colorful_output = true;
163             } else {
164                 colorful_output = false;
165             }
166         }
167
168         empty_time = time(NULL);
169         empty_time += seconds_remaining;
170         empty_tm = localtime(&empty_time);
171
172         if (hide_seconds)
173             (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
174                            max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
175         else
176             (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
177                            max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
178
179         (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
180                        ((float)present_rate / 1000.0 / 1000.0));
181     } else {
182         /* On some systems, present_rate may not exist. Still, make sure
183          * we colorize the output if threshold_type is set to percentage
184          * (since we don't have any information on remaining time). */
185         if (status == CS_DISCHARGING && low_threshold > 0) {
186             if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
187                 START_COLOR("color_bad");
188                 colorful_output = true;
189             }
190         }
191     }
192 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
193     int state;
194     int sysctl_rslt;
195     size_t sysctl_size = sizeof(sysctl_rslt);
196
197     if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
198         OUTPUT_FULL_TEXT(format_down);
199         return;
200     }
201
202     integer_battery_capacity = true;
203     percentage_remaining = sysctl_rslt;
204     if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
205         OUTPUT_FULL_TEXT(format_down);
206         return;
207     }
208
209     hide_seconds = true;
210     seconds_remaining = sysctl_rslt * 60;
211     if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
212         OUTPUT_FULL_TEXT(format_down);
213         return;
214     }
215
216     state = sysctl_rslt;
217     if (state == 0 && percentage_remaining == 100)
218         status = CS_FULL;
219     else if ((state & ACPI_BATT_STAT_CHARGING) && percentage_remaining < 100)
220         status = CS_CHARGING;
221     else
222         status = CS_DISCHARGING;
223
224     full_design = sysctl_rslt;
225
226     if (state == ACPI_BATT_STAT_DISCHARG) {
227         if (strcasecmp(threshold_type, "percentage") == 0 && percentage_remaining < low_threshold) {
228             START_COLOR("color_bad");
229             colorful_output = true;
230         } else if (strcasecmp(threshold_type, "time") == 0 && seconds_remaining < 60 * low_threshold) {
231             START_COLOR("color_bad");
232             colorful_output = true;
233         }
234     }
235 #elif defined(__OpenBSD__)
236     /*
237          * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
238          * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
239          * probing acpi(4) devices.
240          */
241     struct apm_power_info apm_info;
242     int apm_fd;
243
244     apm_fd = open("/dev/apm", O_RDONLY);
245     if (apm_fd < 0) {
246         OUTPUT_FULL_TEXT("can't open /dev/apm");
247         return;
248     }
249     if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
250         OUTPUT_FULL_TEXT("can't read power info");
251
252     close(apm_fd);
253
254     /* Don't bother to go further if there's no battery present. */
255     if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
256         (apm_info.battery_state == APM_BATT_UNKNOWN)) {
257         OUTPUT_FULL_TEXT(format_down);
258         return;
259     }
260
261     switch (apm_info.ac_state) {
262         case APM_AC_OFF:
263             status = CS_DISCHARGING;
264             break;
265         case APM_AC_ON:
266             status = CS_CHARGING;
267             break;
268         default:
269             /* If we don't know what's going on, just assume we're discharging. */
270             status = CS_DISCHARGING;
271             break;
272     }
273
274     integer_battery_capacity = true;
275     percentage_remaining = apm_info.battery_life;
276
277     if (status == CS_DISCHARGING && low_threshold > 0) {
278         if (strcasecmp(threshold_type, "percentage") == 0 && apm_info.battery_life < low_threshold) {
279             START_COLOR("color_bad");
280             colorful_output = true;
281         } else if (strcasecmp(threshold_type, "time") == 0 && apm_info.minutes_left < (u_int)low_threshold) {
282             START_COLOR("color_bad");
283             colorful_output = true;
284         }
285     }
286
287     /* Can't give a meaningful value for remaining minutes if we're charging. */
288     if (status != CS_CHARGING) {
289         seconds_remaining = apm_info.minutes_left * 60;
290     }
291
292     if (colorful_output)
293         END_COLOR;
294 #elif defined(__NetBSD__)
295     /*
296      * Using envsys(4) via sysmon(4).
297      */
298     int fd, rval, last_full_cap;
299     bool is_found = false;
300     char *sensor_desc;
301     bool is_full = false;
302
303     prop_dictionary_t dict;
304     prop_array_t array;
305     prop_object_iterator_t iter;
306     prop_object_iterator_t iter2;
307     prop_object_t obj, obj2, obj3, obj4, obj5;
308
309     asprintf(&sensor_desc, "acpibat%d", number);
310
311     fd = open("/dev/sysmon", O_RDONLY);
312     if (fd < 0) {
313         OUTPUT_FULL_TEXT("can't open /dev/sysmon");
314         return;
315     }
316
317     rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
318     if (rval == -1) {
319         close(fd);
320         return;
321     }
322
323     if (prop_dictionary_count(dict) == 0) {
324         prop_object_release(dict);
325         close(fd);
326         return;
327     }
328
329     iter = prop_dictionary_iterator(dict);
330     if (iter == NULL) {
331         prop_object_release(dict);
332         close(fd);
333     }
334
335     /* iterate over the dictionary returned by the kernel */
336     while ((obj = prop_object_iterator_next(iter)) != NULL) {
337         /* skip this dict if it's not what we're looking for */
338         if ((strlen(prop_dictionary_keysym_cstring_nocopy(obj)) == strlen(sensor_desc)) &&
339             (strncmp(sensor_desc,
340                      prop_dictionary_keysym_cstring_nocopy(obj),
341                      strlen(sensor_desc)) != 0))
342             continue;
343
344         is_found = true;
345
346         array = prop_dictionary_get_keysym(dict, obj);
347         if (prop_object_type(array) != PROP_TYPE_ARRAY) {
348             prop_object_iterator_release(iter);
349             prop_object_release(dict);
350             close(fd);
351             return;
352         }
353
354         iter2 = prop_array_iterator(array);
355         if (!iter2) {
356             prop_object_iterator_release(iter);
357             prop_object_release(dict);
358             close(fd);
359             return;
360         }
361
362         /* iterate over array of dicts specific to target battery */
363         while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
364             obj3 = prop_dictionary_get(obj2, "description");
365
366             if (obj3 &&
367                 strlen(prop_string_cstring_nocopy(obj3)) == 8 &&
368                 strncmp("charging",
369                         prop_string_cstring_nocopy(obj3),
370                         8) == 0) {
371                 obj3 = prop_dictionary_get(obj2, "cur-value");
372
373                 if (prop_number_integer_value(obj3))
374                     status = CS_CHARGING;
375                 else
376                     status = CS_DISCHARGING;
377
378                 continue;
379             }
380
381             if (obj3 &&
382                 strlen(prop_string_cstring_nocopy(obj3)) == 6 &&
383                 strncmp("charge",
384                         prop_string_cstring_nocopy(obj3),
385                         6) == 0) {
386                 obj3 = prop_dictionary_get(obj2, "cur-value");
387                 obj4 = prop_dictionary_get(obj2, "max-value");
388                 obj5 = prop_dictionary_get(obj2, "type");
389
390                 remaining = prop_number_integer_value(obj3);
391                 full_design = prop_number_integer_value(obj4);
392
393                 if (remaining == full_design)
394                     is_full = true;
395
396                 if (strncmp("Ampere hour",
397                             prop_string_cstring_nocopy(obj5),
398                             11) == 0)
399                     watt_as_unit = false;
400                 else
401                     watt_as_unit = true;
402
403                 continue;
404             }
405
406             if (obj3 &&
407                 strlen(prop_string_cstring_nocopy(obj3)) == 14 &&
408                 strncmp("discharge rate",
409                         prop_string_cstring_nocopy(obj3),
410                         14) == 0) {
411                 obj3 = prop_dictionary_get(obj2, "cur-value");
412                 present_rate = prop_number_integer_value(obj3);
413                 continue;
414             }
415
416             if (obj3 &&
417                 strlen(prop_string_cstring_nocopy(obj3)) == 13 &&
418                 strncmp("last full cap",
419                         prop_string_cstring_nocopy(obj3),
420                         13) == 0) {
421                 obj3 = prop_dictionary_get(obj2, "cur-value");
422                 last_full_cap = prop_number_integer_value(obj3);
423                 continue;
424             }
425
426             if (obj3 &&
427                 strlen(prop_string_cstring_nocopy(obj3)) == 7 &&
428                 strncmp("voltage",
429                         prop_string_cstring_nocopy(obj3),
430                         7) == 0) {
431                 obj3 = prop_dictionary_get(obj2, "cur-value");
432                 voltage = prop_number_integer_value(obj3);
433                 continue;
434             }
435         }
436         prop_object_iterator_release(iter2);
437     }
438
439     prop_object_iterator_release(iter);
440     prop_object_release(dict);
441     close(fd);
442
443     if (!is_found) {
444         OUTPUT_FULL_TEXT(format_down);
445         return;
446     }
447
448     if (last_full_capacity)
449         full_design = last_full_cap;
450
451     if (!watt_as_unit) {
452         present_rate = (((float)voltage / 1000.0) * ((float)present_rate / 1000.0));
453         remaining = (((float)voltage / 1000.0) * ((float)remaining / 1000.0));
454         full_design = (((float)voltage / 1000.0) * ((float)full_design / 1000.0));
455     }
456
457     percentage_remaining =
458         (((float)remaining / (float)full_design) * 100);
459
460     /*
461      * Handle percentage low_threshold here, and time low_threshold when
462      * we have it.
463      */
464     if (status == CS_DISCHARGING && low_threshold > 0) {
465         if (strcasecmp(threshold_type, "percentage") == 0 && (((float)remaining / (float)full_design) * 100) < low_threshold) {
466             START_COLOR("color_bad");
467             colorful_output = true;
468         }
469     }
470
471     if (is_full)
472         status = CS_FULL;
473
474     /*
475      * The envsys(4) ACPI routines do not appear to provide a 'time
476      * remaining' figure, so we must deduce it.
477      */
478     float remaining_time;
479
480     if (status == CS_CHARGING)
481         remaining_time = ((float)full_design - (float)remaining) / (float)present_rate;
482     else if (status == CS_DISCHARGING)
483         remaining_time = ((float)remaining / (float)present_rate);
484     else
485         remaining_time = 0;
486
487     seconds_remaining = (int)(remaining_time * 3600.0);
488
489     if (status != CS_CHARGING) {
490         if (low_threshold > 0) {
491             if (strcasecmp(threshold_type, "time") == 0 && ((float)seconds_remaining / 60.0) < (u_int)low_threshold) {
492                 START_COLOR("color_bad");
493                 colorful_output = true;
494             }
495         }
496     }
497
498     empty_time = time(NULL);
499     empty_time += seconds_remaining;
500     empty_tm = localtime(&empty_time);
501
502     /* No need to show empty time if battery is charging */
503     if (status != CS_CHARGING) {
504         if (hide_seconds)
505             (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d",
506                            max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
507         else
508             (void)snprintf(emptytimebuf, sizeof(emptytimebuf), "%02d:%02d:%02d",
509                            max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
510     }
511
512     (void)snprintf(consumptionbuf, sizeof(consumptionbuf), "%1.2fW",
513                    ((float)present_rate / 1000.0 / 1000.0));
514 #endif
515
516 #define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT()              \
517     do {                                                  \
518         if (outwalk == prevoutwalk) {                     \
519             if (outwalk > buffer && isspace(outwalk[-1])) \
520                 outwalk--;                                \
521             else if (isspace(*(walk + 1)))                \
522                 walk++;                                   \
523         }                                                 \
524     } while (0)
525
526     for (walk = format; *walk != '\0'; walk++) {
527         char *prevoutwalk = outwalk;
528
529         if (*walk != '%') {
530             *(outwalk++) = *walk;
531             continue;
532         }
533
534         if (BEGINS_WITH(walk + 1, "status")) {
535             const char *statusstr;
536             switch (status) {
537                 case CS_CHARGING:
538                     statusstr = status_chr;
539                     break;
540                 case CS_DISCHARGING:
541                     statusstr = status_bat;
542                     break;
543                 case CS_FULL:
544                     statusstr = status_full;
545                     break;
546                 default:
547                     statusstr = status_unk;
548             }
549
550             outwalk += sprintf(outwalk, "%s", statusstr);
551             walk += strlen("status");
552         } else if (BEGINS_WITH(walk + 1, "percentage")) {
553             if (integer_battery_capacity) {
554                 outwalk += sprintf(outwalk, "%.00f%s", percentage_remaining, pct_mark);
555             } else {
556                 outwalk += sprintf(outwalk, "%.02f%s", percentage_remaining, pct_mark);
557             }
558             walk += strlen("percentage");
559         } else if (BEGINS_WITH(walk + 1, "remaining")) {
560             if (seconds_remaining >= 0) {
561                 int seconds, hours, minutes;
562
563                 hours = seconds_remaining / 3600;
564                 seconds = seconds_remaining - (hours * 3600);
565                 minutes = seconds / 60;
566                 seconds -= (minutes * 60);
567
568                 if (hide_seconds)
569                     outwalk += sprintf(outwalk, "%02d:%02d",
570                                        max(hours, 0), max(minutes, 0));
571                 else
572                     outwalk += sprintf(outwalk, "%02d:%02d:%02d",
573                                        max(hours, 0), max(minutes, 0), max(seconds, 0));
574             }
575             walk += strlen("remaining");
576             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
577         } else if (BEGINS_WITH(walk + 1, "emptytime")) {
578             outwalk += sprintf(outwalk, "%s", emptytimebuf);
579             walk += strlen("emptytime");
580             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
581         } else if (BEGINS_WITH(walk + 1, "consumption")) {
582             outwalk += sprintf(outwalk, "%s", consumptionbuf);
583             walk += strlen("consumption");
584             EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
585         }
586     }
587
588     if (colorful_output)
589         END_COLOR;
590
591     OUTPUT_FULL_TEXT(buffer);
592 }