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