Merge branch 'collectd-5.6'
[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
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     unsigned char pkt_request[1] = {0xAA};
74     int package_buffer_pos;
75
76     fd_set input;
77
78     /* Initialize timeout structure, set to 2 seconds */
79     struct timeval timeout = {
80       .tv_sec = 2
81     };
82
83     int end_flag;
84     int escape_flag;
85
86     int status;
87
88     assert (fd >= 0);
89
90     /* Initialize the input set*/
91     FD_ZERO (&input);
92     FD_SET (fd, &input);
93
94     /* clear out anything in the buffer */
95     tcflush (fd, TCIFLUSH);
96
97     status = write (fd, pkt_request, sizeof(pkt_request));
98     if (status <= 0)
99     {
100         ERROR ("ted plugin: swrite failed.");
101         return (-1);
102     }
103
104     /* Loop until we find the end of the package */
105     end_flag = 0;
106     package_buffer_pos = 0;
107     while (end_flag == 0)
108     {
109         ssize_t receive_buffer_length;
110
111         /* check for timeout or input error*/
112         status = select (fd + 1, &input, NULL, NULL, &timeout);
113         if (status == 0) /* Timeout */
114         {
115             WARNING ("ted plugin: Timeout while waiting for file descriptor "
116                     "to become ready.");
117             return (-1);
118         }
119         else if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
120         {
121             /* Some signal or something. Start over.. */
122             continue;
123         }
124         else if (status < 0)
125         {
126             char errbuf[1024];
127             ERROR ("ted plugin: select failed: %s",
128                     sstrerror (errno, errbuf, sizeof (errbuf)));
129             return (-1);
130         }
131
132         receive_buffer_length = read (fd, receive_buffer, sizeof (receive_buffer));
133         if (receive_buffer_length < 0)
134         {
135             char errbuf[1024];
136             if ((errno == EAGAIN) || (errno == EINTR))
137                 continue;
138             ERROR ("ted plugin: read(2) failed: %s",
139                     sstrerror (errno, errbuf, sizeof (errbuf)));
140             return (-1);
141         }
142         else if (receive_buffer_length == 0)
143         {
144             /* Should we close the FD in this case? */
145             WARNING ("ted plugin: Received EOF from file descriptor.");
146             return (-1);
147         }
148         else if (((size_t) receive_buffer_length) > sizeof (receive_buffer))
149         {
150             ERROR ("ted plugin: read(2) returned invalid value %zi.",
151                     receive_buffer_length);
152             return (-1);
153         }
154
155         /*
156          * packet filter loop
157          *
158          * Handle escape sequences in `receive_buffer' and put the
159          * result in `package_buffer'.
160          */
161         /* We need to see the begin sequence first. When we receive `ESCAPE
162          * PKT_BEGIN', we set `package_buffer_pos' to zero to signal that
163          * the beginning of the package has been found. */
164
165         escape_flag = 0;
166         for (ssize_t i = 0; i < receive_buffer_length; i++)
167         {
168             /* Check if previous byte was the escape byte. */
169             if (escape_flag == 1)
170             {
171                 escape_flag = 0;
172                 /* escape escape = single escape */
173                 if ((receive_buffer[i] == ESCAPE)
174                         && (package_buffer_pos >= 0))
175                 {
176                     package_buffer[package_buffer_pos] = ESCAPE;
177                     package_buffer_pos++;
178                 }
179                 else if (receive_buffer[i] == PKT_BEGIN)
180                 {
181                     package_buffer_pos = 0;
182                 }
183                 else if  (receive_buffer[i] == PKT_END)
184                 {
185                     end_flag = 1;
186                     break;
187                 }
188                 else
189                 {
190                     DEBUG ("ted plugin: Unknown escaped byte: %#x",
191                             (unsigned int) receive_buffer[i]);
192                 }
193             }
194             else if (receive_buffer[i] == ESCAPE)
195             {
196                 escape_flag = 1;
197             }
198             /* if we are in a package add byte to buffer
199              * otherwise throw away */
200             else if (package_buffer_pos >= 0)
201             {
202                 package_buffer[package_buffer_pos] = receive_buffer[i];
203                 package_buffer_pos++;
204             }
205         } /* for (i = 0; i < receive_buffer_length; i++) */
206     } /* while (end_flag == 0) */
207
208     /* Check for errors inside the loop. */
209     if ((end_flag == 0) || (package_buffer_pos != EXPECTED_PACKAGE_LENGTH))
210         return (-1);
211
212     /*
213      * Power is at positions 247 and 248 (LSB first) in [10kW].
214      * Voltage is at positions 251 and 252 (LSB first) in [.1V].
215      *
216      * Power is in 10 Watt steps
217      * Voltage is in volts
218      */
219     *ret_power = 10.0 * (double) ((((int) package_buffer[248]) * 256)
220             + ((int) package_buffer[247]));
221     *ret_voltage = 0.1 * (double) ((((int) package_buffer[252]) * 256)
222             + ((int) package_buffer[251]));
223
224     /* success */
225     return (0);
226 } /* int ted_read_value */
227
228 static int ted_open_device (void)
229 {
230     const char *dev;
231     struct termios options;
232
233     if (fd >= 0)
234         return (0);
235
236     dev = DEFAULT_DEVICE;
237     if (conf_device != NULL)
238         dev = conf_device;
239
240     fd = open (dev, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
241     if (fd < 0)
242     {
243         ERROR ("ted plugin: Unable to open device %s.", dev);
244         return (-1);
245     }
246
247     /* Get the current options for the port... */
248     tcgetattr(fd, &options);
249     options.c_cflag = B19200 | CS8 | CSTOPB | CREAD | CLOCAL;
250     options.c_iflag = IGNBRK | IGNPAR;
251     options.c_oflag = 0;
252     options.c_lflag = 0;
253     options.c_cc[VTIME] = 20;
254     options.c_cc[VMIN]  = 250;
255
256     /* Set the new options for the port... */
257     tcflush(fd, TCIFLUSH);
258     tcsetattr(fd, TCSANOW, &options);
259
260     INFO ("ted plugin: Successfully opened %s.", dev);
261     return (0);
262 } /* int ted_open_device */
263
264 static void ted_submit (const char *type, double value)
265 {
266     value_list_t vl = VALUE_LIST_INIT;
267
268     vl.values = &(value_t) { .gauge = value };
269     vl.values_len = 1;
270     sstrncpy (vl.plugin, "ted", sizeof (vl.plugin));
271     sstrncpy (vl.type, type, sizeof (vl.type));
272
273     plugin_dispatch_values (&vl);
274 }
275
276 static int ted_config (const char *key, const char *value)
277 {
278     if (strcasecmp ("Device", key) == 0)
279     {
280         sfree (conf_device);
281         conf_device = sstrdup (value);
282     }
283     else if (strcasecmp ("Retries", key) == 0)
284     {
285         int tmp;
286
287         tmp = atoi (value);
288         if (tmp < 0)
289         {
290             WARNING ("ted plugin: Invalid retry count: %i", tmp);
291             return (1);
292         }
293         conf_retries = tmp;
294     }
295     else
296     {
297         ERROR ("ted plugin: Unknown config option: %s", key);
298         return (-1);
299     }
300
301     return (0);
302 } /* int ted_config */
303
304 static int ted_read (void)
305 {
306     double power;
307     double voltage;
308     int status;
309
310     status = ted_open_device ();
311     if (status != 0)
312         return (-1);
313
314     power = NAN;
315     voltage = NAN;
316     for (int i = 0; i <= conf_retries; i++)
317     {
318         status = ted_read_value (&power, &voltage);
319         if (status == 0)
320             break;
321     }
322
323     if (status != 0)
324         return (-1);
325
326     ted_submit ("power", power);
327     ted_submit ("voltage", voltage);
328
329     return (0);
330 } /* int ted_read */
331
332 static int ted_shutdown (void)
333 {
334     if (fd >= 0)
335     {
336         close (fd);
337         fd = -1;
338     }
339
340     return (0);
341 } /* int ted_shutdown */
342
343 void module_register (void)
344 {
345     plugin_register_config ("ted", ted_config,
346             config_keys, config_keys_num);
347     plugin_register_read ("ted", ted_read);
348     plugin_register_shutdown ("ted", ted_shutdown);
349 } /* void module_register */
350
351 /* vim: set sw=4 et : */