90 lines
1.9 KiB
C++
90 lines
1.9 KiB
C++
#ifndef MQTT_H
|
|
#define MQTT_H
|
|
|
|
#include <Stream.h>
|
|
#include "PubSubClient.h"
|
|
#include "wifi.h"
|
|
|
|
extern const String logTopic;
|
|
|
|
extern const String cmdTopic;
|
|
|
|
void mqttLoop();
|
|
|
|
void mqttPublishValue(const String& name, int32_t value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, int64_t value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, uint32_t value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, uint64_t value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, float value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, double value, const char *unit);
|
|
|
|
void mqttPublishValue(const String& name, const String& value, const char *unit);
|
|
|
|
void mqttPublish(const String& topic, const String& payload);
|
|
|
|
class LogClass final : public Stream {
|
|
|
|
PubSubClient& mqtt;
|
|
|
|
uint8_t buffer[500] = {};
|
|
|
|
uint8_t *bufferWrite = buffer;
|
|
|
|
uint8_t *bufferLast = buffer + sizeof(buffer) - 1;
|
|
|
|
size_t overflow = 0;
|
|
|
|
bool due = false;
|
|
|
|
public:
|
|
|
|
explicit LogClass(PubSubClient& mqttClient) : mqtt(mqttClient) {
|
|
Serial.begin(115200);
|
|
}
|
|
|
|
size_t write(const uint8_t data) override {
|
|
Serial.write(data);
|
|
if (bufferWrite < bufferLast) {
|
|
*bufferWrite++ = data;
|
|
*bufferWrite = 0;
|
|
} else {
|
|
overflow++;
|
|
}
|
|
if (due || data == '\n' || bufferWrite >= bufferLast) {
|
|
due = true;
|
|
if (mqtt.connected()) {
|
|
if (overflow > 0) {
|
|
mqttPublish(logTopic, "\n### LOG BUFFER OVERFLOW BY %d BYTES ###\n");
|
|
overflow = 0;
|
|
}
|
|
mqttPublish(logTopic, reinterpret_cast<const char *>(buffer));
|
|
bufferWrite = buffer;
|
|
*bufferWrite = 0;
|
|
due = false;
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int available() override {
|
|
return 0;
|
|
}
|
|
|
|
int read() override {
|
|
return -1;
|
|
}
|
|
|
|
int peek() override {
|
|
return -1;
|
|
}
|
|
};
|
|
|
|
extern LogClass Log;
|
|
|
|
#endif
|