2 * A gateway between MQTT and Prometheus
4 * (c) 2018 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 static struct mosquitto *mosq;
37 static const struct attr attr_table[] = {
39 .metric = "temp_loft",
40 .help = "Temperature in the loft [degC]",
42 .topic = "burrow/loft/temperature"
46 .help = "Fan speed in the loft (0-3)",
48 .topic = "burrow/loft/fan"
51 .metric = "loft_circ",
52 .help = "Warm water circulation (0-1)",
54 .topic = "burrow/loft/circulation"
57 .metric = "temp_ursarium",
58 .help = "Temperature in the Ursarium [degC]",
60 .topic = "burrow/arexxd/ursarium"
63 .metric = "temp_catarium",
64 .help = "Temperature in the Catarium [degC]",
66 .topic = "burrow/arexxd/catarium"
69 .metric = "temp_garage",
70 .help = "Temperature in the garage [degC]",
72 .topic = "burrow/arexxd/garage"
75 .metric = "temp_machinarium",
76 .help = "Temperature in the Machinarium [degC]",
78 .topic = "burrow/arexxd/machinarium"
81 .metric = "rh_garage",
82 .help = "Relative humidity in the garage [%]",
84 .topic = "burrow/arexxd/garage-rh"
88 static char *attr_values[ARRAY_SIZE(attr_table)];
89 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
91 static void mqtt_publish(const char *topic, const char *fmt, ...)
96 int l = vsnprintf(m, sizeof(m), fmt, args);
97 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
98 msg(L_ERROR, "Mosquitto: publish failed");
102 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
105 msg(L_DEBUG, "MQTT: Connection established, subscribing");
106 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
107 die("Mosquitto: subscribe failed");
109 // mqtt_publish("burrow/loft/status", "ok");
113 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
115 // msg(L_INFO, "MQTT(%d): %s", level, message);
118 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
121 if (m->payloadlen >= sizeof(val) - 1) {
122 msg(L_ERROR, "Invalid value for topic %s", m->topic);
125 memcpy(val, m->payload, m->payloadlen);
126 val[m->payloadlen] = 0;
127 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
129 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
130 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
131 pthread_mutex_lock(&attr_mutex);
132 if (attr_values[i]) {
133 xfree(attr_values[i]);
134 attr_values[i] = NULL;
137 attr_values[i] = xstrdup(val);
138 pthread_mutex_unlock(&attr_mutex);
147 uint iobuf_pos, iobuf_max;
149 struct fbpool fbpool;
152 #define IO_TIMEOUT 60000 // in ms
153 #define IOBUF_SIZE 1024
154 #define LINEBUF_SIZE 1024
156 static void http_send(struct http *http)
158 byte *buf = fbpool_end(&http->fbpool);
159 uint len = mp_size(http->mp, buf);
162 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
163 int res = poll(&pfd, 1, IO_TIMEOUT);
165 die("Poll failed: %m");
167 msg(L_ERROR, "HTTP write timed out");
171 res = write(http->sk, buf, len);
173 msg(L_ERROR, "HTTP write failed: %m");
181 static void http_error(struct http *http, const char *err)
183 msg(L_INFO, "HTTP error: %s", err);
184 fbpool_start(&http->fbpool, http->mp, 0);
185 bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
189 static int http_get_char(struct http *http) {
190 if (http->iobuf_pos >= http->iobuf_max) {
191 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
192 int res = poll(&pfd, 1, IO_TIMEOUT);
194 die("Poll failed: %m");
196 msg(L_ERROR, "HTTP read timed out");
199 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
201 msg(L_ERROR, "HTTP read error: %m");
205 msg(L_ERROR, "HTTP connection closed");
209 http->iobuf_max = len;
211 return http->iobuf[http->iobuf_pos++];
214 static bool http_get_line(struct http *http)
218 int c = http_get_char(http);
222 if (i > 0 && http->linebuf[i-1] == '\r')
224 http->linebuf[i] = 0;
227 if (i >= IOBUF_SIZE-1) {
228 http_error(http, "400 Line too long");
231 http->linebuf[i++] = c;
235 static void http_answer(struct fastbuf *fb)
239 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
240 pthread_mutex_lock(&attr_mutex);
241 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
242 pthread_mutex_unlock(&attr_mutex);
244 const struct attr *a = &attr_table[i];
246 bprintf(fb, "# HELP %s %s\n", a->metric, a->help);
248 bprintf(fb, "# TYPE %s %s\n", a->metric, a->type);
249 // FIXME: Add timestamp if known
250 bprintf(fb, "%s %s\n", a->metric, val);
255 static void http_connection(struct http *http)
257 http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
258 http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
259 fbpool_init(&http->fbpool);
261 if (!http_get_line(http))
263 // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
265 if (str_wordsplit(http->linebuf, words, 3) != 3) {
266 http_error(http, "400 Invalid request line");
269 if (strcmp(words[0], "GET")) {
270 http_error(http, "501 Method not implemented");
275 if (!http_get_line(http))
277 if (!http->linebuf[0])
279 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
282 fbpool_start(&http->fbpool, http->mp, 0);
283 struct fastbuf *fb = &http->fbpool.fb;
284 bprintf(fb, "HTTP/1.1 200 OK\r\n");
285 bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
291 static int use_daemon;
292 static int use_debug;
294 static struct opt_section options = {
296 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
298 OPT_HELP("Options:"),
299 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
300 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
307 int main(int argc UNUSED, char **argv)
310 opt_parse(&options, argv+1);
313 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
314 log_set_default_stream(ls);
317 log_default_stream()->levels &= ~(1U << L_DEBUG);
319 mosquitto_lib_init();
320 mosq = mosquitto_new("prometheus", 1, NULL);
322 die("Mosquitto: initialization failed");
324 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
325 mosquitto_log_callback_set(mosq, mqtt_log_callback);
326 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
329 // FIXME: Publish online/offline status
330 if (mosquitto_will_set(mosq, "burrow/loft/status", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
331 die("Mosquitto: unable to set will");
334 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
335 die("Mosquitto: connect failed");
337 if (mosquitto_loop_start(mosq))
338 die("Mosquitto: cannot start service thread");
340 int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
342 die("Cannot create listening socket: %m");
345 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
346 die("Cannot set SO_REUSEADDR: %m");
348 struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
349 if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
350 die("Cannot bind listening socket: %m");
352 if (listen(listen_sk, 64) < 0)
353 die("Cannot listen: %m");
356 int sk = accept(listen_sk, NULL, NULL);
358 msg(L_ERROR, "HTTP accept failed: %m");
361 msg(L_DEBUG, "HTTP accepted connection");
362 struct mempool *mp = mp_new(4096);
363 struct http *http = mp_alloc_zero(mp, sizeof(*http));
366 http_connection(http);