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