/* MQTT (over TCP) Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include #include #include #include #include "esp_wifi.h" #include "esp_system.h" #include "nvs_flash.h" #include "esp_event.h" #include "esp_netif.h" //#include "protocol_examples_common.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "freertos/queue.h" #include "lwip/sockets.h" #include "lwip/dns.h" #include "lwip/netdb.h" #include "esp_log.h" #include "mqtt_client.h" #include "wifi.h" #ifdef MQTT_ENABLED static const char *TAG = "MQTT"; static esp_mqtt_client_handle_t client; static bool connected = false; static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) { //esp_mqtt_client_handle_t client = event->client; //int msg_id; // your_context_t *context = event->context; switch (event->event_id) { case MQTT_EVENT_CONNECTED: connected = true; ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED"); break; case MQTT_EVENT_DISCONNECTED: connected = false; ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED"); break; case MQTT_EVENT_PUBLISHED: ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id); break; case MQTT_EVENT_DATA: ESP_LOGI(TAG, "MQTT_EVENT_DATA"); printf("TOPIC=%.*s\r\n", event->topic_len, event->topic); printf("DATA=%.*s\r\n", event->data_len, event->data); break; case MQTT_EVENT_ERROR: ESP_LOGI(TAG, "MQTT_EVENT_ERROR"); break; default: ESP_LOGI(TAG, "Other event id:%d", event->event_id); break; } return ESP_OK; } static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id); mqtt_event_handler_cb(event_data); } void mqttTask(void *pvParameters) { #ifdef WIFI_ENABLED // Wait for tcpip-comm while( commIsUpAndRunning == false ) vTaskDelay(10000 / portTICK_PERIOD_MS); #endif esp_mqtt_client_config_t mqtt_cfg = { .uri = "mqtt://192.168.1.110:1883", .password = CONFIG_ESP_MQTT_PASSWORD, .username = CONFIG_ESP_MQTT_UNAME }; client = esp_mqtt_client_init(&mqtt_cfg); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client); esp_mqtt_client_start(client); vTaskDelete(NULL); } void mqtt_init(void) { xTaskCreate(mqttTask, "MQTT-Task", 1024*10, NULL, 2, NULL); } void sendMQTTMessage(const char * topic, const char * data) { if( connected ) { int msg_id; msg_id = esp_mqtt_client_publish(client, topic, data, 0, 1, 0); ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id); } else { ESP_LOGI(TAG, "Not connected to MQTT"); } } #endif