70 lines
2.3 KiB
C++
70 lines
2.3 KiB
C++
#include <ArduinoJson.h>
|
|
|
|
#define JSON_SIZE 512
|
|
|
|
namespace Ha {
|
|
|
|
struct SensorConfig {
|
|
const char* name;
|
|
const char* uniqueId;
|
|
const char* stateTopic;
|
|
const char* deviceClass;
|
|
const char* unitMeasure;
|
|
const char* valueTemplate;
|
|
};
|
|
|
|
struct TemperatureConfig : SensorConfig {
|
|
TemperatureConfig(const char* name, const char* uniqueId, const char* stateTopic) {
|
|
this->name = name;
|
|
this->uniqueId = uniqueId;
|
|
this->stateTopic = stateTopic;
|
|
this->deviceClass = "temperature";
|
|
this->unitMeasure = "°C";
|
|
this->valueTemplate = "{{ value_json.temperature }}";
|
|
}
|
|
};
|
|
|
|
struct PressureConfig : SensorConfig {
|
|
PressureConfig(const char* name, const char* uniqueId, const char* stateTopic) {
|
|
this->name = name;
|
|
this->uniqueId = uniqueId;
|
|
this->stateTopic = stateTopic;
|
|
this->deviceClass = "pressure";
|
|
this->unitMeasure = "hPa";
|
|
this->valueTemplate = "{{ value_json.pressure }}";
|
|
}
|
|
};
|
|
|
|
struct AltitudeConfig : SensorConfig {
|
|
AltitudeConfig(const char* name, const char* uniqueId, const char* stateTopic) {
|
|
this->name = name;
|
|
this->uniqueId = uniqueId;
|
|
this->stateTopic = stateTopic;
|
|
this->deviceClass = "distance";
|
|
this->unitMeasure = "m";
|
|
this->valueTemplate = "{{ value_json.altitude }}";
|
|
}
|
|
};
|
|
|
|
void buildDeviceConfig(JsonDocument& jsonDoc) {
|
|
JsonObject device = jsonDoc.createNestedObject("device");
|
|
device["name"] = "ESP Clock";
|
|
JsonArray connections = device.createNestedArray("connections");
|
|
JsonArray mac = connections.createNestedArray();
|
|
mac.add("mac");
|
|
mac.add(WiFi.macAddress());
|
|
}
|
|
|
|
void buildSensorConfig(char(&output)[JSON_SIZE], SensorConfig config) {
|
|
StaticJsonDocument<JSON_SIZE> jsonDoc;
|
|
buildDeviceConfig(jsonDoc);
|
|
jsonDoc["device_class"] = config.deviceClass;
|
|
jsonDoc["name"] = config.name;
|
|
jsonDoc["unique_id"] = config.uniqueId;
|
|
jsonDoc["unit_of_measurement"] = config.unitMeasure;
|
|
jsonDoc["state_topic"] = config.stateTopic;
|
|
jsonDoc["value_template"] = config.valueTemplate;
|
|
serializeJson(jsonDoc, output);
|
|
}
|
|
}
|