treewide: declare loop variable in loop expression
[collectd.git] / src / ted.c
1 /**
2  * collectd - src/ted.c
3  * Copyright (C) 2009  Eric Reed
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; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Eric Reed <ericr at reedhome.net>
21  *
22  *  This is a collectd module for The Energy Detective: A low-cost whole
23  * house energy monitoring system. For more information on TED, see
24  * http://theenergydetective.com
25  *
26  * This module was not created by Energy, Inc. nor is it supported by
27  * them in any way. It was created using information from two sources:
28  * David Satterfield's TED module for Misterhouse, and Micah Dowty's TED
29  * Python Module.
30  *
31  * This has only tested with the model 1001 RDU, with
32  * firmware version 9.01U. The USB port is uses the very common FTDI
33  * USB-to-serial chip, so the RDU will show up as a serial device on
34  * Windows, Mac OS, or Linux.
35  **/
36
37 #include "collectd.h"
38
39 #include "common.h"
40 #include "plugin.h"
41 #include "configfile.h"
42
43 #if HAVE_TERMIOS_H && HAVE_SYS_IOCTL_H && HAVE_MATH_H
44 # include <termios.h>
45 # include <sys/ioctl.h>
46 # include <math.h>
47 #else
48 # error "No applicable input method."
49 #endif
50
51 #define EXPECTED_PACKAGE_LENGTH 278
52 #define ESCAPE       0x10
53 #define PKT_BEGIN    0x04
54 #define PKT_END      0x03
55
56 #define DEFAULT_DEVICE "/dev/ttyUSB0"
57
58 static char *conf_device = NULL;
59 static int   conf_retries = 0;
60
61 static int fd = -1;
62
63 static const char *config_keys[] =
64 {
65     "Device",
66     "Retries"
67 };
68 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
69
70 static int ted_read_value(double *ret_power, double *ret_voltage)
71 {
72     unsigned char receive_buffer[300];
73     unsigned char package_buffer[300];
74     unsigned char pkt_request[1] = {0xAA};
75     int package_buffer_pos;
76
77     fd_set input;
78
79     /* Initialize timeout structure, set to 2 seconds */
80     struct timeval timeout = {
81       .tv_sec = 2
82     };
83
84     int end_flag;
85     int escape_flag;
86
87     int status;
88
89     assert (fd >= 0);
90
91     /* Initialize the input set*/
92     FD_ZERO (&input);
93     FD_SET (fd, &input);
94
95     /* clear out anything in the buffer */
96     tcflush (fd, TCIFLUSH);
97
98     status = write (fd, pkt_request, sizeof(pkt_request));
99     if (status <= 0)
100     {
101         ERROR ("ted plugin: swrite failed.");
102         return (-1);
103     }
104
105     /* Loop until we find the end of the package */
106     end_flag = 0;
107     package_buffer_pos = 0;
108     while (end_flag == 0)
109     {
110         ssize_t receive_buffer_length;
111
112         /* check for timeout or input error*/
113         status = select (fd + 1, &input, NULL, NULL, &timeout);
114         if (status == 0) /* Timeout */
115         {
116             WARNING ("ted plugin: Timeout while waiting for file descriptor "
117                     "to become ready.");
118             return (-1);
119         }
120         else if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
121         {
122             /* Some signal or something. Start over.. */
123             continue;
124         }
125         else if (status < 0)
126         {
127             char errbuf[1024];
128             ERROR ("ted plugin: select failed: %s",
129                     sstrerror (errno, errbuf, sizeof (errbuf)));
130             return (-1);
131         }
132
133         receive_buffer_length = read (fd, receive_buffer, sizeof (receive_buffer));
134         if (receive_buffer_length < 0)
135         {
136             char errbuf[1024];
137             if ((errno == EAGAIN) || (errno == EINTR))
138                 continue;
139             ERROR ("ted plugin: read(2) failed: %s",
140                     sstrerror (errno, errbuf, sizeof (errbuf)));
141             return (-1);
142         }
143         else if (receive_buffer_length == 0)
144         {
145             /* Should we close the FD in this case? */
146             WARNING ("ted plugin: Received EOF from file descriptor.");
147             return (-1);
148         }
149         else if (((size_t) receive_buffer_length) > sizeof (receive_buffer))
150         {
151             ERROR ("ted plugin: read(2) returned invalid value %zi.",
152                     receive_buffer_length);
153             return (-1);
154         }
155
156         /*
157          * packet filter loop
158          *
159          * Handle escape sequences in `receive_buffer' and put the
160          * result in `package_buffer'.
161          */
162         /* We need to see the begin sequence first. When we receive `ESCAPE
163          * PKT_BEGIN', we set `package_buffer_pos' to zero to signal that
164          * the beginning of the package has been found. */
165
166         escape_flag = 0;
167         for (ssize_t i = 0; i < receive_buffer_length; i++)
168         {
169             /* Check if previous byte was the escape byte. */
170             if (escape_flag == 1)
171             {
172                 escape_flag = 0;
173                 /* escape escape = single escape */
174                 if ((receive_buffer[i] == ESCAPE)
175                         && (package_buffer_pos >= 0))
176                 {
177                     package_buffer[package_buffer_pos] = ESCAPE;
178                     package_buffer_pos++;
179                 }
180                 else if (receive_buffer[i] == PKT_BEGIN)
181                 {
182                     package_buffer_pos = 0;
183                 }
184                 else if  (receive_buffer[i] == PKT_END)
185                 {
186                     end_flag = 1;
187                     break;
188                 }
189                 else
190                 {
191                     DEBUG ("ted plugin: Unknown escaped byte: %#x",
192                             (unsigned int) receive_buffer[i]);
193                 }
194             }
195             else if (receive_buffer[i] == ESCAPE)
196             {
197                 escape_flag = 1;
198             }
199             /* if we are in a package add byte to buffer
200              * otherwise throw away */
201             else if (package_buffer_pos >= 0)
202             {
203                 package_buffer[package_buffer_pos] = receive_buffer[i];
204                 package_buffer_pos++;
205             }
206         } /* for (i = 0; i < receive_buffer_length; i++) */
207     } /* while (end_flag == 0) */
208
209     /* Check for errors inside the loop. */
210     if ((end_flag == 0) || (package_buffer_pos != EXPECTED_PACKAGE_LENGTH))
211         return (-1);
212
213     /*
214      * Power is at positions 247 and 248 (LSB first) in [10kW].
215      * Voltage is at positions 251 and 252 (LSB first) in [.1V].
216      *
217      * Power is in 10 Watt steps
218      * Voltage is in volts
219      */
220     *ret_power = 10.0 * (double) ((((int) package_buffer[248]) * 256)
221             + ((int) package_buffer[247]));
222     *ret_voltage = 0.1 * (double) ((((int) package_buffer[252]) * 256)
223             + ((int) package_buffer[251]));
224
225     /* success */
226     return (0);
227 } /* int ted_read_value */
228
229 static int ted_open_device (void)
230 {
231     const char *dev;
232     struct termios options;
233
234     if (fd >= 0)
235         return (0);
236
237     dev = DEFAULT_DEVICE;
238     if (conf_device != NULL)
239         dev = conf_device;
240
241     fd = open (dev, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
242     if (fd < 0)
243     {
244         ERROR ("ted plugin: Unable to open device %s.", dev);
245         return (-1);
246     }
247
248     /* Get the current options for the port... */
249     tcgetattr(fd, &options);
250     options.c_cflag = B19200 | CS8 | CSTOPB | CREAD | CLOCAL;
251     options.c_iflag = IGNBRK | IGNPAR;
252     options.c_oflag = 0;
253     options.c_lflag = 0;
254     options.c_cc[VTIME] = 20;
255     options.c_cc[VMIN]  = 250;
256
257     /* Set the new options for the port... */
258     tcflush(fd, TCIFLUSH);
259     tcsetattr(fd, TCSANOW, &options);
260
261     INFO ("ted plugin: Successfully opened %s.", dev);
262     return (0);
263 } /* int ted_open_device */
264
265 static void ted_submit (const char *type, double value)
266 {
267     value_t values[1];
268     value_list_t vl = VALUE_LIST_INIT;
269
270     values[0].gauge = value;
271
272     vl.values = values;
273     vl.values_len = 1;
274     sstrncpy (vl.host, hostname_g, sizeof (vl.host));
275     sstrncpy (vl.plugin, "ted", sizeof (vl.plugin));
276     sstrncpy (vl.type, type, sizeof (vl.type));
277
278     plugin_dispatch_values (&vl);
279 }
280
281 static int ted_config (const char *key, const char *value)
282 {
283     if (strcasecmp ("Device", key) == 0)
284     {
285         sfree (conf_device);
286         conf_device = sstrdup (value);
287     }
288     else if (strcasecmp ("Retries", key) == 0)
289     {
290         int tmp;
291
292         tmp = atoi (value);
293         if (tmp < 0)
294         {
295             WARNING ("ted plugin: Invalid retry count: %i", tmp);
296             return (1);
297         }
298         conf_retries = tmp;
299     }
300     else
301     {
302         ERROR ("ted plugin: Unknown config option: %s", key);
303         return (-1);
304     }
305
306     return (0);
307 } /* int ted_config */
308
309 static int ted_read (void)
310 {
311     double power;
312     double voltage;
313     int status;
314
315     status = ted_open_device ();
316     if (status != 0)
317         return (-1);
318
319     power = NAN;
320     voltage = NAN;
321     for (int i = 0; i <= conf_retries; i++)
322     {
323         status = ted_read_value (&power, &voltage);
324         if (status == 0)
325             break;
326     }
327
328     if (status != 0)
329         return (-1);
330
331     ted_submit ("power", power);
332     ted_submit ("voltage", voltage);
333
334     return (0);
335 } /* int ted_read */
336
337 static int ted_shutdown (void)
338 {
339     if (fd >= 0)
340     {
341         close (fd);
342         fd = -1;
343     }
344
345     return (0);
346 } /* int ted_shutdown */
347
348 void module_register (void)
349 {
350     plugin_register_config ("ted", ted_config,
351             config_keys, config_keys_num);
352     plugin_register_read ("ted", ted_read);
353     plugin_register_shutdown ("ted", ted_shutdown);
354 } /* void module_register */
355
356 /* vim: set sw=4 et : */