Merge remote branch 'trenkel/collectd-4.10' into collectd-4.10
[collectd.git] / src / battery.c
1 /**
2  * collectd - src/battery.c
3  * Copyright (C) 2006,2007  Florian octo Forster
4  * Copyright (C) 2008       Michał Mirosław
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at verplant.org>
21  *   Michał Mirosław <mirq-linux at rere.qmqm.pl>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27
28 #include "utils_complain.h"
29
30 #if HAVE_MACH_MACH_TYPES_H
31 #  include <mach/mach_types.h>
32 #endif
33 #if HAVE_MACH_MACH_INIT_H
34 #  include <mach/mach_init.h>
35 #endif
36 #if HAVE_MACH_MACH_ERROR_H
37 #  include <mach/mach_error.h>
38 #endif
39 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
40 #  include <CoreFoundation/CoreFoundation.h>
41 #endif
42 #if HAVE_IOKIT_IOKITLIB_H
43 #  include <IOKit/IOKitLib.h>
44 #endif
45 #if HAVE_IOKIT_IOTYPES_H
46 #  include <IOKit/IOTypes.h>
47 #endif
48 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
49 #  include <IOKit/ps/IOPowerSources.h>
50 #endif
51 #if HAVE_IOKIT_PS_IOPSKEYS_H
52 #  include <IOKit/ps/IOPSKeys.h>
53 #endif
54
55 #if !HAVE_IOKIT_IOKITLIB_H && !HAVE_IOKIT_PS_IOPOWERSOURCES_H && !KERNEL_LINUX
56 # error "No applicable input method."
57 #endif
58
59 #define INVALID_VALUE 47841.29
60
61 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
62         /* No global variables */
63 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
64
65 #elif KERNEL_LINUX
66 static int   battery_pmu_num = 0;
67 static char *battery_pmu_file = "/proc/pmu/battery_%i";
68 static const char *battery_acpi_dir = "/proc/acpi/battery";
69 #endif /* KERNEL_LINUX */
70
71 static int battery_init (void)
72 {
73 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
74         /* No init neccessary */
75 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
76
77 #elif KERNEL_LINUX
78         int len;
79         char filename[128];
80
81         for (battery_pmu_num = 0; ; battery_pmu_num++)
82         {
83                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
84
85                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
86                         break;
87
88                 if (access (filename, R_OK))
89                         break;
90         }
91 #endif /* KERNEL_LINUX */
92
93         return (0);
94 }
95
96 static void battery_submit (const char *plugin_instance, const char *type, double value)
97 {
98         value_t values[1];
99         value_list_t vl = VALUE_LIST_INIT;
100
101         values[0].gauge = value;
102
103         vl.values = values;
104         vl.values_len = 1;
105         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
106         sstrncpy (vl.plugin, "battery", sizeof (vl.plugin));
107         sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
108         sstrncpy (vl.type, type, sizeof (vl.type));
109
110         plugin_dispatch_values (&vl);
111 } /* void battery_submit */
112
113 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
114 double dict_get_double (CFDictionaryRef dict, char *key_string)
115 {
116         double      val_double;
117         long long   val_int;
118         CFNumberRef val_obj;
119         CFStringRef key_obj;
120
121         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key_string,
122                         kCFStringEncodingASCII);
123         if (key_obj == NULL)
124         {
125                 DEBUG ("CFStringCreateWithCString (%s) failed.\n", key_string);
126                 return (INVALID_VALUE);
127         }
128
129         if ((val_obj = CFDictionaryGetValue (dict, key_obj)) == NULL)
130         {
131                 DEBUG ("CFDictionaryGetValue (%s) failed.", key_string);
132                 CFRelease (key_obj);
133                 return (INVALID_VALUE);
134         }
135         CFRelease (key_obj);
136
137         if (CFGetTypeID (val_obj) == CFNumberGetTypeID ())
138         {
139                 if (CFNumberIsFloatType (val_obj))
140                 {
141                         CFNumberGetValue (val_obj,
142                                         kCFNumberDoubleType,
143                                         &val_double);
144                 }
145                 else
146                 {
147                         CFNumberGetValue (val_obj,
148                                         kCFNumberLongLongType,
149                                         &val_int);
150                         val_double = val_int;
151                 }
152         }
153         else
154         {
155                 DEBUG ("CFGetTypeID (val_obj) = %i", (int) CFGetTypeID (val_obj));
156                 return (INVALID_VALUE);
157         }
158
159         return (val_double);
160 }
161 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H */
162
163 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
164 static void get_via_io_power_sources (double *ret_charge,
165                 double *ret_current,
166                 double *ret_voltage)
167 {
168         CFTypeRef       ps_raw;
169         CFArrayRef      ps_array;
170         int             ps_array_len;
171         CFDictionaryRef ps_dict;
172         CFTypeRef       ps_obj;
173
174         double temp_double;
175         int i;
176
177         ps_raw       = IOPSCopyPowerSourcesInfo ();
178         ps_array     = IOPSCopyPowerSourcesList (ps_raw);
179         ps_array_len = CFArrayGetCount (ps_array);
180
181         DEBUG ("ps_array_len == %i", ps_array_len);
182
183         for (i = 0; i < ps_array_len; i++)
184         {
185                 ps_obj  = CFArrayGetValueAtIndex (ps_array, i);
186                 ps_dict = IOPSGetPowerSourceDescription (ps_raw, ps_obj);
187
188                 if (ps_dict == NULL)
189                 {
190                         DEBUG ("IOPSGetPowerSourceDescription failed.");
191                         continue;
192                 }
193
194                 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
195                 {
196                         DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
197                         continue;
198                 }
199
200                 /* FIXME: Check if this is really an internal battery */
201
202                 if (*ret_charge == INVALID_VALUE)
203                 {
204                         /* This is the charge in percent. */
205                         temp_double = dict_get_double (ps_dict,
206                                         kIOPSCurrentCapacityKey);
207                         if ((temp_double != INVALID_VALUE)
208                                         && (temp_double >= 0.0)
209                                         && (temp_double <= 100.0))
210                                 *ret_charge = temp_double;
211                 }
212
213                 if (*ret_current == INVALID_VALUE)
214                 {
215                         temp_double = dict_get_double (ps_dict,
216                                         kIOPSCurrentKey);
217                         if (temp_double != INVALID_VALUE)
218                                 *ret_current = temp_double / 1000.0;
219                 }
220
221                 if (*ret_voltage == INVALID_VALUE)
222                 {
223                         temp_double = dict_get_double (ps_dict,
224                                         kIOPSVoltageKey);
225                         if (temp_double != INVALID_VALUE)
226                                 *ret_voltage = temp_double / 1000.0;
227                 }
228         }
229
230         CFRelease(ps_array);
231         CFRelease(ps_raw);
232 }
233 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
234
235 #if HAVE_IOKIT_IOKITLIB_H
236 static void get_via_generic_iokit (double *ret_charge,
237                 double *ret_current,
238                 double *ret_voltage)
239 {
240         kern_return_t   status;
241         io_iterator_t   iterator;
242         io_object_t     io_obj;
243
244         CFDictionaryRef bat_root_dict;
245         CFArrayRef      bat_info_arry;
246         CFIndex         bat_info_arry_len;
247         CFIndex         bat_info_arry_pos;
248         CFDictionaryRef bat_info_dict;
249
250         double temp_double;
251
252         status = IOServiceGetMatchingServices (kIOMasterPortDefault,
253                         IOServiceNameMatching ("battery"),
254                         &iterator);
255         if (status != kIOReturnSuccess)
256         {
257                 DEBUG ("IOServiceGetMatchingServices failed.");
258                 return;
259         }
260
261         while ((io_obj = IOIteratorNext (iterator)))
262         {
263                 status = IORegistryEntryCreateCFProperties (io_obj,
264                                 (CFMutableDictionaryRef *) &bat_root_dict,
265                                 kCFAllocatorDefault,
266                                 kNilOptions);
267                 if (status != kIOReturnSuccess)
268                 {
269                         DEBUG ("IORegistryEntryCreateCFProperties failed.");
270                         continue;
271                 }
272
273                 bat_info_arry = (CFArrayRef) CFDictionaryGetValue (bat_root_dict,
274                                 CFSTR ("IOBatteryInfo"));
275                 if (bat_info_arry == NULL)
276                 {
277                         CFRelease (bat_root_dict);
278                         continue;
279                 }
280                 bat_info_arry_len = CFArrayGetCount (bat_info_arry);
281
282                 for (bat_info_arry_pos = 0;
283                                 bat_info_arry_pos < bat_info_arry_len;
284                                 bat_info_arry_pos++)
285                 {
286                         bat_info_dict = (CFDictionaryRef) CFArrayGetValueAtIndex (bat_info_arry, bat_info_arry_pos);
287
288                         if (*ret_charge == INVALID_VALUE)
289                         {
290                                 temp_double = dict_get_double (bat_info_dict,
291                                                 "Capacity");
292                                 if (temp_double != INVALID_VALUE)
293                                         *ret_charge = temp_double / 1000.0;
294                         }
295
296                         if (*ret_current == INVALID_VALUE)
297                         {
298                                 temp_double = dict_get_double (bat_info_dict,
299                                                 "Current");
300                                 if (temp_double != INVALID_VALUE)
301                                         *ret_current = temp_double / 1000.0;
302                         }
303
304                         if (*ret_voltage == INVALID_VALUE)
305                         {
306                                 temp_double = dict_get_double (bat_info_dict,
307                                                 "Voltage");
308                                 if (temp_double != INVALID_VALUE)
309                                         *ret_voltage = temp_double / 1000.0;
310                         }
311                 }
312                 
313                 CFRelease (bat_root_dict);
314         }
315
316         IOObjectRelease (iterator);
317 }
318 #endif /* HAVE_IOKIT_IOKITLIB_H */
319
320 #if KERNEL_LINUX
321 static int battery_read_acpi (const char __attribute__((unused)) *dir,
322                 const char *name, void __attribute__((unused)) *user_data)
323 {
324         double  current = INVALID_VALUE;
325         double  voltage = INVALID_VALUE;
326         double  charge  = INVALID_VALUE;
327         double *valptr = NULL;
328         int charging = 0;
329
330         char filename[256];
331         FILE *fh;
332
333         char buffer[1024];
334         char *fields[8];
335         int numfields;
336         char *endptr;
337         int len;
338
339         len = ssnprintf (filename, sizeof (filename), "%s/%s/state", battery_acpi_dir, name);
340
341         if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
342                 return -1;
343
344         if ((fh = fopen (filename, "r")) == NULL) {
345                 char errbuf[1024];
346                 ERROR ("Cannot open `%s': %s", filename,
347                         sstrerror (errno, errbuf, sizeof (errbuf)));
348                 return -1;
349         }
350
351         /*
352          * [11:00] <@tokkee> $ cat /proc/acpi/battery/BAT1/state
353          * [11:00] <@tokkee> present:                 yes
354          * [11:00] <@tokkee> capacity state:          ok
355          * [11:00] <@tokkee> charging state:          charging
356          * [11:00] <@tokkee> present rate:            1724 mA
357          * [11:00] <@tokkee> remaining capacity:      4136 mAh
358          * [11:00] <@tokkee> present voltage:         12428 mV
359          */
360         while (fgets (buffer, sizeof (buffer), fh) != NULL)
361         {
362                 numfields = strsplit (buffer, fields, 8);
363
364                 if (numfields < 3)
365                         continue;
366
367                 if ((strcmp (fields[0], "charging") == 0)
368                                 && (strcmp (fields[1], "state:") == 0))
369                 {
370                         if (strcmp (fields[2], "charging") == 0)
371                                 charging = 1;
372                         else
373                                 charging = 0;
374                         continue;
375                 }
376
377                 if ((strcmp (fields[0], "present") == 0)
378                                 && (strcmp (fields[1], "rate:") == 0))
379                         valptr = &current;
380                 else if ((strcmp (fields[0], "remaining") == 0)
381                                 && (strcmp (fields[1], "capacity:") == 0))
382                         valptr = &charge;
383                 else if ((strcmp (fields[0], "present") == 0)
384                                 && (strcmp (fields[1], "voltage:") == 0))
385                         valptr = &voltage;
386                 else
387                         continue;
388
389                 endptr = NULL;
390                 errno  = 0;
391                 *valptr = strtod (fields[2], &endptr) / 1000.0;
392
393                 if ((fields[2] == endptr) || (errno != 0))
394                         *valptr = INVALID_VALUE;
395         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
396
397         fclose (fh);
398
399         if ((current != INVALID_VALUE) && (charging == 0))
400                         current *= -1;
401
402         if (charge != INVALID_VALUE)
403                 battery_submit ("0", "charge", charge);
404         if (current != INVALID_VALUE)
405                 battery_submit ("0", "current", current);
406         if (voltage != INVALID_VALUE)
407                 battery_submit ("0", "voltage", voltage);
408
409         return 0;
410 }
411 #endif /* KERNEL_LINUX */
412
413
414 static int battery_read (void)
415 {
416 #if HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H
417         double charge  = INVALID_VALUE; /* Current charge in Ah */
418         double current = INVALID_VALUE; /* Current in A */
419         double voltage = INVALID_VALUE; /* Voltage in V */
420
421         double charge_rel = INVALID_VALUE; /* Current charge in percent */
422         double charge_abs = INVALID_VALUE; /* Total capacity */
423
424 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H
425         get_via_io_power_sources (&charge_rel, &current, &voltage);
426 #endif
427 #if HAVE_IOKIT_IOKITLIB_H
428         get_via_generic_iokit (&charge_abs, &current, &voltage);
429 #endif
430
431         if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
432                 charge = charge_abs * charge_rel / 100.0;
433
434         if (charge != INVALID_VALUE)
435                 battery_submit ("0", "charge", charge);
436         if (current != INVALID_VALUE)
437                 battery_submit ("0", "current", current);
438         if (voltage != INVALID_VALUE)
439                 battery_submit ("0", "voltage", voltage);
440 /* #endif HAVE_IOKIT_IOKITLIB_H || HAVE_IOKIT_PS_IOPOWERSOURCES_H */
441
442 #elif KERNEL_LINUX
443         static c_complain_t acpi_dir_complaint = C_COMPLAIN_INIT_STATIC;
444
445         FILE *fh;
446         char buffer[1024];
447         char filename[256];
448         
449         char *fields[8];
450         int numfields;
451
452         int i;
453         int len;
454
455         for (i = 0; i < battery_pmu_num; i++)
456         {
457                 char    batnum_str[256];
458                 double  current = INVALID_VALUE;
459                 double  voltage = INVALID_VALUE;
460                 double  charge  = INVALID_VALUE;
461                 double *valptr = NULL;
462
463                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, i);
464                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
465                         continue;
466
467                 len = ssnprintf (batnum_str, sizeof (batnum_str), "%i", i);
468                 if ((len < 0) || ((unsigned int)len >= sizeof (batnum_str)))
469                         continue;
470
471                 if ((fh = fopen (filename, "r")) == NULL)
472                         continue;
473
474                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
475                 {
476                         numfields = strsplit (buffer, fields, 8);
477
478                         if (numfields < 3)
479                                 continue;
480
481                         if (strcmp ("current", fields[0]) == 0)
482                                 valptr = &current;
483                         else if (strcmp ("voltage", fields[0]) == 0)
484                                 valptr = &voltage;
485                         else if (strcmp ("charge", fields[0]) == 0)
486                                 valptr = &charge;
487                         else
488                                 valptr = NULL;
489
490                         if (valptr != NULL)
491                         {
492                                 char *endptr;
493
494                                 endptr = NULL;
495                                 errno  = 0;
496
497                                 *valptr = strtod (fields[2], &endptr) / 1000.0;
498
499                                 if ((fields[2] == endptr) || (errno != 0))
500                                         *valptr = INVALID_VALUE;
501                         }
502                 }
503
504                 fclose (fh);
505                 fh = NULL;
506
507                 if (charge != INVALID_VALUE)
508                         battery_submit ("0", "charge", charge);
509                 if (current != INVALID_VALUE)
510                         battery_submit ("0", "current", current);
511                 if (voltage != INVALID_VALUE)
512                         battery_submit ("0", "voltage", voltage);
513         }
514
515         if (0 == access (battery_acpi_dir, R_OK))
516                 walk_directory (battery_acpi_dir, battery_read_acpi,
517                                 /* user_data = */ NULL,
518                                 /* include hidden */ 0);
519         else
520         {
521                 char errbuf[1024];
522                 c_complain_once (LOG_WARNING, &acpi_dir_complaint,
523                                 "battery plugin: Failed to access `%s': %s",
524                                 battery_acpi_dir,
525                                 sstrerror (errno, errbuf, sizeof (errbuf)));
526         }
527
528 #endif /* KERNEL_LINUX */
529
530         return (0);
531 }
532
533 void module_register (void)
534 {
535         plugin_register_init ("battery", battery_init);
536         plugin_register_read ("battery", battery_read);
537 } /* void module_register */