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