]> mj.ucw.cz Git - home-hw.git/blob - influx/burrow-influx.c
6894062fc8e4ae80ab7a844a56a89f3e75357939
[home-hw.git] / influx / burrow-influx.c
1 /*
2  *      A gateway between MQTT and InfluxDB
3  *
4  *      (c) 2018--2020 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8 #include <ucw/fastbuf.h>
9 #include <ucw/log.h>
10 #include <ucw/opt.h>
11 #include <ucw/string.h>
12
13 #include <pthread.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <syslog.h>
18 #include <time.h>
19 #include <unistd.h>
20
21 #include <curl/curl.h>
22 #include <mosquitto.h>
23
24 #define MEASUREMENT_TIMEOUT 120
25
26 #define INFLUX_URL "http://localhost:8086/write?db=burrow&precision=s"
27 #define INFLUX_TIMEOUT 30
28 #define INFLUX_VERBOSE 0
29 #define INFLUX_INTERVAL 60
30
31 static struct mosquitto *mosq;
32
33 struct attr {
34         const char *metric;
35         const char *value_name;
36         const char *topic;
37         uint timeout;
38 };
39
40 static const struct attr attr_table[] = {
41         {
42                 .metric = "temp,where=loft",
43                 .value_name = "t",
44                 .topic = "burrow/temp/loft",
45         },
46         {
47                 .metric = "temp,where=ursarium",
48                 .value_name = "t",
49                 .topic = "burrow/temp/ursarium"
50         },
51         {
52                 .metric = "temp,where=catarium",
53                 .value_name = "t",
54                 .topic = "burrow/temp/catarium"
55         },
56         {
57                 .metric = "temp,where=garage",
58                 .value_name = "t",
59                 .topic = "burrow/temp/garage"
60         },
61         {
62                 .metric = "temp,where=kitchen",
63                 .value_name = "t",
64                 .topic = "burrow/temp/kitchen"
65         },
66         {
67                 .metric = "rh,where=ursarium",
68                 .value_name = "rh",
69                 .topic = "burrow/temp/ursarium-rh"
70         },
71         {
72                 .metric = "temp,where=catarium_clock",
73                 .value_name = "t",
74                 .topic = "burrow/temp/clock"
75         },
76         {
77                 .metric = "pressure,where=catarium_clock",
78                 .value_name = "pa",
79                 .topic = "burrow/pressure/clock"
80         },
81         {
82                 .metric = "air,where=inside_intake",
83                 .value_name = "t",
84                 .topic = "burrow/air/inside-intake",
85         },
86         {
87                 .metric = "air,where=inside_exhaust",
88                 .value_name = "t",
89                 .topic = "burrow/air/inside-exhaust",
90         },
91         {
92                 .metric = "air,where=outside_intake",
93                 .value_name = "t",
94                 .topic = "burrow/air/outside-intake",
95         },
96         {
97                 .metric = "air,where=outside_exhaust",
98                 .value_name = "t",
99                 .topic = "burrow/air/outside-exhaust",
100         },
101         {
102                 .metric = "air,where=mixed",
103                 .value_name = "t",
104                 .topic = "burrow/air/mixed",
105         },
106         {
107                 .metric = "air,where=inside_intake_avg",
108                 .value_name = "t",
109                 .topic = "burrow/avg/air/inside-intake",
110         },
111         {
112                 .metric = "air,where=outside_intake_avg",
113                 .value_name = "t",
114                 .topic = "burrow/avg/air/outside-intake",
115         },
116         {
117                 .metric = "air_bypass",
118                 .value_name = "on",
119                 .topic = "burrow/air/bypass"
120         },
121         {
122                 .metric = "air_fan_pwm",
123                 .value_name = "pwm",
124                 .topic = "burrow/air/exchanger-fan"
125         },
126 #if 0
127         {
128                 .metric = "loft_fan",
129                 .topic = "burrow/loft/fan"
130         },
131 #endif
132         {
133                 .metric = "water_circ",
134                 .value_name = "on",
135                 .topic = "burrow/loft/circulation"
136         },
137         {
138                 .metric = "pm_voltage,phase=L1N",
139                 .value_name = "V",
140                 .topic = "burrow/power/voltage/l1n",
141         },
142         {
143                 .metric = "pm_voltage,phase=L2N",
144                 .value_name = "V",
145                 .topic = "burrow/power/voltage/l2n",
146         },
147         {
148                 .metric = "pm_voltage,phase=L3N",
149                 .value_name = "V",
150                 .topic = "burrow/power/voltage/l3n",
151         },
152         {
153                 .metric = "pm_current,phase=L1",
154                 .value_name = "A",
155                 .topic = "burrow/power/current/l1",
156         },
157         {
158                 .metric = "pm_current,phase=L2",
159                 .value_name = "A",
160                 .topic = "burrow/power/current/l2",
161         },
162         {
163                 .metric = "pm_current,phase=L3",
164                 .value_name = "A",
165                 .topic = "burrow/power/current/l3",
166         },
167         {
168                 .metric = "pm_power",
169                 .value_name = "W",
170                 .topic = "burrow/power/power",
171         },
172         {
173                 .metric = "pm_energy",
174                 .value_name = "kWh",
175                 .topic = "burrow/power/energy",
176         },
177         {
178                 .metric = "pm_reactive_power",
179                 .value_name = "VAr",
180                 .topic = "burrow/power/reactive/power",
181         },
182         {
183                 .metric = "pm_reactive_energy",
184                 .value_name = "kVArh",
185                 .topic = "burrow/power/reactive/energy",
186         },
187         {
188                 .metric = "heating_water_pressure",
189                 .value_name = "p",
190                 .topic = "burrow/heating/water-pressure",
191                 .timeout = 300,
192         },
193         {
194                 .metric = "heating_outside_temp",
195                 .value_name = "t",
196                 .topic = "burrow/heating/outside-temp",
197                 .timeout = 300,
198         },
199         {
200                 .metric = "heating_room_temp,circuit=1",
201                 .value_name = "t",
202                 .topic = "burrow/heating/circuit1/room-temp",
203                 .timeout = 300,
204         },
205         {
206                 .metric = "heating_mix-temp,circuit=1",
207                 .value_name = "t",
208                 .topic = "burrow/heating/circuit1/mix-temp",
209                 .timeout = 300,
210         },
211         {
212                 .metric = "heating_mix-valve,circuit=1",
213                 .value_name = "x",
214                 .topic = "burrow/heating/circuit1/mix-valve",
215                 .timeout = 300,
216         },
217         {
218                 .metric = "heating_room_temp,circuit=2",
219                 .value_name = "t",
220                 .topic = "burrow/heating/circuit2/room-temp",
221                 .timeout = 300,
222         },
223 };
224
225 /*** MQTT ***/
226
227 static char *attr_values[ARRAY_SIZE(attr_table)];
228 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
229
230 static void mqtt_publish(const char *topic, const char *fmt, ...)
231 {
232         va_list args;
233         va_start(args, fmt);
234         char m[256];
235         int l = vsnprintf(m, sizeof(m), fmt, args);
236         if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
237                 msg(L_ERROR, "Mosquitto: publish failed");
238         va_end(args);
239 }
240
241 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
242 {
243         if (!status) {
244                 msg(L_DEBUG, "MQTT: Connection established, subscribing");
245                 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
246                         die("Mosquitto: subscribe failed");
247
248                 mqtt_publish("status/influx", "ok");
249         }
250 }
251
252 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
253 {
254         // msg(L_INFO, "MQTT(%d): %s", level, message);
255 }
256
257 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
258 {
259         char val[256];
260         if (m->payloadlen >= sizeof(val) - 1) {
261                 msg(L_ERROR, "Invalid value for topic %s", m->topic);
262                 return;
263         }
264         memcpy(val, m->payload, m->payloadlen);
265         val[m->payloadlen] = 0;
266         msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
267
268         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
269                 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
270                         pthread_mutex_lock(&attr_mutex);
271                         if (attr_values[i]) {
272                                 xfree(attr_values[i]);
273                                 attr_values[i] = NULL;
274                         }
275                         if (val[0])
276                                 attr_values[i] = xstrdup(val);
277                         pthread_mutex_unlock(&attr_mutex);
278                 }
279         }
280 }
281
282 /*** InfluxDB ***/
283
284 static CURL *curl;
285
286 static struct fastbuf *influx_fb;
287 static struct fastbuf *influx_err_fb;
288
289 static size_t influx_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata UNUSED)
290 {
291         ASSERT(size == 1);
292         for (size_t i=0; i<nmemb; i++) {
293                 int c = *(byte *)ptr;
294                 ptr++;
295                 if (c == '\r')
296                         continue;
297                 if (c == '\n')
298                         c = ' ';
299                 else if (c < 0x20 || c > 0x7e)
300                         c = '?';
301                 bputc(influx_err_fb, c);
302         }
303         return nmemb;
304 }
305
306 static void influx_init(void)
307 {
308         curl = curl_easy_init();
309         if (!curl)
310                 die("libcurl init failed");
311
312         curl_easy_setopt(curl, CURLOPT_URL, INFLUX_URL);
313         curl_easy_setopt(curl, CURLOPT_VERBOSE, (long) INFLUX_VERBOSE);
314         curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long) INFLUX_TIMEOUT);
315         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, influx_write_callback);
316
317         influx_fb = fbgrow_create(4096);
318         influx_err_fb = fbgrow_create(256);
319 }
320
321 static struct fastbuf *influx_write_start(void)
322 {
323         fbgrow_reset(influx_fb);
324         return influx_fb;
325 }
326
327 static void influx_write_flush(void)
328 {
329         bputc(influx_fb, 0);
330         byte *buf;
331         fbgrow_get_buf(influx_fb, &buf);
332         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf);
333
334         msg(L_DEBUG, "InfluxDB: Sending data (%u bytes)", strlen(buf));
335         if (INFLUX_VERBOSE)
336                 fprintf(stderr, "%s", buf);
337
338         fbgrow_reset(influx_err_fb);
339
340         CURLcode code = curl_easy_perform(curl);
341
342         if (code != CURLE_OK) {
343                 msg(L_ERROR, "Write to InfluxDB failed: %s", curl_easy_strerror(code));
344                 return;
345         }
346
347         long rc = 0;
348         curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
349         if (rc != 200 && rc != 204) {
350                 bputc(influx_err_fb, 0);
351                 byte *err;
352                 fbgrow_get_buf(influx_err_fb, &err);
353                 msg(L_DEBUG, "InfluxDB HTTP error %ld: %s [...]", rc, err);
354         }
355 }
356
357 /*** Main ***/
358
359 static int use_daemon;
360 static int use_debug;
361
362 static struct opt_section options = {
363         OPT_ITEMS {
364                 OPT_HELP("A daemon for transferring MQTT data to InfluxDB"),
365                 OPT_HELP(""),
366                 OPT_HELP("Options:"),
367                 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
368                 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
369                 OPT_HELP_OPTION,
370                 OPT_CONF_OPTIONS,
371                 OPT_END
372         }
373 };
374
375 int main(int argc UNUSED, char **argv)
376 {
377         log_init(argv[0]);
378         opt_parse(&options, argv+1);
379
380         if (use_daemon) {
381                 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
382                 log_set_default_stream(ls);
383         }
384         if (!use_debug)
385                 log_default_stream()->levels &= ~(1U << L_DEBUG);
386
387         mosquitto_lib_init();
388         mosq = mosquitto_new("influx", 1, NULL);
389         if (!mosq)
390                 die("Mosquitto: initialization failed");
391
392         mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
393         mosquitto_log_callback_set(mosq, mqtt_log_callback);
394         mosquitto_message_callback_set(mosq, mqtt_msg_callback);
395
396         if (mosquitto_will_set(mosq, "status/influx", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
397                 die("Mosquitto: unable to set will");
398
399         if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
400                 die("Mosquitto: connect failed");
401
402         if (mosquitto_loop_start(mosq))
403                 die("Mosquitto: cannot start service thread");
404
405         influx_init();
406
407         for (;;) {
408                 struct fastbuf *f = influx_write_start();
409                 char val[256], *w[2];
410                 time_t now = time(NULL);
411
412                 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
413                         const struct attr *a = &attr_table[i];
414
415                         pthread_mutex_lock(&attr_mutex);
416                         snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
417                         pthread_mutex_unlock(&attr_mutex);
418
419                         if (!val[0])
420                                 continue;
421                         int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
422                         if (fields < 1)
423                                 continue;
424                         if (fields >= 2) {
425                                 time_t t = atoll(w[1]);
426                                 uint timeout = a->timeout ? : MEASUREMENT_TIMEOUT;
427                                 if (t < now - timeout)
428                                         continue;
429                         }
430
431                         bprintf(f, "%s %s=%s\n", a->metric, a->value_name, val);
432                 }
433                 influx_write_flush();
434                 sleep(INFLUX_INTERVAL);
435         }
436 }