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