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
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.
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.
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
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>
30 #include "utils_complain.h"
32 #if HAVE_MACH_MACH_TYPES_H
33 # include <mach/mach_types.h>
35 #if HAVE_MACH_MACH_INIT_H
36 # include <mach/mach_init.h>
38 #if HAVE_MACH_MACH_ERROR_H
39 # include <mach/mach_error.h>
41 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
42 # include <CoreFoundation/CoreFoundation.h>
44 #if HAVE_IOKIT_IOKITLIB_H
45 # include <IOKit/IOKitLib.h>
47 #if HAVE_IOKIT_IOTYPES_H
48 # include <IOKit/IOTypes.h>
50 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
51 # include <IOKit/ps/IOPowerSources.h>
53 #if HAVE_IOKIT_PS_IOPSKEYS_H
54 # include <IOKit/ps/IOPSKeys.h>
57 #if !HAVE_IOKIT_IOKITLIB_H && !HAVE_IOKIT_PS_IOPOWERSOURCES_H && !KERNEL_LINUX
58 # error "No applicable input method."
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 */
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 */
73 static _Bool report_percent = 0;
74 static _Bool report_degraded = 0;
76 static void battery_submit2 (char const *plugin_instance, /* {{{ */
77 char const *type, char const *type_instance, gauge_t value)
80 value_list_t vl = VALUE_LIST_INIT;
82 values[0].gauge = value;
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));
93 plugin_dispatch_values (&vl);
94 } /* }}} void battery_submit2 */
96 static void battery_submit (char const *plugin_instance, /* {{{ */
97 char const *type, gauge_t value)
99 battery_submit2 (plugin_instance, type, NULL, value);
100 } /* }}} void battery_submit */
102 static void submit_capacity (char const *plugin_instance, /* {{{ */
103 gauge_t capacity_charged,
104 gauge_t capacity_full,
105 gauge_t capacity_design)
107 if (report_percent && (capacity_charged > capacity_full))
109 if (report_degraded && (capacity_full > capacity_design))
114 gauge_t capacity_max;
117 capacity_max = capacity_design;
119 capacity_max = capacity_full;
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);
127 battery_submit2 (plugin_instance, "percent", "degraded",
128 100.0 * (capacity_design - capacity_full) / capacity_max);
130 else if (report_degraded) /* && !report_percent */
132 battery_submit2 (plugin_instance, "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));
139 else /* !report_percent && !report_degraded */
141 battery_submit (plugin_instance, "capacity", capacity_charged);
143 } /* }}} void submit_capacity */
145 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
146 static double dict_get_double (CFDictionaryRef dict, const char *key_string) /* {{{ */
153 key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
154 kCFStringEncodingASCII);
157 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
161 if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
163 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
169 if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
171 if (CFNumberIsFloatType (val_obj))
173 CFNumberGetValue (val_obj,
179 CFNumberGetValue (val_obj,
180 kCFNumberLongLongType,
182 val_double = val_int;
187 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
192 } /* }}} double dict_get_double */
194 # if HAVE_IOKIT_PS_IOPOWERSOURCES_H
195 static void get_via_io_power_sources (double *ret_charge, /* {{{ */
202 CFDictionaryRef ps_dict;
208 ps_raw = IOPSCopyPowerSourcesInfo ();
209 ps_array = IOPSCopyPowerSourcesList (ps_raw);
210 ps_array_len = CFArrayGetCount (ps_array);
212 DEBUG ("ps_array_len == %i", ps_array_len);
214 for (i = 0; i < ps_array_len; i++)
216 ps_obj = CFArrayGetValueAtIndex (ps_array, i);
217 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
221 DEBUG ("IOPSGetPowerSourceDescription failed.");
225 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
227 DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
231 /* FIXME: Check if this is really an internal battery */
233 if (isnan (*ret_charge))
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;
244 if (isnan (*ret_current))
246 temp_double = dict_get_double (ps_dict,
248 if (!isnan (temp_double))
249 *ret_current = temp_double / 1000.0;
252 if (isnan (*ret_voltage))
254 temp_double = dict_get_double (ps_dict,
256 if (!isnan (temp_double))
257 *ret_voltage = temp_double / 1000.0;
263 } /* }}} void get_via_io_power_sources */
264 # endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
266 # if HAVE_IOKIT_IOKITLIB_H
267 static void get_via_generic_iokit (double *ret_capacity_full, /* {{{ */
268 double *ret_capacity_design,
272 kern_return_t status;
273 io_iterator_t iterator;
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;
284 status = IOServiceGetMatchingServices (kIOMasterPortDefault,
285 IOServiceNameMatching ("battery"),
287 if (status != kIOReturnSuccess)
289 DEBUG ("IOServiceGetMatchingServices failed.");
293 while ((io_obj = IOIteratorNext (iterator)))
295 status = IORegistryEntryCreateCFProperties (io_obj,
296 (CFMutableDictionaryRef *) &bat_root_dict,
299 if (status != kIOReturnSuccess)
301 DEBUG ("IORegistryEntryCreateCFProperties failed.");
305 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
306 CFSTR ("IOBatteryInfo"));
307 if (bat_info_arry == NULL)
309 CFRelease (bat_root_dict);
312 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
314 for (bat_info_arry_pos = 0;
315 bat_info_arry_pos < bat_info_arry_len;
318 bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
320 if (isnan (*ret_capacity_full))
322 temp_double = dict_get_double (bat_info_dict, "Capacity");
323 *ret_capacity_full = temp_double / 1000.0;
326 if (isnan (*ret_capacity_design))
328 temp_double = dict_get_double (bat_info_dict, "AbsoluteMaxCapacity");
329 *ret_capacity_design = temp_double / 1000.0;
332 if (isnan (*ret_current))
334 temp_double = dict_get_double (bat_info_dict, "Current");
335 *ret_current = temp_double / 1000.0;
338 if (isnan (*ret_voltage))
340 temp_double = dict_get_double (bat_info_dict, "Voltage");
341 *ret_voltage = temp_double / 1000.0;
345 CFRelease (bat_root_dict);
348 IOObjectRelease (iterator);
349 } /* }}} void get_via_generic_iokit */
350 # endif /* HAVE_IOKIT_IOKITLIB_H */
352 static int battery_read (void) /* {{{ */
354 gauge_t current = NAN; /* Current in A */
355 gauge_t voltage = NAN; /* Voltage in V */
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 */
365 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
366 get_via_io_power_sources (&charge_rel, ¤t, &voltage);
368 #if HAVE_IOKIT_IOKITLIB_H
369 get_via_generic_iokit (&capacity_full, &capacity_design, ¤t, &voltage);
372 capacity_charged = charge_rel * capacity_full / 100.0;
373 submit_capacity ("0", capacity_charged, capacity_full, capacity_design);
375 if (!isnan (current))
376 battery_submit ("0", "current", current);
377 if (!isnan (voltage))
378 battery_submit ("0", "voltage", voltage);
381 } /* }}} int battery_read */
382 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
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)
394 char filename[PATH_MAX];
396 ssnprintf (filename, sizeof (filename), "%s/%s/%s",
397 dir, power_supply, basename);
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)
404 fp = fopen (filename, "r");
408 if (status != ENOENT)
411 WARNING ("battery plugin: fopen (%s) failed: %s", filename,
412 sstrerror (status, errbuf, sizeof (errbuf)));
417 if (fgets (buffer, buffer_size, fp) == NULL)
420 if (status != ENODEV)
423 WARNING ("battery plugin: fgets (%s) failed: %s", filename,
424 sstrerror (status, errbuf, sizeof (errbuf)));
430 strstripnewline (buffer);
434 } /* }}} int sysfs_file_to_buffer */
436 /* Reads a file which contains only a number (and optionally a trailing
437 * newline) and parses that number. */
438 static int sysfs_file_to_gauge(char const *dir, /* {{{ */
439 char const *power_supply,
440 char const *basename, gauge_t *ret_value)
443 char buffer[32] = "";
445 status = sysfs_file_to_buffer (dir, power_supply, basename, buffer, sizeof (buffer));
449 return (strtogauge (buffer, ret_value));
450 } /* }}} sysfs_file_to_gauge */
452 static int read_sysfs_capacity (char const *dir, /* {{{ */
453 char const *power_supply,
454 char const *plugin_instance)
456 gauge_t capacity_charged = NAN;
457 gauge_t capacity_full = NAN;
458 gauge_t capacity_design = NAN;
461 status = sysfs_file_to_gauge (dir, power_supply, "energy_now", &capacity_charged);
465 status = sysfs_file_to_gauge (dir, power_supply, "energy_full", &capacity_full);
469 status = sysfs_file_to_gauge (dir, power_supply, "energy_full_design", &capacity_design);
473 submit_capacity (plugin_instance,
474 capacity_charged * SYSFS_FACTOR,
475 capacity_full * SYSFS_FACTOR,
476 capacity_design * SYSFS_FACTOR);
478 } /* }}} int read_sysfs_capacity */
480 static int read_sysfs_callback (char const *dir, /* {{{ */
481 char const *power_supply,
484 int *battery_index = user_data;
486 char const *plugin_instance;
489 _Bool discharging = 0;
492 /* Ignore non-battery directories, such as AC power. */
493 status = sysfs_file_to_buffer (dir, power_supply, "type", buffer, sizeof (buffer));
496 if (strcasecmp ("Battery", buffer) != 0)
499 (void) sysfs_file_to_buffer (dir, power_supply, "status", buffer, sizeof (buffer));
500 if (strcasecmp ("Discharging", buffer) == 0)
503 /* FIXME: This is a dirty hack for backwards compatibility: The battery
504 * plugin, for a very long time, has had the plugin_instance
505 * hard-coded to "0". So, to keep backwards compatibility, we'll use
506 * "0" for the first battery we find and the power_supply name for all
507 * following. This should be reverted in a future major version. */
508 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
511 read_sysfs_capacity (dir, power_supply, plugin_instance);
513 if (sysfs_file_to_gauge (dir, power_supply, "power_now", &v) == 0)
517 battery_submit (plugin_instance, "power", v * SYSFS_FACTOR);
519 if (sysfs_file_to_gauge (dir, power_supply, "current_now", &v) == 0)
523 battery_submit (plugin_instance, "current", v * SYSFS_FACTOR);
526 if (sysfs_file_to_gauge (dir, power_supply, "voltage_now", &v) == 0)
527 battery_submit (plugin_instance, "voltage", v * SYSFS_FACTOR);
530 } /* }}} int read_sysfs_callback */
532 static int read_sysfs (void) /* {{{ */
535 int battery_counter = 0;
537 if (access (SYSFS_PATH, R_OK) != 0)
540 status = walk_directory (SYSFS_PATH, read_sysfs_callback,
541 /* user_data = */ &battery_counter,
542 /* include hidden */ 0);
544 } /* }}} int read_sysfs */
546 static int read_acpi_full_capacity (char const *dir, /* {{{ */
547 char const *power_supply,
548 gauge_t *ret_capacity_full,
549 gauge_t *ret_capacity_design)
552 char filename[PATH_MAX];
557 ssnprintf (filename, sizeof (filename), "%s/%s/info", dir, power_supply);
558 fh = fopen (filename, "r");
562 /* last full capacity: 40090 mWh */
563 while (fgets (buffer, sizeof (buffer), fh) != NULL)
570 if (strncmp ("last full capacity:", buffer, strlen ("last full capacity:")) == 0)
572 value_ptr = ret_capacity_full;
575 else if (strncmp ("design capacity:", buffer, strlen ("design capacity:")) == 0)
577 value_ptr = ret_capacity_design;
585 fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
586 if (fields_num <= index)
589 strtogauge (fields[index], value_ptr);
594 } /* }}} int read_acpi_full_capacity */
596 static int read_acpi_callback (char const *dir, /* {{{ */
597 char const *power_supply,
600 int *battery_index = user_data;
603 gauge_t voltage = NAN;
604 gauge_t capacity_charged = NAN;
605 gauge_t capacity_full = NAN;
606 gauge_t capacity_design = NAN;
608 _Bool is_current = 0;
610 char const *plugin_instance;
611 char filename[PATH_MAX];
616 ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
617 fh = fopen (filename, "r");
620 if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
627 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
628 * [11:00] <@tokkee> present: yes
629 * [11:00] <@tokkee> capacity state: ok
630 * [11:00] <@tokkee> charging state: charging
631 * [11:00] <@tokkee> present rate: 1724 mA
632 * [11:00] <@tokkee> remaining capacity: 4136 mAh
633 * [11:00] <@tokkee> present voltage: 12428 mV
635 while (fgets (buffer, sizeof (buffer), fh) != NULL)
640 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
644 if ((strcmp (fields[0], "charging") == 0)
645 && (strcmp (fields[1], "state:") == 0))
647 if (strcmp (fields[2], "charging") == 0)
654 /* The unit of "present rate" depends on the battery. Modern
655 * batteries export power (watts), older batteries (used to)
656 * export current (amperes). We check the fourth column and try
657 * to find old batteries this way. */
658 if ((strcmp (fields[0], "present") == 0)
659 && (strcmp (fields[1], "rate:") == 0))
661 strtogauge (fields[2], &power);
663 if ((numfields >= 4) && (strcmp ("mA", fields[3]) == 0))
666 else if ((strcmp (fields[0], "remaining") == 0)
667 && (strcmp (fields[1], "capacity:") == 0))
668 strtogauge (fields[2], &capacity_charged);
669 else if ((strcmp (fields[0], "present") == 0)
670 && (strcmp (fields[1], "voltage:") == 0))
671 strtogauge (fields[2], &voltage);
672 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
679 /* FIXME: This is a dirty hack for backwards compatibility: The battery
680 * plugin, for a very long time, has had the plugin_instance
681 * hard-coded to "0". So, to keep backwards compatibility, we'll use
682 * "0" for the first battery we find and the power_supply name for all
683 * following. This should be reverted in a future major version. */
684 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
687 read_acpi_full_capacity (dir, power_supply, &capacity_full, &capacity_design);
689 submit_capacity (plugin_instance,
690 capacity_charged * PROC_ACPI_FACTOR,
691 capacity_full * PROC_ACPI_FACTOR,
692 capacity_design * PROC_ACPI_FACTOR);
694 battery_submit (plugin_instance,
695 is_current ? "current" : "power",
696 power * PROC_ACPI_FACTOR);
697 battery_submit (plugin_instance, "voltage", voltage * PROC_ACPI_FACTOR);
700 } /* }}} int read_acpi_callback */
702 static int read_acpi (void) /* {{{ */
705 int battery_counter = 0;
707 if (access (PROC_ACPI_PATH, R_OK) != 0)
710 status = walk_directory (PROC_ACPI_PATH, read_acpi_callback,
711 /* user_data = */ &battery_counter,
712 /* include hidden */ 0);
714 } /* }}} int read_acpi */
716 static int read_pmu (void) /* {{{ */
720 /* The upper limit here is just a safeguard. If there is a system with
721 * more than 100 batteries, this can easily be increased. */
722 for (i = 0; i < 100; i++)
727 char filename[PATH_MAX];
728 char plugin_instance[DATA_MAX_NAME_LEN];
730 gauge_t current = NAN;
731 gauge_t voltage = NAN;
732 gauge_t charge = NAN;
734 ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
735 if (access (filename, R_OK) != 0)
738 ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);
740 fh = fopen (filename, "r");
745 else if ((errno == EAGAIN) || (errno == EINTR))
751 while (fgets (buffer, sizeof (buffer), fh) != NULL)
756 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
760 if (strcmp ("current", fields[0]) == 0)
761 strtogauge (fields[2], ¤t);
762 else if (strcmp ("voltage", fields[0]) == 0)
763 strtogauge (fields[2], &voltage);
764 else if (strcmp ("charge", fields[0]) == 0)
765 strtogauge (fields[2], &charge);
771 battery_submit (plugin_instance, "charge", charge / 1000.0);
772 battery_submit (plugin_instance, "current", current / 1000.0);
773 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
779 } /* }}} int read_pmu */
781 static int battery_read (void) /* {{{ */
785 DEBUG ("battery plugin: Trying sysfs ...");
786 status = read_sysfs ();
790 DEBUG ("battery plugin: Trying acpi ...");
791 status = read_acpi ();
795 DEBUG ("battery plugin: Trying pmu ...");
796 status = read_pmu ();
800 ERROR ("battery plugin: Add available input methods failed.");
802 } /* }}} int battery_read */
803 #endif /* KERNEL_LINUX */
805 static int battery_config (oconfig_item_t *ci)
809 for (i = 0; i < ci->children_num; i++)
811 oconfig_item_t *child = ci->children + i;
813 if (strcasecmp ("ValuesPercentage", child->key) == 0)
814 cf_util_get_boolean (child, &report_percent);
815 else if (strcasecmp ("ReportDegraded", child->key) == 0)
816 cf_util_get_boolean (child, &report_degraded);
818 WARNING ("battery plugin: Ignoring unknown "
819 "configuration option \"%s\".",
824 } /* }}} int battery_config */
826 void module_register (void)
828 plugin_register_complex_config ("battery", battery_config);
829 plugin_register_read ("battery", battery_read);
830 } /* void module_register */