battery plugin: Add StateFS backend.
[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         int status;
396         FILE *fp;
397         char filename[PATH_MAX];
398
399         ssnprintf (filename, sizeof (filename), "%s/%s/%s",
400                         dir, power_supply, basename);
401
402         /* No file isn't the end of the world -- not every system will be
403          * reporting the same set of statistics */
404         if (access (filename, R_OK) != 0)
405                 return ENOENT;
406
407         fp = fopen (filename, "r");
408         if (fp == NULL)
409         {
410                 status = errno;
411                 if (status != ENOENT)
412                 {
413                         char errbuf[1024];
414                         WARNING ("battery plugin: fopen (%s) failed: %s", filename,
415                                         sstrerror (status, errbuf, sizeof (errbuf)));
416                 }
417                 return status;
418         }
419
420         if (fgets (buffer, buffer_size, fp) == NULL)
421         {
422                 status = errno;
423                 if (status != ENODEV)
424                 {
425                         char errbuf[1024];
426                         WARNING ("battery plugin: fgets (%s) failed: %s", filename,
427                                         sstrerror (status, errbuf, sizeof (errbuf)));
428                 }
429                 fclose (fp);
430                 return status;
431         }
432
433         strstripnewline (buffer);
434
435         fclose (fp);
436         return 0;
437 } /* }}} int sysfs_file_to_buffer */
438
439 /* Reads a file which contains only a number (and optionally a trailing
440  * newline) and parses that number. */
441 static int sysfs_file_to_gauge(char const *dir, /* {{{ */
442                 char const *power_supply,
443                 char const *basename, gauge_t *ret_value)
444 {
445         int status;
446         char buffer[32] = "";
447
448         status = sysfs_file_to_buffer (dir, power_supply, basename, buffer, sizeof (buffer));
449         if (status != 0)
450                 return (status);
451
452         return (strtogauge (buffer, ret_value));
453 } /* }}} sysfs_file_to_gauge */
454
455 static int read_sysfs_capacity (char const *dir, /* {{{ */
456                 char const *power_supply,
457                 char const *plugin_instance)
458 {
459         gauge_t capacity_charged = NAN;
460         gauge_t capacity_full = NAN;
461         gauge_t capacity_design = NAN;
462         int status;
463
464         status = sysfs_file_to_gauge (dir, power_supply, "energy_now", &capacity_charged);
465         if (status != 0)
466                 return (status);
467
468         status = sysfs_file_to_gauge (dir, power_supply, "energy_full", &capacity_full);
469         if (status != 0)
470                 return (status);
471
472         status = sysfs_file_to_gauge (dir, power_supply, "energy_full_design", &capacity_design);
473         if (status != 0)
474                 return (status);
475
476         submit_capacity (plugin_instance,
477                         capacity_charged * SYSFS_FACTOR,
478                         capacity_full * SYSFS_FACTOR,
479                         capacity_design * SYSFS_FACTOR);
480         return (0);
481 } /* }}} int read_sysfs_capacity */
482
483 static int read_sysfs_callback (char const *dir, /* {{{ */
484                 char const *power_supply,
485                 void *user_data)
486 {
487         int *battery_index = user_data;
488
489         char const *plugin_instance;
490         char buffer[32];
491         gauge_t v = NAN;
492         _Bool discharging = 0;
493         int status;
494
495         /* Ignore non-battery directories, such as AC power. */
496         status = sysfs_file_to_buffer (dir, power_supply, "type", buffer, sizeof (buffer));
497         if (status != 0)
498                 return (0);
499         if (strcasecmp ("Battery", buffer) != 0)
500                 return (0);
501
502         (void) sysfs_file_to_buffer (dir, power_supply, "status", buffer, sizeof (buffer));
503         if (strcasecmp ("Discharging", buffer) == 0)
504                 discharging = 1;
505
506         /* FIXME: This is a dirty hack for backwards compatibility: The battery
507          * plugin, for a very long time, has had the plugin_instance
508          * hard-coded to "0". So, to keep backwards compatibility, we'll use
509          * "0" for the first battery we find and the power_supply name for all
510          * following. This should be reverted in a future major version. */
511         plugin_instance = (*battery_index == 0) ? "0" : power_supply;
512         (*battery_index)++;
513
514         read_sysfs_capacity (dir, power_supply, plugin_instance);
515
516         if (sysfs_file_to_gauge (dir, power_supply, "power_now", &v) == 0)
517         {
518                 if (discharging)
519                         v *= -1.0;
520                 battery_submit (plugin_instance, "power", v * SYSFS_FACTOR);
521         }
522         if (sysfs_file_to_gauge (dir, power_supply, "current_now", &v) == 0)
523         {
524                 if (discharging)
525                         v *= -1.0;
526                 battery_submit (plugin_instance, "current", v * SYSFS_FACTOR);
527         }
528
529         if (sysfs_file_to_gauge (dir, power_supply, "voltage_now", &v) == 0)
530                 battery_submit (plugin_instance, "voltage", v * SYSFS_FACTOR);
531
532         return (0);
533 } /* }}} int read_sysfs_callback */
534
535 static int read_sysfs (void) /* {{{ */
536 {
537         int status;
538         int battery_counter = 0;
539
540         if (access (SYSFS_PATH, R_OK) != 0)
541                 return (ENOENT);
542
543         status = walk_directory (SYSFS_PATH, read_sysfs_callback,
544                         /* user_data = */ &battery_counter,
545                         /* include hidden */ 0);
546         return (status);
547 } /* }}} int read_sysfs */
548
549 static int read_acpi_full_capacity (char const *dir, /* {{{ */
550                 char const *power_supply,
551                 gauge_t *ret_capacity_full,
552                 gauge_t *ret_capacity_design)
553
554 {
555         char filename[PATH_MAX];
556         char buffer[1024];
557
558         FILE *fh;
559
560         ssnprintf (filename, sizeof (filename), "%s/%s/info", dir, power_supply);
561         fh = fopen (filename, "r");
562         if (fh == NULL)
563                 return (errno);
564
565         /* last full capacity:      40090 mWh */
566         while (fgets (buffer, sizeof (buffer), fh) != NULL)
567         {
568                 gauge_t *value_ptr;
569                 int fields_num;
570                 char *fields[8];
571                 int index;
572
573                 if (strncmp ("last full capacity:", buffer, strlen ("last full capacity:")) == 0)
574                 {
575                         value_ptr = ret_capacity_full;
576                         index = 3;
577                 }
578                 else if (strncmp ("design capacity:", buffer, strlen ("design capacity:")) == 0)
579                 {
580                         value_ptr = ret_capacity_design;
581                         index = 2;
582                 }
583                 else
584                 {
585                         continue;
586                 }
587
588                 fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
589                 if (fields_num <= index)
590                         continue;
591
592                 strtogauge (fields[index], value_ptr);
593         }
594
595         fclose (fh);
596         return (0);
597 } /* }}} int read_acpi_full_capacity */
598
599 static int read_acpi_callback (char const *dir, /* {{{ */
600                 char const *power_supply,
601                 void *user_data)
602 {
603         int *battery_index = user_data;
604
605         gauge_t power = NAN;
606         gauge_t voltage = NAN;
607         gauge_t capacity_charged = NAN;
608         gauge_t capacity_full = NAN;
609         gauge_t capacity_design = NAN;
610         _Bool charging = 0;
611         _Bool is_current = 0;
612
613         char const *plugin_instance;
614         char filename[PATH_MAX];
615         char buffer[1024];
616
617         FILE *fh;
618
619         ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
620         fh = fopen (filename, "r");
621         if (fh == NULL)
622         {
623                 if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
624                         return (0);
625                 else
626                         return (errno);
627         }
628
629         /*
630          * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
631          * [11:00] <@tokkee> present:                 yes
632          * [11:00] <@tokkee> capacity state:          ok
633          * [11:00] <@tokkee> charging state:          charging
634          * [11:00] <@tokkee> present rate:            1724 mA
635          * [11:00] <@tokkee> remaining capacity:      4136 mAh
636          * [11:00] <@tokkee> present voltage:         12428 mV
637          */
638         while (fgets (buffer, sizeof (buffer), fh) != NULL)
639         {
640                 char *fields[8];
641                 int numfields;
642
643                 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
644                 if (numfields < 3)
645                         continue;
646
647                 if ((strcmp (fields[0], "charging") == 0)
648                                 && (strcmp (fields[1], "state:") == 0))
649                 {
650                         if (strcmp (fields[2], "charging") == 0)
651                                 charging = 1;
652                         else
653                                 charging = 0;
654                         continue;
655                 }
656
657                 /* The unit of "present rate" depends on the battery. Modern
658                  * batteries export power (watts), older batteries (used to)
659                  * export current (amperes). We check the fourth column and try
660                  * to find old batteries this way. */
661                 if ((strcmp (fields[0], "present") == 0)
662                                 && (strcmp (fields[1], "rate:") == 0))
663                 {
664                         strtogauge (fields[2], &power);
665
666                         if ((numfields >= 4) && (strcmp ("mA", fields[3]) == 0))
667                                 is_current = 1;
668                 }
669                 else if ((strcmp (fields[0], "remaining") == 0)
670                                 && (strcmp (fields[1], "capacity:") == 0))
671                         strtogauge (fields[2], &capacity_charged);
672                 else if ((strcmp (fields[0], "present") == 0)
673                                 && (strcmp (fields[1], "voltage:") == 0))
674                         strtogauge (fields[2], &voltage);
675         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
676
677         fclose (fh);
678
679         if (!charging)
680                 power *= -1.0;
681
682         /* FIXME: This is a dirty hack for backwards compatibility: The battery
683          * plugin, for a very long time, has had the plugin_instance
684          * hard-coded to "0". So, to keep backwards compatibility, we'll use
685          * "0" for the first battery we find and the power_supply name for all
686          * following. This should be reverted in a future major version. */
687         plugin_instance = (*battery_index == 0) ? "0" : power_supply;
688         (*battery_index)++;
689
690         read_acpi_full_capacity (dir, power_supply, &capacity_full, &capacity_design);
691
692         submit_capacity (plugin_instance,
693                         capacity_charged * PROC_ACPI_FACTOR,
694                         capacity_full * PROC_ACPI_FACTOR,
695                         capacity_design * PROC_ACPI_FACTOR);
696
697         battery_submit (plugin_instance,
698                         is_current ? "current" : "power",
699                         power * PROC_ACPI_FACTOR);
700         battery_submit (plugin_instance, "voltage", voltage * PROC_ACPI_FACTOR);
701
702         return 0;
703 } /* }}} int read_acpi_callback */
704
705 static int read_acpi (void) /* {{{ */
706 {
707         int status;
708         int battery_counter = 0;
709
710         if (access (PROC_ACPI_PATH, R_OK) != 0)
711                 return (ENOENT);
712
713         status = walk_directory (PROC_ACPI_PATH, read_acpi_callback,
714                         /* user_data = */ &battery_counter,
715                         /* include hidden */ 0);
716         return (status);
717 } /* }}} int read_acpi */
718
719 static int read_pmu (void) /* {{{ */
720 {
721         int i = 0;
722         /* The upper limit here is just a safeguard. If there is a system with
723          * more than 100 batteries, this can easily be increased. */
724         for (; i < 100; i++)
725         {
726                 FILE *fh;
727
728                 char buffer[1024];
729                 char filename[PATH_MAX];
730                 char plugin_instance[DATA_MAX_NAME_LEN];
731
732                 gauge_t current = NAN;
733                 gauge_t voltage = NAN;
734                 gauge_t charge  = NAN;
735
736                 ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
737                 if (access (filename, R_OK) != 0)
738                         break;
739
740                 ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);
741
742                 fh = fopen (filename, "r");
743                 if (fh == NULL)
744                 {
745                         if (errno == ENOENT)
746                                 break;
747                         else if ((errno == EAGAIN) || (errno == EINTR))
748                                 continue;
749                         else
750                                 return (errno);
751                 }
752
753                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
754                 {
755                         char *fields[8];
756                         int numfields;
757
758                         numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
759                         if (numfields < 3)
760                                 continue;
761
762                         if (strcmp ("current", fields[0]) == 0)
763                                 strtogauge (fields[2], &current);
764                         else if (strcmp ("voltage", fields[0]) == 0)
765                                 strtogauge (fields[2], &voltage);
766                         else if (strcmp ("charge", fields[0]) == 0)
767                                 strtogauge (fields[2], &charge);
768                 }
769
770                 fclose (fh);
771                 fh = NULL;
772
773                 battery_submit (plugin_instance, "charge", charge / 1000.0);
774                 battery_submit (plugin_instance, "current", current / 1000.0);
775                 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
776         }
777
778         if (i == 0)
779                 return (ENOENT);
780         return (0);
781 } /* }}} int read_pmu */
782
783 static int battery_read (void) /* {{{ */
784 {
785         int status;
786
787         if (query_statefs)
788                 return battery_read_statefs ();
789
790         DEBUG ("battery plugin: Trying sysfs ...");
791         status = read_sysfs ();
792         if (status == 0)
793                 return (0);
794
795         DEBUG ("battery plugin: Trying acpi ...");
796         status = read_acpi ();
797         if (status == 0)
798                 return (0);
799
800         DEBUG ("battery plugin: Trying pmu ...");
801         status = read_pmu ();
802         if (status == 0)
803                 return (0);
804
805         ERROR ("battery plugin: Add available input methods failed.");
806         return (-1);
807 } /* }}} int battery_read */
808 #endif /* KERNEL_LINUX */
809
810 static int battery_config (oconfig_item_t *ci)
811 {
812         for (int i = 0; i < ci->children_num; i++)
813         {
814                 oconfig_item_t *child = ci->children + i;
815
816                 if (strcasecmp ("ValuesPercentage", child->key) == 0)
817                         cf_util_get_boolean (child, &report_percent);
818                 else if (strcasecmp ("ReportDegraded", child->key) == 0)
819                         cf_util_get_boolean (child, &report_degraded);
820                 else if (strcasecmp ("QueryStateFS", child->key) == 0)
821                         cf_util_get_boolean (child, &query_statefs);
822                 else
823                         WARNING ("battery plugin: Ignoring unknown "
824                                         "configuration option \"%s\".",
825                                         child->key);
826         }
827
828         return (0);
829 } /* }}} int battery_config */
830
831 void module_register (void)
832 {
833         plugin_register_complex_config ("battery", battery_config);
834         plugin_register_read ("battery", battery_read);
835 } /* void module_register */