61 lines
1.7 KiB
C++
61 lines
1.7 KiB
C++
#include "mqtt.h"
|
|
#include "wifi.h"
|
|
|
|
#include <PubSubClient.h>
|
|
#include <WiFiClient.h>
|
|
|
|
WiFiClient client;
|
|
|
|
PubSubClient mqtt(client);
|
|
|
|
MySerialClass MySerial(mqtt);
|
|
|
|
unsigned long mqttFailureMillis = 0;
|
|
|
|
void mqttLoop() {
|
|
if (!mqtt.loop() && isWifiConnected() && (mqttFailureMillis == 0 || millis() - mqttFailureMillis >= 3000)) {
|
|
mqtt.setServer("10.0.0.50", 1883);
|
|
if (mqtt.connect(HOSTNAME, HOSTNAME, 0, false, "disconnected\n")) {
|
|
yield();
|
|
mqttPublish(HOSTNAME, "connected\n");
|
|
MySerial.printf("MQTT connected as \"%s\"\n", HOSTNAME);
|
|
mqttFailureMillis = 0;
|
|
} else {
|
|
MySerial.printf("Failed to connect MQTT.\n");
|
|
mqttFailureMillis = max(1UL, millis());
|
|
}
|
|
}
|
|
}
|
|
|
|
void mqttPublish(const char *topic, const int32_t value, const char *unit) {
|
|
if (!isTimeSet()) {
|
|
return;
|
|
}
|
|
char buffer[200];
|
|
snprintf(buffer, sizeof buffer, R"({"timestamp": %lld, "value": %d, "unit": "%s"})", time(nullptr), value, unit);
|
|
mqttPublish(topic, buffer);
|
|
}
|
|
|
|
void mqttPublish(const char *topic, const uint32_t value, const char *unit) {
|
|
if (!isTimeSet()) {
|
|
return;
|
|
}
|
|
char buffer[200];
|
|
snprintf(buffer, sizeof buffer, R"({"timestamp": %lld, "value": %d, "unit": "%s"})", time(nullptr), value, unit);
|
|
mqttPublish(topic, buffer);
|
|
}
|
|
|
|
void mqttPublish(const char *topic, const float value, const char *unit) {
|
|
if (!isTimeSet()) {
|
|
return;
|
|
}
|
|
char buffer[200];
|
|
snprintf(buffer, sizeof buffer, R"({"timestamp": %lld, "value": %s, "unit": "%s"})", time(nullptr), isnan(value) ? "null" : String(value).c_str(), unit);
|
|
mqttPublish(topic, buffer);
|
|
}
|
|
|
|
void mqttPublish(const char *topic, const char *payload) {
|
|
mqtt.publish(topic, payload);
|
|
yield();
|
|
}
|