d227d5599fc3c1c6c76c22f88e30607d8a76ec26
[collectd.git] / src / battery.c
1 /**
2  * collectd - src/battery.c
3  * Copyright (C) 2006-2014  Florian octo Forster
4  * Copyright (C) 2008       Michał Mirosław
5  * Copyright (C) 2014       Andy Parkins
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; only version 2 of the License is applicable.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  *
20  * Authors:
21  *   Florian octo Forster <octo at collectd.org>
22  *   Michał Mirosław <mirq-linux at rere.qmqm.pl>
23  *   Andy Parkins <andyp at fussylogic.co.uk>
24  **/
25
26 #include "collectd.h"
27
28 #include "common.h"
29 #include "plugin.h"
30
31 #if HAVE_MACH_MACH_TYPES_H
32 #  include <mach/mach_types.h>
33 #endif
34 #if HAVE_MACH_MACH_INIT_H
35 #  include <mach/mach_init.h>
36 #endif
37 #if HAVE_MACH_MACH_ERROR_H
38 #  include <mach/mach_error.h>
39 #endif
40 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
41 #  include <CoreFoundation/CoreFoundation.h>
42 #endif
43 #if HAVE_IOKIT_IOKITLIB_H
44 #  include <IOKit/IOKitLib.h>
45 #endif
46 #if HAVE_IOKIT_IOTYPES_H
47 #  include <IOKit/IOTypes.h>
48 #endif
49 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
50 #  include <IOKit/ps/IOPowerSources.h>
51 #endif
52 #if HAVE_IOKIT_PS_IOPSKEYS_H
53 #  include <IOKit/ps/IOPSKeys.h>
54 #endif
55
56 #if !HAVE_IOKIT_IOKITLIB_H && !HAVE_IOKIT_PS_IOPOWERSOURCES_H && !KERNEL_LINUX
57 # error "No applicable input method."
58 #endif
59
60 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
61         /* No global variables */
62 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
63
64 #elif KERNEL_LINUX
65 # define PROC_PMU_PATH_FORMAT "/proc/pmu/battery_%i"
66 # define PROC_ACPI_PATH "/proc/acpi/battery"
67 # define PROC_ACPI_FACTOR 0.001
68 # define SYSFS_PATH "/sys/class/power_supply"
69 # define SYSFS_FACTOR 0.000001
70 #endif /* KERNEL_LINUX */
71
72 int battery_read_statefs (void); /* defined in battery_statefs; used by StateFS backend */
73
74 static _Bool report_percent = 0;
75 static _Bool report_degraded = 0;
76 static _Bool query_statefs = 0;
77
78 static void battery_submit2 (char const *plugin_instance, /* {{{ */
79                 char const *type, char const *type_instance, gauge_t value)
80 {
81         value_t values[1];
82         value_list_t vl = VALUE_LIST_INIT;
83
84         values[0].gauge = value;
85
86         vl.values = values;
87         vl.values_len = 1;
88         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
89         sstrncpy (vl.plugin, "battery", sizeof (vl.plugin));
90         sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
91         sstrncpy (vl.type, type, sizeof (vl.type));
92         if (type_instance != NULL)
93                 sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
94
95         plugin_dispatch_values (&vl);
96 } /* }}} void battery_submit2 */
97
98 static void battery_submit (char const *plugin_instance, /* {{{ */
99                 char const *type, gauge_t value)
100 {
101         battery_submit2 (plugin_instance, type, NULL, value);
102 } /* }}} void battery_submit */
103
104 static void submit_capacity (char const *plugin_instance, /* {{{ */
105                 gauge_t capacity_charged,
106                 gauge_t capacity_full,
107                 gauge_t capacity_design)
108 {
109         if (report_percent && (capacity_charged > capacity_full))
110                 return;
111         if (report_degraded && (capacity_full > capacity_design))
112                 return;
113
114         if (report_percent)
115         {
116                 gauge_t capacity_max;
117
118                 if (report_degraded)
119                         capacity_max = capacity_design;
120                 else
121                         capacity_max = capacity_full;
122
123                 battery_submit2 (plugin_instance, "percent", "charged",
124                                 100.0 * capacity_charged / capacity_max);
125                 battery_submit2 (plugin_instance, "percent", "discharged",
126                                 100.0 * (capacity_full - capacity_charged) / capacity_max);
127
128                 if (report_degraded)
129                         battery_submit2 (plugin_instance, "percent", "degraded",
130                                         100.0 * (capacity_design - capacity_full) / capacity_max);
131         }
132         else if (report_degraded) /* && !report_percent */
133         {
134                 battery_submit2 (plugin_instance, "capacity", "charged",
135                                 capacity_charged);
136                 battery_submit2 (plugin_instance, "capacity", "discharged",
137                                 (capacity_full - capacity_charged));
138                 battery_submit2 (plugin_instance, "capacity", "degraded",
139                                 (capacity_design - capacity_full));
140         }
141         else /* !report_percent && !report_degraded */
142         {
143                 battery_submit (plugin_instance, "capacity", capacity_charged);
144         }
145 } /* }}} void submit_capacity */
146
147 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
148 static double dict_get_double (CFDictionaryRef dict, const char *key_string) /* {{{ */
149 {
150         double      val_double;
151         long long   val_int;
152         CFNumberRef val_obj;
153         CFStringRef key_obj;
154
155         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
156                         kCFStringEncodingASCII);
157         if (key_obj == NULL)
158         {
159                 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
160                 return (NAN);
161         }
162
163         if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
164         {
165                 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
166                 CFRelease (key_obj);
167                 return (NAN);
168         }
169         CFRelease (key_obj);
170
171         if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
172         {
173                 if (CFNumberIsFloatType (val_obj))
174                 {
175                         CFNumberGetValue (val_obj,
176                                         kCFNumberDoubleType,
177                                         &val_double);
178                 }
179                 else
180                 {
181                         CFNumberGetValue (val_obj,
182                                         kCFNumberLongLongType,
183                                         &val_int);
184                         val_double = val_int;
185                 }
186         }
187         else
188         {
189                 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
190                 return (NAN);
191         }
192
193         return (val_double);
194 } /* }}} double dict_get_double */
195
196 # if HAVE_IOKIT_PS_IOPOWERSOURCES_H
197 static void get_via_io_power_sources (double *ret_charge, /* {{{ */
198                 double *ret_current,
199                 double *ret_voltage)
200 {
201         CFTypeRef       ps_raw;
202         CFArrayRef      ps_array;
203         int             ps_array_len;
204         CFDictionaryRef ps_dict;
205         CFTypeRef       ps_obj;
206
207         double temp_double;
208
209         ps_raw       = IOPSCopyPowerSourcesInfo ();
210         ps_array     = IOPSCopyPowerSourcesList (ps_raw);
211         ps_array_len = CFArrayGetCount (ps_array);
212
213         DEBUG ("ps_array_len == %i", ps_array_len);
214
215         for (int i = 0; i < ps_array_len; i++)
216         {
217                 ps_obj  = CFArrayGetValueAtIndex (ps_array, i);
218                 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
219
220                 if (ps_dict == NULL)
221                 {
222                         DEBUG ("IOPSGetPowerSourceDescription failed.");
223                         continue;
224                 }
225
226                 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
227                 {
228                         DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
229                         continue;
230                 }
231
232                 /* FIXME: Check if this is really an internal battery */
233
234                 if (isnan (*ret_charge))
235                 {
236                         /* This is the charge in percent. */
237                         temp_double = dict_get_double (ps_dict,
238                                         kIOPSCurrentCapacityKey);
239                         if (!isnan ((temp_double))
240                                         && (temp_double >= 0.0)
241                                         && (temp_double <= 100.0))
242                                 *ret_charge = temp_double;
243                 }
244
245                 if (isnan (*ret_current))
246                 {
247                         temp_double = dict_get_double (ps_dict,
248                                         kIOPSCurrentKey);
249                         if (!isnan (temp_double))
250                                 *ret_current = temp_double / 1000.0;
251                 }
252
253                 if (isnan (*ret_voltage))
254                 {
255                         temp_double = dict_get_double (ps_dict,
256                                         kIOPSVoltageKey);
257                         if (!isnan (temp_double))
258                                 *ret_voltage = temp_double / 1000.0;
259                 }
260         }
261
262         CFRelease(ps_array);
263         CFRelease(ps_raw);
264 } /* }}} void get_via_io_power_sources */
265 # endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
266
267 # if HAVE_IOKIT_IOKITLIB_H
268 static void get_via_generic_iokit (double *ret_capacity_full, /* {{{ */
269                 double *ret_capacity_design,
270                 double *ret_current,
271                 double *ret_voltage)
272 {
273         kern_return_t   status;
274         io_iterator_t   iterator;
275         io_object_t     io_obj;
276
277         CFDictionaryRef bat_root_dict;
278         CFArrayRef      bat_info_arry;
279         CFIndex         bat_info_arry_len;
280         CFDictionaryRef bat_info_dict;
281
282         double temp_double;
283
284         status = IOServiceGetMatchingServices (kIOMasterPortDefault,
285                         IOServiceNameMatching ("battery"),
286                         &iterator);
287         if (status != kIOReturnSuccess)
288         {
289                 DEBUG ("IOServiceGetMatchingServices failed.");
290                 return;
291         }
292
293         while ((io_obj = IOIteratorNext (iterator)))
294         {
295                 status = IORegistryEntryCreateCFProperties (io_obj,
296                                 (CFMutableDictionaryRef *) &bat_root_dict,
297                                 kCFAllocatorDefault,
298                                 kNilOptions);
299                 if (status != kIOReturnSuccess)
300                 {
301                         DEBUG ("IORegistryEntryCreateCFProperties failed.");
302                         continue;
303                 }
304
305                 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
306                                 CFSTR ("IOBatteryInfo"));
307                 if (bat_info_arry == NULL)
308                 {
309                         CFRelease (bat_root_dict);
310                         continue;
311                 }
312                 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
313
314                 for (CFIndex bat_info_arry_pos = 0;
315                                 bat_info_arry_pos < bat_info_arry_len;
316                                 bat_info_arry_pos++)
317                 {
318                         bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
319
320                         if (isnan (*ret_capacity_full))
321                         {
322                                 temp_double = dict_get_double (bat_info_dict, "Capacity");
323                                 *ret_capacity_full = temp_double / 1000.0;
324                         }
325
326                         if (isnan (*ret_capacity_design))
327                         {
328                                 temp_double = dict_get_double (bat_info_dict, "AbsoluteMaxCapacity");
329                                 *ret_capacity_design = temp_double / 1000.0;
330                         }
331
332                         if (isnan (*ret_current))
333                         {
334                                 temp_double = dict_get_double (bat_info_dict, "Current");
335                                 *ret_current = temp_double / 1000.0;
336                         }
337
338                         if (isnan (*ret_voltage))
339                         {
340                                 temp_double = dict_get_double (bat_info_dict, "Voltage");
341                                 *ret_voltage = temp_double / 1000.0;
342                         }
343                 }
344
345                 CFRelease (bat_root_dict);
346         }
347
348         IOObjectRelease (iterator);
349 } /* }}} void get_via_generic_iokit */
350 # endif /* HAVE_IOKIT_IOKITLIB_H */
351
352 static int battery_read (void) /* {{{ */
353 {
354         gauge_t current = NAN; /* Current in A */
355         gauge_t voltage = NAN; /* Voltage in V */
356
357         /* We only get the charged capacity as a percentage from
358          * IOPowerSources. IOKit, on the other hand, only reports the full
359          * capacity. We use the two to calculate the current charged capacity. */
360         gauge_t charge_rel = NAN; /* Current charge in percent */
361         gauge_t capacity_charged; /* Charged capacity */
362         gauge_t capacity_full = NAN; /* Total capacity */
363         gauge_t capacity_design = NAN; /* Full design capacity */
364
365         if (query_statefs)
366                 return battery_read_statefs ();
367
368 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
369         get_via_io_power_sources (&charge_rel, &current, &voltage);
370 #endif
371 #if HAVE_IOKIT_IOKITLIB_H
372         get_via_generic_iokit (&capacity_full, &capacity_design, &current, &voltage);
373 #endif
374
375         capacity_charged = charge_rel * capacity_full / 100.0;
376         submit_capacity ("0", capacity_charged, capacity_full, capacity_design);
377
378         if (!isnan (current))
379                 battery_submit ("0", "current", current);
380         if (!isnan (voltage))
381                 battery_submit ("0", "voltage", voltage);
382
383         return (0);
384 } /* }}} int battery_read */
385 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
386
387 #elif KERNEL_LINUX
388 /* Reads a file which contains only a number (and optionally a trailing
389  * newline) and parses that number. */
390 static int sysfs_file_to_buffer(char const *dir, /* {{{ */
391                 char const *power_supply,
392                 char const *basename,
393                 char *buffer, size_t buffer_size)
394 {
395         char filename[PATH_MAX];
396         int status;
397
398         ssnprintf (filename, sizeof (filename), "%s/%s/%s",
399                         dir, power_supply, basename);
400
401         status = (int) read_file_contents (filename, buffer, buffer_size);
402         if (status < 0)
403                 return status;
404
405         strstripnewline (buffer);
406         return 0;
407 } /* }}} int sysfs_file_to_buffer */
408
409 /* Reads a file which contains only a number (and optionally a trailing
410  * newline) and parses that number. */
411 static int sysfs_file_to_gauge(char const *dir, /* {{{ */
412                 char const *power_supply,
413                 char const *basename, gauge_t *ret_value)
414 {
415         int status;
416         char buffer[32] = "";
417
418         status = sysfs_file_to_buffer (dir, power_supply, basename, buffer, sizeof (buffer));
419         if (status != 0)
420                 return (status);
421
422         return (strtogauge (buffer, ret_value));
423 } /* }}} sysfs_file_to_gauge */
424
425 static int read_sysfs_capacity (char const *dir, /* {{{ */
426                 char const *power_supply,
427                 char const *plugin_instance)
428 {
429         gauge_t capacity_charged = NAN;
430         gauge_t capacity_full = NAN;
431         gauge_t capacity_design = NAN;
432         int status;
433
434         status = sysfs_file_to_gauge (dir, power_supply, "energy_now", &capacity_charged);
435         if (status != 0)
436                 return (status);
437
438         status = sysfs_file_to_gauge (dir, power_supply, "energy_full", &capacity_full);
439         if (status != 0)
440                 return (status);
441
442         status = sysfs_file_to_gauge (dir, power_supply, "energy_full_design", &capacity_design);
443         if (status != 0)
444                 return (status);
445
446         submit_capacity (plugin_instance,
447                         capacity_charged * SYSFS_FACTOR,
448                         capacity_full * SYSFS_FACTOR,
449                         capacity_design * SYSFS_FACTOR);
450         return (0);
451 } /* }}} int read_sysfs_capacity */
452
453 static int read_sysfs_callback (char const *dir, /* {{{ */
454                 char const *power_supply,
455                 void *user_data)
456 {
457         int *battery_index = user_data;
458
459         char const *plugin_instance;
460         char buffer[32];
461         gauge_t v = NAN;
462         _Bool discharging = 0;
463         int status;
464
465         /* Ignore non-battery directories, such as AC power. */
466         status = sysfs_file_to_buffer (dir, power_supply, "type", buffer, sizeof (buffer));
467         if (status != 0)
468                 return (0);
469         if (strcasecmp ("Battery", buffer) != 0)
470                 return (0);
471
472         (void) sysfs_file_to_buffer (dir, power_supply, "status", buffer, sizeof (buffer));
473         if (strcasecmp ("Discharging", buffer) == 0)
474                 discharging = 1;
475
476         /* FIXME: This is a dirty hack for backwards compatibility: The battery
477          * plugin, for a very long time, has had the plugin_instance
478          * hard-coded to "0". So, to keep backwards compatibility, we'll use
479          * "0" for the first battery we find and the power_supply name for all
480          * following. This should be reverted in a future major version. */
481         plugin_instance = (*battery_index == 0) ? "0" : power_supply;
482         (*battery_index)++;
483
484         read_sysfs_capacity (dir, power_supply, plugin_instance);
485
486         if (sysfs_file_to_gauge (dir, power_supply, "power_now", &v) == 0)
487         {
488                 if (discharging)
489                         v *= -1.0;
490                 battery_submit (plugin_instance, "power", v * SYSFS_FACTOR);
491         }
492         if (sysfs_file_to_gauge (dir, power_supply, "current_now", &v) == 0)
493         {
494                 if (discharging)
495                         v *= -1.0;
496                 battery_submit (plugin_instance, "current", v * SYSFS_FACTOR);
497         }
498
499         if (sysfs_file_to_gauge (dir, power_supply, "voltage_now", &v) == 0)
500                 battery_submit (plugin_instance, "voltage", v * SYSFS_FACTOR);
501
502         return (0);
503 } /* }}} int read_sysfs_callback */
504
505 static int read_sysfs (void) /* {{{ */
506 {
507         int status;
508         int battery_counter = 0;
509
510         if (access (SYSFS_PATH, R_OK) != 0)
511                 return (ENOENT);
512
513         status = walk_directory (SYSFS_PATH, read_sysfs_callback,
514                         /* user_data = */ &battery_counter,
515                         /* include hidden */ 0);
516         return (status);
517 } /* }}} int read_sysfs */
518
519 static int read_acpi_full_capacity (char const *dir, /* {{{ */
520                 char const *power_supply,
521                 gauge_t *ret_capacity_full,
522                 gauge_t *ret_capacity_design)
523
524 {
525         char filename[PATH_MAX];
526         char buffer[1024];
527
528         FILE *fh;
529
530         ssnprintf (filename, sizeof (filename), "%s/%s/info", dir, power_supply);
531         fh = fopen (filename, "r");
532         if (fh == NULL)
533                 return (errno);
534
535         /* last full capacity:      40090 mWh */
536         while (fgets (buffer, sizeof (buffer), fh) != NULL)
537         {
538                 gauge_t *value_ptr;
539                 int fields_num;
540                 char *fields[8];
541                 int index;
542
543                 if (strncmp ("last full capacity:", buffer, strlen ("last full capacity:")) == 0)
544                 {
545                         value_ptr = ret_capacity_full;
546                         index = 3;
547                 }
548                 else if (strncmp ("design capacity:", buffer, strlen ("design capacity:")) == 0)
549                 {
550                         value_ptr = ret_capacity_design;
551                         index = 2;
552                 }
553                 else
554                 {
555                         continue;
556                 }
557
558                 fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
559                 if (fields_num <= index)
560                         continue;
561
562                 strtogauge (fields[index], value_ptr);
563         }
564
565         fclose (fh);
566         return (0);
567 } /* }}} int read_acpi_full_capacity */
568
569 static int read_acpi_callback (char const *dir, /* {{{ */
570                 char const *power_supply,
571                 void *user_data)
572 {
573         int *battery_index = user_data;
574
575         gauge_t power = NAN;
576         gauge_t voltage = NAN;
577         gauge_t capacity_charged = NAN;
578         gauge_t capacity_full = NAN;
579         gauge_t capacity_design = NAN;
580         _Bool charging = 0;
581         _Bool is_current = 0;
582
583         char const *plugin_instance;
584         char filename[PATH_MAX];
585         char buffer[1024];
586
587         FILE *fh;
588
589         ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
590         fh = fopen (filename, "r");
591         if (fh == NULL)
592         {
593                 if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
594                         return (0);
595                 else
596                         return (errno);
597         }
598
599         /*
600          * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
601          * [11:00] <@tokkee> present:                 yes
602          * [11:00] <@tokkee> capacity state:          ok
603          * [11:00] <@tokkee> charging state:          charging
604          * [11:00] <@tokkee> present rate:            1724 mA
605          * [11:00] <@tokkee> remaining capacity:      4136 mAh
606          * [11:00] <@tokkee> present voltage:         12428 mV
607          */
608         while (fgets (buffer, sizeof (buffer), fh) != NULL)
609         {
610                 char *fields[8];
611                 int numfields;
612
613                 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
614                 if (numfields < 3)
615                         continue;
616
617                 if ((strcmp (fields[0], "charging") == 0)
618                                 && (strcmp (fields[1], "state:") == 0))
619                 {
620                         if (strcmp (fields[2], "charging") == 0)
621                                 charging = 1;
622                         else
623                                 charging = 0;
624                         continue;
625                 }
626
627                 /* The unit of "present rate" depends on the battery. Modern
628                  * batteries export power (watts), older batteries (used to)
629                  * export current (amperes). We check the fourth column and try
630                  * to find old batteries this way. */
631                 if ((strcmp (fields[0], "present") == 0)
632                                 && (strcmp (fields[1], "rate:") == 0))
633                 {
634                         strtogauge (fields[2], &power);
635
636                         if ((numfields >= 4) && (strcmp ("mA", fields[3]) == 0))
637                                 is_current = 1;
638                 }
639                 else if ((strcmp (fields[0], "remaining") == 0)
640                                 && (strcmp (fields[1], "capacity:") == 0))
641                         strtogauge (fields[2], &capacity_charged);
642                 else if ((strcmp (fields[0], "present") == 0)
643                                 && (strcmp (fields[1], "voltage:") == 0))
644                         strtogauge (fields[2], &voltage);
645         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
646
647         fclose (fh);
648
649         if (!charging)
650                 power *= -1.0;
651
652         /* FIXME: This is a dirty hack for backwards compatibility: The battery
653          * plugin, for a very long time, has had the plugin_instance
654          * hard-coded to "0". So, to keep backwards compatibility, we'll use
655          * "0" for the first battery we find and the power_supply name for all
656          * following. This should be reverted in a future major version. */
657         plugin_instance = (*battery_index == 0) ? "0" : power_supply;
658         (*battery_index)++;
659
660         read_acpi_full_capacity (dir, power_supply, &capacity_full, &capacity_design);
661
662         submit_capacity (plugin_instance,
663                         capacity_charged * PROC_ACPI_FACTOR,
664                         capacity_full * PROC_ACPI_FACTOR,
665                         capacity_design * PROC_ACPI_FACTOR);
666
667         battery_submit (plugin_instance,
668                         is_current ? "current" : "power",
669                         power * PROC_ACPI_FACTOR);
670         battery_submit (plugin_instance, "voltage", voltage * PROC_ACPI_FACTOR);
671
672         return 0;
673 } /* }}} int read_acpi_callback */
674
675 static int read_acpi (void) /* {{{ */
676 {
677         int status;
678         int battery_counter = 0;
679
680         if (access (PROC_ACPI_PATH, R_OK) != 0)
681                 return (ENOENT);
682
683         status = walk_directory (PROC_ACPI_PATH, read_acpi_callback,
684                         /* user_data = */ &battery_counter,
685                         /* include hidden */ 0);
686         return (status);
687 } /* }}} int read_acpi */
688
689 static int read_pmu (void) /* {{{ */
690 {
691         int i = 0;
692         /* The upper limit here is just a safeguard. If there is a system with
693          * more than 100 batteries, this can easily be increased. */
694         for (; i < 100; i++)
695         {
696                 FILE *fh;
697
698                 char buffer[1024];
699                 char filename[PATH_MAX];
700                 char plugin_instance[DATA_MAX_NAME_LEN];
701
702                 gauge_t current = NAN;
703                 gauge_t voltage = NAN;
704                 gauge_t charge  = NAN;
705
706                 ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
707                 if (access (filename, R_OK) != 0)
708                         break;
709
710                 ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);
711
712                 fh = fopen (filename, "r");
713                 if (fh == NULL)
714                 {
715                         if (errno == ENOENT)
716                                 break;
717                         else if ((errno == EAGAIN) || (errno == EINTR))
718                                 continue;
719                         else
720                                 return (errno);
721                 }
722
723                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
724                 {
725                         char *fields[8];
726                         int numfields;
727
728                         numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
729                         if (numfields < 3)
730                                 continue;
731
732                         if (strcmp ("current", fields[0]) == 0)
733                                 strtogauge (fields[2], &current);
734                         else if (strcmp ("voltage", fields[0]) == 0)
735                                 strtogauge (fields[2], &voltage);
736                         else if (strcmp ("charge", fields[0]) == 0)
737                                 strtogauge (fields[2], &charge);
738                 }
739
740                 fclose (fh);
741                 fh = NULL;
742
743                 battery_submit (plugin_instance, "charge", charge / 1000.0);
744                 battery_submit (plugin_instance, "current", current / 1000.0);
745                 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
746         }
747
748         if (i == 0)
749                 return (ENOENT);
750         return (0);
751 } /* }}} int read_pmu */
752
753 static int battery_read (void) /* {{{ */
754 {
755         int status;
756
757         if (query_statefs)
758                 return battery_read_statefs ();
759
760         DEBUG ("battery plugin: Trying sysfs ...");
761         status = read_sysfs ();
762         if (status == 0)
763                 return (0);
764
765         DEBUG ("battery plugin: Trying acpi ...");
766         status = read_acpi ();
767         if (status == 0)
768                 return (0);
769
770         DEBUG ("battery plugin: Trying pmu ...");
771         status = read_pmu ();
772         if (status == 0)
773                 return (0);
774
775         ERROR ("battery plugin: Add available input methods failed.");
776         return (-1);
777 } /* }}} int battery_read */
778 #endif /* KERNEL_LINUX */
779
780 static int battery_config (oconfig_item_t *ci)
781 {
782         for (int i = 0; i < ci->children_num; i++)
783         {
784                 oconfig_item_t *child = ci->children + i;
785
786                 if (strcasecmp ("ValuesPercentage", child->key) == 0)
787                         cf_util_get_boolean (child, &report_percent);
788                 else if (strcasecmp ("ReportDegraded", child->key) == 0)
789                         cf_util_get_boolean (child, &report_degraded);
790                 else if (strcasecmp ("QueryStateFS", child->key) == 0)
791                         cf_util_get_boolean (child, &query_statefs);
792                 else
793                         WARNING ("battery plugin: Ignoring unknown "
794                                         "configuration option \"%s\".",
795                                         child->key);
796         }
797
798         return (0);
799 } /* }}} int battery_config */
800
801 void module_register (void)
802 {
803         plugin_register_complex_config ("battery", battery_config);
804         plugin_register_read ("battery", battery_read);
805 } /* void module_register */