1 /**
2 * collectd - src/battery.c
3 * Copyright (C) 2006,2007 Florian octo Forster
4 * Copyright (C) 2008 Michał Mirosław
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; only version 2 of the License is applicable.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 * Authors:
20 * Florian octo Forster <octo at verplant.org>
21 * Michał Mirosław <mirq-linux at rere.qmqm.pl>
22 **/
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
28 #include "utils_complain.h"
30 #if HAVE_MACH_MACH_TYPES_H
31 # include <mach/mach_types.h>
32 #endif
33 #if HAVE_MACH_MACH_INIT_H
34 # include <mach/mach_init.h>
35 #endif
36 #if HAVE_MACH_MACH_ERROR_H
37 # include <mach/mach_error.h>
38 #endif
39 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
40 # include <CoreFoundation/CoreFoundation.h>
41 #endif
42 #if HAVE_IOKIT_IOKITLIB_H
43 # include <IOKit/IOKitLib.h>
44 #endif
45 #if HAVE_IOKIT_IOTYPES_H
46 # include <IOKit/IOTypes.h>
47 #endif
48 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
49 # include <IOKit/ps/IOPowerSources.h>
50 #endif
51 #if HAVE_IOKIT_PS_IOPSKEYS_H
52 # include <IOKit/ps/IOPSKeys.h>
53 #endif
55 #if !HAVE_IOKIT_IOKITLIB_H && !HAVE_IOKIT_PS_IOPOWERSOURCES_H && !KERNEL_LINUX
56 # error "No applicable input method."
57 #endif
59 #define INVALID_VALUE 47841.29
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 */
65 #elif KERNEL_LINUX
66 static int battery_pmu_num = 0;
67 static char *battery_pmu_file = "/proc/pmu/battery_%i";
68 static const char *battery_acpi_dir = "/proc/acpi/battery";
69 #endif /* KERNEL_LINUX */
71 static int battery_init (void)
72 {
73 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
74 /* No init neccessary */
75 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
77 #elif KERNEL_LINUX
78 int len;
79 char filename[128];
81 for (battery_pmu_num = 0; ; battery_pmu_num++)
82 {
83 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
85 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
86 break;
88 if (access (filename, R_OK))
89 break;
90 }
91 #endif /* KERNEL_LINUX */
93 return (0);
94 }
96 static void battery_submit (const char *plugin_instance, const char *type, double value)
97 {
98 value_t values[1];
99 value_list_t vl = VALUE_LIST_INIT;
101 values[0].gauge = value;
103 vl.values = values;
104 vl.values_len = 1;
105 vl.time = time (NULL);
106 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
107 sstrncpy (vl.plugin, "battery", sizeof (vl.plugin));
108 sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
109 sstrncpy (vl.type, type, sizeof (vl.type));
111 plugin_dispatch_values (&vl);
112 } /* void battery_submit */
114 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
115 double dict_get_double (CFDictionaryRef dict, char *key_string)
116 {
117 double val_double;
118 long long val_int;
119 CFNumberRef val_obj;
120 CFStringRef key_obj;
122 key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
123 kCFStringEncodingASCII);
124 if (key_obj == NULL)
125 {
126 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
127 return (INVALID_VALUE);
128 }
130 if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
131 {
132 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
133 CFRelease (key_obj);
134 return (INVALID_VALUE);
135 }
136 CFRelease (key_obj);
138 if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
139 {
140 if (CFNumberIsFloatType (val_obj))
141 {
142 CFNumberGetValue (val_obj,
143 kCFNumberDoubleType,
144 &val_double);
145 }
146 else
147 {
148 CFNumberGetValue (val_obj,
149 kCFNumberLongLongType,
150 &val_int);
151 val_double = val_int;
152 }
153 }
154 else
155 {
156 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
157 return (INVALID_VALUE);
158 }
160 return (val_double);
161 }
162 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H */
164 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
165 static void get_via_io_power_sources (double *ret_charge,
166 double *ret_current,
167 double *ret_voltage)
168 {
169 CFTypeRef ps_raw;
170 CFArrayRef ps_array;
171 int ps_array_len;
172 CFDictionaryRef ps_dict;
173 CFTypeRef ps_obj;
175 double temp_double;
176 int i;
178 ps_raw = IOPSCopyPowerSourcesInfo ();
179 ps_array = IOPSCopyPowerSourcesList (ps_raw);
180 ps_array_len = CFArrayGetCount (ps_array);
182 DEBUG ("ps_array_len == %i", ps_array_len);
184 for (i = 0; i < ps_array_len; i++)
185 {
186 ps_obj = CFArrayGetValueAtIndex (ps_array, i);
187 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
189 if (ps_dict == NULL)
190 {
191 DEBUG ("IOPSGetPowerSourceDescription failed.");
192 continue;
193 }
195 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
196 {
197 DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
198 continue;
199 }
201 /* FIXME: Check if this is really an internal battery */
203 if (*ret_charge == INVALID_VALUE)
204 {
205 /* This is the charge in percent. */
206 temp_double = dict_get_double (ps_dict,
207 kIOPSCurrentCapacityKey);
208 if ((temp_double != INVALID_VALUE)
209 && (temp_double >= 0.0)
210 && (temp_double <= 100.0))
211 *ret_charge = temp_double;
212 }
214 if (*ret_current == INVALID_VALUE)
215 {
216 temp_double = dict_get_double (ps_dict,
217 kIOPSCurrentKey);
218 if (temp_double != INVALID_VALUE)
219 *ret_current = temp_double / 1000.0;
220 }
222 if (*ret_voltage == INVALID_VALUE)
223 {
224 temp_double = dict_get_double (ps_dict,
225 kIOPSVoltageKey);
226 if (temp_double != INVALID_VALUE)
227 *ret_voltage = temp_double / 1000.0;
228 }
229 }
231 CFRelease(ps_array);
232 CFRelease(ps_raw);
233 }
234 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
236 #if HAVE_IOKIT_IOKITLIB_H
237 static void get_via_generic_iokit (double *ret_charge,
238 double *ret_current,
239 double *ret_voltage)
240 {
241 kern_return_t status;
242 io_iterator_t iterator;
243 io_object_t io_obj;
245 CFDictionaryRef bat_root_dict;
246 CFArrayRef bat_info_arry;
247 CFIndex bat_info_arry_len;
248 CFIndex bat_info_arry_pos;
249 CFDictionaryRef bat_info_dict;
251 double temp_double;
253 status = IOServiceGetMatchingServices (kIOMasterPortDefault,
254 IOServiceNameMatching ("battery"),
255 &iterator);
256 if (status != kIOReturnSuccess)
257 {
258 DEBUG ("IOServiceGetMatchingServices failed.");
259 return;
260 }
262 while ((io_obj = IOIteratorNext (iterator)))
263 {
264 status = IORegistryEntryCreateCFProperties (io_obj,
265 (CFMutableDictionaryRef *) &bat_root_dict,
266 kCFAllocatorDefault,
267 kNilOptions);
268 if (status != kIOReturnSuccess)
269 {
270 DEBUG ("IORegistryEntryCreateCFProperties failed.");
271 continue;
272 }
274 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
275 CFSTR ("IOBatteryInfo"));
276 if (bat_info_arry == NULL)
277 {
278 CFRelease (bat_root_dict);
279 continue;
280 }
281 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
283 for (bat_info_arry_pos = 0;
284 bat_info_arry_pos < bat_info_arry_len;
285 bat_info_arry_pos++)
286 {
287 bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
289 if (*ret_charge == INVALID_VALUE)
290 {
291 temp_double = dict_get_double (bat_info_dict,
292 "Capacity");
293 if (temp_double != INVALID_VALUE)
294 *ret_charge = temp_double / 1000.0;
295 }
297 if (*ret_current == INVALID_VALUE)
298 {
299 temp_double = dict_get_double (bat_info_dict,
300 "Current");
301 if (temp_double != INVALID_VALUE)
302 *ret_current = temp_double / 1000.0;
303 }
305 if (*ret_voltage == INVALID_VALUE)
306 {
307 temp_double = dict_get_double (bat_info_dict,
308 "Voltage");
309 if (temp_double != INVALID_VALUE)
310 *ret_voltage = temp_double / 1000.0;
311 }
312 }
314 CFRelease (bat_root_dict);
315 }
317 IOObjectRelease (iterator);
318 }
319 #endif /* HAVE_IOKIT_IOKITLIB_H */
321 #if KERNEL_LINUX
322 static int battery_read_acpi (const char *dir, const char *name,
323 void *user_data)
324 {
325 double current = INVALID_VALUE;
326 double voltage = INVALID_VALUE;
327 double charge = INVALID_VALUE;
328 double *valptr = NULL;
329 int charging = 0;
331 char filename[256];
332 FILE *fh;
334 char buffer[1024];
335 char *fields[8];
336 int numfields;
337 char *endptr;
338 int len;
340 len = ssnprintf (filename, sizeof (filename), "%s/%s/state", battery_acpi_dir, name);
342 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
343 return -1;
345 if ((fh = fopen (filename, "r")) == NULL) {
346 char errbuf[1024];
347 ERROR ("Cannot open `%s': %s", filename,
348 sstrerror (errno, errbuf, sizeof (errbuf)));
349 return -1;
350 }
352 /*
353 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
354 * [11:00] <@tokkee> present: yes
355 * [11:00] <@tokkee> capacity state: ok
356 * [11:00] <@tokkee> charging state: charging
357 * [11:00] <@tokkee> present rate: 1724 mA
358 * [11:00] <@tokkee> remaining capacity: 4136 mAh
359 * [11:00] <@tokkee> present voltage: 12428 mV
360 */
361 while (fgets (buffer, sizeof (buffer), fh) != NULL)
362 {
363 numfields = strsplit (buffer, fields, 8);
365 if (numfields < 3)
366 continue;
368 if ((strcmp (fields[0], "charging") == 0)
369 && (strcmp (fields[1], "state:") == 0))
370 {
371 if (strcmp (fields[2], "charging") == 0)
372 charging = 1;
373 else
374 charging = 0;
375 continue;
376 }
378 if ((strcmp (fields[0], "present") == 0)
379 && (strcmp (fields[1], "rate:") == 0))
380 valptr = ¤t;
381 else if ((strcmp (fields[0], "remaining") == 0)
382 && (strcmp (fields[1], "capacity:") == 0))
383 valptr = &charge;
384 else if ((strcmp (fields[0], "present") == 0)
385 && (strcmp (fields[1], "voltage:") == 0))
386 valptr = &voltage;
387 else
388 continue;
390 endptr = NULL;
391 errno = 0;
392 *valptr = strtod (fields[2], &endptr) / 1000.0;
394 if ((fields[2] == endptr) || (errno != 0))
395 *valptr = INVALID_VALUE;
396 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
398 fclose (fh);
400 if ((current != INVALID_VALUE) && (charging == 0))
401 current *= -1;
403 if (charge != INVALID_VALUE)
404 battery_submit ("0", "charge", charge);
405 if (current != INVALID_VALUE)
406 battery_submit ("0", "current", current);
407 if (voltage != INVALID_VALUE)
408 battery_submit ("0", "voltage", voltage);
410 return 0;
411 }
412 #endif /* KERNEL_LINUX */
415 static int battery_read (void)
416 {
417 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
418 double charge = INVALID_VALUE; /* Current charge in Ah */
419 double current = INVALID_VALUE; /* Current in A */
420 double voltage = INVALID_VALUE; /* Voltage in V */
422 double charge_rel = INVALID_VALUE; /* Current charge in percent */
423 double charge_abs = INVALID_VALUE; /* Total capacity */
425 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
426 get_via_io_power_sources (&charge_rel, ¤t, &voltage);
427 #endif
428 #if HAVE_IOKIT_IOKITLIB_H
429 get_via_generic_iokit (&charge_abs, ¤t, &voltage);
430 #endif
432 if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
433 charge = charge_abs * charge_rel / 100.0;
435 if (charge != INVALID_VALUE)
436 battery_submit ("0", "charge", charge);
437 if (current != INVALID_VALUE)
438 battery_submit ("0", "current", current);
439 if (voltage != INVALID_VALUE)
440 battery_submit ("0", "voltage", voltage);
441 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
443 #elif KERNEL_LINUX
444 static c_complain_t acpi_dir_complaint = C_COMPLAIN_INIT_STATIC;
446 FILE *fh;
447 char buffer[1024];
448 char filename[256];
450 char *fields[8];
451 int numfields;
453 int i;
454 int len;
456 for (i = 0; i < battery_pmu_num; i++)
457 {
458 char batnum_str[256];
459 double current = INVALID_VALUE;
460 double voltage = INVALID_VALUE;
461 double charge = INVALID_VALUE;
462 double *valptr = NULL;
464 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, i);
465 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
466 continue;
468 len = ssnprintf (batnum_str, sizeof (batnum_str), "%i", i);
469 if ((len < 0) || ((unsigned int)len >= sizeof (batnum_str)))
470 continue;
472 if ((fh = fopen (filename, "r")) == NULL)
473 continue;
475 while (fgets (buffer, sizeof (buffer), fh) != NULL)
476 {
477 numfields = strsplit (buffer, fields, 8);
479 if (numfields < 3)
480 continue;
482 if (strcmp ("current", fields[0]) == 0)
483 valptr = ¤t;
484 else if (strcmp ("voltage", fields[0]) == 0)
485 valptr = &voltage;
486 else if (strcmp ("charge", fields[0]) == 0)
487 valptr = &charge;
488 else
489 valptr = NULL;
491 if (valptr != NULL)
492 {
493 char *endptr;
495 endptr = NULL;
496 errno = 0;
498 *valptr = strtod (fields[2], &endptr) / 1000.0;
500 if ((fields[2] == endptr) || (errno != 0))
501 *valptr = INVALID_VALUE;
502 }
503 }
505 fclose (fh);
506 fh = NULL;
508 if (charge != INVALID_VALUE)
509 battery_submit ("0", "charge", charge);
510 if (current != INVALID_VALUE)
511 battery_submit ("0", "current", current);
512 if (voltage != INVALID_VALUE)
513 battery_submit ("0", "voltage", voltage);
514 }
516 if (0 == access (battery_acpi_dir, R_OK))
517 walk_directory (battery_acpi_dir, battery_read_acpi,
518 /* user_data = */ NULL);
519 else
520 {
521 char errbuf[1024];
522 c_complain_once (LOG_WARNING, &acpi_dir_complaint,
523 "battery plugin: Failed to access `%s': %s",
524 battery_acpi_dir,
525 sstrerror (errno, errbuf, sizeof (errbuf)));
526 }
528 #endif /* KERNEL_LINUX */
530 return (0);
531 }
533 void module_register (void)
534 {
535 plugin_register_init ("battery", battery_init);
536 plugin_register_read ("battery", battery_read);
537 } /* void module_register */