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