*/
#include <ucw/lib.h>
+#include <ucw/log.h>
#include <ucw/mainloop.h>
#include <ucw/opt.h>
#include <ucw/strtonum.h>
va_end(args);
}
+static void mqtt_setup(void)
+{
+ if (mosquitto_subscribe(mosq, NULL, "burrow/loft/#", 1) != MOSQ_ERR_SUCCESS)
+ die("Mosquitto: subscribe failed");
+
+ mqtt_publish("burrow/loft/status", "ok");
+}
+
static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
{
// msg(L_INFO, "MQTT(%d): %s", level, message);
}
memcpy(val, m->payload, m->payloadlen);
val[m->payloadlen] = 0;
- msg(L_INFO, "MQTT < %s %s", m->topic, val);
+ msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
if (!strcmp(m->topic, "burrow/loft/fan")) {
uint x;
}
}
+static int use_daemon;
+static int use_debug;
+
static struct opt_section options = {
OPT_ITEMS {
OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
OPT_HELP(""),
OPT_HELP("Options:"),
+ OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
+ OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
OPT_HELP_OPTION,
OPT_CONF_OPTIONS,
OPT_END
{
opt_parse(&options, argv+1);
+ if (use_daemon) {
+ struct log_stream *ls = log_new_syslog("daemon", 0);
+ log_set_default_stream(ls);
+ }
+ if (!use_debug)
+ log_default_stream()->levels &= ~(1U << L_DEBUG);
+
int err;
if (err = libusb_init(&usb_ctxt))
die("Cannot initialize libusb: error %d", err);
- libusb_set_debug(usb_ctxt, 3);
+ if (use_debug)
+ libusb_set_debug(usb_ctxt, 3);
open_device();
set_relays();
if (mosquitto_connect(mosq, "127.0.0.1", 1883, 60) != MOSQ_ERR_SUCCESS)
die("Mosquitto: connect failed");
- if (mosquitto_subscribe(mosq, NULL, "burrow/loft/#", 1) != MOSQ_ERR_SUCCESS)
- die("Mosquitto: subscribe failed");
-
- mqtt_publish("burrow/loft/status", "ok");
+ mqtt_setup();
time_t next_run = 0;
for (;;) {
time_t now = time(NULL);
if (now < next_run) {
int err = mosquitto_loop(mosq, (next_run - now) * 1000, 1);
- if (err != MOSQ_ERR_SUCCESS)
+ if (err == MOSQ_ERR_NO_CONN) {
+ err = mosquitto_reconnect(mosq);
+ if (err == MOSQ_ERR_SUCCESS)
+ mqtt_setup();
+ else
+ msg(L_ERROR, "Mosquitto: cannot reconnect, error %d", err);
+ } else if (err != MOSQ_ERR_SUCCESS)
msg(L_ERROR, "Mosquitto: loop returned error %d", err);
continue;
}