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