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