http_server\async_handlers is unstable

User avatar
Itagaki
Posts: 11
Joined: Thu Mar 14, 2024 12:11 am

http_server\async_handlers is unstable

Postby Itagaki » Wed Jun 26, 2024 3:23 am

I have integrated (with some customization) esp-idf-v5.2\examples\protocols\http_server\async_handlers into our ESP32-S3 project. And I have tried to make it work, but with puzzling results.

I have tried requesting files via HTTP GET from dozens of other devices (they are also ESP32-S3). It usually works, but occasionally a different file is sent than the one it requested. In other words, it seems that when processing requests from multiple clients, it sometimes sends the response to the wrong destination.

Do you have any idea what might be going on?

Here is my handler
  1. #define MAX_ASYNC_REQUESTS  4
  2. #define SCRATCH_BUFSIZE  8192
  3.  
  4. static esp_err_t my_handler(httpd_req_t *req)
  5. {
  6.     char filepath[STORAGE_MAXPATH];
  7.     FILE *fd = NULL;
  8.     struct stat file_stat;
  9.  
  10.     const char *filename = get_path_from_uri(filepath, req->uri, sizeof filepath);
  11.     if (!filename) {
  12.         httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Filename too long");
  13.         return ESP_FAIL;
  14.     }
  15.  
  16.     if (stat(filepath, &file_stat) == -1) {
  17.         httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, "File does not exist");
  18.         return ESP_FAIL;
  19.     }
  20.  
  21.     fd = fopen(filepath, "r");
  22.     if (!fd) {
  23.         httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to read existing file");
  24.         return ESP_FAIL;
  25.     }
  26.  
  27.     httpd_resp_set_type(req, "application/octet-stream");
  28.  
  29.     char *chunk = heap_caps_malloc(SCRATCH_BUFSIZE, MALLOC_CAP_SPIRAM);
  30.     if (chunk) {
  31.         size_t chunksize;
  32.         do {
  33.             chunksize = fread(chunk, 1, SCRATCH_BUFSIZE, fd);
  34.             if (chunksize > 0) {
  35.                 esp_err_t err = httpd_resp_send_chunk(req, chunk, chunksize);
  36.                 if (ESP_OK == err) {
  37.                     continue;
  38.                 }
  39.                 if (ECONNRESET == errno) {
  40.                     free(chunk);
  41.                     fclose(fd);
  42.                     return ESP_OK;
  43.                 }
  44.                 httpd_resp_sendstr_chunk(req, NULL);
  45.                 httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
  46.                 free(chunk);
  47.                 fclose(fd);
  48.                 return ESP_FAIL;
  49.             }
  50.         } while (chunksize != 0);
  51.         free(chunk);
  52.     }
  53.     fclose(fd);
  54.     httpd_resp_send_chunk(req, NULL, 0);
  55.     return ESP_OK;
  56. }

Who is online

Users browsing this forum: Gaston1980 and 146 guests