82 lines
2.2 KiB
C++
82 lines
2.2 KiB
C++
#include "mqtt.h"
|
|
|
|
#include <WiFiClient.h>
|
|
#include <WiFi.h>
|
|
#include "log.h"
|
|
#include "PubSubClient.h"
|
|
#include "console.h"
|
|
|
|
#define CONNECT_TIMEOUT_MILLISECONDS 5000
|
|
|
|
#define TOPIC_LOG_FORMAT "log/%s"
|
|
#define TOPIC_CMD_FORMAT "cmd/%s"
|
|
#define TOPIC_DATA_FORMAT "data/%s/%s"
|
|
|
|
unsigned long mqttLastConnectTry = 0;
|
|
|
|
WiFiClient espClient;
|
|
|
|
PubSubClient mqtt(espClient);
|
|
|
|
char logTopic[64] = "log/UNSET";
|
|
|
|
char cmdTopic[64] = "cmd/UNSET";
|
|
|
|
void mqttSetup() {
|
|
snprintf(logTopic, sizeof logTopic, TOPIC_LOG_FORMAT, HOSTNAME);
|
|
snprintf(cmdTopic, sizeof cmdTopic, TOPIC_CMD_FORMAT, HOSTNAME);
|
|
}
|
|
|
|
void mqttDisconnect() {
|
|
mqtt.disconnect();
|
|
}
|
|
|
|
void mqttLoop() {
|
|
if (WiFi.localIP() != 0 && !mqtt.connected() && (mqttLastConnectTry == 0 || millis() - mqttLastConnectTry > CONNECT_TIMEOUT_MILLISECONDS)) {
|
|
mqttLastConnectTry = millis();
|
|
mqtt.setServer("10.0.0.50", 1883);
|
|
if (!mqtt.connect(HOSTNAME, logTopic, 0, false, "disconnected")) {
|
|
error("MQTT", "Failed to connect MQTT server!");
|
|
return;
|
|
}
|
|
info("MQTT", "MQTT server connected!");
|
|
mqtt.setBufferSize(512);
|
|
mqtt.subscribe(cmdTopic);
|
|
mqtt.setCallback([](const char *topic, const uint8_t *bytes, const unsigned int length) {
|
|
char content[64];
|
|
if (length > sizeof content - 1) {
|
|
error("MQTT", "MQTT RECEIVE BUFFER OVERFLOW");
|
|
return;
|
|
}
|
|
memcpy(content, bytes, length);
|
|
content[length] = 0;
|
|
|
|
if (strcmp(topic, cmdTopic) == 0) {
|
|
info("MQTT", "CMD > %s", content);
|
|
consoleHandle(content);
|
|
}
|
|
});
|
|
}
|
|
mqtt.loop();
|
|
}
|
|
|
|
void mqttPublishLog(const size_t len, const char *datetime, const char *header, const char *message) {
|
|
if (mqtt.beginPublish(logTopic, len, false)) {
|
|
mqtt.print(datetime);
|
|
mqtt.print(header);
|
|
mqtt.print(message);
|
|
mqtt.endPublish();
|
|
}
|
|
}
|
|
|
|
bool mqttPublishData(const char *name, const JsonDocument &doc) {
|
|
if (mqtt.connected() != 0) {
|
|
char topic[128];
|
|
snprintf(topic, sizeof topic, TOPIC_DATA_FORMAT, HOSTNAME, name);
|
|
char payload[512];
|
|
const size_t size = serializeJson(doc, payload);
|
|
return mqtt.publish(topic, payload, size);
|
|
}
|
|
return false;
|
|
}
|