2 * A gateway between MQTT and InfluxDB
4 * (c) 2018--2019 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;
39 static const struct attr attr_table[] = {
41 .metric = "temp,where=loft",
43 .topic = "burrow/temp/loft",
46 .metric = "temp,where=ursarium",
48 .topic = "burrow/temp/ursarium"
51 .metric = "temp,where=catarium",
53 .topic = "burrow/temp/catarium"
56 .metric = "temp,where=garage",
58 .topic = "burrow/temp/garage"
61 .metric = "temp,where=kitchen",
63 .topic = "burrow/temp/kitchen"
66 .metric = "rh,where=ursarium",
68 .topic = "burrow/temp/ursarium-rh"
71 .metric = "temp,where=catarium_clock",
73 .topic = "burrow/temp/clock"
76 .metric = "pressure,where=catarium_clock",
78 .topic = "burrow/pressure/clock"
81 .metric = "air,where=inside_intake",
83 .topic = "burrow/air/inside-intake",
86 .metric = "air,where=inside_exhaust",
88 .topic = "burrow/air/inside-exhaust",
91 .metric = "air,where=outside_intake",
93 .topic = "burrow/air/outside-intake",
96 .metric = "air,where=outside_exhaust",
98 .topic = "burrow/air/outside-exhaust",
101 .metric = "air,where=mixed",
103 .topic = "burrow/air/mixed",
106 .metric = "air,where=inside_intake_avg",
108 .topic = "burrow/avg/air/inside-intake",
111 .metric = "air,where=outside_intake_avg",
113 .topic = "burrow/avg/air/outside-intake",
116 .metric = "air_bypass",
118 .topic = "burrow/air/bypass"
121 .metric = "air_fan_pwm",
123 .topic = "burrow/air/exchanger-fan"
127 .metric = "loft_fan",
128 .topic = "burrow/loft/fan"
132 .metric = "water_circ",
134 .topic = "burrow/loft/circulation"
137 .metric = "pm_voltage,phase=L1N",
139 .topic = "burrow/power/voltage/l1n",
142 .metric = "pm_voltage,phase=L2N",
144 .topic = "burrow/power/voltage/l2n",
147 .metric = "pm_voltage,phase=L3N",
149 .topic = "burrow/power/voltage/l3n",
152 .metric = "pm_current,phase=L1",
154 .topic = "burrow/power/current/l1",
157 .metric = "pm_current,phase=L2",
159 .topic = "burrow/power/current/l2",
162 .metric = "pm_current,phase=L3",
164 .topic = "burrow/power/current/l3",
167 .metric = "pm_power",
169 .topic = "burrow/power/power",
172 .metric = "pm_energy",
174 .topic = "burrow/power/energy",
177 .metric = "pm_reactive_power",
179 .topic = "burrow/power/reactive/power",
182 .metric = "pm_reactive_energy",
183 .value_name = "kVArh",
184 .topic = "burrow/power/reactive/energy",
190 static char *attr_values[ARRAY_SIZE(attr_table)];
191 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
193 static void mqtt_publish(const char *topic, const char *fmt, ...)
198 int l = vsnprintf(m, sizeof(m), fmt, args);
199 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
200 msg(L_ERROR, "Mosquitto: publish failed");
204 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
207 msg(L_DEBUG, "MQTT: Connection established, subscribing");
208 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
209 die("Mosquitto: subscribe failed");
211 mqtt_publish("status/influx", "ok");
215 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
217 // msg(L_INFO, "MQTT(%d): %s", level, message);
220 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
223 if (m->payloadlen >= sizeof(val) - 1) {
224 msg(L_ERROR, "Invalid value for topic %s", m->topic);
227 memcpy(val, m->payload, m->payloadlen);
228 val[m->payloadlen] = 0;
229 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
231 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
232 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
233 pthread_mutex_lock(&attr_mutex);
234 if (attr_values[i]) {
235 xfree(attr_values[i]);
236 attr_values[i] = NULL;
239 attr_values[i] = xstrdup(val);
240 pthread_mutex_unlock(&attr_mutex);
249 static struct fastbuf *influx_fb;
250 static struct fastbuf *influx_err_fb;
252 static size_t influx_write_callback(char *ptr, size_t size, size_t nmemb, void *userdata UNUSED)
255 for (size_t i=0; i<nmemb; i++) {
256 int c = *(byte *)ptr;
262 else if (c < 0x20 || c > 0x7e)
264 bputc(influx_err_fb, c);
269 static void influx_init(void)
271 curl = curl_easy_init();
273 die("libcurl init failed");
275 curl_easy_setopt(curl, CURLOPT_URL, INFLUX_URL);
276 curl_easy_setopt(curl, CURLOPT_VERBOSE, (long) INFLUX_VERBOSE);
277 curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long) INFLUX_TIMEOUT);
278 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, influx_write_callback);
280 influx_fb = fbgrow_create(4096);
281 influx_err_fb = fbgrow_create(256);
284 static struct fastbuf *influx_write_start(void)
286 fbgrow_reset(influx_fb);
290 static void influx_write_flush(void)
294 fbgrow_get_buf(influx_fb, &buf);
295 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf);
297 msg(L_DEBUG, "InfluxDB: Sending data (%u bytes)", strlen(buf));
299 fprintf(stderr, "%s", buf);
301 fbgrow_reset(influx_err_fb);
303 CURLcode code = curl_easy_perform(curl);
305 if (code != CURLE_OK) {
306 msg(L_ERROR, "Write to InfluxDB failed: %s", curl_easy_strerror(code));
311 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rc);
312 if (rc != 200 && rc != 204) {
313 bputc(influx_err_fb, 0);
315 fbgrow_get_buf(influx_err_fb, &err);
316 msg(L_DEBUG, "InfluxDB HTTP error %ld: %s [...]", rc, err);
322 static int use_daemon;
323 static int use_debug;
325 static struct opt_section options = {
327 OPT_HELP("A daemon for transferring MQTT data to InfluxDB"),
329 OPT_HELP("Options:"),
330 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
331 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
338 int main(int argc UNUSED, char **argv)
341 opt_parse(&options, argv+1);
344 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
345 log_set_default_stream(ls);
348 log_default_stream()->levels &= ~(1U << L_DEBUG);
350 mosquitto_lib_init();
351 mosq = mosquitto_new("influx", 1, NULL);
353 die("Mosquitto: initialization failed");
355 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
356 mosquitto_log_callback_set(mosq, mqtt_log_callback);
357 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
359 if (mosquitto_will_set(mosq, "status/influx", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
360 die("Mosquitto: unable to set will");
362 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
363 die("Mosquitto: connect failed");
365 if (mosquitto_loop_start(mosq))
366 die("Mosquitto: cannot start service thread");
371 struct fastbuf *f = influx_write_start();
372 char val[256], *w[2];
373 time_t now = time(NULL);
375 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
376 const struct attr *a = &attr_table[i];
378 pthread_mutex_lock(&attr_mutex);
379 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
380 pthread_mutex_unlock(&attr_mutex);
384 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
388 time_t t = atoll(w[1]);
389 if (t < now - MEASUREMENT_TIMEOUT)
393 bprintf(f, "%s %s=%s\n", a->metric, a->value_name, val);
395 influx_write_flush();
396 sleep(INFLUX_INTERVAL);