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