DualLedController/components/Communication/MqttClient.cpp

167 lines
6.7 KiB
C++
Raw Normal View History

2024-05-22 23:07:24 +08:00
#include "MqttClient.h"
2024-06-05 22:59:04 +08:00
#include "Application.h"
2024-06-01 23:47:21 +08:00
#include "LedController.h"
#include <cJSON.h>
2024-05-22 23:07:24 +08:00
#include <esp_log.h>
#include <iostream>
2024-06-01 23:47:21 +08:00
#include <string_view>
2024-05-22 23:07:24 +08:00
static const char *TAG = "mqtt";
2024-06-01 23:47:21 +08:00
void MqttClient::onConnected(struct esp_mqtt_client *client) {
ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "~", "homeassistant/light/bedroom");
cJSON_AddStringToObject(root, "name", "Bedroom");
cJSON_AddStringToObject(root, "uniq_id", "bedroom_light");
cJSON_AddStringToObject(root, "cmd_t", "~/set");
cJSON_AddStringToObject(root, "stat_t", "~/state");
cJSON_AddStringToObject(root, "schema", "json");
2024-06-05 22:59:04 +08:00
cJSON_AddNumberToObject(root, "brightness_scale", LedController::Resolution);
2024-06-01 23:47:21 +08:00
const char *modes[] = {
"color_temp",
};
cJSON *supported_color_modes = cJSON_CreateStringArray(modes, sizeof(modes) / sizeof(modes[0]));
cJSON_AddItemToObject(root, "supported_color_modes", supported_color_modes);
cJSON_AddTrueToObject(root, "brightness");
auto json = cJSON_PrintUnformatted(root);
int msg_id = esp_mqtt_client_publish(client, "homeassistant/light/bedroom/config", json, strlen(json), 1, 0);
cJSON_free(json);
cJSON_Delete(root);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
m_setStatusTopic = "homeassistant/light/bedroom/set";
2024-06-05 22:59:04 +08:00
m_statusTopic = "homeassistant/light/bedroom/state";
2024-06-01 23:47:21 +08:00
msg_id = esp_mqtt_client_subscribe(client, m_setStatusTopic.c_str(), 0);
ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
2024-06-05 22:59:04 +08:00
reportLedState();
2024-06-01 23:47:21 +08:00
}
void MqttClient::onSetStatus(const char *data, int size) {
2024-06-05 22:59:04 +08:00
ESP_LOGI(TAG, "set: %.*s", size, data);
2024-06-01 23:47:21 +08:00
cJSON *root = cJSON_Parse(data);
cJSON *brightness = cJSON_GetObjectItem(root, "brightness");
if (brightness != nullptr) {
ESP_LOGI(TAG, "brightness: %d", brightness->valueint);
2024-06-05 22:59:04 +08:00
LedController::instance()->setBrightness(brightness->valueint);
Application::instance()->setField("brightness", brightness->valueint);
}
cJSON *color_temp = cJSON_GetObjectItem(root, "color_temp");
if (color_temp != nullptr) {
ESP_LOGI(TAG, "color_temp: %d", color_temp->valueint);
LedController::instance()->setColorTemperature(color_temp->valueint);
Application::instance()->setField("color_temp", color_temp->valueint);
}
cJSON *state = cJSON_GetObjectItem(root, "state");
if (state != nullptr) {
if (std::string_view(state->valuestring) == "ON") {
LedController::instance()->setEnabled(true);
} else {
LedController::instance()->setEnabled(false);
}
2024-06-01 23:47:21 +08:00
}
cJSON_Delete(root);
2024-06-05 22:59:04 +08:00
reportLedState();
}
void MqttClient::reportLedState() {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "state", LedController::instance()->enabled() ? "ON" : "OFF");
cJSON_AddNumberToObject(root, "brightness", LedController::instance()->brightness());
cJSON_AddNumberToObject(root, "color_temp", LedController::instance()->colorTemperature());
auto text = cJSON_PrintUnformatted(root);
if (text != nullptr) {
auto messageId = esp_mqtt_client_publish(m_client, m_statusTopic.c_str(), text, strlen(text), 0, 0);
ESP_LOGI(TAG, "sent publish successful, msg_id=%d", messageId);
free(text);
}
cJSON_Delete(root);
}
MqttClient::~MqttClient() {
if (m_client != nullptr) {
esp_mqtt_client_destroy(m_client);
}
2024-06-01 23:47:21 +08:00
}
2024-05-22 23:07:24 +08:00
static void log_error_if_nonzero(const char *message, int error_code) {
if (error_code != 0) {
ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
}
}
2024-06-01 23:47:21 +08:00
void MqttClient::eventHandler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
auto self = reinterpret_cast<MqttClient *>(handler_args);
2024-05-22 23:07:24 +08:00
ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);
auto event = reinterpret_cast<esp_mqtt_event_handle_t>(event_data);
esp_mqtt_client_handle_t client = event->client;
switch ((esp_mqtt_event_id_t)event_id) {
case MQTT_EVENT_CONNECTED:
2024-06-01 23:47:21 +08:00
self->onConnected(client);
2024-05-22 23:07:24 +08:00
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
break;
case MQTT_EVENT_SUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_UNSUBSCRIBED:
ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
break;
case MQTT_EVENT_DATA:
2024-06-01 23:47:21 +08:00
ESP_LOGI(TAG, "MQTT_EVENT_DATA %s", self->m_setStatusTopic.c_str());
if (self->m_setStatusTopic == std::string_view(event->topic, event->topic_len)) {
self->onSetStatus(event->data, event->data_len);
} else {
printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
printf("DATA=%.*s\r\n", event->data_len, event->data);
}
2024-05-22 23:07:24 +08:00
break;
case MQTT_EVENT_ERROR:
ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
}
break;
default:
ESP_LOGI(TAG, "Other event id:%d", event->event_id);
break;
}
}
bool MqttClient::initialize(const std::string &username, const std::string &password) {
esp_mqtt_client_config_t config;
memset(&config, 0, sizeof(esp_mqtt_client_config_t));
config.broker.address.uri = "mqtt://192.168.2.3";
config.credentials.username = username.c_str();
config.credentials.authentication.password = password.c_str();
2024-06-05 22:59:04 +08:00
m_client = esp_mqtt_client_init(&config);
esp_mqtt_client_register_event(m_client, static_cast<esp_mqtt_event_id_t>(ESP_EVENT_ANY_ID),
2024-06-01 23:47:21 +08:00
&MqttClient::eventHandler, this);
2024-06-05 22:59:04 +08:00
esp_mqtt_client_start(m_client);
2024-05-22 23:07:24 +08:00
ESP_LOGI(TAG, "connect to %s, username: %s, password: %s", config.broker.address.uri, config.credentials.username,
config.credentials.authentication.password);
return true;
}
MqttClient *MqttClient::instance() {
static MqttClient self;
return &self;
}