2 * A gateway between MQTT and Prometheus
4 * (c) 2018--2019 Martin Mares <mj@ucw.cz>
8 #include <ucw/fastbuf.h>
10 #include <ucw/mempool.h>
12 #include <ucw/string.h>
14 #include <netinet/in.h>
21 #include <sys/socket.h>
26 #include <mosquitto.h>
28 #define MEASUREMENT_TIMEOUT 120
30 static struct mosquitto *mosq;
39 static const struct attr attr_table[] = {
41 .metric = "temp_loft",
42 .help = "Temperature in the loft [degC]",
44 .topic = "burrow/temp/loft",
48 .help = "Fan speed in the loft (0-3)",
50 .topic = "burrow/loft/fan"
53 .metric = "loft_circ",
54 .help = "Warm water circulation (0-1)",
56 .topic = "burrow/loft/circulation"
59 .metric = "temp_ursarium",
60 .help = "Temperature in the Ursarium [degC]",
62 .topic = "burrow/temp/ursarium"
65 .metric = "temp_catarium",
66 .help = "Temperature in the Catarium [degC]",
68 .topic = "burrow/temp/catarium"
71 .metric = "temp_garage",
72 .help = "Temperature in the garage [degC]",
74 .topic = "burrow/temp/garage"
77 .metric = "temp_kitchen",
78 .help = "Temperature in the kitchen [degC]",
80 .topic = "burrow/temp/kitchen"
83 .metric = "rh_ursarium",
84 .help = "Relative humidity in the Ursarium [%]",
86 .topic = "burrow/temp/ursarium-rh"
89 .metric = "temp_catarium_clock",
90 .help = "Temperature on Catarium clock [degC]",
92 .topic = "burrow/temp/clock"
95 .metric = "press_catarium_clock",
96 .help = "Pressure on Catarium clock [Pa]",
98 .topic = "burrow/pressure/clock"
101 .metric = "air_inside_intake",
102 .help = "Temperature of air intake from inside [degC]",
104 .topic = "burrow/air/inside-intake",
107 .metric = "air_inside_exhaust",
108 .help = "Temperature of air exhaust to inside [degC]",
110 .topic = "burrow/air/inside-exhaust",
113 .metric = "air_outside_intake",
114 .help = "Temperature of air intake from outside [degC]",
116 .topic = "burrow/air/outside-intake",
119 .metric = "air_outside_exhaust",
120 .help = "Temperature of air exhaust to outside [degC]",
122 .topic = "burrow/air/outside-exhaust",
125 .metric = "air_mixed",
126 .help = "Temperature of mixed air [degC]",
128 .topic = "burrow/air/mixed",
131 .metric = "air_bypass",
132 .help = "Heat exchanger bypass (0-1)",
134 .topic = "burrow/air/bypass"
137 .metric = "air_fan_pwm",
138 .help = "Heat exchanger fan PWM (0-255)",
140 .topic = "burrow/air/fan-pwm"
143 // Common heading for all voltages
144 .metric = "pm_voltage",
145 .help = "Voltage between phases and neutral [V]",
149 .metric = "pm_voltage{phase=\"L1N\"}",
150 .topic = "burrow/power/voltage/l1n",
153 .metric = "pm_voltage{phase=\"L2N\"}",
154 .topic = "burrow/power/voltage/l2n",
157 .metric = "pm_voltage{phase=\"L3N\"}",
158 .topic = "burrow/power/voltage/l3n",
161 // Common heading for all currents
162 .metric = "pm_current",
163 .help = "Current through phases [A]",
167 .metric = "pm_current{phase=\"L1\"}",
168 .topic = "burrow/power/current/l1",
171 .metric = "pm_current{phase=\"L2\"}",
172 .topic = "burrow/power/current/l2",
175 .metric = "pm_current{phase=\"L3\"}",
176 .topic = "burrow/power/current/l3",
179 .metric = "pm_power",
180 .help = "Total power [W]",
182 .topic = "burrow/power/power",
185 .metric = "pm_energy",
186 .help = "Total energy [kWh]",
188 .topic = "burrow/power/energy",
191 .metric = "pm_reactive_power",
192 .help = "Total reactive power [VAr]",
194 .topic = "burrow/power/reactive/power",
197 .metric = "pm_reactive_energy",
198 .help = "Total reactive energy [kVArh]",
200 .topic = "burrow/power/reactive/energy",
204 static char *attr_values[ARRAY_SIZE(attr_table)];
205 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
207 static void mqtt_publish(const char *topic, const char *fmt, ...)
212 int l = vsnprintf(m, sizeof(m), fmt, args);
213 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
214 msg(L_ERROR, "Mosquitto: publish failed");
218 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
221 msg(L_DEBUG, "MQTT: Connection established, subscribing");
222 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
223 die("Mosquitto: subscribe failed");
225 mqtt_publish("status/prometheus", "ok");
229 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
231 // msg(L_INFO, "MQTT(%d): %s", level, message);
234 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
237 if (m->payloadlen >= sizeof(val) - 1) {
238 msg(L_ERROR, "Invalid value for topic %s", m->topic);
241 memcpy(val, m->payload, m->payloadlen);
242 val[m->payloadlen] = 0;
243 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
245 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
246 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
247 pthread_mutex_lock(&attr_mutex);
248 if (attr_values[i]) {
249 xfree(attr_values[i]);
250 attr_values[i] = NULL;
253 attr_values[i] = xstrdup(val);
254 pthread_mutex_unlock(&attr_mutex);
263 uint iobuf_pos, iobuf_max;
265 struct fbpool fbpool;
268 #define IO_TIMEOUT 60000 // in ms
269 #define IOBUF_SIZE 1024
270 #define LINEBUF_SIZE 1024
272 static void http_send(struct http *http)
274 byte *buf = fbpool_end(&http->fbpool);
275 uint len = mp_size(http->mp, buf);
278 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
279 int res = poll(&pfd, 1, IO_TIMEOUT);
281 die("Poll failed: %m");
283 msg(L_ERROR, "HTTP write timed out");
287 res = write(http->sk, buf, len);
289 msg(L_ERROR, "HTTP write failed: %m");
297 static void http_error(struct http *http, const char *err)
299 msg(L_INFO, "HTTP error: %s", err);
300 fbpool_start(&http->fbpool, http->mp, 0);
301 bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
305 static int http_get_char(struct http *http) {
306 if (http->iobuf_pos >= http->iobuf_max) {
307 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
308 int res = poll(&pfd, 1, IO_TIMEOUT);
310 die("Poll failed: %m");
312 msg(L_ERROR, "HTTP read timed out");
315 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
317 msg(L_ERROR, "HTTP read error: %m");
321 msg(L_ERROR, "HTTP connection closed");
325 http->iobuf_max = len;
327 return http->iobuf[http->iobuf_pos++];
330 static bool http_get_line(struct http *http)
334 int c = http_get_char(http);
338 if (i > 0 && http->linebuf[i-1] == '\r')
340 http->linebuf[i] = 0;
343 if (i >= IOBUF_SIZE-1) {
344 http_error(http, "400 Line too long");
347 http->linebuf[i++] = c;
351 static void http_answer(struct fastbuf *fb)
353 char val[256], *w[2];
354 time_t now = time(NULL);
356 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
357 const struct attr *a = &attr_table[i];
359 pthread_mutex_lock(&attr_mutex);
360 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
361 pthread_mutex_unlock(&attr_mutex);
364 bprintf(fb, "# HELP %s %s\n", a->metric, a->help);
366 bprintf(fb, "# TYPE %s %s\n", a->metric, a->type);
370 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
374 time_t t = atoll(w[1]);
375 if (t < now - MEASUREMENT_TIMEOUT)
380 bprintf(fb, "%s %s", a->metric, val);
382 // Prometheus does not like our timestamps -- why?
384 bprintf(fb, " %s", w[1]);
391 static void http_connection(struct http *http)
393 http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
394 http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
395 fbpool_init(&http->fbpool);
397 if (!http_get_line(http))
399 // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
401 if (str_wordsplit(http->linebuf, words, 3) != 3) {
402 http_error(http, "400 Invalid request line");
405 if (strcmp(words[0], "GET")) {
406 http_error(http, "501 Method not implemented");
411 if (!http_get_line(http))
413 if (!http->linebuf[0])
415 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
418 fbpool_start(&http->fbpool, http->mp, 0);
419 struct fastbuf *fb = &http->fbpool.fb;
420 bprintf(fb, "HTTP/1.1 200 OK\r\n");
421 bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
427 static int use_daemon;
428 static int use_debug;
430 static struct opt_section options = {
432 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
434 OPT_HELP("Options:"),
435 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
436 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
443 int main(int argc UNUSED, char **argv)
446 opt_parse(&options, argv+1);
449 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
450 log_set_default_stream(ls);
453 log_default_stream()->levels &= ~(1U << L_DEBUG);
455 mosquitto_lib_init();
456 mosq = mosquitto_new("prometheus", 1, NULL);
458 die("Mosquitto: initialization failed");
460 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
461 mosquitto_log_callback_set(mosq, mqtt_log_callback);
462 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
464 if (mosquitto_will_set(mosq, "status/prometheus", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
465 die("Mosquitto: unable to set will");
467 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
468 die("Mosquitto: connect failed");
470 if (mosquitto_loop_start(mosq))
471 die("Mosquitto: cannot start service thread");
473 int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
475 die("Cannot create listening socket: %m");
478 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
479 die("Cannot set SO_REUSEADDR: %m");
481 struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
482 if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
483 die("Cannot bind listening socket: %m");
485 if (listen(listen_sk, 64) < 0)
486 die("Cannot listen: %m");
489 int sk = accept(listen_sk, NULL, NULL);
491 msg(L_ERROR, "HTTP accept failed: %m");
494 msg(L_DEBUG, "HTTP accepted connection");
495 struct mempool *mp = mp_new(4096);
496 struct http *http = mp_alloc_zero(mp, sizeof(*http));
499 http_connection(http);