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