Merge branch 'sh/collectd-4.5' into sh/collectd-4.6
[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 static const char *battery_acpi_dir = "/proc/acpi/battery";
65 #endif /* KERNEL_LINUX */
66
67 static int battery_init (void)
68 {
69 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
70         /* No init neccessary */
71 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
72
73 #elif KERNEL_LINUX
74         int len;
75         char filename[128];
76
77         for (battery_pmu_num = 0; ; battery_pmu_num++)
78         {
79                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
80
81                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
82                         break;
83
84                 if (access (filename, R_OK))
85                         break;
86         }
87 #endif /* KERNEL_LINUX */
88
89         return (0);
90 }
91
92 static void battery_submit (const char *plugin_instance, const char *type, double value)
93 {
94         value_t values[1];
95         value_list_t vl = VALUE_LIST_INIT;
96
97         values[0].gauge = value;
98
99         vl.values = values;
100         vl.values_len = 1;
101         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
102         sstrncpy (vl.plugin, "battery", sizeof (vl.plugin));
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 #if KERNEL_LINUX
317 static int battery_read_acpi (const char __attribute__((unused)) *dir,
318                 const char *name, void __attribute__((unused)) *user_data)
319 {
320         double  current = INVALID_VALUE;
321         double  voltage = INVALID_VALUE;
322         double  charge  = INVALID_VALUE;
323         double *valptr = NULL;
324         int charging = 0;
325
326         char filename[256];
327         FILE *fh;
328
329         char buffer[1024];
330         char *fields[8];
331         int numfields;
332         char *endptr;
333         int len;
334
335         len = ssnprintf (filename, sizeof (filename), "%s/%s/state", battery_acpi_dir, name);
336
337         if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
338                 return -1;
339
340         if ((fh = fopen (filename, "r")) == NULL) {
341                 char errbuf[1024];
342                 ERROR ("Cannot open `%s': %s", filename,
343                         sstrerror (errno, errbuf, sizeof (errbuf)));
344                 return -1;
345         }
346
347         /*
348          * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
349          * [11:00] <@tokkee> present:                 yes
350          * [11:00] <@tokkee> capacity state:          ok
351          * [11:00] <@tokkee> charging state:          charging
352          * [11:00] <@tokkee> present rate:            1724 mA
353          * [11:00] <@tokkee> remaining capacity:      4136 mAh
354          * [11:00] <@tokkee> present voltage:         12428 mV
355          */
356         while (fgets (buffer, sizeof (buffer), fh) != NULL)
357         {
358                 numfields = strsplit (buffer, fields, 8);
359
360                 if (numfields < 3)
361                         continue;
362
363                 if ((strcmp (fields[0], "charging") == 0)
364                                 && (strcmp (fields[1], "state:") == 0))
365                 {
366                         if (strcmp (fields[2], "charging") == 0)
367                                 charging = 1;
368                         else
369                                 charging = 0;
370                         continue;
371                 }
372
373                 if ((strcmp (fields[0], "present") == 0)
374                                 && (strcmp (fields[1], "rate:") == 0))
375                         valptr = &current;
376                 else if ((strcmp (fields[0], "remaining") == 0)
377                                 && (strcmp (fields[1], "capacity:") == 0))
378                         valptr = &charge;
379                 else if ((strcmp (fields[0], "present") == 0)
380                                 && (strcmp (fields[1], "voltage:") == 0))
381                         valptr = &voltage;
382                 else
383                         continue;
384
385                 endptr = NULL;
386                 errno  = 0;
387                 *valptr = strtod (fields[2], &endptr) / 1000.0;
388
389                 if ((fields[2] == endptr) || (errno != 0))
390                         *valptr = INVALID_VALUE;
391         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
392
393         fclose (fh);
394
395         if ((current != INVALID_VALUE) && (charging == 0))
396                         current *= -1;
397
398         if (charge != INVALID_VALUE)
399                 battery_submit ("0", "charge", charge);
400         if (current != INVALID_VALUE)
401                 battery_submit ("0", "current", current);
402         if (voltage != INVALID_VALUE)
403                 battery_submit ("0", "voltage", voltage);
404
405         return 0;
406 }
407 #endif /* KERNEL_LINUX */
408
409
410 static int battery_read (void)
411 {
412 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
413         double charge  = INVALID_VALUE; /* Current charge in Ah */
414         double current = INVALID_VALUE; /* Current in A */
415         double voltage = INVALID_VALUE; /* Voltage in V */
416
417         double charge_rel = INVALID_VALUE; /* Current charge in percent */
418         double charge_abs = INVALID_VALUE; /* Total capacity */
419
420 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
421         get_via_io_power_sources (&charge_rel, &current, &voltage);
422 #endif
423 #if HAVE_IOKIT_IOKITLIB_H
424         get_via_generic_iokit (&charge_abs, &current, &voltage);
425 #endif
426
427         if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
428                 charge = charge_abs * charge_rel / 100.0;
429
430         if (charge != INVALID_VALUE)
431                 battery_submit ("0", "charge", charge);
432         if (current != INVALID_VALUE)
433                 battery_submit ("0", "current", current);
434         if (voltage != INVALID_VALUE)
435                 battery_submit ("0", "voltage", voltage);
436 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
437
438 #elif KERNEL_LINUX
439         FILE *fh;
440         char buffer[1024];
441         char filename[256];
442         
443         char *fields[8];
444         int numfields;
445
446         int i;
447         int len;
448
449         for (i = 0; i < battery_pmu_num; i++)
450         {
451                 char    batnum_str[256];
452                 double  current = INVALID_VALUE;
453                 double  voltage = INVALID_VALUE;
454                 double  charge  = INVALID_VALUE;
455                 double *valptr = NULL;
456
457                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, i);
458                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
459                         continue;
460
461                 len = ssnprintf (batnum_str, sizeof (batnum_str), "%i", i);
462                 if ((len < 0) || ((unsigned int)len >= sizeof (batnum_str)))
463                         continue;
464
465                 if ((fh = fopen (filename, "r")) == NULL)
466                         continue;
467
468                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
469                 {
470                         numfields = strsplit (buffer, fields, 8);
471
472                         if (numfields < 3)
473                                 continue;
474
475                         if (strcmp ("current", fields[0]) == 0)
476                                 valptr = &current;
477                         else if (strcmp ("voltage", fields[0]) == 0)
478                                 valptr = &voltage;
479                         else if (strcmp ("charge", fields[0]) == 0)
480                                 valptr = &charge;
481                         else
482                                 valptr = NULL;
483
484                         if (valptr != NULL)
485                         {
486                                 char *endptr;
487
488                                 endptr = NULL;
489                                 errno  = 0;
490
491                                 *valptr = strtod (fields[2], &endptr) / 1000.0;
492
493                                 if ((fields[2] == endptr) || (errno != 0))
494                                         *valptr = INVALID_VALUE;
495                         }
496                 }
497
498                 fclose (fh);
499                 fh = NULL;
500
501                 if (charge != INVALID_VALUE)
502                         battery_submit ("0", "charge", charge);
503                 if (current != INVALID_VALUE)
504                         battery_submit ("0", "current", current);
505                 if (voltage != INVALID_VALUE)
506                         battery_submit ("0", "voltage", voltage);
507         }
508
509         walk_directory (battery_acpi_dir, battery_read_acpi,
510                         /* user_data = */ NULL);
511
512 #endif /* KERNEL_LINUX */
513
514         return (0);
515 }
516
517 void module_register (void)
518 {
519         plugin_register_init ("battery", battery_init);
520         plugin_register_read ("battery", battery_read);
521 } /* void module_register */