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