2 * A gateway between MQTT and InfluxDB
4 * (c) 2018--2020 Martin Mares <mj@ucw.cz>
8 #include <ucw/fastbuf.h>
11 #include <ucw/string.h>
21 #include <curl/curl.h>
22 #include <mosquitto.h>
24 #define MEASUREMENT_TIMEOUT 120
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
31 static struct mosquitto *mosq;
35 const char *value_name;
40 static const struct attr attr_table[] = {
42 .metric = "temp,where=loft",
44 .topic = "burrow/temp/loft",
47 .metric = "temp,where=ursarium",
49 .topic = "burrow/temp/ursarium"
52 .metric = "temp,where=catarium",
54 .topic = "burrow/temp/catarium"
57 .metric = "temp,where=garage",
59 .topic = "burrow/temp/garage"
62 .metric = "temp,where=kitchen",
64 .topic = "burrow/temp/kitchen"
67 .metric = "rh,where=ursarium",
69 .topic = "burrow/temp/ursarium-rh"
72 .metric = "temp,where=catarium_clock",
74 .topic = "burrow/temp/clock"
77 .metric = "pressure,where=catarium_clock",
79 .topic = "burrow/pressure/clock"
82 .metric = "air,where=inside_intake",
84 .topic = "burrow/air/inside-intake",
87 .metric = "air,where=inside_exhaust",
89 .topic = "burrow/air/inside-exhaust",
92 .metric = "air,where=outside_intake",
94 .topic = "burrow/air/outside-intake",
97 .metric = "air,where=outside_exhaust",
99 .topic = "burrow/air/outside-exhaust",
102 .metric = "air,where=mixed",
104 .topic = "burrow/air/mixed",
107 .metric = "air,where=inside_intake_avg",
109 .topic = "burrow/avg/air/inside-intake",
112 .metric = "air,where=outside_intake_avg",
114 .topic = "burrow/avg/air/outside-intake",
117 .metric = "air_bypass",
119 .topic = "burrow/air/bypass"
122 .metric = "air_fan_pwm",
124 .topic = "burrow/air/exchanger-fan"
128 .metric = "loft_fan",
129 .topic = "burrow/loft/fan"
133 .metric = "water_circ",
135 .topic = "burrow/loft/circulation"
138 .metric = "pm_voltage,phase=L1N",
140 .topic = "burrow/power/voltage/l1n",
143 .metric = "pm_voltage,phase=L2N",
145 .topic = "burrow/power/voltage/l2n",
148 .metric = "pm_voltage,phase=L3N",
150 .topic = "burrow/power/voltage/l3n",
153 .metric = "pm_current,phase=L1",
155 .topic = "burrow/power/current/l1",
158 .metric = "pm_current,phase=L2",
160 .topic = "burrow/power/current/l2",
163 .metric = "pm_current,phase=L3",
165 .topic = "burrow/power/current/l3",
168 .metric = "pm_power",
170 .topic = "burrow/power/power",
173 .metric = "pm_energy",
175 .topic = "burrow/power/energy",
178 .metric = "pm_reactive_power",
180 .topic = "burrow/power/reactive/power",
183 .metric = "pm_reactive_energy",
184 .value_name = "kVArh",
185 .topic = "burrow/power/reactive/energy",
188 .metric = "heating_water_pressure",
190 .topic = "burrow/heating/water-pressure",
194 .metric = "heating_outside_temp",
196 .topic = "burrow/heating/outside-temp",
200 .metric = "heating_room_temp,circuit=1",
202 .topic = "burrow/heating/circuit1/room-temp",
206 .metric = "heating_mix-temp,circuit=1",
208 .topic = "burrow/heating/circuit1/mix-temp",
212 .metric = "heating_mix-valve,circuit=1",
214 .topic = "burrow/heating/circuit1/mix-valve",
218 .metric = "heating_active,circuit=1",
220 .topic = "burrow/heating/circuit1/active",
224 .metric = "heating_pump_active,circuit=1",
226 .topic = "burrow/heating/circuit1/pump",
230 .metric = "heating_room_temp,circuit=2",
232 .topic = "burrow/heating/circuit2/room-temp",
236 .metric = "heating_active,circuit=2",
238 .topic = "burrow/heating/circuit2/active",
242 .metric = "heating_active,circuit=water",
244 .topic = "burrow/heating/water/active",
251 static char *attr_values[ARRAY_SIZE(attr_table)];
252 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
254 static void mqtt_publish(const char *topic, const char *fmt, ...)
259 int l = vsnprintf(m, sizeof(m), fmt, args);
260 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
261 msg(L_ERROR, "Mosquitto: publish failed");
265 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
268 msg(L_DEBUG, "MQTT: Connection established, subscribing");
269 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
270 die("Mosquitto: subscribe failed");
272 mqtt_publish("status/influx", "ok");
276 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
278 // msg(L_INFO, "MQTT(%d): %s", level, message);
281 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
284 if (m->payloadlen >= sizeof(val) - 1) {
285 msg(L_ERROR, "Invalid value for topic %s", m->topic);
288 memcpy(val, m->payload, m->payloadlen);
289 val[m->payloadlen] = 0;
290 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
292 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
293 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
294 pthread_mutex_lock(&attr_mutex);
295 if (attr_values[i]) {
296 xfree(attr_values[i]);
297 attr_values[i] = NULL;
300 attr_values[i] = xstrdup(val);
301 pthread_mutex_unlock(&attr_mutex);
310 static struct fastbuf *influx_fb;
311 static struct fastbuf *influx_err_fb;
313 static size_t influx_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata UNUSED)
316 for (size_t i=0; i<nmemb; i++) {
317 int c = *(byte *)ptr;
323 else if (c < 0x20 || c > 0x7e)
325 bputc(influx_err_fb, c);
330 static void influx_init(void)
332 curl = curl_easy_init();
334 die("libcurl init failed");
336 curl_easy_setopt(curl, CURLOPT_URL, INFLUX_URL);
337 curl_easy_setopt(curl, CURLOPT_VERBOSE, (long) INFLUX_VERBOSE);
338 curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long) INFLUX_TIMEOUT);
339 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, influx_write_callback);
341 influx_fb = fbgrow_create(4096);
342 influx_err_fb = fbgrow_create(256);
345 static struct fastbuf *influx_write_start(void)
347 fbgrow_reset(influx_fb);
351 static void influx_write_flush(void)
355 fbgrow_get_buf(influx_fb, &buf);
356 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf);
358 msg(L_DEBUG, "InfluxDB: Sending data (%u bytes)", strlen(buf));
360 fprintf(stderr, "%s", buf);
362 fbgrow_reset(influx_err_fb);
364 CURLcode code = curl_easy_perform(curl);
366 if (code != CURLE_OK) {
367 msg(L_ERROR, "Write to InfluxDB failed: %s", curl_easy_strerror(code));
372 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
373 if (rc != 200 && rc != 204) {
374 bputc(influx_err_fb, 0);
376 fbgrow_get_buf(influx_err_fb, &err);
377 msg(L_DEBUG, "InfluxDB HTTP error %ld: %s [...]", rc, err);
383 static int use_daemon;
384 static int use_debug;
386 static struct opt_section options = {
388 OPT_HELP("A daemon for transferring MQTT data to InfluxDB"),
390 OPT_HELP("Options:"),
391 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
392 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
399 int main(int argc UNUSED, char **argv)
402 opt_parse(&options, argv+1);
405 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
406 log_set_default_stream(ls);
409 log_default_stream()->levels &= ~(1U << L_DEBUG);
411 mosquitto_lib_init();
412 mosq = mosquitto_new("influx", 1, NULL);
414 die("Mosquitto: initialization failed");
416 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
417 mosquitto_log_callback_set(mosq, mqtt_log_callback);
418 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
420 if (mosquitto_will_set(mosq, "status/influx", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
421 die("Mosquitto: unable to set will");
423 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
424 die("Mosquitto: connect failed");
426 if (mosquitto_loop_start(mosq))
427 die("Mosquitto: cannot start service thread");
432 struct fastbuf *f = influx_write_start();
433 char val[256], *w[2];
434 time_t now = time(NULL);
436 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
437 const struct attr *a = &attr_table[i];
439 pthread_mutex_lock(&attr_mutex);
440 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
441 pthread_mutex_unlock(&attr_mutex);
445 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
449 time_t t = atoll(w[1]);
450 uint timeout = a->timeout ? : MEASUREMENT_TIMEOUT;
451 if (t < now - timeout)
455 bprintf(f, "%s %s=%s\n", a->metric, a->value_name, val);
457 influx_write_flush();
458 sleep(INFLUX_INTERVAL);