ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
nextion_upload_esp32.cpp
Go to the documentation of this file.
1#include "nextion.h"
2
3#ifdef USE_NEXTION_TFT_UPLOAD
4#ifdef USE_ESP32
5
6#include <esp_heap_caps.h>
7#include <esp_http_client.h>
8#include <cinttypes>
14#include "esphome/core/log.h"
15#include "esphome/core/util.h"
16
17namespace esphome::nextion {
18
19static const char *const TAG = "nextion.upload.esp32";
20static constexpr size_t NEXTION_MAX_RESPONSE_LOG_BYTES = 16;
21
22// Timeout for display acknowledgment during TFT upload (ms).
23// A single value is used for all chunks; the happy path returns as soon as
24// 0x05/0x08 arrives, so this only bounds failed-detection latency. Field
25// reports showed the previous 500ms steady-state value was too tight for
26// some firmware variants.
27static constexpr uint32_t NEXTION_UPLOAD_ACK_TIMEOUT_MS = 5000;
28
29// Followed guide
30// https://unofficialnextion.com/t/nextion-upload-protocol-v1-2-the-fast-one/1044/2
31
32int Nextion::upload_by_chunks_(esp_http_client_handle_t http_client, uint32_t &range_start) {
33 uint32_t range_size = this->tft_size_ - range_start;
34 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
35 uint32_t range_end = ((upload_first_chunk_sent_ or this->tft_size_ < 4096) ? this->tft_size_ : 4096) - 1;
36 ESP_LOGD(TAG, "Range start: %" PRIu32, range_start);
37 if (range_size <= 0 or range_end <= range_start) {
38 ESP_LOGE(TAG, "Invalid range end: %" PRIu32 ", size: %" PRIu32, range_end, range_size);
39 return -1;
40 }
41
42 char range_header[32];
43 buf_append_printf(range_header, sizeof(range_header), 0, "bytes=%" PRIu32 "-%" PRIu32, range_start, range_end);
44 ESP_LOGV(TAG, "Range: %s", range_header);
45 esp_http_client_set_header(http_client, "Range", range_header);
46 ESP_LOGV(TAG, "Open HTTP");
47 esp_err_t err = esp_http_client_open(http_client, 0);
48 if (err != ESP_OK) {
49 ESP_LOGE(TAG, "HTTP open failed: %s", esp_err_to_name(err));
50 return -1;
51 }
52
53 ESP_LOGV(TAG, "Fetch length");
54 const int chunk_size = esp_http_client_fetch_headers(http_client);
55 ESP_LOGV(TAG, "Length: %d", chunk_size);
56 if (chunk_size <= 0) {
57 ESP_LOGE(TAG, "Get length failed: %d", chunk_size);
58 return -1;
59 }
60
61 // Allocate the buffer dynamically
62 RAMAllocator<uint8_t> allocator;
63 uint8_t *buffer = allocator.allocate(4096);
64 if (!buffer) {
65 ESP_LOGE(TAG, "Buffer alloc failed");
66 return -1;
67 }
68
69 std::string recv_string;
70 while (true) {
71 App.feed_wdt();
72 const uint16_t buffer_size =
73 this->content_length_ < 4096 ? this->content_length_ : 4096; // Limits buffer to the remaining data
74 ESP_LOGV(TAG, "Fetch %" PRIu16 " bytes", buffer_size);
75 uint16_t read_len = 0;
76 int partial_read_len = 0;
77 uint8_t retries = 0;
78 // Attempt to read the chunk with retries.
79 while (retries < this->tft_upload_http_retries_ && read_len < buffer_size) {
80 partial_read_len =
81 esp_http_client_read(http_client, reinterpret_cast<char *>(buffer) + read_len, buffer_size - read_len);
82 if (partial_read_len > 0) {
83 read_len += partial_read_len; // Accumulate the total read length.
84 // Reset retries on successful read.
85 retries = 0;
86 } else {
87 // If no data was read, increment retries.
88 retries++;
89 vTaskDelay(pdMS_TO_TICKS(2)); // NOLINT
90 }
91 App.feed_wdt(); // Feed the watchdog timer.
92 }
93 if (read_len != buffer_size) {
94 // Did not receive the full package within the timeout period
95 ESP_LOGE(TAG, "Read failed: %" PRIu16 "/%" PRIu16 " bytes", read_len, buffer_size);
96 // Deallocate buffer
97 allocator.deallocate(buffer, 4096);
98 buffer = nullptr;
99 return -1;
100 }
101 ESP_LOGV(TAG, "Fetched %d bytes", read_len);
102 if (read_len > 0) {
103 recv_string.clear();
104 this->write_array(buffer, buffer_size);
105 App.feed_wdt();
106 this->recv_ret_string_(recv_string, NEXTION_UPLOAD_ACK_TIMEOUT_MS, true);
107
108 // Some Nextion firmware variants (notably bootloader/recovery mode on panels
109 // with no installed TFT) emit the 5-byte 0x08+position fast-mode ack with a
110 // multi-second gap between the leading 0x08 byte and the 4 trailing position
111 // bytes. recv_ret_string_ returns after the first byte; manually drain the
112 // trailing bytes from the UART before continuing.
113 if (!recv_string.empty() && recv_string[0] == 0x08 && recv_string.size() < 5) {
114 const uint32_t deadline = millis() + NEXTION_UPLOAD_ACK_TIMEOUT_MS;
115 while (recv_string.size() < 5 && millis() < deadline) {
116 if (this->available()) {
117 uint8_t b = 0;
118 if (this->read_byte(&b)) {
119 recv_string.push_back(static_cast<char>(b));
120 }
121 } else {
122 vTaskDelay(pdMS_TO_TICKS(5)); // NOLINT
123 App.feed_wdt();
124 }
125 }
126 if (recv_string.size() < 5) {
127 ESP_LOGE(TAG, "Truncated 0x08 response: got %zu bytes within %" PRIu32 "ms", recv_string.size(),
128 NEXTION_UPLOAD_ACK_TIMEOUT_MS);
129 allocator.deallocate(buffer, 4096);
130 buffer = nullptr;
131 return -1;
132 }
133 }
134 this->content_length_ -= read_len;
135 const float upload_percentage = 100.0f * (this->tft_size_ - this->content_length_) / this->tft_size_;
136#ifdef USE_PSRAM
137 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 "+%" PRIu32 ")", upload_percentage,
138 this->content_length_, static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
139 static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
140#else
141 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 ")", upload_percentage, this->content_length_,
142 static_cast<uint32_t>(esp_get_free_heap_size()));
143#endif
145 if (recv_string.empty()) {
146 ESP_LOGW(TAG, "No response from display after %" PRIu32 "ms", NEXTION_UPLOAD_ACK_TIMEOUT_MS);
147 allocator.deallocate(buffer, 4096);
148 buffer = nullptr;
149 return -1;
150 }
151 if (recv_string[0] == 0x08 && recv_string.size() == 5) { // handle partial upload request
152 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
153 ESP_LOGD(
154 TAG, "Recv: [%s]",
155 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
156 uint32_t result = 0;
157 for (int j = 0; j < 4; ++j) {
158 result += static_cast<uint8_t>(recv_string[j + 1]) << (8 * j);
159 }
160 if (result > 0) {
161 ESP_LOGI(TAG, "New range: %" PRIu32, result);
162 this->content_length_ = this->tft_size_ - result;
163 range_start = result;
164 } else {
165 range_start = range_end + 1;
166 }
167 // Deallocate buffer
168 allocator.deallocate(buffer, 4096);
169 buffer = nullptr;
170 return range_end + 1;
171 } else if (recv_string[0] != 0x05 and recv_string[0] != 0x08) { // 0x05 == "ok"
172 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
173 ESP_LOGE(
174 TAG, "Invalid response: [%s]",
175 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
176 // Deallocate buffer
177 allocator.deallocate(buffer, 4096);
178 buffer = nullptr;
179 return -1;
180 }
181
182 recv_string.clear();
183 } else if (read_len == 0) {
184 ESP_LOGV(TAG, "HTTP end");
185 break; // Exit the loop if there is no more data to read
186 } else {
187 ESP_LOGE(TAG, "HTTP read failed: %" PRIu16, read_len);
188 break; // Exit the loop on error
189 }
190 }
191 range_start = range_end + 1;
192 // Deallocate buffer
193 allocator.deallocate(buffer, 4096);
194 buffer = nullptr;
195 return range_end + 1;
196}
197
198bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) {
199 ESP_LOGD(TAG, "TFT upload requested, exit reparse: %s, URL: %s", YESNO(exit_reparse), this->tft_url_.c_str());
200
201 if (this->connection_state_.is_updating_) {
202 ESP_LOGW(TAG, "Upload in progress");
203 return false;
204 }
205
206 if (!network::is_connected()) {
207 ESP_LOGE(TAG, "No network");
208 return false;
209 }
210
211 // Temporarily adjust watchdog timeout for the duration of the TFT upload
212 watchdog::WatchdogManager wdm(this->tft_upload_watchdog_timeout_);
213
214 this->connection_state_.is_updating_ = true;
215
216 if (exit_reparse) {
217 ESP_LOGD(TAG, "Exit reparse mode");
218 if (!this->set_protocol_reparse_mode(false)) {
219 ESP_LOGW(TAG, "Exit reparse failed");
220 return false;
221 }
222 }
223
224 // Check if baud rate is supported
226 if (baud_rate <= 0) {
227 baud_rate = this->original_baud_rate_;
228 }
229 ESP_LOGD(TAG, "Baud rate: %" PRIu32, baud_rate);
230
231 // Define the configuration for the HTTP client
232 ESP_LOGV(TAG, "Init HTTP client, heap: %" PRIu32, esp_get_free_heap_size());
233 esp_http_client_config_t config = {
234 .url = this->tft_url_.c_str(),
235 .cert_pem = nullptr,
236 .method = HTTP_METHOD_HEAD,
237 .timeout_ms = static_cast<int>(this->tft_upload_http_timeout_),
238 .disable_auto_redirect = false,
239 .max_redirection_count = 10,
240 };
241 // Initialize the HTTP client with the configuration
242 esp_http_client_handle_t http_client = esp_http_client_init(&config);
243 if (!http_client) {
244 ESP_LOGE(TAG, "HTTP init failed");
245 return this->upload_end_(false);
246 }
247
248 esp_err_t err = esp_http_client_set_header(http_client, "Connection", "keep-alive");
249 if (err != ESP_OK) {
250 ESP_LOGE(TAG, "Set header failed: %s", esp_err_to_name(err));
251 esp_http_client_cleanup(http_client);
252 return this->upload_end_(false);
253 }
254
255 // Perform the HTTP request
256 ESP_LOGV(TAG, "Check connection, heap: %" PRIu32, esp_get_free_heap_size());
257 err = esp_http_client_perform(http_client);
258 if (err != ESP_OK) {
259 ESP_LOGE(TAG, "HTTP failed: %s", esp_err_to_name(err));
260 esp_http_client_cleanup(http_client);
261 return this->upload_end_(false);
262 }
263
264 // Check the HTTP Status Code
265 ESP_LOGV(TAG, "Check status, heap: %" PRIu32, esp_get_free_heap_size());
266 int status_code = esp_http_client_get_status_code(http_client);
267 if (status_code != 200 && status_code != 206) {
268 ESP_LOGE(TAG, "HTTP request failed with status %d", status_code);
269 return this->upload_end_(false);
270 }
271
272 this->tft_size_ = esp_http_client_get_content_length(http_client);
273
274 ESP_LOGD(TAG, "TFT size: %zu bytes", this->tft_size_);
275 if (this->tft_size_ < 4096 || this->tft_size_ > 134217728) {
276 ESP_LOGE(TAG, "Size check failed");
277 ESP_LOGD(TAG, "Close HTTP");
278 esp_http_client_close(http_client);
279 esp_http_client_cleanup(http_client);
280 ESP_LOGV(TAG, "Connection closed");
281 return this->upload_end_(false);
282 } else {
283 ESP_LOGV(TAG, "Size check OK");
284 }
285 this->content_length_ = this->tft_size_;
286
287 ESP_LOGD(TAG, "Uploading");
288
289 // The Nextion will ignore the upload command if it is sleeping
290 ESP_LOGV(TAG, "Wake-up");
291 this->connection_state_.ignore_is_setup_ = true;
292 this->send_command_("sleep=0");
293 this->send_command_("dim=100");
294 vTaskDelay(pdMS_TO_TICKS(250)); // NOLINT
295 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
296
297 App.feed_wdt();
298 char command[128];
299 // Tells the Nextion the content length of the tft file and baud rate it will be sent at
300 // Once the Nextion accepts the command it will wait until the file is successfully uploaded
301 // If it fails for any reason a power cycle of the display will be needed
302 snprintf(command, sizeof(command), "whmi-wris %" PRIu32 ",%" PRIu32 ",1", this->content_length_, baud_rate);
303
304 // Clear serial receive buffer
305 ESP_LOGV(TAG, "Clear RX buffer");
306 this->reset_(false);
307 vTaskDelay(pdMS_TO_TICKS(250)); // NOLINT
308 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
309
310 ESP_LOGV(TAG, "Upload cmd: %s", command);
311 this->send_command_(command);
312
313 if (baud_rate != this->original_baud_rate_) {
314 ESP_LOGD(TAG, "Baud: %" PRIu32 "->%" PRIu32, this->original_baud_rate_, baud_rate);
315 this->parent_->set_baud_rate(baud_rate);
316 this->parent_->load_settings();
317 }
318
319 std::string response;
320 ESP_LOGV(TAG, "Wait upload resp");
321 this->recv_ret_string_(response, 5000, true); // This can take some time to return
322
323 // The Nextion display will, if it's ready to accept data, send a 0x05 byte.
324 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
325 ESP_LOGD(TAG, "Upload resp: [%s] %zu B",
326 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(response.data()), response.size()),
327 response.length());
328 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
329
330 if (response.find(0x05) != std::string::npos) {
331 ESP_LOGV(TAG, "Upload prep done");
332 } else {
333 ESP_LOGE(TAG, "Upload prep failed %d '%s'", response[0], response.c_str());
334 ESP_LOGD(TAG, "Close HTTP");
335 esp_http_client_close(http_client);
336 esp_http_client_cleanup(http_client);
337 ESP_LOGV(TAG, "Connection closed");
338 return this->upload_end_(false);
339 }
340
341 ESP_LOGV(TAG, "Set method to GET");
342 esp_err_t set_method_result = esp_http_client_set_method(http_client, HTTP_METHOD_GET);
343 if (set_method_result != ESP_OK) {
344 ESP_LOGE(TAG, "Set GET failed: %s", esp_err_to_name(set_method_result));
345 return this->upload_end_(false);
346 }
347
348 ESP_LOGD(TAG,
349 "Uploading TFT:\n"
350 " URL: %s\n"
351 " Size: %" PRIu32 " bytes\n"
352 " Heap: %" PRIu32,
353 this->tft_url_.c_str(), this->content_length_, esp_get_free_heap_size());
354
355 // Proceed with the content download as before
356
357 ESP_LOGV(TAG, "Start chunk transfer");
358
359 uint32_t position = 0;
360 while (this->content_length_ > 0) {
361 int upload_result = upload_by_chunks_(http_client, position);
362 if (upload_result < 0) {
363 ESP_LOGE(TAG, "TFT upload error");
364 ESP_LOGD(TAG, "Close HTTP");
365 esp_http_client_close(http_client);
366 esp_http_client_cleanup(http_client);
367 ESP_LOGV(TAG, "Connection closed");
368 return this->upload_end_(false);
369 }
370 App.feed_wdt();
371 ESP_LOGV(TAG, "Heap: %" PRIu32 " left: %" PRIu32, esp_get_free_heap_size(), this->content_length_);
372 }
373
374 ESP_LOGD(TAG, "TFT upload complete, closing HTTP");
375 esp_http_client_close(http_client);
376 esp_http_client_cleanup(http_client);
377 ESP_LOGV(TAG, "Connection closed");
378 return this->upload_end_(true);
379}
380
381} // namespace esphome::nextion
382
383#endif // USE_ESP32
384#endif // USE_NEXTION_TFT_UPLOAD
void feed_wdt()
Feed the task watchdog.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2053
void deallocate(T *p, size_t n)
Definition helpers.h:2110
T * allocate(size_t n)
Definition helpers.h:2080
int upload_by_chunks_(esp_http_client_handle_t http_client, uint32_t &range_start)
will request 4096 bytes chunks from the web server and send each to Nextion
bool send_command_(const std::string &command)
Manually send a raw command to the display and don't wait for an acknowledgement packet.
uint8_t tft_upload_http_retries_
HTTP retry count (default: 5)
Definition nextion.h:1550
struct esphome::nextion::Nextion::@144 connection_state_
Status flags for Nextion display state management.
bool upload_tft(uint32_t baud_rate=0, bool exit_reparse=true)
Uploads the TFT file to the Nextion display.
uint16_t tft_upload_http_timeout_
HTTP timeout in ms (default: 4.5s)
Definition nextion.h:1549
bool set_protocol_reparse_mode(bool active_mode)
Sets the Nextion display's protocol reparse mode.
bool upload_end_(bool successful)
Ends the upload process, restart Nextion and, if successful, restarts ESP.
uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag)
void reset_(bool reset_nextion=true)
uint32_t tft_upload_watchdog_timeout_
WDT timeout in ms (0 = no adjustment)
Definition nextion.h:1553
virtual void load_settings(bool dump_config)
Load the UART settings.
void set_baud_rate(uint32_t baud_rate)
UARTComponent * parent_
Definition uart.h:73
bool read_byte(uint8_t *data)
Definition uart.h:34
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
float position
Definition cover.h:0
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:27
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:341
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1386
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t