Merge branch 'collectd-3.11' into collectd-4.0
[collectd.git] / src / battery.c
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  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25
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
50
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
56
57 #define INVALID_VALUE 47841.29
58
59 #if BATTERY_HAVE_READ
60 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
61         /* No global variables */
62 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
63
64 #elif KERNEL_LINUX
65 static int   battery_pmu_num = 0;
66 static char *battery_pmu_file = "/proc/pmu/battery_%i";
67 #endif /* KERNEL_LINUX */
68
69 static int battery_init (void)
70 {
71 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
72         /* No init neccessary */
73 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
74
75 #elif KERNEL_LINUX
76         int len;
77         char filename[128];
78
79         for (battery_pmu_num = 0; ; battery_pmu_num++)
80         {
81                 len = snprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
82
83                 if ((len >= sizeof (filename)) || (len < 0))
84                         break;
85
86                 if (access (filename, R_OK))
87                         break;
88         }
89 #endif /* KERNEL_LINUX */
90
91         return (0);
92 }
93
94 static void battery_submit (const char *plugin_instance, const char *type, double value)
95 {
96         value_t values[1];
97         value_list_t vl = VALUE_LIST_INIT;
98
99         values[0].gauge = value;
100
101         vl.values = values;
102         vl.values_len = 1;
103         vl.time = time (NULL);
104         strcpy (vl.host, hostname_g);
105         strcpy (vl.plugin, "battery");
106         strcpy (vl.plugin_instance, plugin_instance);
107
108         plugin_dispatch_values (type, &vl);
109 } /* void battery_submit */
110
111 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
112 double dict_get_double (CFDictionaryRef dict, char *key_string)
113 {
114         double      val_double;
115         long long   val_int;
116         CFNumberRef val_obj;
117         CFStringRef key_obj;
118
119         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
120                         kCFStringEncodingASCII);
121         if (key_obj == NULL)
122         {
123                 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
124                 return (INVALID_VALUE);
125         }
126
127         if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
128         {
129                 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
130                 CFRelease (key_obj);
131                 return (INVALID_VALUE);
132         }
133         CFRelease (key_obj);
134
135         if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
136         {
137                 if (CFNumberIsFloatType (val_obj))
138                 {
139                         CFNumberGetValue (val_obj,
140                                         kCFNumberDoubleType,
141                                         &val_double);
142                 }
143                 else
144                 {
145                         CFNumberGetValue (val_obj,
146                                         kCFNumberLongLongType,
147                                         &val_int);
148                         val_double = val_int;
149                 }
150         }
151         else
152         {
153                 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
154                 return (INVALID_VALUE);
155         }
156
157         return (val_double);
158 }
159 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H */
160
161 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
162 static void get_via_io_power_sources (double *ret_charge,
163                 double *ret_current,
164                 double *ret_voltage)
165 {
166         CFTypeRef       ps_raw;
167         CFArrayRef      ps_array;
168         int             ps_array_len;
169         CFDictionaryRef ps_dict;
170         CFTypeRef       ps_obj;
171
172         double temp_double;
173         int i;
174
175         ps_raw       = IOPSCopyPowerSourcesInfo ();
176         ps_array     = IOPSCopyPowerSourcesList (ps_raw);
177         ps_array_len = CFArrayGetCount (ps_array);
178
179         DEBUG ("ps_array_len == %i", ps_array_len);
180
181         for (i = 0; i < ps_array_len; i++)
182         {
183                 ps_obj  = CFArrayGetValueAtIndex (ps_array, i);
184                 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
185
186                 if (ps_dict == NULL)
187                 {
188                         DEBUG ("IOPSGetPowerSourceDescription failed.");
189                         continue;
190                 }
191
192                 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
193                 {
194                         DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
195                         continue;
196                 }
197
198                 /* FIXME: Check if this is really an internal battery */
199
200                 if (*ret_charge == INVALID_VALUE)
201                 {
202                         /* This is the charge in percent. */
203                         temp_double = dict_get_double (ps_dict,
204                                         kIOPSCurrentCapacityKey);
205                         if ((temp_double != INVALID_VALUE)
206                                         && (temp_double >= 0.0)
207                                         && (temp_double <= 100.0))
208                                 *ret_charge = temp_double;
209                 }
210
211                 if (*ret_current == INVALID_VALUE)
212                 {
213                         temp_double = dict_get_double (ps_dict,
214                                         kIOPSCurrentKey);
215                         if (temp_double != INVALID_VALUE)
216                                 *ret_current = temp_double / 1000.0;
217                 }
218
219                 if (*ret_voltage == INVALID_VALUE)
220                 {
221                         temp_double = dict_get_double (ps_dict,
222                                         kIOPSVoltageKey);
223                         if (temp_double != INVALID_VALUE)
224                                 *ret_voltage = temp_double / 1000.0;
225                 }
226         }
227
228         CFRelease(ps_array);
229         CFRelease(ps_raw);
230 }
231 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
232
233 #if HAVE_IOKIT_IOKITLIB_H
234 static void get_via_generic_iokit (double *ret_charge,
235                 double *ret_current,
236                 double *ret_voltage)
237 {
238         kern_return_t   status;
239         io_iterator_t   iterator;
240         io_object_t     io_obj;
241
242         CFDictionaryRef bat_root_dict;
243         CFArrayRef      bat_info_arry;
244         CFIndex         bat_info_arry_len;
245         CFIndex         bat_info_arry_pos;
246         CFDictionaryRef bat_info_dict;
247
248         double temp_double;
249
250         status = IOServiceGetMatchingServices (kIOMasterPortDefault,
251                         IOServiceNameMatching ("battery"),
252                         &iterator);
253         if (status != kIOReturnSuccess)
254         {
255                 DEBUG ("IOServiceGetMatchingServices failed.");
256                 return;
257         }
258
259         while ((io_obj = IOIteratorNext (iterator)))
260         {
261                 status = IORegistryEntryCreateCFProperties (io_obj,
262                                 (CFMutableDictionaryRef *) &bat_root_dict,
263                                 kCFAllocatorDefault,
264                                 kNilOptions);
265                 if (status != kIOReturnSuccess)
266                 {
267                         DEBUG ("IORegistryEntryCreateCFProperties failed.");
268                         continue;
269                 }
270
271                 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
272                                 CFSTR ("IOBatteryInfo"));
273                 if (bat_info_arry == NULL)
274                 {
275                         CFRelease (bat_root_dict);
276                         continue;
277                 }
278                 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
279
280                 for (bat_info_arry_pos = 0;
281                                 bat_info_arry_pos < bat_info_arry_len;
282                                 bat_info_arry_pos++)
283                 {
284                         bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
285
286                         if (*ret_charge == INVALID_VALUE)
287                         {
288                                 temp_double = dict_get_double (bat_info_dict,
289                                                 "Capacity");
290                                 if (temp_double != INVALID_VALUE)
291                                         *ret_charge = temp_double / 1000.0;
292                         }
293
294                         if (*ret_current == INVALID_VALUE)
295                         {
296                                 temp_double = dict_get_double (bat_info_dict,
297                                                 "Current");
298                                 if (temp_double != INVALID_VALUE)
299                                         *ret_current = temp_double / 1000.0;
300                         }
301
302                         if (*ret_voltage == INVALID_VALUE)
303                         {
304                                 temp_double = dict_get_double (bat_info_dict,
305                                                 "Voltage");
306                                 if (temp_double != INVALID_VALUE)
307                                         *ret_voltage = temp_double / 1000.0;
308                         }
309                 }
310                 
311                 CFRelease (bat_root_dict);
312         }
313
314         IOObjectRelease (iterator);
315 }
316 #endif /* HAVE_IOKIT_IOKITLIB_H */
317
318 static int battery_read (void)
319 {
320 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
321         double charge  = INVALID_VALUE; /* Current charge in Ah */
322         double current = INVALID_VALUE; /* Current in A */
323         double voltage = INVALID_VALUE; /* Voltage in V */
324
325         double charge_rel = INVALID_VALUE; /* Current charge in percent */
326         double charge_abs = INVALID_VALUE; /* Total capacity */
327
328 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
329         get_via_io_power_sources (&charge_rel, &current, &voltage);
330 #endif
331 #if HAVE_IOKIT_IOKITLIB_H
332         get_via_generic_iokit (&charge_abs, &current, &voltage);
333 #endif
334
335         if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
336                 charge = charge_abs * charge_rel / 100.0;
337
338         if (charge != INVALID_VALUE)
339                 battery_submit ("0", "charge", charge);
340         if (current != INVALID_VALUE)
341                 battery_submit ("0", "current", current);
342         if (voltage != INVALID_VALUE)
343                 battery_submit ("0", "voltage", voltage);
344 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
345
346 #elif KERNEL_LINUX
347         FILE *fh;
348         char buffer[1024];
349         char filename[256];
350         
351         char *fields[8];
352         int numfields;
353
354         int i;
355         int len;
356
357         for (i = 0; i < battery_pmu_num; i++)
358         {
359                 char    batnum_str[256];
360                 double  current = INVALID_VALUE;
361                 double  voltage = INVALID_VALUE;
362                 double  charge  = INVALID_VALUE;
363                 double *valptr = NULL;
364
365                 len = snprintf (filename, sizeof (filename), battery_pmu_file, i);
366                 if ((len >= sizeof (filename)) || (len < 0))
367                         continue;
368
369                 len = snprintf (batnum_str, sizeof (batnum_str), "%i", i);
370                 if ((len >= sizeof (batnum_str)) || (len < 0))
371                         continue;
372
373                 if ((fh = fopen (filename, "r")) == NULL)
374                         continue;
375
376                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
377                 {
378                         numfields = strsplit (buffer, fields, 8);
379
380                         if (numfields < 3)
381                                 continue;
382
383                         if (strcmp ("current", fields[0]) == 0)
384                                 valptr = &current;
385                         else if (strcmp ("voltage", fields[0]) == 0)
386                                 valptr = &voltage;
387                         else if (strcmp ("charge", fields[0]) == 0)
388                                 valptr = &charge;
389                         else
390                                 valptr = NULL;
391
392                         if (valptr != NULL)
393                         {
394                                 char *endptr;
395
396                                 endptr = NULL;
397                                 errno  = 0;
398
399                                 *valptr = strtod (fields[2], &endptr) / 1000.0;
400
401                                 if ((fields[2] == endptr) || (errno != 0))
402                                         *valptr = INVALID_VALUE;
403                         }
404                 }
405
406                 fclose (fh);
407                 fh = NULL;
408
409                 if (charge != INVALID_VALUE)
410                         battery_submit ("0", "charge", charge);
411                 if (current != INVALID_VALUE)
412                         battery_submit ("0", "current", current);
413                 if (voltage != INVALID_VALUE)
414                         battery_submit ("0", "voltage", voltage);
415         }
416
417         if (access ("/proc/acpi/battery", R_OK | X_OK) == 0)
418         {
419                 double  current = INVALID_VALUE;
420                 double  voltage = INVALID_VALUE;
421                 double  charge  = INVALID_VALUE;
422                 double *valptr = NULL;
423                 int charging = 0;
424
425                 struct dirent *ent;
426                 DIR *dh;
427
428                 if ((dh = opendir ("/proc/acpi/battery")) == NULL)
429                 {
430                         char errbuf[1024];
431                         ERROR ("Cannot open `/proc/acpi/battery': %s",
432                                         sstrerror (errno, errbuf, sizeof (errbuf)));
433                         return (-1);
434                 }
435
436                 while ((ent = readdir (dh)) != NULL)
437                 {
438                         if (ent->d_name[0] == '.')
439                                 continue;
440
441                         len = snprintf (filename, sizeof (filename),
442                                         "/proc/acpi/battery/%s/state",
443                                         ent->d_name);
444                         if ((len >= sizeof (filename)) || (len < 0))
445                                 continue;
446
447                         if ((fh = fopen (filename, "r")) == NULL)
448                         {
449                                 char errbuf[1024];
450                                 ERROR ("Cannot open `%s': %s", filename,
451                                                 sstrerror (errno, errbuf,
452                                                         sizeof (errbuf)));
453                                 continue;
454                         }
455
456                         /*
457                          * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
458                          * [11:00] <@tokkee> present:                 yes
459                          * [11:00] <@tokkee> capacity state:          ok
460                          * [11:00] <@tokkee> charging state:          charging
461                          * [11:00] <@tokkee> present rate:            1724 mA
462                          * [11:00] <@tokkee> remaining capacity:      4136 mAh
463                          * [11:00] <@tokkee> present voltage:         12428 mV
464                          */
465                         while (fgets (buffer, sizeof (buffer), fh) != NULL)
466                         {
467                                 numfields = strsplit (buffer, fields, 8);
468
469                                 if (numfields < 3)
470                                         continue;
471
472                                 if ((strcmp (fields[0], "present") == 0)
473                                                 && (strcmp (fields[1], "rate:") == 0))
474                                         valptr = &current;
475                                 else if ((strcmp (fields[0], "remaining") == 0)
476                                                 && (strcmp (fields[1], "capacity:") == 0))
477                                         valptr = &charge;
478                                 else if ((strcmp (fields[0], "present") == 0)
479                                                 && (strcmp (fields[1], "voltage:") == 0))
480                                         valptr = &voltage;
481                                 else
482                                         valptr = NULL;
483
484                                 if ((strcmp (fields[0], "charging") == 0)
485                                                 && (strcmp (fields[1], "state:") == 0))
486                                 {
487                                         if (strcmp (fields[2], "charging") == 0)
488                                                 charging = 1;
489                                         else
490                                                 charging = 0;
491                                 }
492
493                                 if (valptr != NULL)
494                                 {
495                                         char *endptr;
496
497                                         endptr = NULL;
498                                         errno  = 0;
499
500                                         *valptr = strtod (fields[2], &endptr) / 1000.0;
501
502                                         if ((fields[2] == endptr) || (errno != 0))
503                                                 *valptr = INVALID_VALUE;
504                                 }
505                         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
506
507                         fclose (fh);
508
509                         if ((current != INVALID_VALUE) && (charging == 0))
510                                         current *= -1;
511
512                         if (charge != INVALID_VALUE)
513                                 battery_submit ("0", "charge", charge);
514                         if (current != INVALID_VALUE)
515                                 battery_submit ("0", "current", current);
516                         if (voltage != INVALID_VALUE)
517                                 battery_submit ("0", "voltage", voltage);
518                 }
519
520                 closedir (dh);
521         }
522 #endif /* KERNEL_LINUX */
523
524         return (0);
525 }
526 #endif /* BATTERY_HAVE_READ */
527
528 void module_register (void)
529 {
530 #if BATTERY_HAVE_READ
531         plugin_register_init ("battery", battery_init);
532         plugin_register_read ("battery", battery_read);
533 #endif /* BATTERY_HAVE_READ */
534 } /* void module_register */