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