ESPHome 2026.3.0
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 {
18namespace nextion {
19static const char *const TAG = "nextion.upload.esp32";
20static constexpr size_t NEXTION_MAX_RESPONSE_LOG_BYTES = 16;
21
22// Followed guide
23// https://unofficialnextion.com/t/nextion-upload-protocol-v1-2-the-fast-one/1044/2
24
25int Nextion::upload_by_chunks_(esp_http_client_handle_t http_client, uint32_t &range_start) {
26 uint32_t range_size = this->tft_size_ - range_start;
27 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
28 uint32_t range_end = ((upload_first_chunk_sent_ or this->tft_size_ < 4096) ? this->tft_size_ : 4096) - 1;
29 ESP_LOGD(TAG, "Range start: %" PRIu32, range_start);
30 if (range_size <= 0 or range_end <= range_start) {
31 ESP_LOGE(TAG, "Invalid range end: %" PRIu32 ", size: %" PRIu32, range_end, range_size);
32 return -1;
33 }
34
35 char range_header[32];
36 buf_append_printf(range_header, sizeof(range_header), 0, "bytes=%" PRIu32 "-%" PRIu32, range_start, range_end);
37 ESP_LOGV(TAG, "Range: %s", range_header);
38 esp_http_client_set_header(http_client, "Range", range_header);
39 ESP_LOGV(TAG, "Open HTTP");
40 esp_err_t err = esp_http_client_open(http_client, 0);
41 if (err != ESP_OK) {
42 ESP_LOGE(TAG, "HTTP open failed: %s", esp_err_to_name(err));
43 return -1;
44 }
45
46 ESP_LOGV(TAG, "Fetch length");
47 const int chunk_size = esp_http_client_fetch_headers(http_client);
48 ESP_LOGV(TAG, "Length: %d", chunk_size);
49 if (chunk_size <= 0) {
50 ESP_LOGE(TAG, "Get length failed: %d", chunk_size);
51 return -1;
52 }
53
54 // Allocate the buffer dynamically
55 RAMAllocator<uint8_t> allocator;
56 uint8_t *buffer = allocator.allocate(4096);
57 if (!buffer) {
58 ESP_LOGE(TAG, "Buffer alloc failed");
59 return -1;
60 }
61
62 std::string recv_string;
63 while (true) {
64 App.feed_wdt();
65 const uint16_t buffer_size =
66 this->content_length_ < 4096 ? this->content_length_ : 4096; // Limits buffer to the remaining data
67 ESP_LOGV(TAG, "Fetch %" PRIu16 " bytes", buffer_size);
68 uint16_t read_len = 0;
69 int partial_read_len = 0;
70 uint8_t retries = 0;
71 // Attempt to read the chunk with retries.
72 while (retries < this->tft_upload_http_retries_ && read_len < buffer_size) {
73 partial_read_len =
74 esp_http_client_read(http_client, reinterpret_cast<char *>(buffer) + read_len, buffer_size - read_len);
75 if (partial_read_len > 0) {
76 read_len += partial_read_len; // Accumulate the total read length.
77 // Reset retries on successful read.
78 retries = 0;
79 } else {
80 // If no data was read, increment retries.
81 retries++;
82 vTaskDelay(pdMS_TO_TICKS(2)); // NOLINT
83 }
84 App.feed_wdt(); // Feed the watchdog timer.
85 }
86 if (read_len != buffer_size) {
87 // Did not receive the full package within the timeout period
88 ESP_LOGE(TAG, "Read failed: %" PRIu16 "/%" PRIu16 " bytes", read_len, buffer_size);
89 // Deallocate buffer
90 allocator.deallocate(buffer, 4096);
91 buffer = nullptr;
92 return -1;
93 }
94 ESP_LOGV(TAG, "Fetched %d bytes", read_len);
95 if (read_len > 0) {
96 recv_string.clear();
97 this->write_array(buffer, buffer_size);
98 App.feed_wdt();
99 this->recv_ret_string_(recv_string, upload_first_chunk_sent_ ? 500 : 5000, true);
100 this->content_length_ -= read_len;
101 const float upload_percentage = 100.0f * (this->tft_size_ - this->content_length_) / this->tft_size_;
102#ifdef USE_PSRAM
103 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 "+%" PRIu32 ")", upload_percentage,
104 this->content_length_, static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
105 static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
106#else
107 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 ")", upload_percentage, this->content_length_,
108 static_cast<uint32_t>(esp_get_free_heap_size()));
109#endif
111 if (recv_string.empty()) {
112 ESP_LOGW(TAG, "No response from display during upload");
113 allocator.deallocate(buffer, 4096);
114 buffer = nullptr;
115 return -1;
116 }
117 if (recv_string[0] == 0x08 && recv_string.size() == 5) { // handle partial upload request
118 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
119 ESP_LOGD(
120 TAG, "Recv: [%s]",
121 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
122 uint32_t result = 0;
123 for (int j = 0; j < 4; ++j) {
124 result += static_cast<uint8_t>(recv_string[j + 1]) << (8 * j);
125 }
126 if (result > 0) {
127 ESP_LOGI(TAG, "New range: %" PRIu32, result);
128 this->content_length_ = this->tft_size_ - result;
129 range_start = result;
130 } else {
131 range_start = range_end + 1;
132 }
133 // Deallocate buffer
134 allocator.deallocate(buffer, 4096);
135 buffer = nullptr;
136 return range_end + 1;
137 } else if (recv_string[0] != 0x05 and recv_string[0] != 0x08) { // 0x05 == "ok"
138 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
139 ESP_LOGE(
140 TAG, "Invalid response: [%s]",
141 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
142 // Deallocate buffer
143 allocator.deallocate(buffer, 4096);
144 buffer = nullptr;
145 return -1;
146 }
147
148 recv_string.clear();
149 } else if (read_len == 0) {
150 ESP_LOGV(TAG, "HTTP end");
151 break; // Exit the loop if there is no more data to read
152 } else {
153 ESP_LOGE(TAG, "HTTP read failed: %" PRIu16, read_len);
154 break; // Exit the loop on error
155 }
156 }
157 range_start = range_end + 1;
158 // Deallocate buffer
159 allocator.deallocate(buffer, 4096);
160 buffer = nullptr;
161 return range_end + 1;
162}
163
164bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) {
165 ESP_LOGD(TAG, "TFT upload requested, exit reparse: %s, URL: %s", YESNO(exit_reparse), this->tft_url_.c_str());
166
167 if (this->connection_state_.is_updating_) {
168 ESP_LOGW(TAG, "Upload in progress");
169 return false;
170 }
171
172 if (!network::is_connected()) {
173 ESP_LOGE(TAG, "No network");
174 return false;
175 }
176
177 // Temporarily adjust watchdog timeout for the duration of the TFT upload
178 watchdog::WatchdogManager wdm(this->tft_upload_watchdog_timeout_);
179
180 this->connection_state_.is_updating_ = true;
181
182 if (exit_reparse) {
183 ESP_LOGD(TAG, "Exit reparse mode");
184 if (!this->set_protocol_reparse_mode(false)) {
185 ESP_LOGW(TAG, "Exit reparse failed");
186 return false;
187 }
188 }
189
190 // Check if baud rate is supported
192 if (baud_rate <= 0) {
193 baud_rate = this->original_baud_rate_;
194 }
195 ESP_LOGD(TAG, "Baud rate: %" PRIu32, baud_rate);
196
197 // Define the configuration for the HTTP client
198 ESP_LOGV(TAG, "Init HTTP client, heap: %" PRIu32, esp_get_free_heap_size());
199 esp_http_client_config_t config = {
200 .url = this->tft_url_.c_str(),
201 .cert_pem = nullptr,
202 .method = HTTP_METHOD_HEAD,
203 .timeout_ms = static_cast<int>(this->tft_upload_http_timeout_),
204 .disable_auto_redirect = false,
205 .max_redirection_count = 10,
206 };
207 // Initialize the HTTP client with the configuration
208 esp_http_client_handle_t http_client = esp_http_client_init(&config);
209 if (!http_client) {
210 ESP_LOGE(TAG, "HTTP init failed");
211 return this->upload_end_(false);
212 }
213
214 esp_err_t err = esp_http_client_set_header(http_client, "Connection", "keep-alive");
215 if (err != ESP_OK) {
216 ESP_LOGE(TAG, "Set header failed: %s", esp_err_to_name(err));
217 esp_http_client_cleanup(http_client);
218 return this->upload_end_(false);
219 }
220
221 // Perform the HTTP request
222 ESP_LOGV(TAG, "Check connection, heap: %" PRIu32, esp_get_free_heap_size());
223 err = esp_http_client_perform(http_client);
224 if (err != ESP_OK) {
225 ESP_LOGE(TAG, "HTTP failed: %s", esp_err_to_name(err));
226 esp_http_client_cleanup(http_client);
227 return this->upload_end_(false);
228 }
229
230 // Check the HTTP Status Code
231 ESP_LOGV(TAG, "Check status, heap: %" PRIu32, esp_get_free_heap_size());
232 int status_code = esp_http_client_get_status_code(http_client);
233 if (status_code != 200 && status_code != 206) {
234 ESP_LOGE(TAG, "HTTP request failed with status %d", status_code);
235 return this->upload_end_(false);
236 }
237
238 this->tft_size_ = esp_http_client_get_content_length(http_client);
239
240 ESP_LOGD(TAG, "TFT size: %zu bytes", this->tft_size_);
241 if (this->tft_size_ < 4096 || this->tft_size_ > 134217728) {
242 ESP_LOGE(TAG, "Size check failed");
243 ESP_LOGD(TAG, "Close HTTP");
244 esp_http_client_close(http_client);
245 esp_http_client_cleanup(http_client);
246 ESP_LOGV(TAG, "Connection closed");
247 return this->upload_end_(false);
248 } else {
249 ESP_LOGV(TAG, "Size check OK");
250 }
251 this->content_length_ = this->tft_size_;
252
253 ESP_LOGD(TAG, "Uploading");
254
255 // The Nextion will ignore the upload command if it is sleeping
256 ESP_LOGV(TAG, "Wake-up");
257 this->connection_state_.ignore_is_setup_ = true;
258 this->send_command_("sleep=0");
259 this->send_command_("dim=100");
260 vTaskDelay(pdMS_TO_TICKS(250)); // NOLINT
261 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
262
263 App.feed_wdt();
264 char command[128];
265 // Tells the Nextion the content length of the tft file and baud rate it will be sent at
266 // Once the Nextion accepts the command it will wait until the file is successfully uploaded
267 // If it fails for any reason a power cycle of the display will be needed
268 snprintf(command, sizeof(command), "whmi-wris %" PRIu32 ",%" PRIu32 ",1", this->content_length_, baud_rate);
269
270 // Clear serial receive buffer
271 ESP_LOGV(TAG, "Clear RX buffer");
272 this->reset_(false);
273 vTaskDelay(pdMS_TO_TICKS(250)); // NOLINT
274 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
275
276 ESP_LOGV(TAG, "Upload cmd: %s", command);
277 this->send_command_(command);
278
279 if (baud_rate != this->original_baud_rate_) {
280 ESP_LOGD(TAG, "Baud: %" PRIu32 "->%" PRIu32, this->original_baud_rate_, baud_rate);
281 this->parent_->set_baud_rate(baud_rate);
282 this->parent_->load_settings();
283 }
284
285 std::string response;
286 ESP_LOGV(TAG, "Wait upload resp");
287 this->recv_ret_string_(response, 5000, true); // This can take some time to return
288
289 // The Nextion display will, if it's ready to accept data, send a 0x05 byte.
290 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
291 ESP_LOGD(TAG, "Upload resp: [%s] %zu B",
292 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(response.data()), response.size()),
293 response.length());
294 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
295
296 if (response.find(0x05) != std::string::npos) {
297 ESP_LOGV(TAG, "Upload prep done");
298 } else {
299 ESP_LOGE(TAG, "Upload prep failed %d '%s'", response[0], response.c_str());
300 ESP_LOGD(TAG, "Close HTTP");
301 esp_http_client_close(http_client);
302 esp_http_client_cleanup(http_client);
303 ESP_LOGV(TAG, "Connection closed");
304 return this->upload_end_(false);
305 }
306
307 ESP_LOGV(TAG, "Set method to GET");
308 esp_err_t set_method_result = esp_http_client_set_method(http_client, HTTP_METHOD_GET);
309 if (set_method_result != ESP_OK) {
310 ESP_LOGE(TAG, "Set GET failed: %s", esp_err_to_name(set_method_result));
311 return this->upload_end_(false);
312 }
313
314 ESP_LOGD(TAG,
315 "Uploading TFT:\n"
316 " URL: %s\n"
317 " Size: %" PRIu32 " bytes\n"
318 " Heap: %" PRIu32,
319 this->tft_url_.c_str(), this->content_length_, esp_get_free_heap_size());
320
321 // Proceed with the content download as before
322
323 ESP_LOGV(TAG, "Start chunk transfer");
324
325 uint32_t position = 0;
326 while (this->content_length_ > 0) {
327 int upload_result = upload_by_chunks_(http_client, position);
328 if (upload_result < 0) {
329 ESP_LOGE(TAG, "TFT upload error");
330 ESP_LOGD(TAG, "Close HTTP");
331 esp_http_client_close(http_client);
332 esp_http_client_cleanup(http_client);
333 ESP_LOGV(TAG, "Connection closed");
334 return this->upload_end_(false);
335 }
336 App.feed_wdt();
337 ESP_LOGV(TAG, "Heap: %" PRIu32 " left: %" PRIu32, esp_get_free_heap_size(), this->content_length_);
338 }
339
340 ESP_LOGD(TAG, "TFT upload complete, closing HTTP");
341 esp_http_client_close(http_client);
342 esp_http_client_cleanup(http_client);
343 ESP_LOGV(TAG, "Connection closed");
344 return this->upload_end_(true);
345}
346
347} // namespace nextion
348} // namespace esphome
349
350#endif // USE_ESP32
351#endif // USE_NEXTION_TFT_UPLOAD
void feed_wdt(uint32_t time=0)
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
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.
Definition nextion.cpp:27
uint8_t tft_upload_http_retries_
HTTP retry count (default: 5)
Definition nextion.h:1470
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:1469
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)
Definition nextion.cpp:991
void reset_(bool reset_nextion=true)
Definition nextion.cpp:137
uint32_t tft_upload_watchdog_timeout_
WDT timeout in ms (0 = no adjustment)
Definition nextion.h:1473
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
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
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:353
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:1200
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t