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