Sensor3/lib/patrix/data.h
2024-04-22 12:22:24 +02:00

79 lines
1.4 KiB
C++

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