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;
35 static const struct attr attr_table[] = {
36 { "# HELP loft_temp Temperature in the loft [degC]", NULL },
37 { "# TYPE loft_temp gauge", NULL },
38 { "loft_temp", "burrow/loft/temperature" },
39 { "# HELP loft_fan Fan speed in the loft", NULL },
40 { "# TYPE loft_fan gauge", NULL },
41 { "loft_fan", "burrow/loft/fan" },
44 static char *attr_values[ARRAY_SIZE(attr_table)];
45 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
47 static void mqtt_publish(const char *topic, const char *fmt, ...)
52 int l = vsnprintf(m, sizeof(m), fmt, args);
53 if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
54 msg(L_ERROR, "Mosquitto: publish failed");
58 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
61 msg(L_DEBUG, "MQTT: Connection established, subscribing");
62 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
63 die("Mosquitto: subscribe failed");
65 // mqtt_publish("burrow/loft/status", "ok");
69 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
71 // msg(L_INFO, "MQTT(%d): %s", level, message);
74 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
77 if (m->payloadlen >= sizeof(val) - 1) {
78 msg(L_ERROR, "Invalid value for topic %s", m->topic);
81 memcpy(val, m->payload, m->payloadlen);
82 val[m->payloadlen] = 0;
83 msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
85 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
86 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
87 pthread_mutex_lock(&attr_mutex);
89 xfree(attr_values[i]);
90 attr_values[i] = NULL;
93 attr_values[i] = xstrdup(val);
94 pthread_mutex_unlock(&attr_mutex);
103 uint iobuf_pos, iobuf_max;
105 struct fbpool fbpool;
108 #define IO_TIMEOUT 60000 // in ms
109 #define IOBUF_SIZE 1024
110 #define LINEBUF_SIZE 1024
112 static void http_send(struct http *http)
114 byte *buf = fbpool_end(&http->fbpool);
115 uint len = mp_size(http->mp, buf);
118 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
119 int res = poll(&pfd, 1, IO_TIMEOUT);
121 die("Poll failed: %m");
123 msg(L_ERROR, "HTTP write timed out");
127 res = write(http->sk, buf, len);
129 msg(L_ERROR, "HTTP write failed: %m");
137 static void http_error(struct http *http, const char *err)
139 msg(L_INFO, "HTTP error: %s", err);
140 fbpool_start(&http->fbpool, http->mp, 0);
141 bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
145 static int http_get_char(struct http *http) {
146 if (http->iobuf_pos >= http->iobuf_max) {
147 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
148 int res = poll(&pfd, 1, IO_TIMEOUT);
150 die("Poll failed: %m");
152 msg(L_ERROR, "HTTP read timed out");
155 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
157 msg(L_ERROR, "HTTP read error: %m");
161 msg(L_ERROR, "HTTP connection closed");
165 http->iobuf_max = len;
167 return http->iobuf[http->iobuf_pos++];
170 static bool http_get_line(struct http *http)
174 int c = http_get_char(http);
178 if (i > 0 && http->linebuf[i-1] == '\r')
180 http->linebuf[i] = 0;
183 if (i >= IOBUF_SIZE-1) {
184 http_error(http, "400 Line too long");
187 http->linebuf[i++] = c;
191 static void http_connection(struct http *http)
193 http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
194 http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
195 fbpool_init(&http->fbpool);
197 if (!http_get_line(http))
199 // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
201 if (str_wordsplit(http->linebuf, words, 3) != 3) {
202 http_error(http, "400 Invalid request line");
205 if (strcmp(words[0], "GET")) {
206 http_error(http, "501 Method not implemented");
211 if (!http_get_line(http))
213 if (!http->linebuf[0])
215 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
218 fbpool_start(&http->fbpool, http->mp, 0);
219 struct fastbuf *fb = &http->fbpool.fb;
220 bprintf(fb, "HTTP/1.1 200 OK\r\n");
221 bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
223 for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
224 if (attr_table[i].topic) {
225 pthread_mutex_lock(&attr_mutex);
226 bprintf(fb, "%s %s\n", attr_table[i].pm, attr_values[i] ? : "");
227 pthread_mutex_unlock(&attr_mutex);
229 bprintf(fb, "%s\n", attr_table[i].pm);
235 static int use_daemon;
236 static int use_debug;
238 static struct opt_section options = {
240 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
242 OPT_HELP("Options:"),
243 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
244 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
251 int main(int argc UNUSED, char **argv)
254 opt_parse(&options, argv+1);
257 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
258 log_set_default_stream(ls);
261 log_default_stream()->levels &= ~(1U << L_DEBUG);
263 mosquitto_lib_init();
264 mosq = mosquitto_new("prometheus", 1, NULL);
266 die("Mosquitto: initialization failed");
268 mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
269 mosquitto_log_callback_set(mosq, mqtt_log_callback);
270 mosquitto_message_callback_set(mosq, mqtt_msg_callback);
273 // FIXME: Publish online/offline status
274 if (mosquitto_will_set(mosq, "burrow/loft/status", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
275 die("Mosquitto: unable to set will");
278 if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
279 die("Mosquitto: connect failed");
281 if (mosquitto_loop_start(mosq))
282 die("Mosquitto: cannot start service thread");
284 int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
286 die("Cannot create listening socket: %m");
289 if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
290 die("Cannot set SO_REUSEADDR: %m");
292 struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
293 if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
294 die("Cannot bind listening socket: %m");
296 if (listen(listen_sk, 64) < 0)
297 die("Cannot listen: %m");
300 int sk = accept(listen_sk, NULL, NULL);
302 msg(L_ERROR, "HTTP accept failed: %m");
305 msg(L_DEBUG, "HTTP accepted connection");
306 struct mempool *mp = mp_new(4096);
307 struct http *http = mp_alloc_zero(mp, sizeof(*http));
310 http_connection(http);