2022-06-05 10:14:23 +03:00
|
|
|
#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) {}
|
|
|
|
|
2022-06-05 10:14:23 +03:00
|
|
|
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-06-05 10:14:23 +03:00
|
|
|
|
2023-01-18 19:23:01 +03:00
|
|
|
patchConfigJSON(doc);
|
|
|
|
|
|
|
|
return doc;
|
|
|
|
}
|
|
|
|
|
|
|
|
JSON_DOCUMENT_TYPE HALight::patchConfigJSON(JSON_DOCUMENT_TYPE &doc) {
|
2022-12-30 18:31:20 +03:00
|
|
|
return doc;
|
|
|
|
}
|
2022-06-05 10:14:23 +03:00
|
|
|
|
2022-12-30 18:31:20 +03:00
|
|
|
JSON_DOCUMENT_TYPE HALight::createStateJSON() {
|
|
|
|
JSON_DOCUMENT_TYPE doc;
|
|
|
|
|
2022-06-05 10:14:23 +03:00
|
|
|
if (light->getState()) {
|
|
|
|
doc["state"] = "ON";
|
|
|
|
} else {
|
|
|
|
doc["state"] = "OFF";
|
|
|
|
}
|
|
|
|
|
2023-01-18 19:23:01 +03:00
|
|
|
patchStateJSON(doc);
|
|
|
|
|
|
|
|
return doc;
|
|
|
|
}
|
|
|
|
|
|
|
|
JSON_DOCUMENT_TYPE HALight::patchStateJSON(JSON_DOCUMENT_TYPE &doc) {
|
2022-12-30 18:31:20 +03:00
|
|
|
return doc;
|
|
|
|
}
|
|
|
|
|
2023-01-18 19:23:01 +03:00
|
|
|
void HALight::innerHandler(const JSON_DOCUMENT_TYPE &doc) {
|
2022-12-30 18:31:20 +03:00
|
|
|
if (strcmp(doc["state"], "ON") == 0) {
|
|
|
|
light->setState(true);
|
|
|
|
} else {
|
|
|
|
light->setState(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void HALight::sendState() {
|
|
|
|
JSON_DOCUMENT_TYPE doc = createStateJSON();
|
|
|
|
|
|
|
|
buffer[0] = '\0';
|
2022-06-05 10:14:23 +03:00
|
|
|
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();
|
2022-06-05 10:14:23 +03:00
|
|
|
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;
|
2022-06-05 10:14:23 +03:00
|
|
|
deserializeJson(doc, (const byte *)payload, length);
|
|
|
|
|
2023-01-18 19:23:01 +03:00
|
|
|
innerHandler(doc);
|
2022-06-05 10:14:23 +03:00
|
|
|
|
|
|
|
sendState();
|
|
|
|
}
|