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