#include "esp_event_base.h" #include "esp_log.h" #include "mqtt_client.h" #include #include static const char *TAG = "mqtt"; // Logs are coming from this mqtt module static uint32_t MQTT_CONNECTED = 0; static int s_retry_num = 0; #define MQTT_TOPIC "/topic/test" #define MQTT_BROKER "mqtt://192.168.178.53:1883" #define MAX_RETRY 5 esp_mqtt_client_handle_t mqtt_connect(); static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { if (event_id == MQTT_EVENT_CONNECTED) { ESP_LOGI(TAG, "Connected to MQTT broker."); MQTT_CONNECTED = 1; } if (event_id == MQTT_EVENT_PUBLISHED) { // Cast event which is void to a specific type provided by ESP-IDF // Then dereference and get `msg_id` field esp_mqtt_event_handle_t event = (esp_mqtt_event_handle_t)event_data; ESP_LOGI(TAG, "Message published succesfully, msg_id: %d", (*event).msg_id); } if (event_id == MQTT_EVENT_DISCONNECTED) { MQTT_CONNECTED = 0; ESP_LOGI(TAG, "Disconnected from MQTT broker. Attempting to reconnect."); if (s_retry_num < MAX_RETRY) { mqtt_connect(); s_retry_num++; ESP_LOGI(TAG, "Retrying MQTT connection."); } else { ESP_LOGI(TAG, "Could not connect to MQTT broker. Giving up."); } } } esp_mqtt_client_handle_t mqtt_connect() { ESP_LOGI(TAG, "Attempting to connect to MQTT broker %s", MQTT_BROKER); esp_mqtt_client_config_t mqtt_config = {.broker.address.uri = MQTT_BROKER}; esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_config); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client); esp_mqtt_client_start(client); return client; } void mqtt_publish(esp_mqtt_client_handle_t client, const char *payload) { if (MQTT_CONNECTED) { ESP_LOGI(TAG, "Publishing payload %s to topic %s", payload, MQTT_TOPIC); esp_mqtt_client_publish(client, MQTT_TOPIC, payload, strlen(payload), 0, 0); } else { ESP_LOGI(TAG, "Could not publish to MQTT topic %s. Not connected to broker", MQTT_TOPIC); } } // https://github.com/ESP32Tutorials/esp32-mqtt-pub-sub-esp-idf/blob/main/main/app_main.c