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