Code

Merge branch 'collectd-4.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  **/
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
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
51 #if !HAVE_IOKIT_IOKITLIB_H && !HAVE_IOKIT_PS_IOPOWERSOURCES_H && !KERNEL_LINUX
52 # error "No applicable input method."
53 #endif
55 #define INVALID_VALUE 47841.29
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 */
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 */
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 */
73 #elif KERNEL_LINUX
74         int len;
75         char filename[128];
77         for (battery_pmu_num = 0; ; battery_pmu_num++)
78         {
79                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, battery_pmu_num);
81                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
82                         break;
84                 if (access (filename, R_OK))
85                         break;
86         }
87 #endif /* KERNEL_LINUX */
89         return (0);
90 }
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;
97         values[0].gauge = value;
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));
107         plugin_dispatch_values (&vl);
108 } /* void battery_submit */
110 #if HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H
111 double dict_get_double (CFDictionaryRef dict, char *key_string)
113         double      val_double;
114         long long   val_int;
115         CFNumberRef val_obj;
116         CFStringRef key_obj;
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         }
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);
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         }
156         return (val_double);
158 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H || HAVE_IOKIT_IOKITLIB_H */
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)
165         CFTypeRef       ps_raw;
166         CFArrayRef      ps_array;
167         int             ps_array_len;
168         CFDictionaryRef ps_dict;
169         CFTypeRef       ps_obj;
171         double temp_double;
172         int i;
174         ps_raw       = IOPSCopyPowerSourcesInfo ();
175         ps_array     = IOPSCopyPowerSourcesList (ps_raw);
176         ps_array_len = CFArrayGetCount (ps_array);
178         DEBUG ("ps_array_len == %i", ps_array_len);
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);
185                 if (ps_dict == NULL)
186                 {
187                         DEBUG ("IOPSGetPowerSourceDescription failed.");
188                         continue;
189                 }
191                 if (CFGetTypeID (ps_dict) != CFDictionaryGetTypeID ())
192                 {
193                         DEBUG ("IOPSGetPowerSourceDescription did not return a CFDictionaryRef");
194                         continue;
195                 }
197                 /* FIXME: Check if this is really an internal battery */
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                 }
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                 }
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         }
227         CFRelease(ps_array);
228         CFRelease(ps_raw);
230 #endif /* HAVE_IOKIT_PS_IOPOWERSOURCES_H */
232 #if HAVE_IOKIT_IOKITLIB_H
233 static void get_via_generic_iokit (double *ret_charge,
234                 double *ret_current,
235                 double *ret_voltage)
237         kern_return_t   status;
238         io_iterator_t   iterator;
239         io_object_t     io_obj;
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;
247         double temp_double;
249         status = IOServiceGetMatchingServices (kIOMasterPortDefault,
250                         IOServiceNameMatching ("battery"),
251                         &iterator);
252         if (status != kIOReturnSuccess)
253         {
254                 DEBUG ("IOServiceGetMatchingServices failed.");
255                 return;
256         }
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                 }
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);
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);
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                         }
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                         }
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         }
313         IOObjectRelease (iterator);
315 #endif /* HAVE_IOKIT_IOKITLIB_H */
317 #if KERNEL_LINUX
318 static int battery_read_acpi (const char *dir, const char *name,
319                 void *user_data)
321         double  current = INVALID_VALUE;
322         double  voltage = INVALID_VALUE;
323         double  charge  = INVALID_VALUE;
324         double *valptr = NULL;
325         int charging = 0;
327         char filename[256];
328         FILE *fh;
330         char buffer[1024];
331         char *fields[8];
332         int numfields;
333         char *endptr;
334         int len;
336         len = ssnprintf (filename, sizeof (filename), "%s/%s/state", battery_acpi_dir, name);
338         if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
339                 return -1;
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         }
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);
361                 if (numfields < 3)
362                         continue;
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                 }
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;
386                 endptr = NULL;
387                 errno  = 0;
388                 *valptr = strtod (fields[2], &endptr) / 1000.0;
390                 if ((fields[2] == endptr) || (errno != 0))
391                         *valptr = INVALID_VALUE;
392         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
394         fclose (fh);
396         if ((current != INVALID_VALUE) && (charging == 0))
397                         current *= -1;
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);
406         return 0;
408 #endif /* KERNEL_LINUX */
411 static int battery_read (void)
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 */
418         double charge_rel = INVALID_VALUE; /* Current charge in percent */
419         double charge_abs = INVALID_VALUE; /* Total capacity */
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
428         if ((charge_rel != INVALID_VALUE) && (charge_abs != INVALID_VALUE))
429                 charge = charge_abs * charge_rel / 100.0;
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 */
439 #elif KERNEL_LINUX
440         FILE *fh;
441         char buffer[1024];
442         char filename[256];
443         
444         char *fields[8];
445         int numfields;
447         int i;
448         int len;
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;
458                 len = ssnprintf (filename, sizeof (filename), battery_pmu_file, i);
459                 if ((len < 0) || ((unsigned int)len >= sizeof (filename)))
460                         continue;
462                 len = ssnprintf (batnum_str, sizeof (batnum_str), "%i", i);
463                 if ((len < 0) || ((unsigned int)len >= sizeof (batnum_str)))
464                         continue;
466                 if ((fh = fopen (filename, "r")) == NULL)
467                         continue;
469                 while (fgets (buffer, sizeof (buffer), fh) != NULL)
470                 {
471                         numfields = strsplit (buffer, fields, 8);
473                         if (numfields < 3)
474                                 continue;
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;
485                         if (valptr != NULL)
486                         {
487                                 char *endptr;
489                                 endptr = NULL;
490                                 errno  = 0;
492                                 *valptr = strtod (fields[2], &endptr) / 1000.0;
494                                 if ((fields[2] == endptr) || (errno != 0))
495                                         *valptr = INVALID_VALUE;
496                         }
497                 }
499                 fclose (fh);
500                 fh = NULL;
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         }
510         walk_directory (battery_acpi_dir, battery_read_acpi,
511                         /* user_data = */ NULL);
513 #endif /* KERNEL_LINUX */
515         return (0);
518 void module_register (void)
520         plugin_register_init ("battery", battery_init);
521         plugin_register_read ("battery", battery_read);
522 } /* void module_register */