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