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