|
- static const char *TAG = "device";
- #include <esp_log.h>
-
- #include "device.hpp"
-
-
- Device::Device(std::string _id) :
- id(_id),
- state_topic("light/" + id + "/state"),
- cmd_topic("light/" + id + "/cmd"),
- ready(false), should_publish(false),
- mutex(xSemaphoreCreateMutex()),
- sem(xSemaphoreCreateBinary()),
- power_on(false), strip_length(0),
- client(start_mqtt_client(on_mqtt_connect, on_mqtt_message, this))
- {}
-
- void Device::set_json_config(const cJSON *json) {
- xSemaphoreTake(mutex, portMAX_DELAY);
-
- const cJSON *state = cJSON_GetObjectItem(json, "state");
- if (state && cJSON_IsString(state)) {
- power_on = strcmp(state->valuestring, "ON") == 0;
- }
- const cJSON *fx = cJSON_GetObjectItem(json, "effect");
- if (fx && cJSON_IsString(fx)) {
- effect = fx->valuestring;
- }
- const cJSON *length = cJSON_GetObjectItem(json, "length");
- if (length && cJSON_IsNumber(length)) {
- strip_length = length->valuedouble;
- }
-
- publish_state_locked();
-
- xSemaphoreGive(mutex);
- }
-
- void Device::on_mqtt_connect(esp_mqtt_client_handle_t client) {
- xSemaphoreTake(mutex, portMAX_DELAY);
-
- ESP_LOGI(TAG, "Connected to MQTT");
-
- if (esp_mqtt_client_subscribe(client, cmd_topic.c_str(), 0) < 0) {
- ESP_LOGE(TAG, "Failed to subscribe to %s", cmd_topic.c_str());
- }
- 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,
- 0, 0
- )) {
- ESP_LOGE(TAG, "Failed to publish discovery message");
- }
-
- ready = true;
- if (should_publish) publish_state_locked();
-
- xSemaphoreGive(mutex);
- }
-
- void Device::on_mqtt_message(esp_mqtt_client_handle_t, esp_mqtt_event_handle_t event) {
- ESP_LOGI(TAG, "Received command via MQTT");
- cJSON *json = cJSON_ParseWithLength(event->data, event->data_len);
- if (json) {
- set_json_config(json);
- cJSON_Delete(json);
- } else {
- ESP_LOGE(TAG, "Invalid JSON data");
- }
- xSemaphoreGive(sem);
- }
-
- 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));
- return json;
- }
-
- void Device::publish_state_locked() {
- if (!(should_publish = !ready)) {
- cJSON *json = make_json_config_locked();
- char *config = cJSON_PrintUnformatted(json);
- ESP_ERROR_CHECK(esp_mqtt_client_publish(
- client, state_topic.c_str(), config, 0, 0, 0
- ));
- cJSON_Delete(json);
- cJSON_free(config);
- }
- }
|