ESPHome 2026.1.0-dev
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>
12#include "esphome/core/log.h"
13#include "esphome/core/util.h"
14
15namespace esphome {
16namespace nextion {
17static const char *const TAG = "nextion.upload.esp32";
18
19// Followed guide
20// https://unofficialnextion.com/t/nextion-upload-protocol-v1-2-the-fast-one/1044/2
21
22int Nextion::upload_by_chunks_(esp_http_client_handle_t http_client, uint32_t &range_start) {
23 uint32_t range_size = this->tft_size_ - range_start;
24 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
25 uint32_t range_end = ((upload_first_chunk_sent_ or this->tft_size_ < 4096) ? this->tft_size_ : 4096) - 1;
26 ESP_LOGD(TAG, "Range start: %" PRIu32, range_start);
27 if (range_size <= 0 or range_end <= range_start) {
28 ESP_LOGD(TAG,
29 "Range end: %" PRIu32 "\n"
30 "Range size: %" PRIu32,
31 range_end, range_size);
32 ESP_LOGE(TAG, "Invalid range");
33 return -1;
34 }
35
36 char range_header[32];
37 sprintf(range_header, "bytes=%" PRIu32 "-%" PRIu32, range_start, range_end);
38 ESP_LOGV(TAG, "Range: %s", range_header);
39 esp_http_client_set_header(http_client, "Range", range_header);
40 ESP_LOGV(TAG, "Open HTTP");
41 esp_err_t err = esp_http_client_open(http_client, 0);
42 if (err != ESP_OK) {
43 ESP_LOGE(TAG, "HTTP open failed: %s", esp_err_to_name(err));
44 return -1;
45 }
46
47 ESP_LOGV(TAG, "Fetch length");
48 const int chunk_size = esp_http_client_fetch_headers(http_client);
49 ESP_LOGV(TAG, "Length: %d", chunk_size);
50 if (chunk_size <= 0) {
51 ESP_LOGE(TAG, "Get length failed: %d", chunk_size);
52 return -1;
53 }
54
55 // Allocate the buffer dynamically
56 RAMAllocator<uint8_t> allocator;
57 uint8_t *buffer = allocator.allocate(4096);
58 if (!buffer) {
59 ESP_LOGE(TAG, "Buffer alloc failed");
60 return -1;
61 }
62
63 std::string recv_string;
64 while (true) {
65 App.feed_wdt();
66 const uint16_t buffer_size =
67 this->content_length_ < 4096 ? this->content_length_ : 4096; // Limits buffer to the remaining data
68 ESP_LOGV(TAG, "Fetch %" PRIu16 " bytes", buffer_size);
69 uint16_t read_len = 0;
70 int partial_read_len = 0;
71 uint8_t retries = 0;
72 // Attempt to read the chunk with retries.
73 while (retries < 5 && read_len < buffer_size) {
74 partial_read_len =
75 esp_http_client_read(http_client, reinterpret_cast<char *>(buffer) + read_len, buffer_size - read_len);
76 if (partial_read_len > 0) {
77 read_len += partial_read_len; // Accumulate the total read length.
78 // Reset retries on successful read.
79 retries = 0;
80 } else {
81 // If no data was read, increment retries.
82 retries++;
83 vTaskDelay(pdMS_TO_TICKS(2)); // NOLINT
84 }
85 App.feed_wdt(); // Feed the watchdog timer.
86 }
87 if (read_len != buffer_size) {
88 // Did not receive the full package within the timeout period
89 ESP_LOGE(TAG, "Read failed: %" PRIu16 "/%" PRIu16 " bytes", read_len, buffer_size);
90 // Deallocate buffer
91 allocator.deallocate(buffer, 4096);
92 buffer = nullptr;
93 return -1;
94 }
95 ESP_LOGV(TAG, "Fetched %d bytes", read_len);
96 if (read_len > 0) {
97 recv_string.clear();
98 this->write_array(buffer, buffer_size);
99 App.feed_wdt();
100 this->recv_ret_string_(recv_string, upload_first_chunk_sent_ ? 500 : 5000, true);
101 this->content_length_ -= read_len;
102 const float upload_percentage = 100.0f * (this->tft_size_ - this->content_length_) / this->tft_size_;
103#ifdef USE_PSRAM
104 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 "+%" PRIu32 ")", upload_percentage,
105 this->content_length_, static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
106 static_cast<uint32_t>(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
107#else
108 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 ")", upload_percentage, this->content_length_,
109 static_cast<uint32_t>(esp_get_free_heap_size()));
110#endif
112 if (recv_string[0] == 0x08 && recv_string.size() == 5) { // handle partial upload request
113 ESP_LOGD(TAG, "Recv: [%s]",
114 format_hex_pretty(reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()).c_str());
115 uint32_t result = 0;
116 for (int j = 0; j < 4; ++j) {
117 result += static_cast<uint8_t>(recv_string[j + 1]) << (8 * j);
118 }
119 if (result > 0) {
120 ESP_LOGI(TAG, "New range: %" PRIu32, result);
121 this->content_length_ = this->tft_size_ - result;
122 range_start = result;
123 } else {
124 range_start = range_end + 1;
125 }
126 // Deallocate buffer
127 allocator.deallocate(buffer, 4096);
128 buffer = nullptr;
129 return range_end + 1;
130 } else if (recv_string[0] != 0x05 and recv_string[0] != 0x08) { // 0x05 == "ok"
131 ESP_LOGE(TAG, "Invalid response: [%s]",
132 format_hex_pretty(reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()).c_str());
133 // Deallocate buffer
134 allocator.deallocate(buffer, 4096);
135 buffer = nullptr;
136 return -1;
137 }
138
139 recv_string.clear();
140 } else if (read_len == 0) {
141 ESP_LOGV(TAG, "HTTP end");
142 break; // Exit the loop if there is no more data to read
143 } else {
144 ESP_LOGE(TAG, "HTTP read failed: %" PRIu16, read_len);
145 break; // Exit the loop on error
146 }
147 }
148 range_start = range_end + 1;
149 // Deallocate buffer
150 allocator.deallocate(buffer, 4096);
151 buffer = nullptr;
152 return range_end + 1;
153}
154
155bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) {
156 ESP_LOGD(TAG,
157 "TFT upload requested\n"
158 "Exit reparse: %s\n"
159 "URL: %s",
160 YESNO(exit_reparse), this->tft_url_.c_str());
161
162 if (this->connection_state_.is_updating_) {
163 ESP_LOGW(TAG, "Upload in progress");
164 return false;
165 }
166
167 if (!network::is_connected()) {
168 ESP_LOGE(TAG, "No network");
169 return false;
170 }
171
172 this->connection_state_.is_updating_ = true;
173
174 if (exit_reparse) {
175 ESP_LOGD(TAG, "Exit reparse mode");
176 if (!this->set_protocol_reparse_mode(false)) {
177 ESP_LOGW(TAG, "Exit reparse failed");
178 return false;
179 }
180 }
181
182 // Check if baud rate is supported
184 if (baud_rate <= 0) {
185 baud_rate = this->original_baud_rate_;
186 }
187 ESP_LOGD(TAG, "Baud rate: %" PRIu32, baud_rate);
188
189 // Define the configuration for the HTTP client
190 ESP_LOGV(TAG,
191 "Init HTTP client\n"
192 "Heap: %" PRIu32,
193 esp_get_free_heap_size());
194 esp_http_client_config_t config = {
195 .url = this->tft_url_.c_str(),
196 .cert_pem = nullptr,
197 .method = HTTP_METHOD_HEAD,
198 .timeout_ms = 15000,
199 .disable_auto_redirect = false,
200 .max_redirection_count = 10,
201 };
202 // Initialize the HTTP client with the configuration
203 esp_http_client_handle_t http_client = esp_http_client_init(&config);
204 if (!http_client) {
205 ESP_LOGE(TAG, "HTTP init failed");
206 return this->upload_end_(false);
207 }
208
209 esp_err_t err = esp_http_client_set_header(http_client, "Connection", "keep-alive");
210 if (err != ESP_OK) {
211 ESP_LOGE(TAG, "Set header failed: %s", esp_err_to_name(err));
212 esp_http_client_cleanup(http_client);
213 return this->upload_end_(false);
214 }
215
216 // Perform the HTTP request
217 ESP_LOGV(TAG,
218 "Check connection\n"
219 "Heap: %" PRIu32,
220 esp_get_free_heap_size());
221 err = esp_http_client_perform(http_client);
222 if (err != ESP_OK) {
223 ESP_LOGE(TAG, "HTTP failed: %s", esp_err_to_name(err));
224 esp_http_client_cleanup(http_client);
225 return this->upload_end_(false);
226 }
227
228 // Check the HTTP Status Code
229 ESP_LOGV(TAG,
230 "Check status\n"
231 "Heap: %" PRIu32,
232 esp_get_free_heap_size());
233 int status_code = esp_http_client_get_status_code(http_client);
234 if (status_code != 200 && status_code != 206) {
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 ESP_LOGD(TAG, "Upload resp: [%s] %zu B",
291 format_hex_pretty(reinterpret_cast<const uint8_t *>(response.data()), response.size()).c_str(),
292 response.length());
293 ESP_LOGV(TAG, "Heap: %" PRIu32, esp_get_free_heap_size());
294
295 if (response.find(0x05) != std::string::npos) {
296 ESP_LOGV(TAG, "Upload prep done");
297 } else {
298 ESP_LOGE(TAG, "Upload prep failed %d '%s'", response[0], response.c_str());
299 ESP_LOGD(TAG, "Close HTTP");
300 esp_http_client_close(http_client);
301 esp_http_client_cleanup(http_client);
302 ESP_LOGV(TAG, "Connection closed");
303 return this->upload_end_(false);
304 }
305
306 ESP_LOGV(TAG, "Set method to GET");
307 esp_err_t set_method_result = esp_http_client_set_method(http_client, HTTP_METHOD_GET);
308 if (set_method_result != ESP_OK) {
309 ESP_LOGE(TAG, "Set GET failed: %s", esp_err_to_name(set_method_result));
310 return this->upload_end_(false);
311 }
312
313 ESP_LOGD(TAG,
314 "Uploading TFT:\n"
315 " URL: %s\n"
316 " Size: %" PRIu32 " bytes\n"
317 " Heap: %" PRIu32,
318 this->tft_url_.c_str(), this->content_length_, esp_get_free_heap_size());
319
320 // Proceed with the content download as before
321
322 ESP_LOGV(TAG, "Start chunk transfer");
323
324 uint32_t position = 0;
325 while (this->content_length_ > 0) {
326 int upload_result = upload_by_chunks_(http_client, position);
327 if (upload_result < 0) {
328 ESP_LOGE(TAG, "TFT upload error");
329 ESP_LOGD(TAG, "Close HTTP");
330 esp_http_client_close(http_client);
331 esp_http_client_cleanup(http_client);
332 ESP_LOGV(TAG, "Connection closed");
333 return this->upload_end_(false);
334 }
335 App.feed_wdt();
336 ESP_LOGV(TAG, "Heap: %" PRIu32 " left: %" PRIu32, esp_get_free_heap_size(), this->content_length_);
337 }
338
339 ESP_LOGD(TAG, "TFT upload complete\n"
340 "Close 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:1215
void deallocate(T *p, size_t n)
Definition helpers.h:1273
T * allocate(size_t n)
Definition helpers.h:1235
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:26
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.
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:976
void reset_(bool reset_nextion=true)
Definition nextion.cpp:136
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
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
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:318
Application App
Global storage of Application pointer - only one Application can exist.