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