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