ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
http_request_idf.cpp
Go to the documentation of this file.
1#include "http_request_idf.h"
2
3#ifdef USE_ESP32
4
7
9#include "esphome/core/log.h"
10
11#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
12#include "esp_crt_bundle.h"
13#endif
14
15#include "esp_task_wdt.h"
16
17namespace esphome::http_request {
18
19static const char *const TAG = "http_request";
20static constexpr uint32_t ERROR_DURATION_MS = 1000;
21
24 ESP_LOGCONFIG(TAG,
25 " Buffer Size RX: %u\n"
26 " Buffer Size TX: %u\n"
27 " Custom CA Certificate: %s",
28 this->buffer_size_rx_, this->buffer_size_tx_, YESNO(this->ca_certificate_ != nullptr));
29}
30
31esp_err_t HttpRequestIDF::http_event_handler(esp_http_client_event_t *evt) {
32 auto *container = (HttpContainerIDF *) evt->user_data;
33
34 switch (evt->event_id) {
35 case HTTP_EVENT_ON_HEADER: {
36 const std::string header_name = str_lower_case(evt->header_key); // NOLINT
37 if (should_collect_header(container->collect_headers_, header_name)) {
38 const std::string header_value = evt->header_value;
39 ESP_LOGD(TAG, "Received response header, name: %s, value: %s", header_name.c_str(), header_value.c_str());
40 container->response_headers_.push_back({header_name, header_value});
41 }
42 break;
43 }
44 default: {
45 break;
46 }
47 }
48 return ESP_OK;
49}
50
51std::shared_ptr<HttpContainer> HttpRequestIDF::perform(const std::string &url, const std::string &method,
52 const std::string &body,
53 const std::vector<Header> &request_headers,
54 const std::vector<std::string> &lower_case_collect_headers) {
55 if (!network::is_connected()) {
56 this->status_momentary_error("failed", ERROR_DURATION_MS);
57 ESP_LOGE(TAG, "HTTP Request failed; Not connected to network");
58 return nullptr;
59 }
60
61 esp_http_client_method_t method_idf;
62 if (method == "GET") {
63 method_idf = HTTP_METHOD_GET;
64 } else if (method == "POST") {
65 method_idf = HTTP_METHOD_POST;
66 } else if (method == "PUT") {
67 method_idf = HTTP_METHOD_PUT;
68 } else if (method == "DELETE") {
69 method_idf = HTTP_METHOD_DELETE;
70 } else if (method == "PATCH") {
71 method_idf = HTTP_METHOD_PATCH;
72 } else {
73 this->status_momentary_error("failed", ERROR_DURATION_MS);
74 ESP_LOGE(TAG, "HTTP Request failed; Unsupported method");
75 return nullptr;
76 }
77
78 bool secure = url.find("https:") != std::string::npos;
79
80 esp_http_client_config_t config = {};
81
82 config.url = url.c_str();
83 config.method = method_idf;
84 config.timeout_ms = this->timeout_;
85 config.disable_auto_redirect = !this->follow_redirects_;
86 config.max_redirection_count = this->redirect_limit_;
87 config.auth_type = HTTP_AUTH_TYPE_BASIC;
88 if (secure && this->verify_ssl_) {
89 if (this->ca_certificate_ != nullptr) {
90 config.cert_pem = this->ca_certificate_;
91#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE
92 } else {
93 config.crt_bundle_attach = esp_crt_bundle_attach;
94#endif
95 }
96 }
97
98 if (this->useragent_ != nullptr) {
99 config.user_agent = this->useragent_;
100 }
101
102 config.buffer_size = this->buffer_size_rx_;
103 config.buffer_size_tx = this->buffer_size_tx_;
104
105 const uint32_t start = millis();
107
108 config.event_handler = http_event_handler;
109
110 esp_http_client_handle_t client = esp_http_client_init(&config);
111 if (client == nullptr) {
112 this->status_momentary_error("failed", ERROR_DURATION_MS);
113 ESP_LOGE(TAG, "HTTP Request failed; client could not be initialized");
114 return nullptr;
115 }
116
117 std::shared_ptr<HttpContainerIDF> container = std::make_shared<HttpContainerIDF>(client);
118 container->set_parent(this);
119
120 container->set_secure(secure);
121
122 container->collect_headers_ = lower_case_collect_headers;
123 esp_http_client_set_user_data(client, static_cast<void *>(container.get()));
124
125 for (const auto &header : request_headers) {
126 esp_http_client_set_header(client, header.name.c_str(), header.value.c_str());
127 }
128
129 const int body_len = body.length();
130
131 esp_err_t err = esp_http_client_open(client, body_len);
132 if (err != ESP_OK) {
133 this->status_momentary_error("failed", ERROR_DURATION_MS);
134 ESP_LOGE(TAG, "HTTP Request failed: %s", esp_err_to_name(err));
135 esp_http_client_cleanup(client);
136 return nullptr;
137 }
138
139 if (body_len > 0) {
140 int write_left = body_len;
141 int write_index = 0;
142 const char *buf = body.c_str();
143 while (write_left > 0) {
144 int written = esp_http_client_write(client, buf + write_index, write_left);
145 if (written <= 0) {
146 err = ESP_FAIL;
147 break;
148 }
149 write_left -= written;
150 write_index += written;
151 container->feed_wdt();
152 }
153 }
154
155 if (err != ESP_OK) {
156 this->status_momentary_error("failed", ERROR_DURATION_MS);
157 ESP_LOGE(TAG, "HTTP Request failed: %s", esp_err_to_name(err));
158 esp_http_client_cleanup(client);
159 return nullptr;
160 }
161
162 container->feed_wdt();
163 // esp_http_client_fetch_headers() returns 0 for chunked transfer encoding (no Content-Length header).
164 // The read() method handles content_length == 0 specially to support chunked responses.
165 container->content_length = esp_http_client_fetch_headers(client);
166 container->set_chunked(esp_http_client_is_chunked_response(client));
167 container->feed_wdt();
168 container->status_code = esp_http_client_get_status_code(client);
169 container->feed_wdt();
170 container->duration_ms = millis() - start;
171 if (is_success(container->status_code)) {
172 return container;
173 }
174
175 if (this->follow_redirects_) {
176 auto num_redirects = this->redirect_limit_;
177 while (is_redirect(container->status_code) && num_redirects > 0) {
178 err = esp_http_client_set_redirection(client);
179 if (err != ESP_OK) {
180 ESP_LOGE(TAG, "esp_http_client_set_redirection failed: %s", esp_err_to_name(err));
181 this->status_momentary_error("failed", ERROR_DURATION_MS);
182 esp_http_client_cleanup(client);
183 return nullptr;
184 }
185#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
186 char redirect_url[256]{};
187 if (esp_http_client_get_url(client, redirect_url, sizeof(redirect_url) - 1) == ESP_OK) {
188 ESP_LOGV(TAG, "redirecting to url: %s", redirect_url);
189 }
190#endif
191 err = esp_http_client_open(client, 0);
192 if (err != ESP_OK) {
193 ESP_LOGE(TAG, "esp_http_client_open failed: %s", esp_err_to_name(err));
194 this->status_momentary_error("failed", ERROR_DURATION_MS);
195 esp_http_client_cleanup(client);
196 return nullptr;
197 }
198
199 container->feed_wdt();
200 // IDF is the only backend reusing the container across redirect hops;
201 // drop the previous hop's headers (Arduino/host collect only the final response)
202 container->response_headers_.clear();
203 container->content_length = esp_http_client_fetch_headers(client);
204 container->set_chunked(esp_http_client_is_chunked_response(client));
205 container->feed_wdt();
206 container->status_code = esp_http_client_get_status_code(client);
207 container->feed_wdt();
208 container->duration_ms = millis() - start;
209 if (is_success(container->status_code)) {
210 return container;
211 }
212
213 num_redirects--;
214 }
215
216 if (num_redirects == 0) {
217 ESP_LOGW(TAG, "Reach redirect limit count=%d", this->redirect_limit_);
218 }
219 }
220
221 ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
222 this->status_momentary_error("failed", ERROR_DURATION_MS);
223 return container;
224}
225
227 // Base class handles no-body status codes and non-chunked content_length completion
229 return true;
230 }
231 // For chunked responses, use the authoritative ESP-IDF completion check
232 return this->is_chunked_ && esp_http_client_is_complete_data_received(this->client_);
233}
234
235// ESP-IDF HTTP read implementation (blocking mode)
236//
237// WARNING: Return values differ from BSD sockets! See http_request.h for full documentation.
238//
239// esp_http_client_read() in blocking mode returns:
240// > 0: bytes read
241// 0: all chunked data received (is_chunk_complete true) or connection closed
242// -ESP_ERR_HTTP_EAGAIN: transport timeout, no data available yet
243// < 0: error
244//
245// We normalize to HttpContainer::read() contract:
246// > 0: bytes read
247// 0: all content read (for both content_length-based and chunked completion)
248// < 0: error/connection closed
249//
250// Note on chunked transfer encoding:
251// esp_http_client_fetch_headers() returns 0 for chunked responses (no Content-Length header).
252// When esp_http_client_read() returns 0 for a chunked response, is_read_complete() calls
253// esp_http_client_is_complete_data_received() to distinguish successful completion from
254// connection errors. Callers use http_read_loop_result() which checks is_read_complete()
255// to return COMPLETE for successful chunked EOF.
256//
257// Streaming chunked responses are not supported (see http_request.h for details).
258// When data stops arriving, esp_http_client_read() returns -ESP_ERR_HTTP_EAGAIN
259// after its internal transport timeout (configured via timeout_ms) expires.
260// This is passed through as a negative return value, which callers treat as an error.
261int HttpContainerIDF::read(uint8_t *buf, size_t max_len) {
262 const uint32_t start = millis();
263 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
264
265 // Check if we've already read all expected content (non-chunked and no-body only).
266 // Use the base class check here, NOT the override: esp_http_client_is_complete_data_received()
267 // returns true as soon as all data arrives from the network, but data may still be in
268 // the client's internal buffer waiting to be consumed by esp_http_client_read().
270 return 0; // All content read successfully
271 }
272
273 this->feed_wdt();
274 int read_len_or_error = esp_http_client_read(this->client_, (char *) buf, max_len);
275 this->feed_wdt();
276
277 this->duration_ms += (millis() - start);
278
279 if (read_len_or_error > 0) {
280 this->bytes_read_ += read_len_or_error;
281 return read_len_or_error;
282 }
283
284 // esp_http_client_read() returns 0 when:
285 // - Known content_length: connection closed before all data received (error)
286 // - Chunked encoding: all chunks received (is_chunk_complete true, genuine EOF)
287 //
288 // Return 0 in both cases. Callers use http_read_loop_result() which calls
289 // is_read_complete() to distinguish these:
290 // - Chunked complete: is_read_complete() returns true (via
291 // esp_http_client_is_complete_data_received()), caller gets COMPLETE
292 // - Non-chunked incomplete: is_read_complete() returns false, caller
293 // eventually gets TIMEOUT (since no more data arrives)
294 if (read_len_or_error == 0) {
295 return 0;
296 }
297
298 // Negative value - error, return the actual error code for debugging
299 return read_len_or_error;
300}
301
303 if (this->client_ == nullptr) {
304 return; // Already cleaned up
305 }
306 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
307
308 esp_http_client_close(this->client_);
309 esp_http_client_cleanup(this->client_);
310 this->client_ = nullptr;
311}
312
314 // Tests to see if the executing task has a watchdog timer attached
315 if (esp_task_wdt_status(nullptr) == ESP_OK) {
316 App.feed_wdt();
317 }
318}
319
320} // namespace esphome::http_request
321
322#endif // USE_ESP32
void feed_wdt()
Feed the task watchdog.
void status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
virtual bool is_read_complete() const
Check if all expected content has been read.
bool is_chunked_
True if response uses chunked transfer encoding.
int read(uint8_t *buf, size_t max_len) override
void feed_wdt()
Feeds the watchdog timer if the executing task has one attached.
std::shared_ptr< HttpContainer > start(const std::string &url, const std::string &method, const std::string &body, const std::vector< Header > &request_headers)
std::shared_ptr< HttpContainer > perform(const std::string &url, const std::string &method, const std::string &body, const std::vector< Header > &request_headers, const std::vector< std::string > &lower_case_collect_headers) override
static esp_err_t http_event_handler(esp_http_client_event_t *evt)
Monitors the http client events to gather response headers.
bool should_collect_header(const std::vector< std::string > &lower_case_collect_headers, const std::string &lower_header_name)
Check if a header name should be collected (linear scan, fine for small lists)
bool is_success(int const status)
Checks if the given HTTP status code indicates a successful request.
bool is_redirect(int const status)
Returns true if the HTTP status code is a redirect.
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:28
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
int written
Definition helpers.h:1099
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t