ESPHome 2026.1.4
Loading...
Searching...
No Matches
http_request_arduino.cpp
Go to the documentation of this file.
2
3#if defined(USE_ARDUINO) && !defined(USE_ESP32)
4
7
10#include "esphome/core/log.h"
11
12namespace esphome::http_request {
13
14static const char *const TAG = "http_request.arduino";
15
16std::shared_ptr<HttpContainer> HttpRequestArduino::perform(const std::string &url, const std::string &method,
17 const std::string &body,
18 const std::list<Header> &request_headers,
19 const std::set<std::string> &collect_headers) {
20 if (!network::is_connected()) {
21 this->status_momentary_error("failed", 1000);
22 ESP_LOGW(TAG, "HTTP Request failed; Not connected to network");
23 return nullptr;
24 }
25
26 std::shared_ptr<HttpContainerArduino> container = std::make_shared<HttpContainerArduino>();
27 container->set_parent(this);
28
29 const uint32_t start = millis();
30
31 bool secure = url.find("https:") != std::string::npos;
32 container->set_secure(secure);
33
35
36 if (this->follow_redirects_) {
37 container->client_.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
38 container->client_.setRedirectLimit(this->redirect_limit_);
39 } else {
40 container->client_.setFollowRedirects(HTTPC_DISABLE_FOLLOW_REDIRECTS);
41 }
42
43#if defined(USE_ESP8266)
44 std::unique_ptr<WiFiClient> stream_ptr;
45#ifdef USE_HTTP_REQUEST_ESP8266_HTTPS
46 if (secure) {
47 ESP_LOGV(TAG, "ESP8266 HTTPS connection with WiFiClientSecure");
48 stream_ptr = std::make_unique<WiFiClientSecure>();
49 WiFiClientSecure *secure_client = static_cast<WiFiClientSecure *>(stream_ptr.get());
50 secure_client->setBufferSizes(512, 512);
51 secure_client->setInsecure();
52 } else {
53 stream_ptr = std::make_unique<WiFiClient>();
54 }
55#else
56 ESP_LOGV(TAG, "ESP8266 HTTP connection with WiFiClient");
57 if (secure) {
58 ESP_LOGE(TAG, "Can't use HTTPS connection with esp8266_disable_ssl_support");
59 return nullptr;
60 }
61 stream_ptr = std::make_unique<WiFiClient>();
62#endif // USE_HTTP_REQUEST_ESP8266_HTTPS
63
64#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 1, 0) // && USE_ARDUINO_VERSION_CODE < VERSION_CODE(?, ?, ?)
65 if (!secure) {
66 ESP_LOGW(TAG, "Using HTTP on Arduino version >= 3.1 is **very** slow. Consider setting framework version to 3.0.2 "
67 "in your YAML, or use HTTPS");
68 }
69#endif // USE_ARDUINO_VERSION_CODE
70 bool status = container->client_.begin(*stream_ptr, url.c_str());
71
72#elif defined(USE_RP2040)
73 if (secure) {
74 container->client_.setInsecure();
75 }
76 bool status = container->client_.begin(url.c_str());
77#endif
78
79 App.feed_wdt();
80
81 if (!status) {
82 ESP_LOGW(TAG, "HTTP Request failed; URL: %s", url.c_str());
83 container->end();
84 this->status_momentary_error("failed", 1000);
85 return nullptr;
86 }
87
88 container->client_.setReuse(true);
89 container->client_.setTimeout(this->timeout_);
90
91 if (this->useragent_ != nullptr) {
92 container->client_.setUserAgent(this->useragent_);
93 }
94 for (const auto &header : request_headers) {
95 container->client_.addHeader(header.name.c_str(), header.value.c_str(), false, true);
96 }
97
98 // returned needed headers must be collected before the requests
99 const char *header_keys[collect_headers.size()];
100 int index = 0;
101 for (auto const &header_name : collect_headers) {
102 header_keys[index++] = header_name.c_str();
103 }
104 container->client_.collectHeaders(header_keys, index);
105
106 App.feed_wdt();
107 container->status_code = container->client_.sendRequest(method.c_str(), body.c_str());
108 App.feed_wdt();
109 if (container->status_code < 0) {
110 ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(),
111 HTTPClient::errorToString(container->status_code).c_str());
112 this->status_momentary_error("failed", 1000);
113 container->end();
114 return nullptr;
115 }
116
117 if (!is_success(container->status_code)) {
118 ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
119 this->status_momentary_error("failed", 1000);
120 // Still return the container, so it can be used to get the status code and error message
121 }
122
123 container->response_headers_ = {};
124 auto header_count = container->client_.headers();
125 for (int i = 0; i < header_count; i++) {
126 const std::string header_name = str_lower_case(container->client_.headerName(i).c_str());
127 if (collect_headers.count(header_name) > 0) {
128 std::string header_value = container->client_.header(i).c_str();
129 ESP_LOGD(TAG, "Received response header, name: %s, value: %s", header_name.c_str(), header_value.c_str());
130 container->response_headers_[header_name].push_back(header_value);
131 }
132 }
133
134 // HTTPClient::getSize() returns -1 for chunked transfer encoding (no Content-Length).
135 // When cast to size_t, -1 becomes SIZE_MAX (4294967295 on 32-bit).
136 // The read() method handles this: bytes_read_ can never reach SIZE_MAX, so the
137 // early return check (bytes_read_ >= content_length) will never trigger.
138 //
139 // TODO: Chunked transfer encoding is NOT properly supported on Arduino.
140 // The implementation in #7884 was incomplete - it only works correctly on ESP-IDF where
141 // esp_http_client_read() decodes chunks internally. On Arduino, using getStreamPtr()
142 // returns raw TCP data with chunk framing (e.g., "12a\r\n{json}\r\n0\r\n\r\n") instead
143 // of decoded content. This wasn't noticed because requests would complete and payloads
144 // were only examined on IDF. The long transfer times were also masked by the misleading
145 // "HTTP on Arduino version >= 3.1 is **very** slow" warning above. This causes two issues:
146 // 1. Response body is corrupted - contains chunk size headers mixed with data
147 // 2. Cannot detect end of transfer - connection stays open (keep-alive), causing timeout
148 // The proper fix would be to use getString() for chunked responses, which decodes chunks
149 // internally, but this buffers the entire response in memory.
150 int content_length = container->client_.getSize();
151 ESP_LOGD(TAG, "Content-Length: %d", content_length);
152 container->content_length = (size_t) content_length;
153 // -1 (SIZE_MAX when cast to size_t) means chunked transfer encoding
154 container->set_chunked(content_length == -1);
155 container->duration_ms = millis() - start;
156
157 return container;
158}
159
160// Arduino HTTP read implementation
161//
162// WARNING: Return values differ from BSD sockets! See http_request.h for full documentation.
163//
164// Arduino's WiFiClient is inherently non-blocking - available() returns 0 when
165// no data is ready. We use connected() to distinguish "no data yet" from
166// "connection closed".
167//
168// WiFiClient behavior:
169// available() > 0: data ready to read
170// available() == 0 && connected(): no data yet, still connected
171// available() == 0 && !connected(): connection closed
172//
173// We normalize to HttpContainer::read() contract (NOT BSD socket semantics!):
174// > 0: bytes read
175// 0: no data yet, retry <-- NOTE: 0 means retry, NOT EOF!
176// < 0: error/connection closed <-- connection closed returns -1, not 0
177int HttpContainerArduino::read(uint8_t *buf, size_t max_len) {
178 const uint32_t start = millis();
179 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
180
181 WiFiClient *stream_ptr = this->client_.getStreamPtr();
182 if (stream_ptr == nullptr) {
183 ESP_LOGE(TAG, "Stream pointer vanished!");
184 return HTTP_ERROR_CONNECTION_CLOSED;
185 }
186
187 int available_data = stream_ptr->available();
188 // For chunked transfer encoding, HTTPClient::getSize() returns -1, which becomes SIZE_MAX when
189 // cast to size_t. SIZE_MAX - bytes_read_ is still huge, so it won't limit the read.
190 size_t remaining = (this->content_length > 0) ? (this->content_length - this->bytes_read_) : max_len;
191 int bufsize = std::min(max_len, std::min(remaining, (size_t) available_data));
192
193 if (bufsize == 0) {
194 this->duration_ms += (millis() - start);
195 // Check if we've read all expected content (non-chunked only)
196 // For chunked encoding (content_length == SIZE_MAX), is_read_complete() returns false
197 if (this->is_read_complete()) {
198 return 0; // All content read successfully
199 }
200 // No data available - check if connection is still open
201 // For chunked encoding, !connected() after reading means EOF (all chunks received)
202 // For known content_length with bytes_read_ < content_length, it means connection dropped
203 if (!stream_ptr->connected()) {
204 return HTTP_ERROR_CONNECTION_CLOSED; // Connection closed or EOF for chunked
205 }
206 return 0; // No data yet, caller should retry
207 }
208
209 App.feed_wdt();
210 int read_len = stream_ptr->readBytes(buf, bufsize);
211 this->bytes_read_ += read_len;
212
213 this->duration_ms += (millis() - start);
214
215 return read_len;
216}
217
219 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
220 this->client_.end();
221}
222
223} // namespace esphome::http_request
224
225#endif // USE_ARDUINO && !USE_ESP32
uint8_t status
Definition bl0942.h:8
void feed_wdt(uint32_t time=0)
void status_momentary_error(const char *name, uint32_t length=5000)
Set error status flag and automatically clear it after a timeout.
int read(uint8_t *buf, size_t max_len) override
bool is_read_complete() const
Check if all expected content has been read For chunked responses, returns false (completion detected...
std::shared_ptr< HttpContainer > perform(const std::string &url, const std::string &method, const std::string &body, const std::list< Header > &request_headers, const std::set< std::string > &collect_headers) override
std::shared_ptr< HttpContainer > start(const std::string &url, const std::string &method, const std::string &body, const std::list< Header > &request_headers)
bool is_success(int const status)
Checks if the given HTTP status code indicates a successful request.
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:193
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.