From 7223302deb3ffefe60cc645c6d792fd5e4d6259c Mon Sep 17 00:00:00 2001 From: Gregory Eslinger Date: Tue, 11 Jun 2019 19:57:58 +0200 Subject: [PATCH] MQTT Client: Check for connection before sending disconnect message Closes https://github.com/espressif/esp-idf/issues/3619 Closes https://github.com/espressif/esp-mqtt/issues/120 Merges https://github.com/espressif/esp-mqtt/pull/118 Signed-off-by: David Cermak --- mqtt_client.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/mqtt_client.c b/mqtt_client.c index a95f4b3..079f7d8 100644 --- a/mqtt_client.c +++ b/mqtt_client.c @@ -1134,13 +1134,16 @@ esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client) esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) { if (client->run) { - // Notify the broker we are disconnecting - MQTT_API_LOCK_FROM_OTHER_TASK(client); - client->mqtt_state.outbound_message = mqtt_msg_disconnect(&client->mqtt_state.mqtt_connection); - if (mqtt_write_data(client) != ESP_OK) { - ESP_LOGE(TAG, "Error sending disconnect message"); + // Only send the disconnect message if the client is connected + if(client->state == MQTT_STATE_CONNECTED) { + // Notify the broker we are disconnecting + MQTT_API_LOCK_FROM_OTHER_TASK(client); + client->mqtt_state.outbound_message = mqtt_msg_disconnect(&client->mqtt_state.mqtt_connection); + if (mqtt_write_data(client) != ESP_OK) { + ESP_LOGE(TAG, "Error sending disconnect message"); + } + MQTT_API_UNLOCK_FROM_OTHER_TASK(client); } - MQTT_API_UNLOCK_FROM_OTHER_TASK(client); client->run = false; xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);