1 /**
2 * collectd - src/battery.c
3 * Copyright (C) 2006,2007 Florian octo Forster
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Authors:
19 * Florian octo Forster <octo at verplant.org>
20 **/
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
26 #if HAVE_MACH_MACH_TYPES_H
27 # include <mach/mach_types.h>
28 #endif
29 #if HAVE_MACH_MACH_INIT_H
30 # include <mach/mach_init.h>
31 #endif
32 #if HAVE_MACH_MACH_ERROR_H
33 # include <mach/mach_error.h>
34 #endif
35 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
36 # include <CoreFoundation/CoreFoundation.h>
37 #endif
38 #if HAVE_IOKIT_IOKITLIB_H
39 # include <IOKit/IOKitLib.h>
40 #endif
41 #if HAVE_IOKIT_IOTYPES_H
42 # include <IOKit/IOTypes.h>
43 #endif
44 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
45 # include <IOKit/ps/IOPowerSources.h>
46 #endif
47 #if HAVE_IOKIT_PS_IOPSKEYS_H
48 # include <IOKit/ps/IOPSKeys.h>
49 #endif
51 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H || KERNEL_LINUX
52 # define BATTERY_HAVE_READ 1
53 #else
54 # define BATTERY_HAVE_READ 0
55 #endif
57 #define INVALID_VALUE 47841.29
59 static data_source_t data_source_charge[1] =
60 {
61 {"value", DS_TYPE_GAUGE, 0, NAN}
62 };
64 static data_set_t charge_ds =
65 {
66 "charge", 1, data_source_charge
67 };
69 static data_source_t data_source_current[1] =
70 {
71 {"value", DS_TYPE_GAUGE, NAN, NAN}
72 };
74 static data_set_t current_ds =
75 {
76 "current", 1, data_source_current
77 };
79 static data_source_t data_source_voltage[1] =
80 {
81 {"value", DS_TYPE_GAUGE, NAN, NAN}
82 };
84 static data_set_t voltage_ds =
85 {
86 "voltage", 1, data_source_voltage
87 };
89 #if BATTERY_HAVE_READ
90 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
91 /* No global variables */
92 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
94 #elif KERNEL_LINUX
95 static int battery_pmu_num = 0;
96 static char *battery_pmu_file = "/proc/pmu/battery_%i";
97 #endif /* KERNEL_LINUX */
99 static int battery_init (void)
100 {
101 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
102 /* No init neccessary */
103 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
105 #elif KERNEL_LINUX
106 int len;
107 char filename[128];
109 for (battery_pmu_num = 0; ; battery_pmu_num++)
110 {
111 len = snprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
113 if ((len >= sizeof (filename)) || (len < 0))
114 break;
116 if (access (filename, R_OK))
117 break;
118 }
119 #endif /* KERNEL_LINUX */
121 return (0);
122 }
124 static void battery_submit (const char *plugin_instance, const char *type, double value)
125 {
126 value_t values[1];
127 value_list_t vl = VALUE_LIST_INIT;
129 values[0].gauge = value;
131 vl.values = values;
132 vl.values_len = 1;
133 vl.time = time (NULL);
134 strcpy (vl.host, hostname_g);
135 strcpy (vl.plugin, "battery");
136 strcpy (vl.plugin_instance, plugin_instance);
138 plugin_dispatch_values (type, &vl);
139 } /* void battery_submit */
141 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
142 double dict_get_double (CFDictionaryRef dict, char *key_string)
143 {
144 double val_double;
145 long long val_int;
146 CFNumberRef val_obj;
147 CFStringRef key_obj;
149 key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
150 kCFStringEncodingASCII);
151 if (key_obj == NULL)
152 {
153 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
154 return (INVALID_VALUE);
155 }
157 if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
158 {
159 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
160 CFRelease (key_obj);
161 return (INVALID_VALUE);
162 }
163 CFRelease (key_obj);
165 if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
166 {
167 if (CFNumberIsFloatType (val_obj))
168 {
169 CFNumberGetValue (val_obj,
170 kCFNumberDoubleType,
171 &val_double);
172 }
173 else
174 {
175 CFNumberGetValue (val_obj,
176 kCFNumberLongLongType,
177 &val_int);
178 val_double = val_int;
179 }
180 }
181 else
182 {
183 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
184 return (INVALID_VALUE);
185 }
187 return (val_double);
188 }
189 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H */
191 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
192 static void get_via_io_power_sources (double *ret_charge,
193 double *ret_current,
194 double *ret_voltage)
195 {
196 CFTypeRef ps_raw;
197 CFArrayRef ps_array;
198 int ps_array_len;
199 CFDictionaryRef ps_dict;
200 CFTypeRef ps_obj;
202 double temp_double;
203 int i;
205 ps_raw = IOPSCopyPowerSourcesInfo ();
206 ps_array = IOPSCopyPowerSourcesList (ps_raw);
207 ps_array_len = CFArrayGetCount (ps_array);
209 DEBUG ("ps_array_len == %i", ps_array_len);
211 for (i = 0; i < ps_array_len; i++)
212 {
213 ps_obj = CFArrayGetValueAtIndex (ps_array, i);
214 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
216 if (ps_dict == NULL)
217 {
218 DEBUG ("IOPSGetPowerSourceDescription failed.");
219 continue;
220 }
222 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
223 {
224 DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
225 continue;
226 }
228 /* FIXME: Check if this is really an internal battery */
230 if (*ret_charge == INVALID_VALUE)
231 {
232 /* This is the charge in percent. */
233 temp_double = dict_get_double (ps_dict,
234 kIOPSCurrentCapacityKey);
235 if ((temp_double != INVALID_VALUE)
236 && (temp_double >= 0.0)
237 && (temp_double <= 100.0))
238 *ret_charge = temp_double;
239 }
241 if (*ret_current == INVALID_VALUE)
242 {
243 temp_double = dict_get_double (ps_dict,
244 kIOPSCurrentKey);
245 if (temp_double != INVALID_VALUE)
246 *ret_current = temp_double / 1000.0;
247 }
249 if (*ret_voltage == INVALID_VALUE)
250 {
251 temp_double = dict_get_double (ps_dict,
252 kIOPSVoltageKey);
253 if (temp_double != INVALID_VALUE)
254 *ret_voltage = temp_double / 1000.0;
255 }
256 }
258 CFRelease(ps_array);
259 CFRelease(ps_raw);
260 }
261 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
263 #if HAVE_IOKIT_IOKITLIB_H
264 static void get_via_generic_iokit (double *ret_charge,
265 double *ret_current,
266 double *ret_voltage)
267 {
268 kern_return_t status;
269 io_iterator_t iterator;
270 io_object_t io_obj;
272 CFDictionaryRef bat_root_dict;
273 CFArrayRef bat_info_arry;
274 CFIndex bat_info_arry_len;
275 CFIndex bat_info_arry_pos;
276 CFDictionaryRef bat_info_dict;
278 double temp_double;
280 status = IOServiceGetMatchingServices (kIOMasterPortDefault,
281 IOServiceNameMatching ("battery"),
282 &iterator);
283 if (status != kIOReturnSuccess)
284 {
285 DEBUG ("IOServiceGetMatchingServices failed.");
286 return;
287 }
289 while ((io_obj = IOIteratorNext (iterator)))
290 {
291 status = IORegistryEntryCreateCFProperties (io_obj,
292 (CFMutableDictionaryRef *) &bat_root_dict,
293 kCFAllocatorDefault,
294 kNilOptions);
295 if (status != kIOReturnSuccess)
296 {
297 DEBUG ("IORegistryEntryCreateCFProperties failed.");
298 continue;
299 }
301 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
302 CFSTR ("IOBatteryInfo"));
303 if (bat_info_arry == NULL)
304 {
305 CFRelease (bat_root_dict);
306 continue;
307 }
308 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
310 for (bat_info_arry_pos = 0;
311 bat_info_arry_pos < bat_info_arry_len;
312 bat_info_arry_pos++)
313 {
314 bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
316 if (*ret_charge == INVALID_VALUE)
317 {
318 temp_double = dict_get_double (bat_info_dict,
319 "Capacity");
320 if (temp_double != INVALID_VALUE)
321 *ret_charge = temp_double / 1000.0;
322 }
324 if (*ret_current == INVALID_VALUE)
325 {
326 temp_double = dict_get_double (bat_info_dict,
327 "Current");
328 if (temp_double != INVALID_VALUE)
329 *ret_current = temp_double / 1000.0;
330 }
332 if (*ret_voltage == INVALID_VALUE)
333 {
334 temp_double = dict_get_double (bat_info_dict,
335 "Voltage");
336 if (temp_double != INVALID_VALUE)
337 *ret_voltage = temp_double / 1000.0;
338 }
339 }
341 CFRelease (bat_root_dict);
342 }
344 IOObjectRelease (iterator);
345 }
346 #endif /* HAVE_IOKIT_IOKITLIB_H */
348 static int battery_read (void)
349 {
350 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
351 double charge = INVALID_VALUE; /* Current charge in Ah */
352 double current = INVALID_VALUE; /* Current in A */
353 double voltage = INVALID_VALUE; /* Voltage in V */
355 double charge_rel = INVALID_VALUE; /* Current charge in percent */
356 double charge_abs = INVALID_VALUE; /* Total capacity */
358 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
359 get_via_io_power_sources (&charge_rel, ¤t, &voltage);
360 #endif
361 #if HAVE_IOKIT_IOKITLIB_H
362 get_via_generic_iokit (&charge_abs, ¤t, &voltage);
363 #endif
365 if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
366 charge = charge_abs * charge_rel / 100.0;
368 if (charge != INVALID_VALUE)
369 battery_submit ("0", "charge", charge);
370 if (current != INVALID_VALUE)
371 battery_submit ("0", "current", current);
372 if (voltage != INVALID_VALUE)
373 battery_submit ("0", "voltage", voltage);
374 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
376 #elif KERNEL_LINUX
377 FILE *fh;
378 char buffer[1024];
379 char filename[256];
381 char *fields[8];
382 int numfields;
384 int i;
385 int len;
387 for (i = 0; i < battery_pmu_num; i++)
388 {
389 char batnum_str[256];
390 double current = INVALID_VALUE;
391 double voltage = INVALID_VALUE;
392 double charge = INVALID_VALUE;
393 double *valptr = NULL;
395 len = snprintf (filename, sizeof (filename), battery_pmu_file, i);
396 if ((len >= sizeof (filename)) || (len < 0))
397 continue;
399 len = snprintf (batnum_str, sizeof (batnum_str), "%i", i);
400 if ((len >= sizeof (batnum_str)) || (len < 0))
401 continue;
403 if ((fh = fopen (filename, "r")) == NULL)
404 continue;
406 while (fgets (buffer, sizeof (buffer), fh) != NULL)
407 {
408 numfields = strsplit (buffer, fields, 8);
410 if (numfields < 3)
411 continue;
413 if (strcmp ("current", fields[0]) == 0)
414 valptr = ¤t;
415 else if (strcmp ("voltage", fields[0]) == 0)
416 valptr = &voltage;
417 else if (strcmp ("charge", fields[0]) == 0)
418 valptr = &charge;
419 else
420 valptr = NULL;
422 if (valptr != NULL)
423 {
424 char *endptr;
426 endptr = NULL;
427 errno = 0;
429 *valptr = strtod (fields[2], &endptr) / 1000.0;
431 if ((fields[2] == endptr) || (errno != 0))
432 *valptr = INVALID_VALUE;
433 }
434 }
436 fclose (fh);
437 fh = NULL;
439 if (charge != INVALID_VALUE)
440 battery_submit ("0", "charge", charge);
441 if (current != INVALID_VALUE)
442 battery_submit ("0", "current", current);
443 if (voltage != INVALID_VALUE)
444 battery_submit ("0", "voltage", voltage);
445 }
447 if (access ("/proc/acpi/battery", R_OK | X_OK) == 0)
448 {
449 double current = INVALID_VALUE;
450 double voltage = INVALID_VALUE;
451 double charge = INVALID_VALUE;
452 double *valptr = NULL;
453 int charging = 0;
455 struct dirent *ent;
456 DIR *dh;
458 if ((dh = opendir ("/proc/acpi/battery")) == NULL)
459 {
460 char errbuf[1024];
461 ERROR ("Cannot open `/proc/acpi/battery': %s",
462 sstrerror (errno, errbuf, sizeof (errbuf)));
463 return (-1);
464 }
466 while ((ent = readdir (dh)) != NULL)
467 {
468 if (ent->d_name[0] == '.')
469 continue;
471 len = snprintf (filename, sizeof (filename),
472 "/proc/acpi/battery/%s/state",
473 ent->d_name);
474 if ((len >= sizeof (filename)) || (len < 0))
475 continue;
477 if ((fh = fopen (filename, "r")) == NULL)
478 {
479 char errbuf[1024];
480 ERROR ("Cannot open `%s': %s", filename,
481 sstrerror (errno, errbuf,
482 sizeof (errbuf)));
483 continue;
484 }
486 /*
487 * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
488 * [11:00] <@tokkee> present: yes
489 * [11:00] <@tokkee> capacity state: ok
490 * [11:00] <@tokkee> charging state: charging
491 * [11:00] <@tokkee> present rate: 1724 mA
492 * [11:00] <@tokkee> remaining capacity: 4136 mAh
493 * [11:00] <@tokkee> present voltage: 12428 mV
494 */
495 while (fgets (buffer, sizeof (buffer), fh) != NULL)
496 {
497 numfields = strsplit (buffer, fields, 8);
499 if (numfields < 3)
500 continue;
502 if ((strcmp (fields[0], "present") == 0)
503 && (strcmp (fields[1], "rate:") == 0))
504 valptr = ¤t;
505 else if ((strcmp (fields[0], "remaining") == 0)
506 && (strcmp (fields[1], "capacity:") == 0))
507 valptr = &charge;
508 else if ((strcmp (fields[0], "present") == 0)
509 && (strcmp (fields[1], "voltage:") == 0))
510 valptr = &voltage;
511 else
512 valptr = NULL;
514 if ((strcmp (fields[0], "charging") == 0)
515 && (strcmp (fields[1], "state:") == 0))
516 {
517 if (strcmp (fields[2], "charging") == 0)
518 charging = 1;
519 else
520 charging = 0;
521 }
523 if (valptr != NULL)
524 {
525 char *endptr;
527 endptr = NULL;
528 errno = 0;
530 *valptr = strtod (fields[2], &endptr) / 1000.0;
532 if ((fields[2] == endptr) || (errno != 0))
533 *valptr = INVALID_VALUE;
534 }
535 } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
537 fclose (fh);
539 if ((current != INVALID_VALUE) && (charging == 0))
540 current *= -1;
542 if (charge != INVALID_VALUE)
543 battery_submit ("0", "charge", charge);
544 if (current != INVALID_VALUE)
545 battery_submit ("0", "current", current);
546 if (voltage != INVALID_VALUE)
547 battery_submit ("0", "voltage", voltage);
548 }
550 closedir (dh);
551 }
552 #endif /* KERNEL_LINUX */
554 return (0);
555 }
556 #endif /* BATTERY_HAVE_READ */
558 void module_register (modreg_e load)
559 {
560 if (load & MR_DATASETS)
561 {
562 plugin_register_data_set (&charge_ds);
563 plugin_register_data_set (¤t_ds);
564 plugin_register_data_set (&voltage_ds);
565 }
567 #if BATTERY_HAVE_READ
568 if (load & MR_READ)
569 {
570 plugin_register_init ("battery", battery_init);
571 plugin_register_read ("battery", battery_read);
572 }
573 #endif /* BATTERY_HAVE_READ */
574 } /* void module_register */