ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ota_web_server.cpp
Go to the documentation of this file.
1#include "ota_web_server.h"
2#ifdef USE_WEBSERVER_OTA
3
5#include "esphome/core/log.h"
6
7#ifdef USE_CAPTIVE_PORTAL
9#endif
10
11namespace esphome::web_server {
12
13ESPHOME_LOG_TAG(TAG, "web_server.ota");
14
15bool WebServerOTAComponent::canHandle(AsyncWebServerRequest *request) const {
16 if (request->method() != HTTP_POST)
17 return false;
18 // Check if this is an OTA update request
19#ifdef USE_ESP32
20 char url_buf[AsyncWebServerRequest::URL_BUF_SIZE];
21 bool is_ota_request = request->url_to(url_buf) == "/update";
22#else
23 bool is_ota_request = request->url() == ESPHOME_F("/update");
24#endif
25
26#if defined(USE_WEBSERVER_OTA_DISABLED) && defined(USE_CAPTIVE_PORTAL)
27 // IMPORTANT: USE_WEBSERVER_OTA_DISABLED only disables OTA for the web_server component
28 // Captive portal can still perform OTA updates - check if request is from active captive portal
29 // Note: global_captive_portal is the standard way components communicate in ESPHome
30 return is_ota_request && captive_portal::global_captive_portal != nullptr &&
32#elif defined(USE_WEBSERVER_OTA_DISABLED)
33 // OTA disabled for web_server and no captive portal compiled in
34 return false;
35#else
36 // OTA enabled for web_server
37 return is_ota_request;
38#endif
39}
40
41void WebServerOTAComponent::report_ota_progress_(AsyncWebServerRequest *request) {
42 const uint32_t now = millis();
43 if (now - this->last_ota_progress_ > 1000) {
44 float percentage = 0.0f;
45 if (request->contentLength() != 0) {
46 // Note: Using contentLength() for progress calculation is technically wrong as it includes
47 // multipart headers/boundaries, but it's only off by a small amount and we don't have
48 // access to the actual firmware size until the upload is complete. This is intentional
49 // as it still gives the user a reasonable progress indication.
50 percentage = (this->ota_read_length_ * 100.0f) / request->contentLength();
51 ESP_LOGD(TAG, "OTA in progress: %0.1f%%", percentage);
52 } else {
53 ESP_LOGD(TAG, "OTA in progress: %" PRIu32 " bytes read", this->ota_read_length_);
54 }
55#ifdef USE_OTA_STATE_LISTENER
56 // Report progress - use notify_state_deferred_ since we're in web server task
57 this->notify_state_deferred_(ota::OTA_IN_PROGRESS, percentage, 0);
58#endif
59 this->last_ota_progress_ = now;
60 }
61}
62
64 ESP_LOGI(TAG, "OTA update successful!");
65 this->set_timeout(100, []() {
66 ESP_LOGI(TAG, "Performing OTA reboot now");
68 });
69}
70
71void WebServerOTAComponent::ota_init_(const char *filename) {
72 ESP_LOGI(TAG, "OTA Update Start: %s", filename);
73 this->ota_read_length_ = 0;
74 this->ota_success_ = false;
75}
76
77void WebServerOTAComponent::handleUpload(AsyncWebServerRequest *request, const PlatformString &filename, size_t index,
78 uint8_t *data, size_t len, bool final) {
80
81 // First byte of a new upload: index==0 with actual data. (web_server_idf
82 // fires a separate start-marker call with data==nullptr/len==0 before the
83 // first real chunk; gate on len>0 so we only trigger once per upload.)
84 if (index == 0 && len > 0) {
85 // A stalled upload times out and onDisconnect() frees it, so refusing can't block for long.
86 if (this->ota_backend_) {
87 ESP_LOGW(TAG, "OTA upload refused: another upload is in progress");
88 this->refuse_(request);
89 return;
90 }
91
92 this->ota_backend_ = ota::make_ota_backend();
93 if (!this->ota_backend_) {
94 ESP_LOGE(TAG, "Failed to create OTA backend");
95#ifdef USE_OTA_STATE_LISTENER
97#endif
98 return;
99 }
100
101 // Web server OTA uses multipart uploads where the actual firmware size
102 // is unknown (contentLength includes multipart overhead)
103 // Pass 0 to indicate unknown size
104 error_code = this->ota_backend_->begin(0);
105 if (error_code == ota::OTA_RESPONSE_ERROR_UPDATE_BUSY) {
106 // Nothing started: no state notifications.
107 ESP_LOGW(TAG, "OTA upload refused: another update is in progress");
108 this->ota_backend_.reset();
109 this->refuse_(request);
110 return;
111 }
112
113 // Initialize OTA on first call
114 this->ota_init_(filename.c_str());
115
116#ifdef USE_OTA_STATE_LISTENER
117 // Notify OTA started - use notify_state_deferred_ since we're in web server task
119#endif
120
121 if (error_code != ota::OTA_RESPONSE_OK) {
122 ESP_LOGE(TAG, "OTA begin failed: %d", error_code);
123 this->ota_backend_.reset();
124#ifdef USE_OTA_STATE_LISTENER
125 this->notify_state_deferred_(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
126#endif
127 return;
128 }
129
130 // An interrupted upload gets no final chunk.
131 this->ota_request_ = request;
132 request->onDisconnect([this, request]() {
133 if (this->ota_request_ == request && this->ota_backend_) {
134 ESP_LOGW(TAG, "OTA upload interrupted; aborting");
135 this->abort_session_();
136 }
137 });
138 }
139
140 if (!this->ota_backend_ || request != this->ota_request_) {
141 return;
142 }
143
144 // Process data
145 if (len > 0) {
146 error_code = this->ota_backend_->write(data, len);
147 if (error_code != ota::OTA_RESPONSE_OK) {
148 ESP_LOGE(TAG, "OTA write failed: %d", error_code);
149 this->ota_backend_->abort();
150 this->ota_backend_.reset();
151 this->ota_request_ = nullptr;
152#ifdef USE_OTA_STATE_LISTENER
153 this->notify_state_deferred_(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
154#endif
155 return;
156 }
157 this->ota_read_length_ += len;
158 this->report_ota_progress_(request);
159 }
160
161 // Finalize
162 if (final) {
163 ESP_LOGD(TAG, "OTA final chunk: index=%zu, len=%zu, total_read=%" PRIu32 ", contentLength=%zu", index, len,
164 this->ota_read_length_, request->contentLength());
165
166 // For Arduino framework, the Update library tracks expected size from firmware header
167 // If we haven't received enough data, calling end() will fail
168 // This can happen if the upload is interrupted or the client disconnects
169 error_code = this->ota_backend_->end();
170 if (error_code == ota::OTA_RESPONSE_OK) {
171 this->ota_success_ = true;
172#ifdef USE_OTA_STATE_LISTENER
173 // Report completion before reboot - use notify_state_deferred_ since we're in web server task
175#endif
176 this->schedule_ota_reboot_();
177 } else {
178 ESP_LOGE(TAG, "OTA end failed: %d", error_code);
179 // Reset the platform updater before the lock is released.
180 this->ota_backend_->abort();
181#ifdef USE_OTA_STATE_LISTENER
182 this->notify_state_deferred_(ota::OTA_ERROR, 0.0f, static_cast<uint8_t>(error_code));
183#endif
184 }
185 this->ota_backend_.reset();
186 this->ota_request_ = nullptr;
187 }
188}
189
191 this->ota_backend_->abort();
192#ifdef USE_OTA_STATE_LISTENER
194#endif
195 this->ota_backend_.reset();
196 this->ota_request_ = nullptr;
197}
198
199void WebServerOTAComponent::refuse_(AsyncWebServerRequest *request) {
200 this->refused_request_ = request;
201 request->onDisconnect([this, request]() {
202 if (this->refused_request_ == request)
203 this->refused_request_ = nullptr;
204 });
205}
206
207void WebServerOTAComponent::handleRequest(AsyncWebServerRequest *request) {
208 AsyncWebServerResponse *response;
209 // Use the ota_success_ flag to determine the actual result
210 const bool refused = request == this->refused_request_;
211 if (refused)
212 this->refused_request_ = nullptr;
213#ifdef USE_ESP8266
214 static const char UPDATE_SUCCESS[] PROGMEM = "Update Successful!";
215 static const char UPDATE_FAILED[] PROGMEM = "Update Failed!";
216 static const char UPDATE_BUSY[] PROGMEM = "Update Failed! Another update is in progress, retry later.";
217 static const char TEXT_PLAIN[] PROGMEM = "text/plain";
218 static const char CONNECTION_STR[] PROGMEM = "Connection";
219 static const char CLOSE_STR[] PROGMEM = "close";
220 const char *msg = refused ? UPDATE_BUSY : (this->ota_success_ ? UPDATE_SUCCESS : UPDATE_FAILED);
221 response = request->beginResponse_P(200, TEXT_PLAIN, msg);
222 response->addHeader(CONNECTION_STR, CLOSE_STR);
223#else
224 const char *msg = refused ? "Update Failed! Another update is in progress, retry later."
225 : this->ota_success_ ? "Update Successful!"
226 : "Update Failed!";
227 response = request->beginResponse(200, "text/plain", msg);
228 response->addHeader("Connection", "close");
229#endif
230 request->send(response);
231}
232
234 // Get the global web server base instance and register our handler
236 if (base == nullptr) {
237 ESP_LOGE(TAG, "WebServerBase not found");
238 this->mark_failed();
239 return;
240 }
241
242 base->add_handler(this);
243}
244
245void WebServerOTAComponent::dump_config() { ESP_LOGCONFIG(TAG, "Web Server OTA"); }
246
247} // namespace esphome::web_server
248
249#endif // USE_WEBSERVER_OTA
void mark_failed()
Mark this component as failed.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void notify_state_deferred_(OTAState state, float progress, uint8_t error)
Notify state with deferral to main loop (for thread safety).
void handleRequest(AsyncWebServerRequest *request) override
void report_ota_progress_(AsyncWebServerRequest *request)
bool canHandle(AsyncWebServerRequest *request) const override
void refuse_(AsyncWebServerRequest *request)
Reply "busy" without touching the running upload.
void abort_session_()
Abort and drop the backend, releasing the lock.
void handleUpload(AsyncWebServerRequest *request, const PlatformString &filename, size_t index, uint8_t *data, size_t len, bool final) override
void add_handler(AsyncWebHandler *handler)
CaptivePortal * global_captive_portal
@ OTA_RESPONSE_ERROR_UPDATE_BUSY
Definition ota_backend.h:54
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:55
std::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
WebServerBase * global_web_server_base
ESPHOME_LOG_TAG(TAG, "web_server.ota")
constexpr uint8_t INDEX_GZ[] PROGMEM
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
std::string PlatformString