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

55 lines
1.2 KiB
C++
Raw Normal View History

#include <HALight.hpp>
HALight::HALight(PubSubClient &client, const char *name, const char *unique_id,
HALightController &baseLight)
: HAControllableDevice(client, "light", name, unique_id),
light(&baseLight) {}
void HALight::sendState() {
StaticJsonDocument<256> doc;
buffer[0] = '\0';
if (light->getState()) {
doc["state"] = "ON";
} else {
doc["state"] = "OFF";
}
serializeJson(doc, buffer, buffer_size);
Serial.println(state_topic);
client.publish(state_topic, buffer, true);
}
void HALight::sendConfig() {
StaticJsonDocument<256> doc;
buffer[0] = '\0';
doc["~"] = device_topic;
doc["name"] = name;
doc["unique_id"] = unique_id;
doc["cmd_t"] = "~/cmd";
doc["stat_t"] = "~/state";
doc["schema"] = "json";
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;
StaticJsonDocument<256> doc;
deserializeJson(doc, (const byte *)payload, length);
if (strcmp(doc["state"], "ON") == 0) {
light->setState(true);
} else {
light->setState(false);
}
sendState();
}