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 #define INVALID_VALUE 47841.29
63 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
64 /* No global variables */
65 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
68 # define PROC_PMU_PATH_FORMAT "/proc/pmu/battery_%i"
69 # define PROC_ACPI_PATH "/proc/acpi/battery"
70 # define SYSFS_PATH "/sys/class/power_supply"
71 #endif /* KERNEL_LINUX */
73 static _Bool report_percent = 0;
75 static void battery_submit2 (char const *plugin_instance, /* {{{ */
76 char const *type, char const *type_instance, gauge_t value)
79 value_list_t vl = VALUE_LIST_INIT;
81 values[0].gauge = value;
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));
92 plugin_dispatch_values (&vl);
93 } /* }}} void battery_submit2 */
95 static void battery_submit (char const *plugin_instance, /* {{{ */
96 char const *type, gauge_t value)
98 battery_submit2 (plugin_instance, type, NULL, value);
99 } /* }}} void battery_submit */
101 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
102 static double dict_get_double (CFDictionaryRef dict, char *key_string) /* {{{ */
109 key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
110 kCFStringEncodingASCII);
113 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
114 return (INVALID_VALUE);
117 if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
119 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
121 return (INVALID_VALUE);
125 if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
127 if (CFNumberIsFloatType (val_obj))
129 CFNumberGetValue (val_obj,
135 CFNumberGetValue (val_obj,
136 kCFNumberLongLongType,
138 val_double = val_int;
143 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
144 return (INVALID_VALUE);
148 } /* }}} double dict_get_double */
150 # if HAVE_IOKIT_PS_IOPOWERSOURCES_H
151 static void get_via_io_power_sources (double *ret_charge, /* {{{ */
158 CFDictionaryRef ps_dict;
164 ps_raw = IOPSCopyPowerSourcesInfo ();
165 ps_array = IOPSCopyPowerSourcesList (ps_raw);
166 ps_array_len = CFArrayGetCount (ps_array);
168 DEBUG ("ps_array_len == %i", ps_array_len);
170 for (i = 0; i < ps_array_len; i++)
172 ps_obj = CFArrayGetValueAtIndex (ps_array, i);
173 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
177 DEBUG ("IOPSGetPowerSourceDescription failed.");
181 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
183 DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
187 /* FIXME: Check if this is really an internal battery */
189 if (*ret_charge == INVALID_VALUE)
191 /* This is the charge in percent. */
192 temp_double = dict_get_double (ps_dict,
193 kIOPSCurrentCapacityKey);
194 if ((temp_double != INVALID_VALUE)
195 && (temp_double >= 0.0)
196 && (temp_double <= 100.0))
197 *ret_charge = temp_double;
200 if (*ret_current == INVALID_VALUE)
202 temp_double = dict_get_double (ps_dict,
204 if (temp_double != INVALID_VALUE)
205 *ret_current = temp_double / 1000.0;
208 if (*ret_voltage == INVALID_VALUE)
210 temp_double = dict_get_double (ps_dict,
212 if (temp_double != INVALID_VALUE)
213 *ret_voltage = temp_double / 1000.0;
219 } /* }}} void get_via_io_power_sources */
220 # endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
222 # if HAVE_IOKIT_IOKITLIB_H
223 static void get_via_generic_iokit (double *ret_charge, /* {{{ */
227 kern_return_t status;
228 io_iterator_t iterator;
231 CFDictionaryRef bat_root_dict;
232 CFArrayRef bat_info_arry;
233 CFIndex bat_info_arry_len;
234 CFIndex bat_info_arry_pos;
235 CFDictionaryRef bat_info_dict;
239 status = IOServiceGetMatchingServices (kIOMasterPortDefault,
240 IOServiceNameMatching ("battery"),
242 if (status != kIOReturnSuccess)
244 DEBUG ("IOServiceGetMatchingServices failed.");
248 while ((io_obj = IOIteratorNext (iterator)))
250 status = IORegistryEntryCreateCFProperties (io_obj,
251 (CFMutableDictionaryRef *) &bat_root_dict,
254 if (status != kIOReturnSuccess)
256 DEBUG ("IORegistryEntryCreateCFProperties failed.");
260 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
261 CFSTR ("IOBatteryInfo"));
262 if (bat_info_arry == NULL)
264 CFRelease (bat_root_dict);
267 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
269 for (bat_info_arry_pos = 0;
270 bat_info_arry_pos < bat_info_arry_len;
273 bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
275 /* Design capacity available in "AbsoluteMaxCapacity" */
276 if (*ret_charge == INVALID_VALUE)
278 temp_double = dict_get_double (bat_info_dict,
280 if (temp_double != INVALID_VALUE)
281 *ret_charge = temp_double / 1000.0;
284 if (*ret_current == INVALID_VALUE)
286 temp_double = dict_get_double (bat_info_dict,
288 if (temp_double != INVALID_VALUE)
289 *ret_current = temp_double / 1000.0;
292 if (*ret_voltage == INVALID_VALUE)
294 temp_double = dict_get_double (bat_info_dict,
296 if (temp_double != INVALID_VALUE)
297 *ret_voltage = temp_double / 1000.0;
301 CFRelease (bat_root_dict);
304 IOObjectRelease (iterator);
305 } /* }}} void get_via_generic_iokit */
306 # endif /* HAVE_IOKIT_IOKITLIB_H */
308 static int battery_read (void) /* {{{ */
310 double current = INVALID_VALUE; /* Current in A */
311 double voltage = INVALID_VALUE; /* Voltage in V */
313 /* We only get the charged capacity as a percentage from
314 * IOPowerSources. IOKit, on the other hand, only reports the full
315 * capacity. We use the two to calculate the current charged capacity. */
316 double charge_rel = INVALID_VALUE; /* Current charge in percent */
317 double charge_abs = INVALID_VALUE; /* Total capacity */
319 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
320 get_via_io_power_sources (&charge_rel, ¤t, &voltage);
322 #if HAVE_IOKIT_IOKITLIB_H
323 get_via_generic_iokit (&charge_abs, ¤t, &voltage);
326 if (charge_rel != INVALID_VALUE)
329 battery_submit2 ("0", "percent", "charged", charge_rel);
330 else if (charge_abs != INVALID_VALUE)
331 battery_submit ("0", "charge", charge_abs * charge_rel / 100.0);
333 if (current != INVALID_VALUE)
334 battery_submit ("0", "current", current);
335 if (voltage != INVALID_VALUE)
336 battery_submit ("0", "voltage", voltage);
337 } /* }}} int battery_read */
338 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
341 /* Reads a file which contains only a number (and optionally a trailing
342 * newline) and parses that number. */
343 static int sysfs_file_to_buffer(char const *dir, /* {{{ */
344 char const *power_supply,
345 char const *basename,
346 char *buffer, size_t buffer_size)
350 char filename[PATH_MAX];
352 ssnprintf (filename, sizeof (filename), "%s/%s/%s",
353 dir, power_supply, basename);
355 /* No file isn't the end of the world -- not every system will be
356 * reporting the same set of statistics */
357 if (access (filename, R_OK) != 0)
360 fp = fopen (filename, "r");
364 if (status != ENOENT)
367 WARNING ("battery plugin: fopen (%s) failed: %s", filename,
368 sstrerror (status, errbuf, sizeof (errbuf)));
373 if (fgets (buffer, buffer_size, fp) == NULL)
377 WARNING ("battery plugin: fgets failed: %s",
378 sstrerror (status, errbuf, sizeof (errbuf)));
383 strstripnewline (buffer);
387 } /* }}} int sysfs_file_to_buffer */
389 /* Reads a file which contains only a number (and optionally a trailing
390 * newline) and parses that number. */
391 static int sysfs_file_to_gauge(char const *dir, /* {{{ */
392 char const *power_supply,
393 char const *basename, gauge_t *ret_value)
396 char buffer[32] = "";
398 status = sysfs_file_to_buffer (dir, power_supply, basename, buffer, sizeof (buffer));
402 return (strtogauge (buffer, ret_value));
403 } /* }}} sysfs_file_to_gauge */
405 static int read_sysfs_callback (char const *dir, /* {{{ */
406 char const *power_supply,
409 int *battery_index = user_data;
411 char const *plugin_instance;
414 _Bool discharging = 0;
417 /* Ignore non-battery directories, such as AC power. */
418 status = sysfs_file_to_buffer (dir, power_supply, "type", buffer, sizeof (buffer));
421 if (strcasecmp ("Battery", buffer) != 0)
424 (void) sysfs_file_to_buffer (dir, power_supply, "status", buffer, sizeof (buffer));
425 if (strcasecmp ("Discharging", buffer) == 0)
428 /* FIXME: This is a dirty hack for backwards compatibility: The battery
429 * plugin, for a very long time, has had the plugin_instance
430 * hard-coded to "0". So, to keep backwards compatibility, we'll use
431 * "0" for the first battery we find and the power_supply name for all
432 * following. This should be reverted in a future major version. */
433 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
441 if ((sysfs_file_to_gauge (dir, power_supply, "energy_now", &now) == 0)
442 && (sysfs_file_to_gauge (dir, power_supply, "energy_full", &max) == 0))
444 v = 100.0 * now / max;
445 battery_submit2 (plugin_instance, "percent", "charged", v);
448 else if (sysfs_file_to_gauge (dir, power_supply, "energy_now", &v) == 0)
449 battery_submit (plugin_instance, "charge", v / 1000000.0);
451 if (sysfs_file_to_gauge (dir, power_supply, "power_now", &v) == 0)
455 battery_submit (plugin_instance, "power", v / 1000000.0);
458 if (sysfs_file_to_gauge (dir, power_supply, "voltage_now", &v) == 0)
459 battery_submit (plugin_instance, "voltage", v / 1000000.0);
461 if (sysfs_file_to_gauge (dir, power_supply, "energy_full_design", &v) == 0)
462 battery_submit (plugin_instance, "charge", v / 1000000.0);
463 if (sysfs_file_to_gauge (dir, power_supply, "energy_full", &v) == 0)
464 battery_submit (plugin_instance, "charge", v / 1000000.0);
465 if (sysfs_file_to_gauge (dir, power_supply, "voltage_min_design", &v) == 0)
466 battery_submit (plugin_instance, "voltage", v / 1000000.0);
470 } /* }}} int read_sysfs_callback */
472 static int read_sysfs (void) /* {{{ */
475 int battery_counter = 0;
477 if (access (SYSFS_PATH, R_OK) != 0)
480 status = walk_directory (SYSFS_PATH, read_sysfs_callback,
481 /* user_data = */ &battery_counter,
482 /* include hidden */ 0);
484 } /* }}} int read_sysfs */
486 static int read_acpi_full_capacity (char const *dir, /* {{{ */
487 char const *power_supply,
488 gauge_t *ret_capacity)
490 char filename[PATH_MAX];
495 ssnprintf (filename, sizeof (filename), "%s/%s/info", dir, power_supply);
496 fh = fopen (filename, "r");
497 if ((fh = fopen (filename, "r")) == NULL)
500 /* last full capacity: 40090 mWh */
501 while (fgets (buffer, sizeof (buffer), fh) != NULL)
507 if (strncmp ("last full capacity:", buffer, strlen ("last full capacity:")) != 0)
510 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
514 status = strtogauge (fields[3], ret_capacity);
521 } /* }}} int read_acpi_full_capacity */
523 static int read_acpi_callback (char const *dir, /* {{{ */
524 char const *power_supply,
527 int *battery_index = user_data;
530 gauge_t voltage = NAN;
531 gauge_t charge = NAN;
533 _Bool is_current = 0;
535 char const *plugin_instance;
536 char filename[PATH_MAX];
541 ssnprintf (filename, sizeof (filename), "%s/%s/state", dir, power_supply);
542 fh = fopen (filename, "r");
543 if ((fh = fopen (filename, "r")) == NULL)
545 if ((errno == EAGAIN) || (errno == EINTR) || (errno == ENOENT))
552 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
553 * [11:00] <@tokkee> present: yes
554 * [11:00] <@tokkee> capacity state: ok
555 * [11:00] <@tokkee> charging state: charging
556 * [11:00] <@tokkee> present rate: 1724 mA
557 * [11:00] <@tokkee> remaining capacity: 4136 mAh
558 * [11:00] <@tokkee> present voltage: 12428 mV
560 while (fgets (buffer, sizeof (buffer), fh) != NULL)
565 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
569 if ((strcmp (fields[0], "charging") == 0)
570 && (strcmp (fields[1], "state:") == 0))
572 if (strcmp (fields[2], "charging") == 0)
579 /* The unit of "present rate" depends on the battery. Modern
580 * batteries export power (watts), older batteries (used to)
581 * export current (amperes). We check the fourth column and try
582 * to find old batteries this way. */
583 if ((strcmp (fields[0], "present") == 0)
584 && (strcmp (fields[1], "rate:") == 0))
586 strtogauge (fields[2], &power);
588 if ((numfields >= 4) && (strcmp ("mA", fields[3]) == 0))
591 else if ((strcmp (fields[0], "remaining") == 0)
592 && (strcmp (fields[1], "capacity:") == 0))
593 strtogauge (fields[2], &charge);
594 else if ((strcmp (fields[0], "present") == 0)
595 && (strcmp (fields[1], "voltage:") == 0))
596 strtogauge (fields[2], &voltage);
597 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
604 /* FIXME: This is a dirty hack for backwards compatibility: The battery
605 * plugin, for a very long time, has had the plugin_instance
606 * hard-coded to "0". So, to keep backwards compatibility, we'll use
607 * "0" for the first battery we find and the power_supply name for all
608 * following. This should be reverted in a future major version. */
609 plugin_instance = (*battery_index == 0) ? "0" : power_supply;
614 gauge_t full_capacity;
617 status = read_acpi_full_capacity (dir, power_supply, &full_capacity);
619 battery_submit2 (plugin_instance, "percent", "charged",
620 100.0 * charge / full_capacity);
624 battery_submit (plugin_instance, "charge", charge / 1000.0);
627 battery_submit (plugin_instance,
628 is_current ? "current" : "power",
630 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
633 } /* }}} int read_acpi_callback */
635 static int read_acpi (void) /* {{{ */
638 int battery_counter = 0;
640 if (access (PROC_ACPI_PATH, R_OK) != 0)
643 status = walk_directory (PROC_ACPI_PATH, read_acpi_callback,
644 /* user_data = */ &battery_counter,
645 /* include hidden */ 0);
647 } /* }}} int read_acpi */
649 static int read_pmu (void) /* {{{ */
653 /* The upper limit here is just a safeguard. If there is a system with
654 * more than 100 batteries, this can easily be increased. */
655 for (i = 0; i < 100; i++)
660 char filename[PATH_MAX];
661 char plugin_instance[DATA_MAX_NAME_LEN];
663 gauge_t current = NAN;
664 gauge_t voltage = NAN;
665 gauge_t charge = NAN;
667 ssnprintf (filename, sizeof (filename), PROC_PMU_PATH_FORMAT, i);
668 if (access (filename, R_OK) != 0)
671 ssnprintf (plugin_instance, sizeof (plugin_instance), "%i", i);
673 fh = fopen (filename, "r");
678 else if ((errno == EAGAIN) || (errno == EINTR))
684 while (fgets (buffer, sizeof (buffer), fh) != NULL)
689 numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
693 if (strcmp ("current", fields[0]) == 0)
694 strtogauge (fields[2], ¤t);
695 else if (strcmp ("voltage", fields[0]) == 0)
696 strtogauge (fields[2], &voltage);
697 else if (strcmp ("charge", fields[0]) == 0)
698 strtogauge (fields[2], &charge);
704 battery_submit (plugin_instance, "charge", charge / 1000.0);
705 battery_submit (plugin_instance, "current", current / 1000.0);
706 battery_submit (plugin_instance, "voltage", voltage / 1000.0);
712 } /* }}} int read_pmu */
714 static int battery_read (void) /* {{{ */
718 DEBUG ("battery plugin: Trying sysfs ...");
719 status = read_sysfs ();
723 DEBUG ("battery plugin: Trying acpi ...");
724 status = read_acpi ();
728 DEBUG ("battery plugin: Trying pmu ...");
729 status = read_pmu ();
733 ERROR ("battery plugin: Add available input methods failed.");
735 } /* }}} int battery_read */
736 #endif /* KERNEL_LINUX */
738 static int battery_config (oconfig_item_t *ci)
742 for (i = 0; i < ci->children_num; i++)
744 oconfig_item_t *child = ci->children + i;
746 if (strcasecmp ("ValuesPercentage", child->key) == 0)
747 cf_util_get_boolean (child, &report_percent);
749 WARNING ("battery plugin: Ignoring unknown "
750 "configuration option \"%s\".",
755 } /* }}} int battery_config */
757 void module_register (void)
759 plugin_register_complex_config ("battery", battery_config);
760 plugin_register_read ("battery", battery_read);
761 } /* void module_register */