ESPHome 2026.4.3
Loading...
Searching...
No Matches
nextion_upload_arduino.cpp
Go to the documentation of this file.
1#include "nextion.h"
2
3#ifdef USE_NEXTION_TFT_UPLOAD
4#ifndef USE_ESP32
5
6#include <cinttypes>
11#include "esphome/core/log.h"
12#include "esphome/core/util.h"
13
14namespace esphome::nextion {
15
16static const char *const TAG = "nextion.upload.arduino";
17static constexpr size_t NEXTION_MAX_RESPONSE_LOG_BYTES = 16;
18
19// Timeout for display acknowledgment during TFT upload (ms).
20// A single value is used for all chunks; the happy path returns as soon as
21// 0x05/0x08 arrives, so this only bounds failed-detection latency. Field
22// reports showed the previous 500ms steady-state value was too tight for
23// some firmware variants.
24static constexpr uint32_t NEXTION_UPLOAD_ACK_TIMEOUT_MS = 5000;
25
26// Followed guide
27// https://unofficialnextion.com/t/nextion-upload-protocol-v1-2-the-fast-one/1044/2
28
29int Nextion::upload_by_chunks_(HTTPClient &http_client, uint32_t &range_start) {
30 uint32_t range_size = this->tft_size_ - range_start;
31 ESP_LOGV(TAG, "Heap: %" PRIu32, EspClass::getFreeHeap());
32 uint32_t range_end = ((this->upload_first_chunk_sent_ || this->tft_size_ < 4096) ? this->tft_size_ : 4096) - 1;
33 ESP_LOGD(TAG, "Range start: %" PRIu32, range_start);
34 if (range_size <= 0 || range_end <= range_start) {
35 ESP_LOGE(TAG, "Invalid range end: %" PRIu32 ", size: %" PRIu32, range_end, range_size);
36 return -1;
37 }
38
39 char range_header[32];
40 buf_append_printf(range_header, sizeof(range_header), 0, "bytes=%" PRIu32 "-%" PRIu32, range_start, range_end);
41 ESP_LOGV(TAG, "Range: %s", range_header);
42 http_client.addHeader("Range", range_header);
43 int code = http_client.GET();
44 if (code != HTTP_CODE_OK && code != HTTP_CODE_PARTIAL_CONTENT) {
45 ESP_LOGW(TAG, "HTTP failed: %s", HTTPClient::errorToString(code).c_str());
46 return -1;
47 }
48
49 // Allocate the buffer dynamically
50 RAMAllocator<uint8_t> allocator;
51 uint8_t *buffer = allocator.allocate(4096);
52 if (!buffer) {
53 ESP_LOGE(TAG, "Buffer alloc failed");
54 return -1;
55 }
56
57 std::string recv_string;
58 while (true) {
59 App.feed_wdt();
60 const uint16_t buffer_size =
61 this->content_length_ < 4096 ? this->content_length_ : 4096; // Limits buffer to the remaining data
62 ESP_LOGV(TAG, "Fetch %" PRIu16 " bytes", buffer_size);
63 uint16_t read_len = 0;
64 int partial_read_len = 0;
65 const uint32_t start_time = App.get_loop_component_start_time();
66 while (read_len < buffer_size && App.get_loop_component_start_time() - start_time < 5000) {
67 if (http_client.getStreamPtr()->available() > 0) {
68 partial_read_len =
69 http_client.getStreamPtr()->readBytes(reinterpret_cast<char *>(buffer) + read_len, buffer_size - read_len);
70 read_len += partial_read_len;
71 if (partial_read_len > 0) {
72 App.feed_wdt();
73 delay(2);
74 }
75 }
76 }
77 if (read_len != buffer_size) {
78 // Did not receive the full package within the timeout period
79 ESP_LOGE(TAG, "Read failed: %" PRIu16 "/%" PRIu16 " bytes", read_len, buffer_size);
80 // Deallocate buffer
81 allocator.deallocate(buffer, 4096);
82 buffer = nullptr;
83 return -1;
84 }
85 ESP_LOGV(TAG, "Fetched %d bytes", read_len);
86 if (read_len > 0) {
87 recv_string.clear();
88 this->write_array(buffer, buffer_size);
89 App.feed_wdt();
90 this->recv_ret_string_(recv_string, NEXTION_UPLOAD_ACK_TIMEOUT_MS, true);
91 this->content_length_ -= read_len;
92 const float upload_percentage = 100.0f * (this->tft_size_ - this->content_length_) / this->tft_size_;
93 ESP_LOGD(TAG, "Upload: %0.2f%% (%" PRIu32 " left, heap: %" PRIu32 ")", upload_percentage, this->content_length_,
94 EspClass::getFreeHeap());
95 this->upload_first_chunk_sent_ = true;
96 if (recv_string.empty()) {
97 ESP_LOGW(TAG, "No response from display after %" PRIu32 "ms", NEXTION_UPLOAD_ACK_TIMEOUT_MS);
98 allocator.deallocate(buffer, 4096);
99 buffer = nullptr;
100 return -1;
101 }
102 if (recv_string[0] == 0x08 && recv_string.size() == 5) { // handle partial upload request
103 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
104 ESP_LOGD(
105 TAG, "Recv: [%s]",
106 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
107 uint32_t result = 0;
108 for (int j = 0; j < 4; ++j) {
109 result += static_cast<uint8_t>(recv_string[j + 1]) << (8 * j);
110 }
111 if (result > 0) {
112 ESP_LOGI(TAG, "New range: %" PRIu32, result);
113 this->content_length_ = this->tft_size_ - result;
114 range_start = result;
115 } else {
116 range_start = range_end + 1;
117 }
118 // Deallocate buffer
119 allocator.deallocate(buffer, 4096);
120 buffer = nullptr;
121 return range_end + 1;
122 } else if (recv_string[0] != 0x05 && recv_string[0] != 0x08) { // 0x05 == "ok"
123 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
124 ESP_LOGE(
125 TAG, "Invalid response: [%s]",
126 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(recv_string.data()), recv_string.size()));
127 // Deallocate buffer
128 allocator.deallocate(buffer, 4096);
129 buffer = nullptr;
130 return -1;
131 }
132
133 recv_string.clear();
134 } else if (read_len == 0) {
135 ESP_LOGV(TAG, "HTTP end");
136 break; // Exit the loop if there is no more data to read
137 } else {
138 ESP_LOGE(TAG, "HTTP read failed: %d", read_len);
139 break; // Exit the loop on error
140 }
141 }
142 range_start = range_end + 1;
143 // Deallocate buffer
144 allocator.deallocate(buffer, 4096);
145 buffer = nullptr;
146 return range_end + 1;
147}
148
149bool Nextion::upload_tft(uint32_t baud_rate, bool exit_reparse) {
150 ESP_LOGD(TAG, "TFT upload requested, exit reparse: %s, URL: %s", YESNO(exit_reparse), this->tft_url_.c_str());
151
152 if (this->connection_state_.is_updating_) {
153 ESP_LOGW(TAG, "Upload in progress");
154 return false;
155 }
156
157 if (!network::is_connected()) {
158 ESP_LOGE(TAG, "No network");
159 return false;
160 }
161
162 this->connection_state_.is_updating_ = true;
163
164 if (exit_reparse) {
165 ESP_LOGD(TAG, "Exit reparse mode");
166 if (!this->set_protocol_reparse_mode(false)) {
167 ESP_LOGW(TAG, "Exit reparse failed");
168 return false;
169 }
170 }
171
172 // Check if baud rate is supported
174 if (baud_rate <= 0) {
175 baud_rate = this->original_baud_rate_;
176 }
177 ESP_LOGD(TAG, "Baud rate: %" PRIu32, baud_rate);
178
179 // Define the configuration for the HTTP client
180 ESP_LOGV(TAG, "Init HTTP client, heap: %" PRIu32, EspClass::getFreeHeap());
181 HTTPClient http_client;
182 http_client.setTimeout(this->tft_upload_http_timeout_);
183
184 bool begin_status = false;
185#ifdef USE_ESP8266
186#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 7, 0)
187 http_client.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
188#elif USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 6, 0)
189 http_client.setFollowRedirects(true);
190#endif
191#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 6, 0)
192 http_client.setRedirectLimit(3);
193#endif
194 begin_status = http_client.begin(*this->get_wifi_client_(), this->tft_url_.c_str());
195#endif // USE_ESP8266
196 if (!begin_status) {
197 this->connection_state_.is_updating_ = false;
198 ESP_LOGD(TAG, "Connection failed");
199 return false;
200 } else {
201 ESP_LOGD(TAG, "Connected");
202 }
203 http_client.addHeader("Range", "bytes=0-255");
204 const char *header_names[] = {"Content-Range"};
205 http_client.collectHeaders(header_names, 1);
206 ESP_LOGD(TAG, "URL: %s", this->tft_url_.c_str());
207 http_client.setReuse(true);
208
209 int tries = 1;
210 int code = http_client.GET();
211 delay(100); // NOLINT
212
213 App.feed_wdt();
214 while (code != 200 && code != 206 && tries <= this->tft_upload_http_retries_) {
215 ESP_LOGW(TAG, "HTTP fail: URL: %s; Error: %s, retry %d/%u", this->tft_url_.c_str(),
216 HTTPClient::errorToString(code).c_str(), tries, this->tft_upload_http_retries_);
217
218 delay(250); // NOLINT
219 App.feed_wdt();
220 code = http_client.GET();
221 ++tries;
222 }
223
224 if (code != 200 && code != 206) {
225 ESP_LOGE(TAG, "HTTP request failed with status %d", code);
226 return this->upload_end_(false);
227 }
228
229 String content_range_string = http_client.header("Content-Range");
230 content_range_string.remove(0, 12);
231 this->tft_size_ = content_range_string.toInt();
232
233 ESP_LOGD(TAG, "TFT size: %zu bytes", this->tft_size_);
234 if (this->tft_size_ < 4096) {
235 ESP_LOGE(TAG, "Size check failed");
236 ESP_LOGD(TAG, "Close HTTP");
237 http_client.end();
238 ESP_LOGV(TAG, "Connection closed");
239 return this->upload_end_(false);
240 } else {
241 ESP_LOGV(TAG, "Size check OK");
242 }
243 this->content_length_ = this->tft_size_;
244
245 ESP_LOGD(TAG, "Uploading");
246
247 // The Nextion will ignore the upload command if it is sleeping
248 ESP_LOGV(TAG, "Wake-up");
249 this->connection_state_.ignore_is_setup_ = true;
250 this->send_command_("sleep=0");
251 this->send_command_("dim=100");
252 delay(250); // NOLINT
253 ESP_LOGV(TAG, "Heap: %" PRIu32, EspClass::getFreeHeap());
254
255 App.feed_wdt();
256 char command[128];
257 // Tells the Nextion the content length of the tft file and baud rate it will be sent at
258 // Once the Nextion accepts the command it will wait until the file is successfully uploaded
259 // If it fails for any reason a power cycle of the display will be needed
260 snprintf(command, sizeof(command), "whmi-wris %" PRIu32 ",%" PRIu32 ",1", this->content_length_, baud_rate);
261
262 // Clear serial receive buffer
263 ESP_LOGV(TAG, "Clear RX buffer");
264 this->reset_(false);
265 delay(250); // NOLINT
266
267 ESP_LOGV(TAG, "Heap: %" PRIu32 ", upload cmd: %s", EspClass::getFreeHeap(), command);
268 this->send_command_(command);
269
270 if (baud_rate != this->original_baud_rate_) {
271 ESP_LOGD(TAG, "Baud: %" PRIu32 "->%" PRIu32, this->original_baud_rate_, baud_rate);
272 this->parent_->set_baud_rate(baud_rate);
273 this->parent_->load_settings();
274 }
275
276 App.feed_wdt();
277
278 std::string response;
279 ESP_LOGV(TAG, "Wait upload resp");
280 this->recv_ret_string_(response, 5000, true); // This can take some time to return
281
282 // The Nextion display will, if it's ready to accept data, send a 0x05 byte.
283 char hex_buf[format_hex_pretty_size(NEXTION_MAX_RESPONSE_LOG_BYTES)];
284 ESP_LOGD(TAG, "Upload resp: [%s] %zu B",
285 format_hex_pretty_to(hex_buf, reinterpret_cast<const uint8_t *>(response.data()), response.size()),
286 response.length());
287 ESP_LOGV(TAG, "Heap: %" PRIu32, EspClass::getFreeHeap());
288
289 if (response.find(0x05) != std::string::npos) {
290 ESP_LOGV(TAG, "Upload prep done");
291 } else {
292 ESP_LOGE(TAG, "Prep failed %d '%s'", response[0], response.c_str());
293 ESP_LOGD(TAG, "Close HTTP");
294 http_client.end();
295 ESP_LOGV(TAG, "Connection closed");
296 return this->upload_end_(false);
297 }
298
299 ESP_LOGD(TAG,
300 "Upload TFT:\n"
301 " URL: %s\n"
302 " Size: %d bytes\n"
303 " Heap: %" PRIu32,
304 this->tft_url_.c_str(), this->content_length_, EspClass::getFreeHeap());
305
306 // Proceed with the content download as before
307
308 ESP_LOGV(TAG, "Start chunk transfer");
309
310 uint32_t position = 0;
311 while (this->content_length_ > 0) {
312 int upload_result = upload_by_chunks_(http_client, position);
313 if (upload_result < 0) {
314 ESP_LOGE(TAG, "Upload error");
315 ESP_LOGD(TAG, "Close HTTP");
316 http_client.end();
317 ESP_LOGV(TAG, "Connection closed");
318 return this->upload_end_(false);
319 }
320 App.feed_wdt();
321 ESP_LOGV(TAG, "Heap: %" PRIu32 " left: %" PRIu32, EspClass::getFreeHeap(), this->content_length_);
322 }
323
324 ESP_LOGD(TAG, "Upload complete");
325
326 ESP_LOGV(TAG, "Close HTTP");
327 http_client.end();
328 ESP_LOGV(TAG, "Connection closed");
329 return upload_end_(true);
330}
331
332#ifdef USE_ESP8266
334 if (this->tft_url_.compare(0, 6, "https:") == 0) {
335 if (this->wifi_client_secure_ == nullptr) {
336 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
337 this->wifi_client_secure_ = new BearSSL::WiFiClientSecure();
338 this->wifi_client_secure_->setInsecure();
339 this->wifi_client_secure_->setBufferSizes(512, 512);
340 }
341 return this->wifi_client_secure_;
342 }
343
344 if (this->wifi_client_ == nullptr) {
345 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
346 this->wifi_client_ = new WiFiClient();
347 }
348 return this->wifi_client_;
349}
350#endif // USE_ESP8266
351
352} // namespace esphome::nextion
353
354#endif // NOT USE_ESP32
355#endif // USE_NEXTION_TFT_UPLOAD
void feed_wdt()
Feed the task watchdog.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2197
void deallocate(T *p, size_t n)
Definition helpers.h:2252
T * allocate(size_t n)
Definition helpers.h:2214
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.
WiFiClient * wifi_client_
Definition nextion.h:1540
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.
BearSSL::WiFiClientSecure * wifi_client_secure_
Definition nextion.h:1541
uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag)
void reset_(bool reset_nextion=true)
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
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:392
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:1353
void HOT delay(uint32_t ms)
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t