Skip to content

Commit

Permalink
fix(websocket): wait for task on destroy
Browse files Browse the repository at this point in the history
  • Loading branch information
johanstokking committed Jan 29, 2025
1 parent e069ae7 commit bb87623
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions components/esp_websocket_client/esp_websocket_client.c
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,7 @@ esp_websocket_client_handle_t esp_websocket_client_init(const esp_websocket_clie
ESP_WS_CLIENT_MEM_CHECK(TAG, client->status_bits, {
goto _websocket_init_fail;
});
xEventGroupSetBits(client->status_bits, STOPPED_BIT);

client->buffer_size = buffer_size;
return client;
Expand All @@ -763,14 +764,31 @@ esp_websocket_client_handle_t esp_websocket_client_init(const esp_websocket_clie
return NULL;
}

static esp_err_t stop_wait_task(esp_websocket_client_handle_t client)
{
/* A running client cannot be stopped from the websocket task/event handler */
TaskHandle_t running_task = xTaskGetCurrentTaskHandle();
if (running_task == client->task_handle) {
ESP_LOGE(TAG, "Client cannot be stopped from websocket task");
return ESP_FAIL;
}

client->run = false;
xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);
client->state = WEBSOCKET_STATE_UNKNOW;
return ESP_OK;
}

esp_err_t esp_websocket_client_destroy(esp_websocket_client_handle_t client)
{
if (client == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (client->run) {
esp_websocket_client_stop(client);

if (client->status_bits && (STOPPED_BIT & xEventGroupGetBits(client->status_bits)) == 0) {
stop_wait_task(client);
}

destroy_and_free_resources(client);
return ESP_OK;
}
Expand Down Expand Up @@ -1159,23 +1177,13 @@ esp_err_t esp_websocket_client_stop(esp_websocket_client_handle_t client)
if (client == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!client->run) {
ESP_LOGW(TAG, "Client was not started");
return ESP_FAIL;
}

/* A running client cannot be stopped from the websocket task/event handler */
TaskHandle_t running_task = xTaskGetCurrentTaskHandle();
if (running_task == client->task_handle) {
ESP_LOGE(TAG, "Client cannot be stopped from websocket task");
if (xEventGroupGetBits(client->status_bits) & STOPPED_BIT) {
ESP_LOGW(TAG, "Client was not started");
return ESP_FAIL;
}


client->run = false;
xEventGroupWaitBits(client->status_bits, STOPPED_BIT, false, true, portMAX_DELAY);
client->state = WEBSOCKET_STATE_UNKNOW;
return ESP_OK;
return stop_wait_task(client);
}

static int esp_websocket_client_send_close(esp_websocket_client_handle_t client, int code, const char *additional_data, int total_len, TickType_t timeout)
Expand Down

0 comments on commit bb87623

Please sign in to comment.