mqtt cleanup
This commit is contained in:
parent
8ecf88cdb6
commit
cbc1a5bacb
@ -1,13 +1,16 @@
|
||||
#include "mqtt.h"
|
||||
|
||||
#include "base.h"
|
||||
#include <WiFiClient.h>
|
||||
#include <WiFi.h>
|
||||
#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() {
|
||||
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) {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user