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