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"
144 static char *attr_values[ARRAY_SIZE(attr_table)];
145 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
147 static void mqtt_publish(const char *topic, const char *fmt, ...)
152 int l = vsnprintf(m, sizeof(m), fmt, args);
153 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
154 msg(L_ERROR, "Mosquitto: publish failed");
158 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
161 msg(L_DEBUG, "MQTT: Connection established, subscribing");
162 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
163 die("Mosquitto: subscribe failed");
165 mqtt_publish("status/prometheus", "ok");
169 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
171 // msg(L_INFO, "MQTT(%d): %s", level, message);
174 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
177 if (m->payloadlen >= sizeof(val) - 1) {
178 msg(L_ERROR, "Invalid value for topic %s", m->topic);
181 memcpy(val, m->payload, m->payloadlen);
182 val[m->payloadlen] = 0;
183 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
185 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
186 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
187 pthread_mutex_lock(&attr_mutex);
188 if (attr_values[i]) {
189 xfree(attr_values[i]);
190 attr_values[i] = NULL;
193 attr_values[i] = xstrdup(val);
194 pthread_mutex_unlock(&attr_mutex);
203 uint iobuf_pos, iobuf_max;
205 struct fbpool fbpool;
208 #define IO_TIMEOUT 60000 // in ms
209 #define IOBUF_SIZE 1024
210 #define LINEBUF_SIZE 1024
212 static void http_send(struct http *http)
214 byte *buf = fbpool_end(&http->fbpool);
215 uint len = mp_size(http->mp, buf);
218 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
219 int res = poll(&pfd, 1, IO_TIMEOUT);
221 die("Poll failed: %m");
223 msg(L_ERROR, "HTTP write timed out");
227 res = write(http->sk, buf, len);
229 msg(L_ERROR, "HTTP write failed: %m");
237 static void http_error(struct http *http, const char *err)
239 msg(L_INFO, "HTTP error: %s", err);
240 fbpool_start(&http->fbpool, http->mp, 0);
241 bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
245 static int http_get_char(struct http *http) {
246 if (http->iobuf_pos >= http->iobuf_max) {
247 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
248 int res = poll(&pfd, 1, IO_TIMEOUT);
250 die("Poll failed: %m");
252 msg(L_ERROR, "HTTP read timed out");
255 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
257 msg(L_ERROR, "HTTP read error: %m");
261 msg(L_ERROR, "HTTP connection closed");
265 http->iobuf_max = len;
267 return http->iobuf[http->iobuf_pos++];
270 static bool http_get_line(struct http *http)
274 int c = http_get_char(http);
278 if (i > 0 && http->linebuf[i-1] == '\r')
280 http->linebuf[i] = 0;
283 if (i >= IOBUF_SIZE-1) {
284 http_error(http, "400 Line too long");
287 http->linebuf[i++] = c;
291 static void http_answer(struct fastbuf *fb)
293 char val[256], *w[2];
294 time_t now = time(NULL);
296 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
297 const struct attr *a = &attr_table[i];
299 pthread_mutex_lock(&attr_mutex);
300 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
301 pthread_mutex_unlock(&attr_mutex);
305 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
309 time_t t = atoll(w[1]);
310 if (t < now - MEASUREMENT_TIMEOUT)
315 bprintf(fb, "# HELP %s %s\n", a->metric, a->help);
317 bprintf(fb, "# TYPE %s %s\n", a->metric, a->type);
318 bprintf(fb, "%s %s", a->metric, val);
320 // Prometheus does not like our timestamps -- why?
322 bprintf(fb, " %s", w[1]);
328 static void http_connection(struct http *http)
330 http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
331 http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
332 fbpool_init(&http->fbpool);
334 if (!http_get_line(http))
336 // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
338 if (str_wordsplit(http->linebuf, words, 3) != 3) {
339 http_error(http, "400 Invalid request line");
342 if (strcmp(words[0], "GET")) {
343 http_error(http, "501 Method not implemented");
348 if (!http_get_line(http))
350 if (!http->linebuf[0])
352 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
355 fbpool_start(&http->fbpool, http->mp, 0);
356 struct fastbuf *fb = &http->fbpool.fb;
357 bprintf(fb, "HTTP/1.1 200 OK\r\n");
358 bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
364 static int use_daemon;
365 static int use_debug;
367 static struct opt_section options = {
369 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
371 OPT_HELP("Options:"),
372 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
373 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
380 int main(int argc UNUSED, char **argv)
383 opt_parse(&options, argv+1);
386 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
387 log_set_default_stream(ls);
390 log_default_stream()->levels &= ~(1U << L_DEBUG);
392 mosquitto_lib_init();
393 mosq = mosquitto_new("prometheus", 1, NULL);
395 die("Mosquitto: initialization failed");
397 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
398 mosquitto_log_callback_set(mosq, mqtt_log_callback);
399 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
401 if (mosquitto_will_set(mosq, "status/prometheus", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
402 die("Mosquitto: unable to set will");
404 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
405 die("Mosquitto: connect failed");
407 if (mosquitto_loop_start(mosq))
408 die("Mosquitto: cannot start service thread");
410 int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
412 die("Cannot create listening socket: %m");
415 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
416 die("Cannot set SO_REUSEADDR: %m");
418 struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
419 if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
420 die("Cannot bind listening socket: %m");
422 if (listen(listen_sk, 64) < 0)
423 die("Cannot listen: %m");
426 int sk = accept(listen_sk, NULL, NULL);
428 msg(L_ERROR, "HTTP accept failed: %m");
431 msg(L_DEBUG, "HTTP accepted connection");
432 struct mempool *mp = mp_new(4096);
433 struct http *http = mp_alloc_zero(mp, sizeof(*http));
436 http_connection(http);