/* ESP drivers */ #include "esp_log.h" #include "esp_system.h" #include "esp_tls.h" /* FreeRTOS */ #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/task.h" /* Cert bundle */ #include "esp_crt_bundle.h" /* MQTT client */ #include "mqtt_client.h" /* Private */ #include "app_wifi.h" #define APP_LOG_TAG "APP_MQTT" typedef struct { char *topic; char *payload; } app_mqtt_queue_item_t; extern const char mqtt_client_cert_start[] asm("_binary_client_crt_start"); extern const char mqtt_client_cert_end[] asm("_binary_client_crt_end"); extern const char mqtt_client_key_start[] asm("_binary_client_key_start"); extern const char mqtt_client_key_end[] asm("_binary_client_key_end"); static void app_mqtt_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data); static void app_mqtt_task(void *pvParameters); static QueueHandle_t s_app_mqtt_publish_queue; int app_mqtt_init(void) { s_app_mqtt_publish_queue = xQueueCreate(4, sizeof(app_mqtt_queue_item_t)); if(s_app_mqtt_publish_queue == NULL) { return -1; } if (xTaskCreate(app_mqtt_task, "MQ_TASK", 2048, NULL, 2U, NULL) != pdPASS) { return -2; } return 0; } int app_mqtt_publish(char *topic, char *payload) { app_mqtt_queue_item_t item; item.topic = malloc(strlen(topic) + 1); if(item.topic == NULL) return -1; item.payload = malloc(strlen(payload) + 1); if(item.payload == NULL) { free(item.topic); return -2; } strcpy(item.topic, topic); strcpy(item.payload, payload); if(xQueueSend(s_app_mqtt_publish_queue, &item, portMAX_DELAY) != pdPASS) { free(item.topic); free(item.payload); return -3; } return 0; } static void app_mqtt_task(void *pvParameters) { const esp_mqtt_client_config_t mqtt_cfg = { .uri = CONFIG_APP_MQTT_BROKER_ADDR, .client_cert_pem = mqtt_client_cert_start, .client_key_pem = mqtt_client_key_start, .clientkey_password = CONFIG_APP_MQTT_TLS_CLIENT_PASSPHRASE, .clientkey_password_len = strlen(CONFIG_APP_MQTT_TLS_CLIENT_PASSPHRASE), .crt_bundle_attach = esp_crt_bundle_attach, }; esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg); esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, app_mqtt_event_handler, NULL); app_wifi_wait_ready(portMAX_DELAY); esp_mqtt_client_start(client); app_mqtt_queue_item_t item; for (;;) { if(xQueueReceive(s_app_mqtt_publish_queue, &item, portMAX_DELAY) == pdPASS) { esp_mqtt_client_publish(client, item.topic, item.payload, strlen(item.payload), 0, 0); /* This is alloc'ed by us. */ free(item.topic); free(item.payload); } } } static void app_mqtt_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { /**/ }