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