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