#ifndef SENSOR3_DATA_H #define SENSOR3_DATA_H #include "base.h" #include struct IData { virtual void toJson(JsonObject &json) const = 0; }; template using ExtendsIData = std::enable_if_t>; template class Cache { private: struct Entry { time_t timestamp = 0; T data; }; const char *name; Entry buffer[size]; Entry *bufferRead = buffer; Entry *bufferWrite = buffer; size_t dataCount = 0; public: template> explicit Cache(const char *name) : name(name) { // - } bool add(const time_t timestamp, const T &data) { if (dataCount >= size) { return false; } bufferWrite->timestamp = timestamp; bufferWrite->data = data; bufferWrite = (bufferWrite - buffer + 1) % size + buffer; dataCount++; return true; } void loop() { if (dataCount == 0 || !isTimeSet()) { return; } JsonDocument json; json["timestamp"] = correctTime(bufferRead->timestamp); JsonObject data = json["data"].to(); bufferRead->data.toJson(data); if (mqttPublishData(name, json)) { bufferRead = (bufferRead - buffer + 1) % size + buffer; dataCount--; } } }; #endif