ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
ota_http_request.cpp
Go to the documentation of this file.
1#include "ota_http_request.h"
2
5#include "esphome/core/log.h"
6
13
14namespace esphome {
15namespace http_request {
16
17static const char *const TAG = "http_request.ota";
18
19void OtaHttpRequestComponent::dump_config() { ESP_LOGCONFIG(TAG, "Over-The-Air updates via HTTP request"); };
20
21void OtaHttpRequestComponent::set_md5_url(const std::string &url) {
22 if (!this->validate_url_(url)) {
23 this->md5_url_.clear(); // URL was not valid; prevent flashing until it is
24 return;
25 }
26 this->md5_url_ = url;
27 this->md5_expected_.clear(); // to be retrieved later
28}
29
30void OtaHttpRequestComponent::set_url(const std::string &url) {
31 if (!this->validate_url_(url)) {
32 this->url_.clear(); // URL was not valid; prevent flashing until it is
33 return;
34 }
35 this->url_ = url;
36}
37
39 if (this->url_.empty()) {
40 ESP_LOGE(TAG, "URL not set; cannot start update");
41 return;
42 }
43
44 ESP_LOGI(TAG, "Starting update");
45#ifdef USE_OTA_STATE_LISTENER
46 this->notify_state_(ota::OTA_STARTED, 0.0f, 0);
47#endif
48
49 auto ota_status = this->do_ota_();
50
51 switch (ota_status) {
53#ifdef USE_OTA_STATE_LISTENER
54 this->notify_state_(ota::OTA_COMPLETED, 100.0f, ota_status);
55#endif
56 delay(10);
58 break;
59
60 default:
61#ifdef USE_OTA_STATE_LISTENER
62 this->notify_state_(ota::OTA_ERROR, 0.0f, ota_status);
63#endif
64 this->md5_computed_.clear(); // will be reset at next attempt
65 this->md5_expected_.clear(); // will be reset at next attempt
66 break;
67 }
68}
69
70void OtaHttpRequestComponent::cleanup_(std::unique_ptr<ota::OTABackend> backend,
71 const std::shared_ptr<HttpContainer> &container) {
72 if (this->update_started_) {
73 ESP_LOGV(TAG, "Aborting OTA backend");
74 backend->abort();
75 }
76 ESP_LOGV(TAG, "Aborting HTTP connection");
77 container->end();
78};
79
82 uint32_t last_progress = 0;
83 uint32_t update_start_time = millis();
84 md5::MD5Digest md5_receive;
85 std::unique_ptr<char[]> md5_receive_str(new char[33]);
86
87 if (this->md5_expected_.empty() && !this->http_get_md5_()) {
88 return OTA_MD5_INVALID;
89 }
90
91 ESP_LOGD(TAG, "MD5 expected: %s", this->md5_expected_.c_str());
92
93 auto url_with_auth = this->get_url_with_auth_(this->url_);
94 if (url_with_auth.empty()) {
95 return OTA_BAD_URL;
96 }
97 ESP_LOGVV(TAG, "url_with_auth: %s", url_with_auth.c_str());
98 ESP_LOGI(TAG, "Connecting to: %s", this->url_.c_str());
99
100 auto container = this->parent_->get(url_with_auth);
101
102 if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
104 }
105
106 // we will compute MD5 on the fly for verification -- Arduino OTA seems to ignore it
107 md5_receive.init();
108 ESP_LOGV(TAG, "MD5Digest initialized");
109
110 ESP_LOGV(TAG, "OTA backend begin");
111 auto backend = ota::make_ota_backend();
112 auto error_code = backend->begin(container->content_length);
113 if (error_code != ota::OTA_RESPONSE_OK) {
114 ESP_LOGW(TAG, "backend->begin error: %d", error_code);
115 this->cleanup_(std::move(backend), container);
116 return error_code;
117 }
118
119 while (container->get_bytes_read() < container->content_length) {
120 // read a maximum of chunk_size bytes into buf. (real read size returned)
121 int bufsize = container->read(buf, OtaHttpRequestComponent::HTTP_RECV_BUFFER);
122 ESP_LOGVV(TAG, "bytes_read_ = %u, body_length_ = %u, bufsize = %i", container->get_bytes_read(),
123 container->content_length, bufsize);
124
125 // feed watchdog and give other tasks a chance to run
126 App.feed_wdt();
127 yield();
128
129 // Exit loop if no data available (stream closed or end of data)
130 if (bufsize <= 0) {
131 if (bufsize < 0) {
132 ESP_LOGE(TAG, "Stream closed with error");
133 this->cleanup_(std::move(backend), container);
135 }
136 // bufsize == 0: no more data available, exit loop
137 break;
138 }
139
141 // add read bytes to MD5
142 md5_receive.add(buf, bufsize);
143
144 // write bytes to OTA backend
145 this->update_started_ = true;
146 error_code = backend->write(buf, bufsize);
147 if (error_code != ota::OTA_RESPONSE_OK) {
148 // error code explanation available at
149 // https://github.com/esphome/esphome/blob/dev/esphome/components/ota/ota_backend.h
150 ESP_LOGE(TAG, "Error code (%02X) writing binary data to flash at offset %d and size %d", error_code,
151 container->get_bytes_read() - bufsize, container->content_length);
152 this->cleanup_(std::move(backend), container);
153 return error_code;
154 }
155 }
156
157 uint32_t now = millis();
158 if ((now - last_progress > 1000) or (container->get_bytes_read() == container->content_length)) {
159 last_progress = now;
160 float percentage = container->get_bytes_read() * 100.0f / container->content_length;
161 ESP_LOGD(TAG, "Progress: %0.1f%%", percentage);
162#ifdef USE_OTA_STATE_LISTENER
163 this->notify_state_(ota::OTA_IN_PROGRESS, percentage, 0);
164#endif
165 }
166 } // while
167
168 ESP_LOGI(TAG, "Done in %.0f seconds", float(millis() - update_start_time) / 1000);
169
170 // verify MD5 is as expected and act accordingly
171 md5_receive.calculate();
172 md5_receive.get_hex(md5_receive_str.get());
173 this->md5_computed_ = md5_receive_str.get();
174 if (strncmp(this->md5_computed_.c_str(), this->md5_expected_.c_str(), MD5_SIZE) != 0) {
175 ESP_LOGE(TAG, "MD5 computed: %s - Aborting due to MD5 mismatch", this->md5_computed_.c_str());
176 this->cleanup_(std::move(backend), container);
178 } else {
179 backend->set_update_md5(md5_receive_str.get());
180 }
181
182 container->end();
183
184 // feed watchdog and give other tasks a chance to run
185 App.feed_wdt();
186 yield();
187 delay(100); // NOLINT
188
189 error_code = backend->end();
190 if (error_code != ota::OTA_RESPONSE_OK) {
191 ESP_LOGW(TAG, "Error ending update! error_code: %d", error_code);
192 this->cleanup_(std::move(backend), container);
193 return error_code;
194 }
195
196 ESP_LOGI(TAG, "Update complete");
198}
199
200std::string OtaHttpRequestComponent::get_url_with_auth_(const std::string &url) {
201 if (this->username_.empty() || this->password_.empty()) {
202 return url;
203 }
204
205 auto start_char = url.find("://");
206 if ((start_char == std::string::npos) || (start_char < 4)) {
207 ESP_LOGE(TAG, "Incorrect URL prefix");
208 return {};
209 }
210
211 ESP_LOGD(TAG, "Using basic HTTP authentication");
212
213 start_char += 3; // skip '://' characters
214 auto url_with_auth =
215 url.substr(0, start_char) + this->username_ + ":" + this->password_ + "@" + url.substr(start_char);
216 return url_with_auth;
217}
218
220 if (this->md5_url_.empty()) {
221 return false;
222 }
223
224 auto url_with_auth = this->get_url_with_auth_(this->md5_url_);
225 if (url_with_auth.empty()) {
226 return false;
227 }
228
229 ESP_LOGVV(TAG, "url_with_auth: %s", url_with_auth.c_str());
230 ESP_LOGI(TAG, "Connecting to: %s", this->md5_url_.c_str());
231 auto container = this->parent_->get(url_with_auth);
232 if (container == nullptr) {
233 ESP_LOGE(TAG, "Failed to connect to MD5 URL");
234 return false;
235 }
236 size_t length = container->content_length;
237 if (length == 0) {
238 container->end();
239 return false;
240 }
241 if (length < MD5_SIZE) {
242 ESP_LOGE(TAG, "MD5 file must be %u bytes; %u bytes reported by HTTP server. Aborting", MD5_SIZE, length);
243 container->end();
244 return false;
245 }
246
247 this->md5_expected_.resize(MD5_SIZE);
248 int read_len = 0;
249 while (container->get_bytes_read() < MD5_SIZE) {
250 read_len = container->read((uint8_t *) this->md5_expected_.data(), MD5_SIZE);
251 if (read_len <= 0) {
252 break;
253 }
254 App.feed_wdt();
255 yield();
256 }
257 container->end();
258
259 ESP_LOGV(TAG, "Read len: %u, MD5 expected: %u", read_len, MD5_SIZE);
260 return read_len == MD5_SIZE;
261}
262
263bool OtaHttpRequestComponent::validate_url_(const std::string &url) {
264 if ((url.length() < 8) || !url.starts_with("http") || (url.find("://") == std::string::npos)) {
265 ESP_LOGE(TAG, "URL is invalid and/or must be prefixed with 'http://' or 'https://'");
266 return false;
267 }
268 return true;
269}
270
271} // namespace http_request
272} // namespace esphome
void feed_wdt(uint32_t time=0)
void get_hex(char *output)
Retrieve the hash as hex characters. Output buffer must hold get_size() * 2 + 1 bytes.
Definition hash_base.h:29
void cleanup_(std::unique_ptr< ota::OTABackend > backend, const std::shared_ptr< HttpContainer > &container)
std::string get_url_with_auth_(const std::string &url)
void set_md5_url(const std::string &md5_url)
void calculate() override
Compute the digest, based on the provided data.
Definition md5.cpp:17
void add(const uint8_t *data, size_t len) override
Add bytes of data for the digest.
Definition md5.cpp:15
void init() override
Initialize a new MD5 digest computation.
Definition md5.cpp:10
void notify_state_(OTAState state, float progress, uint8_t error)
std::unique_ptr< ota::OTABackend > make_ota_backend()
@ OTA_RESPONSE_ERROR_MD5_MISMATCH
Definition ota_backend.h:39
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT yield()
Definition core.cpp:24
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:26
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t length
Definition tt21100.cpp:0