ted plugin: Fix some rough edges.
[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 #include "common.h"
39 #include "plugin.h"
40 #include "configfile.h"
41
42 #if HAVE_TERMIOS_H && HAVE_SYS_IOCTL_H && HAVE_MATH_H
43 # include <termios.h>
44 # include <sys/ioctl.h>
45 # include <math.h>
46 #else
47 # error "No applicable input method."
48 #endif
49
50 #define EXPECTED_PACKAGE_LENGTH 278
51 #define ESCAPE       0x10
52 #define PKT_BEGIN    0x04
53 #define PKT_END      0x03
54
55 #define DEFAULT_DEVICE "/dev/ttyUSB0"
56
57 static char *conf_device = NULL;
58 static int   conf_retries = 0;
59
60 static int fd = -1;
61
62 static const char *config_keys[] =
63 {
64     "Device",
65     "Retries"
66 };
67 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
68
69 static int ted_read_value(double *ret_power, double *ret_voltage)
70 {
71     unsigned char receive_buffer[300];
72     unsigned char package_buffer[300];
73     char pkt_request[1] = {0xAA};
74     int package_buffer_pos;
75
76     fd_set input;
77     struct timeval timeout;
78
79     int end_flag;
80     int escape_flag;
81
82     int status;
83
84     assert (fd >= 0);
85
86     /* Initialize the input set*/
87     FD_ZERO (&input);
88     FD_SET (fd, &input);
89
90     /* Initialize timeout structure, set to 2 seconds */
91     memset (&timeout, 0, sizeof (timeout));
92     timeout.tv_sec = 2;
93     timeout.tv_usec = 0;
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     escape_flag = 0;
108     package_buffer_pos = -1;
109     while (end_flag == 0)
110     {
111         ssize_t receive_buffer_length;
112         ssize_t i;
113
114         /* check for timeout or input error*/
115         status = select (fd + 1, &input, NULL, NULL, &timeout);
116         if (status == 0) /* Timeout */
117         {
118             WARNING ("ted plugin: Timeout while waiting for file descriptor "
119                     "to become ready.");
120             return (-1);
121         }
122         else if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
123         {
124             /* Some signal or something. Start over.. */
125             continue;
126         }
127         else if (status < 0)
128         {
129             char errbuf[1024];
130             ERROR ("ted plugin: select failed: %s",
131                     sstrerror (errno, errbuf, sizeof (errbuf)));
132             return (-1);
133         }
134
135         receive_buffer_length = read (fd, receive_buffer, sizeof (receive_buffer));
136         if (receive_buffer_length < 0)
137         {
138             char errbuf[1024];
139             if ((errno == EAGAIN) || (errno == EINTR))
140                 continue;
141             ERROR ("ted plugin: read(2) failed: %s",
142                     sstrerror (errno, errbuf, sizeof (errbuf)));
143             return (-1);
144         }
145         else if (receive_buffer_length == 0)
146         {
147             /* Should we close the FD in this case? */
148             WARNING ("ted plugin: Received EOF from file descriptor.");
149             return (-1);
150         }
151         else if (receive_buffer_length > sizeof (receive_buffer))
152         {
153             ERROR ("ted plugin: read(2) returned invalid value %zi.",
154                     receive_buffer_length);
155             return (-1);
156         }
157         else if (receive_buffer_length < EXPECTED_PACKAGE_LENGTH)
158         {
159             WARNING ("ted plugin: read(2) returned %zi bytes, "
160                     "but at least %i are necessary for a valid packet.",
161                     receive_buffer_length, EXPECTED_PACKAGE_LENGTH);
162             return (-1);
163         }
164
165         /*
166          * packet filter loop
167          *
168          * Handle escape sequences in `receive_buffer' and put the
169          * result in `package_buffer'.
170          */
171         /* We need to see the begin sequence first. When we receive `ESCAPE
172          * PKT_BEGIN', we set `package_buffer_pos' to zero to signal that
173          * the beginning of the package has been found. */
174         package_buffer_pos = -1;
175         escape_flag = 0;
176         for (i = 0; i < receive_buffer_length; i++)
177         {
178             /* Check if previous byte was the escape byte. */
179             if (escape_flag == 1)
180             {
181                 escape_flag = 0;
182                 /* escape escape = single escape */
183                 if ((receive_buffer[i] == ESCAPE)
184                         && (package_buffer_pos >= 0))
185                 {
186                     package_buffer[package_buffer_pos] = ESCAPE;
187                     package_buffer_pos++;
188                 }
189                 else if (receive_buffer[i] == PKT_BEGIN)
190                 {
191                     package_buffer_pos = 0;
192                 }
193                 else if  (receive_buffer[i] == PKT_END)
194                 {
195                     end_flag = 1;
196                     break;
197                 }
198                 else
199                 {
200                     DEBUG ("ted plugin: Unknown escaped byte: %#x",
201                             (unsigned int) receive_buffer[i]);
202                 }
203             }
204             else if (receive_buffer[i] == ESCAPE)
205             {
206                 escape_flag = 1;
207             }
208             /* if we are in a package add byte to buffer
209              * otherwise throw away */
210             else if (package_buffer_pos >= 0)
211             {
212                 package_buffer[package_buffer_pos] = receive_buffer[i];
213                 package_buffer_pos++;
214             }
215         } /* for (i = 0; i < receive_buffer_length; i++) */
216     } /* while (end_flag == 0) */
217
218     /* Check for errors inside the loop. */
219     if (end_flag == 0)
220         return (-1);
221
222     /* 
223      * Power is at positions 247 and 248 (LSB first) in [10kW].
224      * Voltage is at positions 251 and 252 (LSB first) in [.1V].
225      *
226      * According to Eric's patch the power is in 10kW steps, but according to a
227      * Python module I've found, it's in 0.01kW == 10W. IMHO the Python scale
228      * is more realistic. -octo
229      */
230     *ret_power = 10.0 * (double) ((((int) package_buffer[248]) * 256)
231             + ((int) package_buffer[247]));
232     *ret_voltage = 0.1 * (double) ((((int) package_buffer[252]) * 256)
233             + ((int) package_buffer[251]));
234
235     /* success */
236     return (0);
237 } /* int ted_read_value */
238
239 static int ted_open_device (void)
240 {
241     const char *dev;
242     struct termios options;
243
244     if (fd >= 0)
245         return (0);
246
247     dev = DEFAULT_DEVICE;
248     if (conf_device != NULL)
249         dev = conf_device;
250
251     fd = open (dev, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
252     if (fd < 0)
253     {
254         ERROR ("ted plugin: Unable to open device %s.", dev);
255         return (-1);
256     }
257
258     /* Get the current options for the port... */
259     tcgetattr(fd, &options);
260     options.c_cflag = B19200 | CS8 | CSTOPB | CREAD | CLOCAL;
261     options.c_iflag = IGNBRK | IGNPAR;
262     options.c_oflag = 0;
263     options.c_lflag = 0;
264     options.c_cc[VTIME] = 20;
265     options.c_cc[VMIN]  = 250;
266
267     /* Set the new options for the port... */
268     tcflush(fd, TCIFLUSH);
269     tcsetattr(fd, TCSANOW, &options);
270
271     INFO ("ted plugin: Successfully opened %s.", dev);
272     return (0);
273 } /* int ted_open_device */
274
275 static void ted_submit (char *type_instance, double value)
276 {
277     value_t values[1];
278     value_list_t vl = VALUE_LIST_INIT;
279
280     values[0].gauge = value;
281
282     vl.values = values;
283     vl.values_len = 1;
284     sstrncpy (vl.host, hostname_g, sizeof (vl.host));
285     sstrncpy (vl.plugin, "ted", sizeof (vl.plugin));
286     sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
287     sstrncpy (vl.type, "ted", sizeof (vl.type));
288
289     plugin_dispatch_values (&vl);
290 }
291
292 static int ted_config (const char *key, const char *value)
293 {
294     if (strcasecmp ("Device", key) == 0)
295     {
296         sfree (conf_device);
297         conf_device = sstrdup (value);
298     }
299     else if (strcasecmp ("Retries", key) == 0)
300     {
301         int tmp;
302
303         tmp = atoi (value);
304         if (tmp < 0)
305         {
306             WARNING ("ted plugin: Invalid retry count: %i", tmp);
307             return (1);
308         }
309         conf_retries = tmp;
310     }
311     else
312     {
313         ERROR ("ted plugin: Unknown config option: %s", key);
314         return (-1);
315     }
316
317     return (0);
318 } /* int ted_config */
319
320 static int ted_read (void)
321 {
322     double power;
323     double voltage;
324     int status;
325     int i;
326
327     status = ted_open_device ();
328     if (status != 0)
329         return (-1);
330
331     power = NAN;
332     voltage = NAN;
333     for (i = 0; i <= conf_retries; i++)
334     {
335         status = ted_read_value (&power, &voltage);
336         if (status == 0)
337             break;
338     }
339
340     if (status != 0)
341         return (-1);
342
343     ted_submit ("power", power);
344     ted_submit ("voltage", voltage);
345
346     return (0);
347 } /* int ted_read */
348
349 static int ted_shutdown (void)
350 {
351     if (fd >= 0)
352     {
353         close (fd);
354         fd = -1;
355     }
356
357     return (0);
358 } /* int ted_shutdown */
359
360 void module_register (void)
361 {
362     plugin_register_config ("ted", ted_config,
363             config_keys, config_keys_num);
364     plugin_register_read ("ted", ted_read);
365     plugin_register_shutdown ("ted", ted_shutdown);
366 } /* void module_register */
367
368 /* vim: set sw=4 et : */