Error create mqtt task

alitergee
Posts: 14
Joined: Wed Aug 17, 2022 1:31 pm

Error create mqtt task

Postby alitergee » Wed Aug 24, 2022 2:07 pm

I'm working on a project where mqtt_app is started on event IP_EVENT_STA_GOT_IP and mqtt app is stopped when WIFI_EVENT_STA_DISCONNECTED event occurs.
The general flow when

Code: Select all

MQTT_CLIENT: Error create mqtt task
can be (mostly) seen is as follows -
1.ESP Bootup
2.WIFI_EVENT_STA_START
3.WIFI_EVENT_AP_START
4.WIFI_EVENT_STA_CONNECTED
5.IP_EVENT_STA_GOT_IP
6.MQTT app start

then after some time,
7.WIFI_EVENT_STA_DISCONNECTED
8.MQTT app stop
9.WIFI_EVENT_STA_CONNECTED
10.IP_EVENT_STA_GOT_IP
11. MQTT app start

but,

Code: Select all

E (348564) MQTT_CLIENT: Error create mqtt task
E (348574) MQTT: 
 FAILED TO START MQTT CLIENT -1
following error is faced. And therefore until software reset is done, mqtt won't connect.

mqtt app start function is as follows

Code: Select all

void mqtt_app_start(char mac_id[])
{
    mqtt_events = xEventGroupCreate();
    mqtt_credential_read_nvs(); //++ function to read MQTT credential from NVS

    sprintf(mqtt_var.data_topic, "%s/data", mac_id);

    esp_mqtt_client_config_t mqtt_config = {
        .uri = mqtt_var.mqtt_url,
        .username = mqtt_var.mqtt_user,
        .password = mqtt_var.mqtt_pass,
        .keepalive = 60};

    client = esp_mqtt_client_init(&mqtt_config);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);

    esp_err_t mqtt_err = esp_mqtt_client_start(client);
    if (mqtt_err != ESP_OK)
    {
        ESP_LOGE(TAG, "\n FAILED TO START MQTT CLIENT %d\n", mqtt_err);
        vTaskDelay(100/ portTICK_PERIOD_MS);
        esp_restart();
    }
    else
    {
        xEventGroupWaitBits(mqtt_events, MQTT_CONNECTED | MQTT_DISCONNECTED, pdTRUE, pdFALSE, pdMS_TO_TICKS(10000));
    }
}

mqtt stop function is as follows

Code: Select all

void mqtt_app_stop()
{
    ESP_LOGE(TAG, "\n\nxx -- STOPPING MQTT -- xx\n");
    mqtt_con_flag = false;
    mqtt_connected = false;

    esp_err_t mqtt_err = esp_mqtt_client_stop(client);
    if (mqtt_err != ESP_OK)
    {
        ESP_LOGE(TAG, "\n FAILED TO STOP MQTT CLIENT %s\n", esp_err_to_name(mqtt_err));
    }
    else
    {
        if(HandleMqtt != NULL)
        {
            vTaskDelete(HandleMqtt);
        }
        // vTaskDelete(HandleMqtt); //creating problems in wifi reconnection
        xEventGroupSetBits(mqtt_events, MQTT_DISCONNECTED);
    }
}
I'm new to ESP32 and ESP-IDF. May I know why is this happening?
Please help. Thank you.

chegewara
Posts: 2378
Joined: Wed Jun 14, 2017 9:00 pm

Re: Error create mqtt task

Postby chegewara » Wed Aug 24, 2022 5:05 pm

If you want to do it this way then you are missing one piece of puzzle:

Code: Select all

esp_mqtt_client_destroy(client)

Who is online

Users browsing this forum: Google [Bot] and 157 guests