d1_mini_pro-sensor-mqtt/lib/HomeAssistantDevices/HALight.cpp

71 lines
1.6 KiB
C++
Raw Normal View History

#include <HALight.hpp>
2022-12-30 18:31:20 +03:00
HALight::HALight(PubSubClient &client, const char *name, const char *unique_id)
: HAControllableDevice(client, "light", name, unique_id) {}
HALight::HALight(PubSubClient &client, const char *name, const char *unique_id,
HALightController &baseLight)
: HAControllableDevice(client, "light", name, unique_id),
light(&baseLight) {}
2022-12-30 18:31:20 +03:00
JSON_DOCUMENT_TYPE HALight::createConfigJSON() {
JSON_DOCUMENT_TYPE doc;
doc["~"] = device_topic;
doc["name"] = name;
doc["unique_id"] = unique_id;
doc["cmd_t"] = "~/cmd";
doc["stat_t"] = "~/state";
doc["schema"] = "json";
2022-12-30 18:31:20 +03:00
return doc;
}
2022-12-30 18:31:20 +03:00
JSON_DOCUMENT_TYPE HALight::createStateJSON() {
JSON_DOCUMENT_TYPE doc;
if (light->getState()) {
doc["state"] = "ON";
} else {
doc["state"] = "OFF";
}
2022-12-30 18:31:20 +03:00
return doc;
}
void HALight::innerHanlder(JSON_DOCUMENT_TYPE &doc) {
if (strcmp(doc["state"], "ON") == 0) {
light->setState(true);
} else {
light->setState(false);
}
}
void HALight::sendState() {
JSON_DOCUMENT_TYPE doc = createStateJSON();
buffer[0] = '\0';
serializeJson(doc, buffer, buffer_size);
Serial.println(state_topic);
client.publish(state_topic, buffer, true);
}
void HALight::sendConfig() {
2022-12-30 18:31:20 +03:00
JSON_DOCUMENT_TYPE doc = createConfigJSON();
buffer[0] = '\0';
serializeJson(doc, buffer, buffer_size);
client.publish(config_topic, buffer, true);
}
void HALight::handle(char *topic, byte *payload, unsigned int length) {
if (strcmp(topic, command_topic) != 0)
return;
2022-12-30 18:31:20 +03:00
JSON_DOCUMENT_TYPE doc;
deserializeJson(doc, (const byte *)payload, length);
2022-12-30 18:31:20 +03:00
innerHanlder(doc);
sendState();
}