ESPHome 2026.1.4
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
26static const size_t MAX_READ_SIZE = 256;
27
29
30void HttpRequestUpdate::on_ota_state(ota::OTAState state, float progress, uint8_t error) {
33 this->update_info_.has_progress = true;
34 this->update_info_.progress = progress;
35 this->publish_state();
38 this->status_set_error(LOG_STR("Failed to install firmware"));
39 this->publish_state();
40 }
41}
42
44 if (!network::is_connected()) {
45 ESP_LOGD(TAG, "Network not connected, skipping update check");
46 return;
47 }
48#ifdef USE_ESP32
49 xTaskCreate(HttpRequestUpdate::update_task, "update_task", 8192, (void *) this, 1, &this->update_task_handle_);
50#else
51 this->update_task(this);
52#endif
53}
54
56 HttpRequestUpdate *this_update = (HttpRequestUpdate *) params;
57
58 auto container = this_update->request_parent_->get(this_update->source_url_);
59
60 if (container == nullptr || container->status_code != HTTP_STATUS_OK) {
61 ESP_LOGE(TAG, "Failed to fetch manifest from %s", this_update->source_url_.c_str());
62 // Defer to main loop to avoid race condition on component_state_ read-modify-write
63 this_update->defer([this_update]() { this_update->status_set_error(LOG_STR("Failed to fetch manifest")); });
64 UPDATE_RETURN;
65 }
66
67 RAMAllocator<uint8_t> allocator;
68 uint8_t *data = allocator.allocate(container->content_length);
69 if (data == nullptr) {
70 ESP_LOGE(TAG, "Failed to allocate %zu bytes for manifest", container->content_length);
71 // Defer to main loop to avoid race condition on component_state_ read-modify-write
72 this_update->defer(
73 [this_update]() { this_update->status_set_error(LOG_STR("Failed to allocate memory for manifest")); });
74 container->end();
75 UPDATE_RETURN;
76 }
77
78 auto read_result = http_read_fully(container.get(), data, container->content_length, MAX_READ_SIZE,
79 this_update->request_parent_->get_timeout());
80 if (read_result.status != HttpReadStatus::OK) {
81 if (read_result.status == HttpReadStatus::TIMEOUT) {
82 ESP_LOGE(TAG, "Timeout reading manifest");
83 } else {
84 ESP_LOGE(TAG, "Error reading manifest: %d", read_result.error_code);
85 }
86 // Defer to main loop to avoid race condition on component_state_ read-modify-write
87 this_update->defer([this_update]() { this_update->status_set_error(LOG_STR("Failed to read manifest")); });
88 allocator.deallocate(data, container->content_length);
89 container->end();
90 UPDATE_RETURN;
91 }
92 size_t read_index = container->get_bytes_read();
93
94 bool valid = false;
95 { // Ensures the response string falls out of scope and deallocates before the task ends
96 std::string response((char *) data, read_index);
97 allocator.deallocate(data, container->content_length);
98
99 container->end();
100 container.reset(); // Release ownership of the container's shared_ptr
101
102 valid = json::parse_json(response, [this_update](JsonObject root) -> bool {
103 if (!root[ESPHOME_F("name")].is<const char *>() || !root[ESPHOME_F("version")].is<const char *>() ||
104 !root[ESPHOME_F("builds")].is<JsonArray>()) {
105 ESP_LOGE(TAG, "Manifest does not contain required fields");
106 return false;
107 }
108 this_update->update_info_.title = root[ESPHOME_F("name")].as<std::string>();
109 this_update->update_info_.latest_version = root[ESPHOME_F("version")].as<std::string>();
110
111 for (auto build : root[ESPHOME_F("builds")].as<JsonArray>()) {
112 if (!build[ESPHOME_F("chipFamily")].is<const char *>()) {
113 ESP_LOGE(TAG, "Manifest does not contain required fields");
114 return false;
115 }
116 if (build[ESPHOME_F("chipFamily")] == ESPHOME_VARIANT) {
117 if (!build[ESPHOME_F("ota")].is<JsonObject>()) {
118 ESP_LOGE(TAG, "Manifest does not contain required fields");
119 return false;
120 }
121 JsonObject ota = build[ESPHOME_F("ota")].as<JsonObject>();
122 if (!ota[ESPHOME_F("path")].is<const char *>() || !ota[ESPHOME_F("md5")].is<const char *>()) {
123 ESP_LOGE(TAG, "Manifest does not contain required fields");
124 return false;
125 }
126 this_update->update_info_.firmware_url = ota[ESPHOME_F("path")].as<std::string>();
127 this_update->update_info_.md5 = ota[ESPHOME_F("md5")].as<std::string>();
128
129 if (ota[ESPHOME_F("summary")].is<const char *>())
130 this_update->update_info_.summary = ota[ESPHOME_F("summary")].as<std::string>();
131 if (ota[ESPHOME_F("release_url")].is<const char *>())
132 this_update->update_info_.release_url = ota[ESPHOME_F("release_url")].as<std::string>();
133
134 return true;
135 }
136 }
137 return false;
138 });
139 }
140
141 if (!valid) {
142 ESP_LOGE(TAG, "Failed to parse JSON from %s", this_update->source_url_.c_str());
143 // Defer to main loop to avoid race condition on component_state_ read-modify-write
144 this_update->defer([this_update]() { this_update->status_set_error(LOG_STR("Failed to parse manifest JSON")); });
145 UPDATE_RETURN;
146 }
147
148 // Merge source_url_ and this_update->update_info_.firmware_url
149 if (this_update->update_info_.firmware_url.find("http") == std::string::npos) {
150 std::string path = this_update->update_info_.firmware_url;
151 if (path[0] == '/') {
152 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.find('/', 8));
153 this_update->update_info_.firmware_url = domain + path;
154 } else {
155 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.rfind('/') + 1);
156 this_update->update_info_.firmware_url = domain + path;
157 }
158 }
159
160 { // Ensures the current version string falls out of scope and deallocates before the task ends
161 std::string current_version;
162#ifdef ESPHOME_PROJECT_VERSION
163 current_version = ESPHOME_PROJECT_VERSION;
164#else
165 current_version = ESPHOME_VERSION;
166#endif
167
168 this_update->update_info_.current_version = current_version;
169 }
170
171 bool trigger_update_available = false;
172
173 if (this_update->update_info_.latest_version.empty() ||
174 this_update->update_info_.latest_version == this_update->update_info_.current_version) {
176 } else {
177 if (this_update->state_ != update::UPDATE_STATE_AVAILABLE) {
178 trigger_update_available = true;
179 }
181 }
182
183 // Defer to main loop to ensure thread-safe execution of:
184 // - status_clear_error() performs non-atomic read-modify-write on component_state_
185 // - publish_state() triggers API callbacks that write to the shared protobuf buffer
186 // which can be corrupted if accessed concurrently from task and main loop threads
187 // - update_available trigger to ensure consistent state when the trigger fires
188 this_update->defer([this_update, trigger_update_available]() {
189 this_update->update_info_.has_progress = false;
190 this_update->update_info_.progress = 0.0f;
191
192 this_update->status_clear_error();
193 this_update->publish_state();
194
195 if (trigger_update_available) {
196 this_update->get_update_available_trigger()->trigger(this_update->update_info_);
197 }
198 });
199
200 UPDATE_RETURN;
201}
202
204 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
205 return;
206 }
207
209 this->publish_state();
210
211 this->ota_parent_->set_md5(this->update_info.md5);
213 // Flash in the next loop
214 this->defer([this]() { this->ota_parent_->flash(); });
215}
216
217} // namespace http_request
218} // 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:492
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1422
void deallocate(T *p, size_t n)
Definition helpers.h:1480
T * allocate(size_t n)
Definition helpers.h:1442
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:77
const UpdateState & state
Trigger< const UpdateInfo & > * get_update_available_trigger()
const UpdateInfo & update_info
bool state
Definition fan.h:0
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
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7