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, 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 = NAN; /* 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);
379 } /* }}} int battery_read */
380 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
383 /* Reads a file which contains only a number (and optionally a trailing
384 * newline) and parses that number. */
385 static int sysfs_file_to_buffer(char const *dir, /* {{{ */
386 char const *power_supply,
387 char const *basename,
388 char *buffer, size_t buffer_size)
392 char filename[PATH_MAX];
394 ssnprintf (filename, sizeof (filename), "%s/%s/%s",
395 dir, power_supply, basename);
397 /* No file isn't the end of the world -- not every system will be
398 * reporting the same set of statistics */
399 if (access (filename, R_OK) != 0)
402 fp = fopen (filename, "r");
406 if (status != ENOENT)
409 WARNING ("battery plugin: fopen (%s) failed: %s", filename,
410 sstrerror (status, errbuf, sizeof (errbuf)));
415 if (fgets (buffer, buffer_size, fp) == NULL)
419 WARNING ("battery plugin: fgets failed: %s",
420 sstrerror (status, errbuf, sizeof (errbuf)));
425 strstripnewline (buffer);
429 } /* }}} int sysfs_file_to_buffer */
431 /* Reads a file which contains only a number (and optionally a trailing
432 * newline) and parses that number. */
433 static int sysfs_file_to_gauge(char const *dir, /* {{{ */
434 char const *power_supply,
435 char const *basename, gauge_t *ret_value)
438 char buffer[32] = "";
440 status = sysfs_file_to_buffer (dir, power_supply, basename, buffer, sizeof (buffer));
444 return (strtogauge (buffer, ret_value));
445 } /* }}} sysfs_file_to_gauge */
447 static int read_sysfs_capacity (char const *dir, /* {{{ */
448 char const *power_supply,
449 char const *plugin_instance)
451 gauge_t capacity_charged = NAN;
452 gauge_t capacity_full = NAN;
453 gauge_t capacity_design = NAN;
456 status = sysfs_file_to_gauge (dir, power_supply, "energy_now", &capacity_charged);
460 status = sysfs_file_to_gauge (dir, power_supply, "energy_full", &capacity_full);
464 status = sysfs_file_to_gauge (dir, power_supply, "energy_full_design", &capacity_design);
468 submit_capacity (plugin_instance,
469 capacity_charged * SYSFS_FACTOR,
470 capacity_full * SYSFS_FACTOR,
471 capacity_design * SYSFS_FACTOR);
473 } /* }}} int read_sysfs_capacity */
475 static int read_sysfs_callback (char const *dir, /* {{{ */
476 char const *power_supply,
479 int *battery_index = user_data;
481 char const *plugin_instance;
484 _Bool discharging = 0;
487 /* Ignore non-battery directories, such as AC power. */
488 status = sysfs_file_to_buffer (dir, power_supply, "type", buffer, sizeof (buffer));
491 if (strcasecmp ("Battery", buffer) != 0)
494 (void) sysfs_file_to_buffer (dir, power_supply, "status", buffer, sizeof (buffer));
495 if (strcasecmp ("Discharging", buffer) == 0)
498 /* FIXME: This is a dirty hack for backwards compatibility: The battery
499 * plugin, for a very long time, has had the plugin_instance
500 * hard-coded to "0". So, to keep backwards compatibility, we'll use
501 * "0" for the first battery we find and the power_supply name for all
502 * following. This should be reverted in a future major version. */
503 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
506 read_sysfs_capacity (dir, power_supply, plugin_instance);
508 if (sysfs_file_to_gauge (dir, power_supply, "power_now", &v) == 0)
512 battery_submit (plugin_instance, "power", v * SYSFS_FACTOR);
515 if (sysfs_file_to_gauge (dir, power_supply, "voltage_now", &v) == 0)
516 battery_submit (plugin_instance, "voltage", v * SYSFS_FACTOR);
518 if (sysfs_file_to_gauge (dir, power_supply, "voltage_min_design", &v) == 0)
519 battery_submit (plugin_instance, "voltage", v * SYSFS_FACTOR);
523 } /* }}} int read_sysfs_callback */
525 static int read_sysfs (void) /* {{{ */
528 int battery_counter = 0;
530 if (access (SYSFS_PATH, R_OK) != 0)
533 status = walk_directory (SYSFS_PATH, read_sysfs_callback,
534 /* user_data = */ &battery_counter,
535 /* include hidden */ 0);
537 } /* }}} int read_sysfs */
539 static int read_acpi_full_capacity (char const *dir, /* {{{ */
540 char const *power_supply,
541 gauge_t *ret_capacity_full,
542 gauge_t *ret_capacity_design)
545 char filename[PATH_MAX];
550 ssnprintf (filename, sizeof (filename), "%s/%s/info", dir, power_supply);
551 fh = fopen (filename, "r");
552 if ((fh = fopen (filename, "r")) == NULL)
555 /* last full capacity: 40090 mWh */
556 while (fgets (buffer, sizeof (buffer), fh) != NULL)
563 if (strncmp ("last full capacity:", buffer, strlen ("last full capacity:")) == 0)
565 value_ptr = ret_capacity_full;
568 else if (strncmp ("design capacity:", buffer, strlen ("design capacity:")) == 0)
570 value_ptr = ret_capacity_design;
578 fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
579 if (fields_num <= index)
582 strtogauge (fields[index], value_ptr);
587 } /* }}} int read_acpi_full_capacity */
589 static int read_acpi_callback (char const *dir, /* {{{ */
590 char const *power_supply,
593 int *battery_index = user_data;
596 gauge_t voltage = NAN;
597 gauge_t capacity_charged = NAN;
598 gauge_t capacity_full = NAN;
599 gauge_t capacity_design = NAN;
601 _Bool is_current = 0;
603 char const *plugin_instance;
604 char filename[PATH_MAX];
609 ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
610 fh = fopen (filename, "r");
611 if ((fh = fopen (filename, "r")) == NULL)
613 if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
620 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
621 * [11:00] <@tokkee> present: yes
622 * [11:00] <@tokkee> capacity state: ok
623 * [11:00] <@tokkee> charging state: charging
624 * [11:00] <@tokkee> present rate: 1724 mA
625 * [11:00] <@tokkee> remaining capacity: 4136 mAh
626 * [11:00] <@tokkee> present voltage: 12428 mV
628 while (fgets (buffer, sizeof (buffer), fh) != NULL)
633 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
637 if ((strcmp (fields[0], "charging") == 0)
638 && (strcmp (fields[1], "state:") == 0))
640 if (strcmp (fields[2], "charging") == 0)
647 /* The unit of "present rate" depends on the battery. Modern
648 * batteries export power (watts), older batteries (used to)
649 * export current (amperes). We check the fourth column and try
650 * to find old batteries this way. */
651 if ((strcmp (fields[0], "present") == 0)
652 && (strcmp (fields[1], "rate:") == 0))
654 strtogauge (fields[2], &power);
656 if ((numfields >= 4) && (strcmp ("mA", fields[3]) == 0))
659 else if ((strcmp (fields[0], "remaining") == 0)
660 && (strcmp (fields[1], "capacity:") == 0))
661 strtogauge (fields[2], &capacity_charged);
662 else if ((strcmp (fields[0], "present") == 0)
663 && (strcmp (fields[1], "voltage:") == 0))
664 strtogauge (fields[2], &voltage);
665 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
672 /* FIXME: This is a dirty hack for backwards compatibility: The battery
673 * plugin, for a very long time, has had the plugin_instance
674 * hard-coded to "0". So, to keep backwards compatibility, we'll use
675 * "0" for the first battery we find and the power_supply name for all
676 * following. This should be reverted in a future major version. */
677 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
680 read_acpi_full_capacity (dir, power_supply, &capacity_full, &capacity_design);
682 submit_capacity (plugin_instance,
683 capacity_charged * PROC_ACPI_FACTOR,
684 capacity_full * PROC_ACPI_FACTOR,
685 capacity_design * PROC_ACPI_FACTOR);
687 battery_submit (plugin_instance,
688 is_current ? "current" : "power",
689 power * PROC_ACPI_FACTOR);
690 battery_submit (plugin_instance, "voltage", voltage * PROC_ACPI_FACTOR);
693 } /* }}} int read_acpi_callback */
695 static int read_acpi (void) /* {{{ */
698 int battery_counter = 0;
700 if (access (PROC_ACPI_PATH, R_OK) != 0)
703 status = walk_directory (PROC_ACPI_PATH, read_acpi_callback,
704 /* user_data = */ &battery_counter,
705 /* include hidden */ 0);
707 } /* }}} int read_acpi */
709 static int read_pmu (void) /* {{{ */
713 /* The upper limit here is just a safeguard. If there is a system with
714 * more than 100 batteries, this can easily be increased. */
715 for (i = 0; i < 100; i++)
720 char filename[PATH_MAX];
721 char plugin_instance[DATA_MAX_NAME_LEN];
723 gauge_t current = NAN;
724 gauge_t voltage = NAN;
725 gauge_t charge = NAN;
727 ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
728 if (access (filename, R_OK) != 0)
731 ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);
733 fh = fopen (filename, "r");
738 else if ((errno == EAGAIN) || (errno == EINTR))
744 while (fgets (buffer, sizeof (buffer), fh) != NULL)
749 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
753 if (strcmp ("current", fields[0]) == 0)
754 strtogauge (fields[2], ¤t);
755 else if (strcmp ("voltage", fields[0]) == 0)
756 strtogauge (fields[2], &voltage);
757 else if (strcmp ("charge", fields[0]) == 0)
758 strtogauge (fields[2], &charge);
764 battery_submit (plugin_instance, "charge", charge / 1000.0);
765 battery_submit (plugin_instance, "current", current / 1000.0);
766 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
772 } /* }}} int read_pmu */
774 static int battery_read (void) /* {{{ */
778 DEBUG ("battery plugin: Trying sysfs ...");
779 status = read_sysfs ();
783 DEBUG ("battery plugin: Trying acpi ...");
784 status = read_acpi ();
788 DEBUG ("battery plugin: Trying pmu ...");
789 status = read_pmu ();
793 ERROR ("battery plugin: Add available input methods failed.");
795 } /* }}} int battery_read */
796 #endif /* KERNEL_LINUX */
798 static int battery_config (oconfig_item_t *ci)
802 for (i = 0; i < ci->children_num; i++)
804 oconfig_item_t *child = ci->children + i;
806 if (strcasecmp ("ValuesPercentage", child->key) == 0)
807 cf_util_get_boolean (child, &report_percent);
808 else if (strcasecmp ("ReportDegraded", child->key) == 0)
809 cf_util_get_boolean (child, &report_degraded);
811 WARNING ("battery plugin: Ignoring unknown "
812 "configuration option \"%s\".",
817 } /* }}} int battery_config */
819 void module_register (void)
821 plugin_register_complex_config ("battery", battery_config);
822 plugin_register_read ("battery", battery_read);
823 } /* void module_register */