diff --git a/include/mqtt_client.h b/include/mqtt_client.h index 0b4df874..e7afef1a 100644 --- a/include/mqtt_client.h +++ b/include/mqtt_client.h @@ -441,7 +441,7 @@ esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client); esp_err_t esp_mqtt_client_disconnect(esp_mqtt_client_handle_t client); /** - * @brief Stops *MQTT* client tasks + * @brief Stops *MQTT* client tasks (blocking, waits until stopped) * * * Notes: * - Cannot be called from the *MQTT* event handler @@ -454,6 +454,33 @@ esp_err_t esp_mqtt_client_disconnect(esp_mqtt_client_handle_t client); */ esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client); +/** + * @brief Stops *MQTT* client tasks non-blocking in the background + * Use esp_mqtt_client_is_stopped() to find out if its already + * stopped. + * + * * Notes: + * - Cannot be called from the *MQTT* event handler + * + * @param client *MQTT* client handle + * + * @return ESP_OK on success + * ESP_ERR_INVALID_ARG on wrong initialization + * ESP_FAIL if client is in invalid state + */ +esp_err_t esp_mqtt_client_initiate_stop(esp_mqtt_client_handle_t client); + +/** + * @brief Returns if the *MQTT* client has already stopped + * This api should be used after esp_mqtt_client_initiate_stop() + * has been called. + * + * @param client *MQTT* client handle + * + * @return if its stopped or not + */ +bool esp_mqtt_client_is_stopped(esp_mqtt_client_handle_t client); + #ifdef __cplusplus #define esp_mqtt_client_subscribe esp_mqtt_client_subscribe_single diff --git a/mqtt_client.c b/mqtt_client.c index b70f5180..ad6dd4a1 100644 --- a/mqtt_client.c +++ b/mqtt_client.c @@ -1914,6 +1914,14 @@ static esp_err_t send_disconnect_msg(esp_mqtt_client_handle_t client) } esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) +{ + esp_err_t result = esp_mqtt_client_initiate_stop(client); + if (result == ESP_OK) + xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY); + return result; +} + +esp_err_t esp_mqtt_client_initiate_stop(esp_mqtt_client_handle_t client) { if (!client) { ESP_LOGE(TAG, "Client was not initialized"); @@ -1940,7 +1948,7 @@ esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) client->run = false; client->state = MQTT_STATE_DISCONNECTED; MQTT_API_UNLOCK(client); - xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY); + return ESP_OK; } else { ESP_LOGW(TAG, "Client asked to stop, but was not started"); @@ -1949,6 +1957,17 @@ esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client) } } +bool esp_mqtt_client_is_stopped(esp_mqtt_client_handle_t client) +{ + if (!client) { + ESP_LOGE(TAG, "Client was not initialized"); + return ESP_ERR_INVALID_ARG; + } + + EventBits_t bits = xEventGroupClearBits(client->status_bits, 0); + return bits & STOPPED_BIT; +} + static esp_err_t esp_mqtt_client_ping(esp_mqtt_client_handle_t client) { mqtt_msg_pingreq(&client->mqtt_state.connection);