ESPHome 2026.3.0
Loading...
Searching...
No Matches
http_request_update.cpp
Go to the documentation of this file.
2
5
8
9namespace esphome {
10namespace http_request {
11
12// The update function runs in a task only on ESP32s.
13#ifdef USE_ESP32
14// vTaskDelete doesn't return, but clang-tidy doesn't know that
15#define UPDATE_RETURN \
16 do { \
17 vTaskDelete(nullptr); \
18 __builtin_unreachable(); \
19 } while (0)
20#else
21#define UPDATE_RETURN return
22#endif
23
24static const char *const TAG = "http_request.update";
25
26// Wraps UpdateInfo + error for the task→main-loop handoff.
27struct TaskResult {
28 update::UpdateInfo info;
29 const LogString *error_str{nullptr};
30};
31
32static const size_t MAX_READ_SIZE = 256;
33static constexpr uint32_t INITIAL_CHECK_INTERVAL_ID = 0;
34static constexpr uint32_t INITIAL_CHECK_INTERVAL_MS = 10000;
35static constexpr uint8_t INITIAL_CHECK_MAX_ATTEMPTS = 6;
36
39
40 // Check periodically until network is ready
41 // Only if update interval is > total retry window to avoid redundant checks
43 this->get_update_interval() > INITIAL_CHECK_INTERVAL_MS * INITIAL_CHECK_MAX_ATTEMPTS) {
44 this->initial_check_remaining_ = INITIAL_CHECK_MAX_ATTEMPTS;
45 this->set_interval(INITIAL_CHECK_INTERVAL_ID, INITIAL_CHECK_INTERVAL_MS, [this]() {
46 bool connected = network::is_connected();
47 if (--this->initial_check_remaining_ == 0 || connected) {
48 this->cancel_interval(INITIAL_CHECK_INTERVAL_ID);
49 if (connected) {
50 this->update();
51 }
52 }
53 });
54 }
55}
56
57void HttpRequestUpdate::on_ota_state(ota::OTAState state, float progress, uint8_t error) {
60 this->update_info_.has_progress = true;
61 this->update_info_.progress = progress;
62 this->publish_state();
65 this->status_set_error(LOG_STR("Failed to install firmware"));
66 this->publish_state();
67 }
68}
69
71 if (!network::is_connected()) {
72 ESP_LOGD(TAG, "Network not connected, skipping update check");
73 return;
74 }
75 this->cancel_interval(INITIAL_CHECK_INTERVAL_ID);
76#ifdef USE_ESP32
77 xTaskCreate(HttpRequestUpdate::update_task, "update_task", 8192, (void *) this, 1, &this->update_task_handle_);
78#else
79 this->update_task(this);
80#endif
81}
82
84 HttpRequestUpdate *this_update = (HttpRequestUpdate *) params;
85
86 // Allocate once — every path below returns via the single defer at the end.
87 // On failure, error_str is set; on success it is nullptr.
88 auto *result = new TaskResult();
89 auto *info = &result->info;
90
91 auto container = this_update->request_parent_->get(this_update->source_url_);
92
93 if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
94 ESP_LOGE(TAG, "Failed to fetch manifest from %s", this_update->source_url_.c_str());
95 if (container != nullptr)
96 container->end();
97 result->error_str = LOG_STR("Failed to fetch manifest");
98 goto defer; // NOLINT(cppcoreguidelines-avoid-goto)
99 }
100
101 {
102 RAMAllocator<uint8_t> allocator;
103 uint8_t *data = allocator.allocate(container->content_length);
104 if (data == nullptr) {
105 ESP_LOGE(TAG, "Failed to allocate %zu bytes for manifest", container->content_length);
106 container->end();
107 result->error_str = LOG_STR("Failed to allocate memory for manifest");
108 goto defer; // NOLINT(cppcoreguidelines-avoid-goto)
109 }
110
111 auto read_result = http_read_fully(container.get(), data, container->content_length, MAX_READ_SIZE,
112 this_update->request_parent_->get_timeout());
113 if (read_result.status != HttpReadStatus::OK) {
114 if (read_result.status == HttpReadStatus::TIMEOUT) {
115 ESP_LOGE(TAG, "Timeout reading manifest");
116 } else {
117 ESP_LOGE(TAG, "Error reading manifest: %d", read_result.error_code);
118 }
119 allocator.deallocate(data, container->content_length);
120 container->end();
121 result->error_str = LOG_STR("Failed to read manifest");
122 goto defer; // NOLINT(cppcoreguidelines-avoid-goto)
123 }
124 size_t read_index = container->get_bytes_read();
125 size_t content_length = container->content_length;
126
127 container->end();
128 container.reset(); // Release ownership of the container's shared_ptr
129
130 bool valid = false;
131 { // Scope to ensure JsonDocument is destroyed before deallocating buffer
132 valid = json::parse_json(data, read_index, [info](JsonObject root) -> bool {
133 if (!root[ESPHOME_F("name")].is<const char *>() || !root[ESPHOME_F("version")].is<const char *>() ||
134 !root[ESPHOME_F("builds")].is<JsonArray>()) {
135 ESP_LOGE(TAG, "Manifest does not contain required fields");
136 return false;
137 }
138 info->title = root[ESPHOME_F("name")].as<std::string>();
139 info->latest_version = root[ESPHOME_F("version")].as<std::string>();
140
141 auto builds_array = root[ESPHOME_F("builds")].as<JsonArray>();
142 for (auto build : builds_array) {
143 if (!build[ESPHOME_F("chipFamily")].is<const char *>()) {
144 ESP_LOGE(TAG, "Manifest does not contain required fields");
145 return false;
146 }
147 if (build[ESPHOME_F("chipFamily")] == ESPHOME_VARIANT) {
148 if (!build[ESPHOME_F("ota")].is<JsonObject>()) {
149 ESP_LOGE(TAG, "Manifest does not contain required fields");
150 return false;
151 }
152 JsonObject ota = build[ESPHOME_F("ota")].as<JsonObject>();
153 if (!ota[ESPHOME_F("path")].is<const char *>() || !ota[ESPHOME_F("md5")].is<const char *>()) {
154 ESP_LOGE(TAG, "Manifest does not contain required fields");
155 return false;
156 }
157 info->firmware_url = ota[ESPHOME_F("path")].as<std::string>();
158 info->md5 = ota[ESPHOME_F("md5")].as<std::string>();
159
160 if (ota[ESPHOME_F("summary")].is<const char *>())
161 info->summary = ota[ESPHOME_F("summary")].as<std::string>();
162 if (ota[ESPHOME_F("release_url")].is<const char *>())
163 info->release_url = ota[ESPHOME_F("release_url")].as<std::string>();
164
165 return true;
166 }
167 }
168 return false;
169 });
170 }
171 allocator.deallocate(data, content_length);
172
173 if (!valid) {
174 ESP_LOGE(TAG, "Failed to parse JSON from %s", this_update->source_url_.c_str());
175 result->error_str = LOG_STR("Failed to parse manifest JSON");
176 goto defer; // NOLINT(cppcoreguidelines-avoid-goto)
177 }
178
179 // Merge source_url_ and firmware_url
180 if (!info->firmware_url.empty() && info->firmware_url.find("http") == std::string::npos) {
181 std::string path = info->firmware_url;
182 if (path[0] == '/') {
183 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.find('/', 8));
184 info->firmware_url = domain + path;
185 } else {
186 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.rfind('/') + 1);
187 info->firmware_url = domain + path;
188 }
189 }
190
191#ifdef ESPHOME_PROJECT_VERSION
192 info->current_version = ESPHOME_PROJECT_VERSION;
193#else
194 info->current_version = ESPHOME_VERSION;
195#endif
196 }
197
198defer:
199 // Release container before vTaskDelete (which doesn't call destructors)
200 container.reset();
201
202 // Defer to the main loop so all update_info_ and state_ writes happen on the
203 // same thread as readers (API, MQTT, web server). This is a single defer for
204 // both success and error paths to avoid multiple std::function instantiations.
205 // Lambda captures only 2 pointers (8 bytes) — fits in std::function SBO on supported toolchains.
206 this_update->defer([this_update, result]() {
207 if (result->error_str != nullptr) {
208 this_update->status_set_error(result->error_str);
209 delete result;
210 return;
211 }
212
213 // Determine new state on main loop (avoids extra lambda captures from task)
214 bool trigger_update_available = false;
215 update::UpdateState new_state;
216 if (result->info.latest_version.empty() || result->info.latest_version == result->info.current_version) {
218 } else {
220 if (this_update->state_ != update::UPDATE_STATE_AVAILABLE) {
221 trigger_update_available = true;
222 }
223 }
224
225 this_update->update_info_ = std::move(result->info);
226 this_update->state_ = new_state;
227 delete result; // Safe: moved-from state is valid for destruction
228
229 this_update->status_clear_error();
230 this_update->publish_state();
231
232 if (trigger_update_available) {
233 this_update->get_update_available_trigger()->trigger(this_update->update_info_);
234 }
235 });
236
237 UPDATE_RETURN;
238}
239
241 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
242 return;
243 }
244
246 this->publish_state();
247
248 this->ota_parent_->set_md5(this->update_info.md5);
250 // Flash in the next loop
251 this->defer([this]() { this->ota_parent_->flash(); });
252}
253
254} // namespace http_request
255} // namespace esphome
ESPDEPRECATED("Use const char* overload instead. Removed in 2026.7.0", "2026.1.0") void defer(const std voi defer)(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Definition component.h:501
void status_clear_error()
Definition component.h:260
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_interval(const std voi set_interval)(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.h:358
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_interval(const std boo cancel_interval)(const char *name)
Cancel an interval function.
Definition component.h:380
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1899
void deallocate(T *p, size_t n)
Definition helpers.h:1954
T * allocate(size_t n)
Definition helpers.h:1916
std::shared_ptr< HttpContainer > get(const std::string &url)
void on_ota_state(ota::OTAState state, float progress, uint8_t error) override
void add_state_listener(OTAStateListener *listener)
Definition ota_backend.h:66
const UpdateState & state
Trigger< const UpdateInfo & > * get_update_available_trigger()
const UpdateInfo & update_info
bool state
Definition fan.h:2
constexpr uint32_t INITIAL_CHECK_INTERVAL_ID
HttpReadResult http_read_fully(HttpContainer *container, uint8_t *buffer, size_t total_size, size_t chunk_size, uint32_t timeout_ms)
Read data from HTTP container into buffer with timeout handling Handles feed_wdt, yield,...
@ TIMEOUT
Timeout waiting for data.
@ OK
Read completed successfully.
bool parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
Definition json_util.cpp:27
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:27
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
constexpr uint32_t SCHEDULER_DONT_RUN
Definition component.h:49
bool valid
static void uint32_t