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