ESPHome 2026.1.0-dev
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 int content_length = container->client_.getSize();
135 ESP_LOGD(TAG, "Content-Length: %d", content_length);
136 container->content_length = (size_t) content_length;
137 container->duration_ms = millis() - start;
138
139 return container;
140}
141
142int HttpContainerArduino::read(uint8_t *buf, size_t max_len) {
143 const uint32_t start = millis();
144 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
145
146 WiFiClient *stream_ptr = this->client_.getStreamPtr();
147 if (stream_ptr == nullptr) {
148 ESP_LOGE(TAG, "Stream pointer vanished!");
149 return -1;
150 }
151
152 int available_data = stream_ptr->available();
153 int bufsize = std::min(max_len, std::min(this->content_length - this->bytes_read_, (size_t) available_data));
154
155 if (bufsize == 0) {
156 this->duration_ms += (millis() - start);
157 return 0;
158 }
159
160 App.feed_wdt();
161 int read_len = stream_ptr->readBytes(buf, bufsize);
162 this->bytes_read_ += read_len;
163
164 this->duration_ms += (millis() - start);
165
166 return read_len;
167}
168
170 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
171 this->client_.end();
172}
173
174} // namespace esphome::http_request
175
176#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
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:190
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.