ESPHome 2026.2.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 size_t content_length = container->content_length;
94
95 container->end();
96 container.reset(); // Release ownership of the container's shared_ptr
97
98 bool valid = false;
99 { // Scope to ensure JsonDocument is destroyed before deallocating buffer
100 valid = json::parse_json(data, read_index, [this_update](JsonObject root) -> bool {
101 if (!root[ESPHOME_F("name")].is<const char *>() || !root[ESPHOME_F("version")].is<const char *>() ||
102 !root[ESPHOME_F("builds")].is<JsonArray>()) {
103 ESP_LOGE(TAG, "Manifest does not contain required fields");
104 return false;
105 }
106 this_update->update_info_.title = root[ESPHOME_F("name")].as<std::string>();
107 this_update->update_info_.latest_version = root[ESPHOME_F("version")].as<std::string>();
108
109 for (auto build : root[ESPHOME_F("builds")].as<JsonArray>()) {
110 if (!build[ESPHOME_F("chipFamily")].is<const char *>()) {
111 ESP_LOGE(TAG, "Manifest does not contain required fields");
112 return false;
113 }
114 if (build[ESPHOME_F("chipFamily")] == ESPHOME_VARIANT) {
115 if (!build[ESPHOME_F("ota")].is<JsonObject>()) {
116 ESP_LOGE(TAG, "Manifest does not contain required fields");
117 return false;
118 }
119 JsonObject ota = build[ESPHOME_F("ota")].as<JsonObject>();
120 if (!ota[ESPHOME_F("path")].is<const char *>() || !ota[ESPHOME_F("md5")].is<const char *>()) {
121 ESP_LOGE(TAG, "Manifest does not contain required fields");
122 return false;
123 }
124 this_update->update_info_.firmware_url = ota[ESPHOME_F("path")].as<std::string>();
125 this_update->update_info_.md5 = ota[ESPHOME_F("md5")].as<std::string>();
126
127 if (ota[ESPHOME_F("summary")].is<const char *>())
128 this_update->update_info_.summary = ota[ESPHOME_F("summary")].as<std::string>();
129 if (ota[ESPHOME_F("release_url")].is<const char *>())
130 this_update->update_info_.release_url = ota[ESPHOME_F("release_url")].as<std::string>();
131
132 return true;
133 }
134 }
135 return false;
136 });
137 }
138 allocator.deallocate(data, content_length);
139
140 if (!valid) {
141 ESP_LOGE(TAG, "Failed to parse JSON from %s", this_update->source_url_.c_str());
142 // Defer to main loop to avoid race condition on component_state_ read-modify-write
143 this_update->defer([this_update]() { this_update->status_set_error(LOG_STR("Failed to parse manifest JSON")); });
144 UPDATE_RETURN;
145 }
146
147 // Merge source_url_ and this_update->update_info_.firmware_url
148 if (this_update->update_info_.firmware_url.find("http") == std::string::npos) {
149 std::string path = this_update->update_info_.firmware_url;
150 if (path[0] == '/') {
151 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.find('/', 8));
152 this_update->update_info_.firmware_url = domain + path;
153 } else {
154 std::string domain = this_update->source_url_.substr(0, this_update->source_url_.rfind('/') + 1);
155 this_update->update_info_.firmware_url = domain + path;
156 }
157 }
158
159#ifdef ESPHOME_PROJECT_VERSION
160 this_update->update_info_.current_version = ESPHOME_PROJECT_VERSION;
161#else
162 this_update->update_info_.current_version = ESPHOME_VERSION;
163#endif
164
165 bool trigger_update_available = false;
166
167 if (this_update->update_info_.latest_version.empty() ||
168 this_update->update_info_.latest_version == this_update->update_info_.current_version) {
170 } else {
171 if (this_update->state_ != update::UPDATE_STATE_AVAILABLE) {
172 trigger_update_available = true;
173 }
175 }
176
177 // Defer to main loop to ensure thread-safe execution of:
178 // - status_clear_error() performs non-atomic read-modify-write on component_state_
179 // - publish_state() triggers API callbacks that write to the shared protobuf buffer
180 // which can be corrupted if accessed concurrently from task and main loop threads
181 // - update_available trigger to ensure consistent state when the trigger fires
182 this_update->defer([this_update, trigger_update_available]() {
183 this_update->update_info_.has_progress = false;
184 this_update->update_info_.progress = 0.0f;
185
186 this_update->status_clear_error();
187 this_update->publish_state();
188
189 if (trigger_update_available) {
190 this_update->get_update_available_trigger()->trigger(this_update->update_info_);
191 }
192 });
193
194 UPDATE_RETURN;
195}
196
198 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
199 return;
200 }
201
203 this->publish_state();
204
205 this->ota_parent_->set_md5(this->update_info.md5);
207 // Flash in the next loop
208 this->defer([this]() { this->ota_parent_->flash(); });
209}
210
211} // namespace http_request
212} // 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:479
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:1647
void deallocate(T *p, size_t n)
Definition helpers.h:1705
T * allocate(size_t n)
Definition helpers.h:1667
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:2
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