From cbc1a5bacbaf4aefcc2f9f68a557fa59e99eb04f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patrick=20Ha=C3=9Fel?= Date: Wed, 10 Apr 2024 12:56:55 +0200 Subject: [PATCH] mqtt cleanup --- lib/patrix/mqtt.cpp | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/patrix/mqtt.cpp b/lib/patrix/mqtt.cpp index 3909006..443a09f 100644 --- a/lib/patrix/mqtt.cpp +++ b/lib/patrix/mqtt.cpp @@ -1,13 +1,16 @@ #include "mqtt.h" +#include "base.h" #include #include #include "log.h" #include "PubSubClient.h" #include "console.h" +#include "wifi.h" #define CONNECT_TIMEOUT_MILLISECONDS 5000 +#define MQTT_HOST "10.0.0.50" #define TOPIC_LOG_FORMAT "log/%s" #define TOPIC_CMD_FORMAT "cmd/%s" #define TOPIC_DATA_FORMAT "data/%s/%s" @@ -22,26 +25,41 @@ char logTopic[64] = "log/UNSET"; char cmdTopic[64] = "cmd/UNSET"; +bool mqttConnected = false; + void mqttSetup() { snprintf(logTopic, sizeof logTopic, TOPIC_LOG_FORMAT, HOSTNAME); snprintf(cmdTopic, sizeof cmdTopic, TOPIC_CMD_FORMAT, HOSTNAME); } void mqttDisconnect() { - mqtt.disconnect(); + if (mqttConnected) { + error("MQTT", "Disconnecting..."); + mqtt.disconnect(); + } } void mqttLoop() { - if (WiFi.localIP() != 0 && !mqtt.connected() && (mqttLastConnectTry == 0 || millis() - mqttLastConnectTry > CONNECT_TIMEOUT_MILLISECONDS)) { + const bool connected = mqtt.loop(); + if (mqttConnected != !connected) { + if (!connected) { + error("MQTT", "DISCONNECTED"); + } + mqttConnected = connected; + } + + if (WiFi.localIP() != 0 && isTimeSet() && !connected && (mqttLastConnectTry == 0 || millis() - mqttLastConnectTry > CONNECT_TIMEOUT_MILLISECONDS)) { + error("MQTT", "Connecting: \"%s\"", MQTT_HOST); mqttLastConnectTry = millis(); - mqtt.setServer("10.0.0.50", 1883); - if (!mqtt.connect(HOSTNAME, logTopic, 0, false, "disconnected")) { - error("MQTT", "Failed to connect MQTT server!"); + mqtt.setServer(MQTT_HOST, 1883); + if (!mqtt.connect(HOSTNAME, logTopic, 0, false, "MQTT disconnected")) { + error("MQTT", "FAILED TO CONNECT"); return; } - info("MQTT", "MQTT server connected!"); + info("MQTT", "CONNECTED"); + mqtt.setKeepAlive(10); mqtt.setBufferSize(512); - mqtt.subscribe(cmdTopic); +// mqtt.subscribe(cmdTopic); mqtt.setCallback([](const char *topic, const uint8_t *bytes, const unsigned int length) { char content[64]; if (length > sizeof content - 1) { @@ -57,7 +75,6 @@ void mqttLoop() { } }); } - mqtt.loop(); } void mqttPublishLog(const char *datetime, const char *header, const char *message) {