|
|
|
@@ -2,6 +2,7 @@ static const char *TAG = "device"; |
|
|
|
#include <esp_log.h> |
|
|
|
|
|
|
|
#include "device.hpp" |
|
|
|
#include "presets.hpp" |
|
|
|
|
|
|
|
|
|
|
|
Device::Device(std::string _id) : |
|
|
|
@@ -44,23 +45,35 @@ void Device::on_mqtt_connect(esp_mqtt_client_handle_t client) { |
|
|
|
if (esp_mqtt_client_subscribe(client, cmd_topic.c_str(), 0) < 0) { |
|
|
|
ESP_LOGE(TAG, "Failed to subscribe to %s", cmd_topic.c_str()); |
|
|
|
} |
|
|
|
|
|
|
|
cJSON *json = cJSON_CreateObject(); |
|
|
|
cJSON_AddStringToObject(json, "unique_id", id.c_str()); |
|
|
|
cJSON *device = cJSON_AddObjectToObject(json, "device"); |
|
|
|
cJSON_AddStringToObject(device, "name", id.c_str()); |
|
|
|
cJSON *identifiers = cJSON_AddArrayToObject(device, "identifiers"); |
|
|
|
cJSON_AddItemToArray(identifiers, cJSON_CreateString(id.c_str())); |
|
|
|
cJSON_AddStringToObject(json, "state_topic", state_topic.c_str()); |
|
|
|
cJSON_AddStringToObject(json, "command_topic", cmd_topic.c_str()); |
|
|
|
cJSON_AddStringToObject(json, "schema", "json"); |
|
|
|
cJSON_AddBoolToObject(json, "effect", true); |
|
|
|
cJSON *effects = cJSON_AddArrayToObject(json, "effect_list"); |
|
|
|
for (const auto &[k, _]: Presets::map) |
|
|
|
cJSON_AddItemToArray(effects, cJSON_CreateString(k.c_str())); |
|
|
|
|
|
|
|
char *config = cJSON_PrintUnformatted(json); |
|
|
|
|
|
|
|
if (0 > esp_mqtt_client_publish( |
|
|
|
client, |
|
|
|
("homeassistant/light/" + id + "/config").c_str(), |
|
|
|
("{" |
|
|
|
"\"unique_id\": \"" + id + "\", " |
|
|
|
"\"device\": {\"name\": \"blinky_" + id + "\"}, " |
|
|
|
"\"state_topic\": \"" + state_topic + "\", " |
|
|
|
"\"command_topic\": \"" + cmd_topic + "\", " |
|
|
|
"\"schema\": \"json\", " |
|
|
|
"\"effect\": True, " |
|
|
|
"\"effect_list\": [\"dummy\"]" |
|
|
|
"}").c_str(), 0, |
|
|
|
config, 0, |
|
|
|
0, 0 |
|
|
|
)) { |
|
|
|
ESP_LOGE(TAG, "Failed to publish discovery message"); |
|
|
|
} |
|
|
|
|
|
|
|
cJSON_free(config); |
|
|
|
cJSON_Delete(json); |
|
|
|
|
|
|
|
ready = true; |
|
|
|
if (should_publish) publish_state_locked(); |
|
|
|
|
|
|
|
@@ -81,9 +94,9 @@ void Device::on_mqtt_message(esp_mqtt_client_handle_t, esp_mqtt_event_handle_t e |
|
|
|
|
|
|
|
cJSON* Device::make_json_config_locked() const { |
|
|
|
cJSON *json = cJSON_CreateObject(); |
|
|
|
cJSON_AddItemToObject(json, "state", cJSON_CreateString(power_on ? "ON" : "OFF")); |
|
|
|
cJSON_AddItemToObject(json, "effect", cJSON_CreateString(effect.c_str())); |
|
|
|
cJSON_AddItemToObject(json, "length", cJSON_CreateNumber(strip_length)); |
|
|
|
cJSON_AddStringToObject(json, "state", power_on ? "ON" : "OFF"); |
|
|
|
cJSON_AddStringToObject(json, "effect", effect.c_str()); |
|
|
|
cJSON_AddNumberToObject(json, "length", strip_length); |
|
|
|
return json; |
|
|
|
} |
|
|
|
|
|
|
|
|