ESPHome 2025.5.0
Loading...
Searching...
No Matches
http_request_arduino.cpp
Go to the documentation of this file.
2
3#ifdef USE_ARDUINO
4
7
10#include "esphome/core/log.h"
11
12namespace esphome {
13namespace http_request {
14
15static const char *const TAG = "http_request.arduino";
16
17std::shared_ptr<HttpContainer> HttpRequestArduino::perform(std::string url, std::string method, std::string body,
18 std::list<Header> request_headers,
19 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#elif defined(USE_ESP32)
78 bool status = container->client_.begin(url.c_str());
79#endif
80
81 App.feed_wdt();
82
83 if (!status) {
84 ESP_LOGW(TAG, "HTTP Request failed; URL: %s", url.c_str());
85 container->end();
86 this->status_momentary_error("failed", 1000);
87 return nullptr;
88 }
89
90 container->client_.setReuse(true);
91 container->client_.setTimeout(this->timeout_);
92#if defined(USE_ESP32)
93 container->client_.setConnectTimeout(this->timeout_);
94#endif
95
96 if (this->useragent_ != nullptr) {
97 container->client_.setUserAgent(this->useragent_);
98 }
99 for (const auto &header : request_headers) {
100 container->client_.addHeader(header.name.c_str(), header.value.c_str(), false, true);
101 }
102
103 // returned needed headers must be collected before the requests
104 const char *header_keys[collect_headers.size()];
105 int index = 0;
106 for (auto const &header_name : collect_headers) {
107 header_keys[index++] = header_name.c_str();
108 }
109 container->client_.collectHeaders(header_keys, index);
110
111 App.feed_wdt();
112 container->status_code = container->client_.sendRequest(method.c_str(), body.c_str());
113 App.feed_wdt();
114 if (container->status_code < 0) {
115 ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url.c_str(),
116 HTTPClient::errorToString(container->status_code).c_str());
117 this->status_momentary_error("failed", 1000);
118 container->end();
119 return nullptr;
120 }
121
122 if (!is_success(container->status_code)) {
123 ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url.c_str(), container->status_code);
124 this->status_momentary_error("failed", 1000);
125 // Still return the container, so it can be used to get the status code and error message
126 }
127
128 container->response_headers_ = {};
129 auto header_count = container->client_.headers();
130 for (int i = 0; i < header_count; i++) {
131 const std::string header_name = str_lower_case(container->client_.headerName(i).c_str());
132 if (collect_headers.count(header_name) > 0) {
133 std::string header_value = container->client_.header(i).c_str();
134 ESP_LOGD(TAG, "Received response header, name: %s, value: %s", header_name.c_str(), header_value.c_str());
135 container->response_headers_[header_name].push_back(header_value);
136 break;
137 }
138 }
139
140 int content_length = container->client_.getSize();
141 ESP_LOGD(TAG, "Content-Length: %d", content_length);
142 container->content_length = (size_t) content_length;
143 container->duration_ms = millis() - start;
144
145 return container;
146}
147
148int HttpContainerArduino::read(uint8_t *buf, size_t max_len) {
149 const uint32_t start = millis();
150 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
151
152 WiFiClient *stream_ptr = this->client_.getStreamPtr();
153 if (stream_ptr == nullptr) {
154 ESP_LOGE(TAG, "Stream pointer vanished!");
155 return -1;
156 }
157
158 int available_data = stream_ptr->available();
159 int bufsize = std::min(max_len, std::min(this->content_length - this->bytes_read_, (size_t) available_data));
160
161 if (bufsize == 0) {
162 this->duration_ms += (millis() - start);
163 return 0;
164 }
165
166 App.feed_wdt();
167 int read_len = stream_ptr->readBytes(buf, bufsize);
168 this->bytes_read_ += read_len;
169
170 this->duration_ms += (millis() - start);
171
172 return read_len;
173}
174
176 watchdog::WatchdogManager wdm(this->parent_->get_watchdog_timeout());
177 this->client_.end();
178}
179
180} // namespace http_request
181} // namespace esphome
182
183#endif // USE_ARDUINO
uint8_t status
Definition bl0942.h:8
void feed_wdt(uint32_t time=0)
void status_momentary_error(const std::string &name, uint32_t length=5000)
int read(uint8_t *buf, size_t max_len) override
std::shared_ptr< HttpContainer > perform(std::string url, std::string method, std::string body, std::list< Header > request_headers, 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:15
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
Definition helpers.cpp:290
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:27
Application App
Global storage of Application pointer - only one Application can exist.