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