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