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