ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
nextion.cpp
Go to the documentation of this file.
1#include "nextion.h"
2
3#include <cinttypes>
4#include <cstring>
5#include <new>
6
9#include "esphome/core/log.h"
12#include "esphome/core/util.h"
13
14namespace esphome::nextion {
15
16ESPHOME_LOG_TAG(TAG, "nextion");
17
18// A user entity may be named sleep_wake too; only the internal NO_RESULT command clears the sleeping flag
19static bool is_sleep_wake_command(const NextionComponentBase *component) {
20 return component->get_queue_type() == NextionQueueType::NO_RESULT && component->get_variable_name() == "sleep_wake";
21}
22
23// The display answers a raw "get" with a value instead of 0x01. Its queue entry is named RAW_GET_NAME so that
24// value removes it. An entity with this variable name would clash when it writes its state; none is expected.
25static constexpr const char *RAW_GET_NAME = "raw_get";
26
27static bool is_raw_get_command(const NextionComponentBase *component) {
28 return component->get_queue_type() == NextionQueueType::NO_RESULT && component->get_variable_name() == RAW_GET_NAME;
29}
30
31static const char *raw_command_name(const char *command, const char *name) {
32 return ESPHOME_strncmp_P(command, ESPHOME_PSTR("get "), 4) == 0 ? RAW_GET_NAME : name;
33}
34
35// Nextion command terminator: three consecutive 0xFF bytes (per Nextion Instruction Set v1.1).
36static constexpr uint8_t COMMAND_DELIMITER[3] = {0xFF, 0xFF, 0xFF};
37static constexpr size_t DELIMITER_SIZE = sizeof(COMMAND_DELIMITER);
38
39void Nextion::setup() {
40 this->is_setup_ = false;
41 this->connection_state_.ignore_is_setup_ = true;
42
43 // Wake up the nextion and ensure clean communication state
44 this->send_command_("sleep=0"); // Exit sleep mode if sleeping
45 this->send_command_("bkcmd=0"); // Disable return data during init sequence
46
47 // Reset device for clean state - critical for reliable communication
48 this->send_command_("rest");
49
50 this->connection_state_.ignore_is_setup_ = false;
51}
52
53bool Nextion::send_command_(const std::string &command) {
54 if (!this->connection_state_.ignore_is_setup_ && !this->is_setup()) {
55 return false;
56 }
57
58#ifdef USE_NEXTION_COMMAND_SPACING
60 if (!this->connection_state_.ignore_is_setup_ && !this->command_pacer_.can_send(now)) {
61 ESP_LOGN(TAG, "Command spacing: delaying '%s'", command.c_str());
62 return false;
63 }
64#endif // USE_NEXTION_COMMAND_SPACING
65
66 ESP_LOGN(TAG, "cmd: %s", command.c_str());
67
68 this->write_str(command.c_str());
69 const uint8_t to_send[3] = {0xFF, 0xFF, 0xFF};
70 this->write_array(to_send, sizeof(to_send));
71
72#ifdef USE_NEXTION_COMMAND_SPACING
73 // Mark sent immediately after writing to UART. The pacer enforces inter-command
74 // spacing from the transmit side. Marking on ACK (0x01) would leave last_command_time_
75 // at zero indefinitely, making can_send() always return true and spacing a no-op.
76 // ignore_is_setup_ commands (setup/init sequence) bypass spacing intentionally.
77 if (!this->connection_state_.ignore_is_setup_) {
78 this->command_pacer_.mark_sent(now);
79 }
80#endif // USE_NEXTION_COMMAND_SPACING
81
82 return true;
83}
84
86 if (this->connection_state_.is_connected_)
87 return true;
88
89#ifdef USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
90 ESP_LOGW(TAG, "Connected (no handshake)"); // Log the connection status without handshake
91 this->connection_state_.is_connected_ = true; // Set the connection status to true
92 return true; // Return true indicating the connection is set
93#else // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
94 if (this->comok_sent_ == 0) {
95 this->reset_(false);
96
97 this->connection_state_.ignore_is_setup_ = true;
98 this->send_command_("boguscommand=0"); // bogus command. needed sometimes after updating
99#ifdef USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START
100 this->send_command_("DRAKJHSUYDGBNCJHGJKSHBDN");
101#endif // USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START
102 this->send_command_("connect");
103
105 this->connection_state_.ignore_is_setup_ = false;
106
107 return false;
108 }
109
110 if (App.get_loop_component_start_time() - this->comok_sent_ <= 500) // Wait 500 ms
111 return false;
112
113 std::string response;
114
115 this->recv_ret_string_(response, 0, false);
116 if (!response.empty() && response[0] == 0x1A) {
117 // Swallow invalid variable name responses that may be caused by the above commands
118 ESP_LOGV(TAG, "0x1A error ignored (setup)");
119 return false;
120 }
121 if (response.empty() || response.find("comok") == std::string::npos) {
122#ifdef NEXTION_PROTOCOL_LOG
123 ESP_LOGN(TAG, "Bad connect: %s", response.c_str());
124 for (size_t i = 0; i < response.length(); i++) {
125 ESP_LOGN(TAG, "resp: %s %d %d %c", response.c_str(), i, response[i], response[i]);
126 }
127#endif // NEXTION_PROTOCOL_LOG
128
129 ESP_LOGW(TAG, "Not connected");
130 this->comok_sent_ = 0;
131 return false;
132 }
133
134 this->connection_state_.ignore_is_setup_ = true;
135 ESP_LOGI(TAG, "Connected");
136 this->connection_state_.is_connected_ = true;
137
138 ESP_LOGN(TAG, "connect: %s", response.c_str());
139
140 // Parse comok response fields directly
141 // Format: comok <touch>,<reserved>,<model>,<fw>,<mcu_code>,<serial>,<flash>
142 size_t field_count = 0;
143 size_t start = 0;
144 size_t end = 0;
145 auto copy_field = [&](char *dst, size_t cap) {
146 size_t len = (end == std::string::npos ? response.size() : end) - start;
147 size_t n = len < cap ? len : cap;
148 std::memcpy(dst, response.data() + start, n);
149 dst[n] = '\0';
150 };
151 while ((start = response.find_first_not_of(',', end)) != std::string::npos) {
152 end = response.find(',', start);
153 switch (field_count) {
154 case 2:
155 copy_field(this->device_model_, this->NEXTION_MODEL_MAX);
156 break;
157 case 3:
158 copy_field(this->firmware_version_, this->NEXTION_FW_MAX);
159 break;
160 case 5:
161 copy_field(this->serial_number_, this->NEXTION_SERIAL_MAX);
162 break;
163 case 6:
164 this->flash_size_ = static_cast<uint32_t>(std::strtoul(response.data() + start, nullptr, 10));
165 break;
166 default:
167 break;
168 }
169 ++field_count;
170 }
171
172 this->is_detected_ = (field_count == 7);
173 if (this->is_detected_) {
174 ESP_LOGN(TAG, "Connect info: %zu fields", field_count);
175 } else {
176 ESP_LOGE(TAG, "Bad connect value: '%s'", response.c_str());
177 }
178
179 this->connection_state_.ignore_is_setup_ = false;
180 this->dump_config();
181 return true;
182#endif // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
183}
184
185// NO_RESULT components are owned by their entry; every other component is a user entity. Entry and
186// component storage comes from RAMAllocator, so delete is not valid for either.
187void Nextion::release_queue_entry_(NextionQueue *nb) {
188 if (nb->component != nullptr && nb->component->get_queue_type() == NextionQueueType::NO_RESULT) {
189 nb->component->~NextionComponentBase();
190 RAMAllocator<NextionComponentBase>().deallocate(nb->component, 1);
191 }
192 nb->~NextionQueue();
193 RAMAllocator<NextionQueue>().deallocate(nb, 1);
194}
195
196void Nextion::reset_(bool reset_nextion) {
197 this->discard_available();
198 for (auto *entry : this->nextion_queue_) {
199 this->release_queue_entry_(entry);
200 }
201 this->nextion_queue_.clear();
202#ifdef USE_NEXTION_WAVEFORM
203 for (auto *entry : this->waveform_queue_) {
204 this->release_queue_entry_(entry);
205 }
206 this->waveform_queue_.clear();
207#endif // USE_NEXTION_WAVEFORM
208}
209
211 ESP_LOGCONFIG(TAG, "Nextion:");
212
213#ifdef USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
214 ESP_LOGCONFIG(TAG, " Skip handshake: YES");
215#else // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
216 if (this->is_setup()) {
217 ESP_LOGCONFIG(TAG,
218 " Device Model: %s\n"
219 " FW Version: %s\n"
220 " Serial Number: %s\n"
221 " Flash Size: %" PRIu32 " bytes",
222 this->device_model_, this->firmware_version_, this->serial_number_, this->flash_size_);
223 } else {
224 ESP_LOGCONFIG(TAG, " Device info: not yet detected");
225 }
226 ESP_LOGCONFIG(TAG,
227#ifdef USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START
228 " Exit reparse: YES\n"
229#endif // USE_NEXTION_CONFIG_EXIT_REPARSE_ON_START
230 " Max queue age: %u ms\n"
231 " Startup override: %u ms\n"
232 " Wake On Touch: %s\n"
233 " Touch Timeout: %" PRIu16,
234 this->max_q_age_ms_, this->startup_override_ms_, YESNO(this->connection_state_.auto_wake_on_touch_),
235 this->touch_sleep_timeout_);
236#endif // USE_NEXTION_CONFIG_SKIP_CONNECTION_HANDSHAKE
237
238#ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP
239 ESP_LOGCONFIG(TAG, " Max commands per loop: %u", this->max_commands_per_loop_);
240#endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP
241
242 if (this->wake_up_page_ != 255) {
243 ESP_LOGCONFIG(TAG, " Wake Up Page: %u", this->wake_up_page_);
244 }
245
246#ifdef USE_NEXTION_CONF_START_UP_PAGE
247 if (this->start_up_page_ != 255) {
248 ESP_LOGCONFIG(TAG, " Start Up Page: %u", this->start_up_page_);
249 }
250#endif // USE_NEXTION_CONF_START_UP_PAGE
251
252#ifdef USE_NEXTION_COMMAND_SPACING
253 ESP_LOGCONFIG(TAG, " Cmd spacing: %u ms", this->command_pacer_.get_spacing());
254#endif // USE_NEXTION_COMMAND_SPACING
255
256#ifdef USE_NEXTION_MAX_QUEUE_SIZE
257 ESP_LOGCONFIG(TAG, " Max queue size: %zu", this->max_queue_size_);
258#endif
259#ifdef USE_NEXTION_TFT_UPLOAD
260 ESP_LOGCONFIG(TAG,
261 " TFT URL: %s\n"
262 " TFT upload HTTP timeout: %" PRIu16 "ms\n"
263 " TFT upload HTTP retries: %u",
264 this->tft_url_.c_str(), this->tft_upload_http_timeout_, this->tft_upload_http_retries_);
265#ifdef USE_ESP32
266 if (this->tft_upload_watchdog_timeout_ > 0) {
267 ESP_LOGCONFIG(TAG, " TFT upload WDT timeout: %" PRIu32 "ms", this->tft_upload_watchdog_timeout_);
268 }
269#endif // USE_ESP32
270#endif // USE_NEXTION_TFT_UPLOAD
271}
272
273void Nextion::update() {
274 if (!this->is_setup()) {
275 return;
276 }
277 if (this->writer_.has_value()) {
278 (*this->writer_)(*this);
279 }
280}
281
283 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping())
284 return;
285
286 for (auto *binarysensortype : this->binarysensortype_) {
287 binarysensortype->update_component();
288 }
289 for (auto *sensortype : this->sensortype_) {
290 sensortype->update_component();
291 }
292 for (auto *switchtype : this->switchtype_) {
293 switchtype->update_component();
294 }
295 for (auto *textsensortype : this->textsensortype_) {
296 textsensortype->update_component();
297 }
298}
299
300bool Nextion::send_command(const char *command) {
301 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping())
302 return false;
303
304 this->add_no_result_to_queue_with_command_(raw_command_name(command, "command"), command);
305 return true;
306}
307
308bool Nextion::send_command_printf(const char *format, ...) {
309 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping())
310 return false;
311
312 char buffer[256];
313 va_list arg;
314 va_start(arg, format);
315 int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
316 va_end(arg);
317 if (ret <= 0) {
318 ESP_LOGW(TAG, "Bad cmd format: '%s'", format);
319 return false;
320 }
321
322 this->add_no_result_to_queue_with_command_(raw_command_name(buffer, "command_printf"), buffer);
323 return true;
324}
325
326#ifdef NEXTION_PROTOCOL_LOG
328 ESP_LOGN(TAG, "print_queue_members_ (top 10) size %zu", this->nextion_queue_.size());
329 ESP_LOGN(TAG, "*******************************************");
330 int count = 0;
331 for (auto *i : this->nextion_queue_) {
332 if (count++ == 10)
333 break;
334
335 if (i == nullptr) {
336 ESP_LOGN(TAG, "Queue null");
337 } else {
338 ESP_LOGN(TAG, "Queue type: %d:%s, name: %s", i->component->get_queue_type(),
339 LOG_STR_ARG(i->component->get_queue_type_string()), i->component->get_variable_name().c_str());
340 }
341 }
342 ESP_LOGN(TAG, "*******************************************");
343}
344#endif
345
346void Nextion::loop() {
347 if (!this->check_connect_() || this->connection_state_.is_updating_)
348 return;
349
350 if (this->connection_state_.nextion_reports_is_setup_ && !this->connection_state_.sent_setup_commands_) {
351 this->connection_state_.ignore_is_setup_ = true;
352 this->connection_state_.sent_setup_commands_ = true;
353 this->send_command_("bkcmd=3"); // Always, returns 0x00 to 0x23 result of serial command.
354
355 if (this->brightness_.has_value()) {
356 this->set_backlight_brightness(this->brightness_.value());
357 }
358
359#ifdef USE_NEXTION_CONF_START_UP_PAGE
360 // Check if a startup page has been set and send the command
361 if (this->start_up_page_ != 255) {
362 this->goto_page(this->start_up_page_);
363 }
364#endif // USE_NEXTION_CONF_START_UP_PAGE
365
366 if (this->wake_up_page_ != 255) {
367 this->set_wake_up_page(this->wake_up_page_);
368 }
369
370 if (this->touch_sleep_timeout_ != 0) {
372 }
373
374 this->set_auto_wake_on_touch(this->connection_state_.auto_wake_on_touch_);
375
376 this->connection_state_.ignore_is_setup_ = false;
377 }
378
379 this->process_serial_(); // Receive serial data
380 this->process_nextion_commands_(); // Process nextion return commands
381 this->purge_stale_queue_entries_(); // Drop expired entries even when the display sends no data
382
383 if (!this->connection_state_.nextion_reports_is_setup_) {
384 if (this->started_ms_ == 0)
386
387 if (this->startup_override_ms_ > 0 &&
388 App.get_loop_component_start_time() - this->started_ms_ > this->startup_override_ms_) {
389 ESP_LOGV(TAG, "Manual ready set");
390 this->connection_state_.nextion_reports_is_setup_ = true;
391 }
392 }
393
394#ifdef USE_NEXTION_COMMAND_SPACING
396#ifdef USE_NEXTION_WAVEFORM
397 if (!this->waveform_queue_.empty()) {
399 }
400#endif // USE_NEXTION_WAVEFORM
401#endif // USE_NEXTION_COMMAND_SPACING
402}
403
404#ifdef USE_NEXTION_COMMAND_SPACING
406#ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP
407 size_t commands_sent = 0;
408#endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP
409
410 for (auto *item : this->nextion_queue_) {
411 if (item == nullptr || item->pending_command.empty()) {
412 continue; // Already sent, waiting for ACK — skip, don't stop
413 }
414
415#ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP
416 if (++commands_sent > this->max_commands_per_loop_) {
417 ESP_LOGV(TAG, "Pending cmds: loop limit reached, deferring");
418 break;
419 }
420#endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP
421
423 if (!this->command_pacer_.can_send(now)) {
424 break; // Spacing not elapsed, stop for this loop iteration
425 }
426
427 if (!this->send_command_(item->pending_command)) {
428 break; // Unexpected send failure, stop
429 }
430 item->pending_command.clear();
431 ESP_LOGVV(TAG, "Pending cmd sent: %s", item->component->get_variable_name().c_str());
432 }
433}
434#endif // USE_NEXTION_COMMAND_SPACING
435
436bool Nextion::remove_from_q_(bool report_empty) {
437 if (this->nextion_queue_.empty()) {
438 if (report_empty) {
439 ESP_LOGE(TAG, "Queue empty");
440 }
441 return false;
442 }
443
444 NextionQueue *nb = this->nextion_queue_.front();
445 if (!nb || !nb->component) {
446 ESP_LOGE(TAG, "Invalid queue");
447 if (nb != nullptr) {
448 this->release_queue_entry_(nb);
449 }
450 this->nextion_queue_.pop_front();
451 return false;
452 }
453 NextionComponentBase *component = nb->component;
454
455#ifdef USE_NEXTION_COMMAND_SPACING
456 if (!nb->pending_command.empty()) {
457 // Not sent yet, so this response cannot belong to it. Dropping the
458 // response leaves the command queued instead of losing it.
459 ESP_LOGW(TAG, "Response for unsent cmd '%s' (queue %zu), ignoring", component->get_variable_name().c_str(),
460 this->nextion_queue_.size());
461 return false;
462 }
463#endif // USE_NEXTION_COMMAND_SPACING
464
465 ESP_LOGN(TAG, "Removed: %s", component->get_variable_name().c_str());
466
467 if (is_sleep_wake_command(component)) {
468 this->is_sleeping_ = false;
469 }
470 this->release_queue_entry_(nb);
471 this->nextion_queue_.pop_front();
472 return true;
473}
474
475void Nextion::deliver_queue_response_(const LogString *response_name, const NextionQueueResponse &resp) {
476 auto it = this->nextion_queue_.begin();
477 while (it != this->nextion_queue_.end()) {
478 NextionQueue *nb = *it;
479 if (nb == nullptr || nb->component == nullptr) {
480 ESP_LOGE(TAG, "Invalid queue entry");
481 if (nb != nullptr) {
482 this->release_queue_entry_(nb);
483 }
484 it = this->nextion_queue_.erase(it);
485 continue;
486 }
487 NextionComponentBase *component = nb->component;
488 NextionQueueType qtype = component->get_queue_type();
489 const bool raw_get = is_raw_get_command(component);
490
491 if (!nb->pending_command.empty()) {
492 ESP_LOGV(TAG, "%s: skipping unsent '%s'", LOG_STR_ARG(response_name), component->get_variable_name().c_str());
493 ++it;
494 continue;
495 }
496
497 if (qtype == NextionQueueType::NO_RESULT && !raw_get) {
498 // Leave in queue -- its 0x01 ACK will remove it via remove_from_q_().
499 ESP_LOGV(TAG, "%s: skipping NO_RESULT '%s'", LOG_STR_ARG(response_name), component->get_variable_name().c_str());
500 ++it;
501 continue;
502 }
503
504 // The display answers queries in order, so the response belongs to this query even when the type does
505 // not match. Consume only this entry and never hand the value to a later query.
506 if (raw_get) {
507 // A raw "get" from send_command() has no entity to update
508 ESP_LOGV(TAG, "%s for raw get dropped", LOG_STR_ARG(response_name));
509 } else if (!resp.is_string && (qtype == NextionQueueType::SENSOR || qtype == NextionQueueType::BINARY_SENSOR ||
510 qtype == NextionQueueType::SWITCH)) {
511 ESP_LOGN(TAG, "Numeric: %s type %d:%s val %d", component->get_variable_name().c_str(), qtype,
512 LOG_STR_ARG(component->get_queue_type_string()), resp.int_value);
513 component->set_state_from_int(resp.int_value, true, false);
514 } else if (resp.is_string && qtype == NextionQueueType::TEXT_SENSOR) {
515 ESP_LOGN(TAG, "String resp: '%s' id: %s type: %s", resp.str_value->c_str(),
516 component->get_variable_name().c_str(), LOG_STR_ARG(component->get_queue_type_string()));
517 component->set_state_from_string(*resp.str_value, true, false);
518 } else {
519 ESP_LOGE(TAG, "%s but '%s' invalid type %d", LOG_STR_ARG(response_name), component->get_variable_name().c_str(),
520 qtype);
521 }
522
523 this->release_queue_entry_(nb);
524 this->nextion_queue_.erase(it);
525 return;
526 }
527 ESP_LOGE(TAG, "%s but no sent query in queue", LOG_STR_ARG(response_name));
528}
529
531 NextionQueueResponse resp{};
532 resp.is_string = false;
533 resp.int_value = value;
534 this->deliver_queue_response_(LOG_STR("Numeric return"), resp);
535}
536
537void Nextion::set_string_return_(const std::string &value) {
538 NextionQueueResponse resp{};
539 resp.is_string = true;
540 resp.str_value = &value;
541 this->deliver_queue_response_(LOG_STR("String return"), resp);
542}
543
545 this->read_available_chunks([this](const uint8_t *data, size_t len) {
546 this->command_data_.append(reinterpret_cast<const char *>(data), len);
547 });
548}
549// nextion.tech/instruction-set/
551 if (this->command_data_.empty()) {
552 return;
553 }
554
555#ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP
556 size_t commands_processed = 0;
557#endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP
558
559 size_t to_process_length = 0;
560 std::string to_process;
561
562 ESP_LOGN(TAG, "command_data_ %s len %d", this->command_data_.c_str(), this->command_data_.length());
563#ifdef NEXTION_PROTOCOL_LOG
564 this->print_queue_members_();
565#endif
566 while ((to_process_length = this->command_data_.find(reinterpret_cast<const char *>(COMMAND_DELIMITER), 0,
567 DELIMITER_SIZE)) != std::string::npos) {
568#ifdef USE_NEXTION_MAX_COMMANDS_PER_LOOP
569 if (++commands_processed > this->max_commands_per_loop_) {
570 ESP_LOGV(TAG, "Command limit reached, deferring");
571 break;
572 }
573#endif // USE_NEXTION_MAX_COMMANDS_PER_LOOP
574 ESP_LOGN(TAG, "queue size: %zu", this->nextion_queue_.size());
575 while (to_process_length + DELIMITER_SIZE < this->command_data_.length() &&
576 static_cast<uint8_t>(this->command_data_[to_process_length + DELIMITER_SIZE]) == 0xFF) {
577 ++to_process_length;
578 ESP_LOGN(TAG, "Add 0xFF");
579 }
580
581 const uint8_t nextion_event = this->command_data_[0];
582
583 to_process_length -= 1;
584 to_process = this->command_data_.substr(1, to_process_length);
585
586 switch (nextion_event) {
587 case 0x00: // instruction sent by user has failed
588 ESP_LOGW(TAG, "Invalid instruction");
589 this->remove_from_q_();
590
591 break;
592 case 0x01: // instruction sent by user was successful
593
594 ESP_LOGVV(TAG, "Cmd OK");
595 ESP_LOGN(TAG, "this->nextion_queue_.empty() %s", YESNO(this->nextion_queue_.empty()));
596
597 this->remove_from_q_();
598 if (!this->is_setup_) {
599 if (this->nextion_queue_.empty()) {
600 this->is_setup_ = true;
601 this->setup_callback_.call();
602 }
603 }
604 break;
605 case 0x02: // invalid Component ID or name was used
606 ESP_LOGW(TAG, "Invalid component ID/name");
607 this->remove_from_q_();
608 break;
609 case 0x03: // invalid Page ID or name was used
610 ESP_LOGW(TAG, "Invalid page ID");
611 this->remove_from_q_();
612 break;
613 case 0x04: // invalid Picture ID was used
614 ESP_LOGW(TAG, "Invalid picture ID");
615 this->remove_from_q_();
616 break;
617 case 0x05: // invalid Font ID was used
618 ESP_LOGW(TAG, "Invalid font ID");
619 this->remove_from_q_();
620 break;
621 case 0x06: // File operation fails
622 ESP_LOGW(TAG, "File operation failed");
623 break;
624 case 0x09: // Instructions with CRC validation fails their CRC check
625 ESP_LOGW(TAG, "CRC validation failed");
626 break;
627 case 0x11: // invalid Baud rate was used
628 ESP_LOGW(TAG, "Invalid baud rate");
629 break;
630 case 0x12: // invalid Waveform ID or Channel # was used
631#ifdef USE_NEXTION_WAVEFORM
632 if (this->waveform_queue_.empty()) {
633 ESP_LOGW(TAG, "Waveform ID/ch used but no sensor queued");
634 } else {
635 auto &nb = this->waveform_queue_.front();
636 NextionComponentBase *component = nb->component;
637 ESP_LOGW(TAG, "Invalid waveform ID %d/ch %d", component->get_component_id(),
638 component->get_wave_channel_id());
639 ESP_LOGN(TAG, "Remove waveform ID %d/ch %d", component->get_component_id(), component->get_wave_channel_id());
640 this->release_queue_entry_(nb);
641 this->waveform_queue_.pop();
642 }
643#else // USE_NEXTION_WAVEFORM
644 ESP_LOGW(TAG, "Waveform ID/ch error but waveform not enabled");
645#endif // USE_NEXTION_WAVEFORM
646 break;
647 case 0x1A: // variable name invalid
648 ESP_LOGW(TAG, "Invalid variable name");
649 this->remove_from_q_();
650 break;
651 case 0x1B: // variable operation invalid
652 ESP_LOGW(TAG, "Invalid variable operation");
653 this->remove_from_q_();
654 break;
655 case 0x1C: // failed to assign
656 ESP_LOGW(TAG, "Variable assign failed");
657 this->remove_from_q_();
658 break;
659 case 0x1D: // operate EEPROM failed
660 ESP_LOGW(TAG, "EEPROM operation failed");
661 break;
662 case 0x1E: // parameter quantity invalid
663 ESP_LOGW(TAG, "Invalid parameter count");
664 this->remove_from_q_();
665 break;
666 case 0x1F: // IO operation failed
667 ESP_LOGW(TAG, "Invalid component I/O");
668 break;
669 case 0x20: // undefined escape characters
670 ESP_LOGW(TAG, "Undefined escape chars");
671 this->remove_from_q_();
672 break;
673 case 0x23: // too long variable name
674 ESP_LOGW(TAG, "Variable name too long");
675 this->remove_from_q_();
676 break;
677 case 0x24: // Serial Buffer overflow occurs
678 // Buffer will continue to receive the current instruction, all previous instructions are lost.
679 ESP_LOGE(TAG, "Serial buffer overflow");
680 this->buffer_overflow_callback_.call();
681 break;
682 case 0x65: { // touch event return data
683 if (to_process_length != 3) {
684 ESP_LOGW(TAG, "Incorrect touch len: %zu (need 3)", to_process_length);
685 break;
686 }
687
688 uint8_t page_id = to_process[0];
689 uint8_t component_id = to_process[1];
690 uint8_t touch_event = to_process[2]; // 0 -> release, 1 -> press
691 ESP_LOGV(TAG, "Touch %s: page %u comp %u", touch_event ? LOG_STR_LITERAL("PRESS") : LOG_STR_LITERAL("RELEASE"),
692 page_id, component_id);
693 for (auto *touch : this->touch_) {
694 touch->process_touch(page_id, component_id, touch_event != 0);
695 }
696 this->touch_callback_.call(page_id, component_id, touch_event != 0);
697 break;
698 }
699 case 0x66: { // Nextion initiated new page event return data.
700 // Also is used for sendme command which we never explicitly initiate
701 if (to_process_length != 1) {
702 ESP_LOGW(TAG, "Page event: expect 1, got %zu", to_process_length);
703 break;
704 }
705
706 uint8_t page_id = to_process[0];
707 ESP_LOGV(TAG, "New page: %u", page_id);
708 this->page_callback_.call(page_id);
709 break;
710 }
711 case 0x67: { // Touch Coordinate (awake)
712 break;
713 }
714 case 0x68: { // touch coordinate data (sleep)
715
716 if (to_process_length != 5) {
717 ESP_LOGW(TAG, "Touch coordinate: expect 5, got %zu", to_process_length);
718 ESP_LOGW(TAG, "%s", to_process.c_str());
719 break;
720 }
721
722 const uint16_t x = (uint16_t(to_process[0]) << 8) | to_process[1];
723 const uint16_t y = (uint16_t(to_process[2]) << 8) | to_process[3];
724 const uint8_t touch_event = to_process[4]; // 0 -> release, 1 -> press
725 ESP_LOGV(TAG, "Touch %s at %u,%u", touch_event ? LOG_STR_LITERAL("PRESS") : LOG_STR_LITERAL("RELEASE"), x, y);
726 break;
727 }
728
729 // 0x70 0x61 0x62 0x31 0x32 0x33 0xFF 0xFF 0xFF
730 // Returned when using get command for a string.
731 // Each byte is converted to char.
732 // data: ab123
733 case 0x70: // string variable data return
734 {
735 if (this->nextion_queue_.empty()) {
736 ESP_LOGW(TAG, "String return but queue is empty");
737 break;
738 }
739
740 this->set_string_return_(to_process);
741 break;
742 }
743 // 0x71 0x01 0x02 0x03 0x04 0xFF 0xFF 0xFF
744 // Returned when get command to return a number
745 // 4 byte 32-bit value in little endian order.
746 // (0x01+0x02*256+0x03*65536+0x04*16777216)
747 // data: 67305985
748 case 0x71: // numeric variable data return
749 {
750 if (this->nextion_queue_.empty()) {
751 ESP_LOGE(TAG, "Numeric return but queue empty");
752 break;
753 }
754
755 if (to_process_length < 4) {
756 ESP_LOGE(TAG, "Numeric return but insufficient data (need 4, got %zu)", to_process_length);
757 break;
758 }
759
760 int value = static_cast<int>(encode_uint32(to_process[3], to_process[2], to_process[1], to_process[0]));
761
762 this->set_numeric_return_(value);
763 break;
764 }
765
766 case 0x86: { // device automatically enters into sleep mode
767 ESP_LOGVV(TAG, "Auto sleep");
768 this->is_sleeping_ = true;
769 this->sleep_callback_.call();
770 break;
771 }
772 case 0x87: // device automatically wakes up
773 {
774 ESP_LOGVV(TAG, "Auto wake");
775 this->is_sleeping_ = false;
776 this->wake_callback_.call();
777 this->all_components_send_state_(false);
778 break;
779 }
780 case 0x88: // system successful start up
781 {
782 ESP_LOGV(TAG, "System start: %zu", to_process_length);
783 this->connection_state_.nextion_reports_is_setup_ = true;
784 break;
785 }
786 case 0x89: { // start SD card upgrade
787 break;
788 }
789 // Data from nextion is
790 // 0x90 - Start
791 // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
792 // 00 - NULL
793 // 00/01 - Single byte for on/off
794 // FF FF FF - End
795 case 0x90: { // Switched component
796 std::string variable_name;
797
798 // Get variable name
799 auto index = to_process.find('\0');
800 if (index == std::string::npos || (to_process_length - index - 1) < 1) {
801 ESP_LOGE(TAG, "Bad switch data (0x90)");
802 ESP_LOGN(TAG, "proc: %s %zu %zu", to_process.c_str(), to_process_length, index);
803 break;
804 }
805
806 variable_name = to_process.substr(0, index);
807 ++index;
808
809 ESP_LOGN(TAG, "Switch %s: %s", ONOFF(to_process[index] != 0), variable_name.c_str());
810
811#ifdef USE_NEXTION_TRIGGER_CUSTOM_SWITCH
812 this->custom_switch_callback_.call(StringRef(variable_name), to_process[index] != 0);
813#endif // USE_NEXTION_TRIGGER_CUSTOM_SWITCH
814
815 for (auto *switchtype : this->switchtype_) {
816 switchtype->process_bool(variable_name, to_process[index] != 0);
817 }
818 break;
819 }
820 // Data from nextion is
821 // 0x91 - Start
822 // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
823 // 00 - NULL
824 // variable length of 0x71 return data: prints temp1.val,0
825 // FF FF FF - End
826 case 0x91: { // Sensor component
827 std::string variable_name;
828
829 auto index = to_process.find('\0');
830 if (index == std::string::npos || (to_process_length - index - 1) != 4) {
831 ESP_LOGE(TAG, "Bad sensor data (0x91)");
832 ESP_LOGN(TAG, "proc: %s %zu %zu", to_process.c_str(), to_process_length, index);
833 break;
834 }
835
836 index = to_process.find('\0');
837 variable_name = to_process.substr(0, index);
838 // // Get variable name
839 int value = static_cast<int>(
840 encode_uint32(to_process[index + 4], to_process[index + 3], to_process[index + 2], to_process[index + 1]));
841
842 ESP_LOGN(TAG, "Sensor: %s=%d", variable_name.c_str(), value);
843
844#ifdef USE_NEXTION_TRIGGER_CUSTOM_SENSOR
845 this->custom_sensor_callback_.call(StringRef(variable_name), value);
846#endif // USE_NEXTION_TRIGGER_CUSTOM_SENSOR
847
848 for (auto *sensor : this->sensortype_) {
849 sensor->process_sensor(variable_name, value);
850 }
851 break;
852 }
853
854 // Data from nextion is
855 // 0x92 - Start
856 // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
857 // 00 - NULL
858 // variable length of 0x70 return formatted data (bytes) that contain the text prints temp1.txt,0
859 // 00 - NULL
860 // FF FF FF - End
861 case 0x92: { // Text Sensor Component
862 std::string variable_name;
863 std::string text_value;
864
865 // Get variable name
866 auto index = to_process.find('\0');
867 if (index == std::string::npos || (to_process_length - index - 1) < 1) {
868 ESP_LOGE(TAG, "Bad text data (0x92)");
869 ESP_LOGN(TAG, "proc: %s %zu %zu", to_process.c_str(), to_process_length, index);
870 break;
871 }
872
873 variable_name = to_process.substr(0, index);
874 ++index;
875
876 // Get variable value without terminating NUL byte. Length check above ensures substr len >= 0.
877 text_value = to_process.substr(index, to_process_length - index - 1);
878
879 ESP_LOGN(TAG, "Text sensor: %s='%s'", variable_name.c_str(), text_value.c_str());
880
881 // NextionTextSensorResponseQueue *nq = new NextionTextSensorResponseQueue;
882 // nq->variable_name = variable_name;
883 // nq->state = text_value;
884 // this->textsensorq_.push_back(nq);
885
886#ifdef USE_NEXTION_TRIGGER_CUSTOM_TEXT_SENSOR
887 this->custom_text_sensor_callback_.call(StringRef(variable_name), StringRef(text_value));
888#endif // USE_NEXTION_TRIGGER_CUSTOM_TEXT_SENSOR
889
890 for (auto *textsensortype : this->textsensortype_) {
891 textsensortype->process_text(variable_name, text_value);
892 }
893 break;
894 }
895 // Data from nextion is
896 // 0x93 - Start
897 // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
898 // 00 - NULL
899 // 00/01 - Single byte for on/off
900 // FF FF FF - End
901 case 0x93: { // Binary Sensor component
902 std::string variable_name;
903
904 // Get variable name
905 auto index = to_process.find('\0');
906 if (index == std::string::npos || (to_process_length - index - 1) < 1) {
907 ESP_LOGE(TAG, "Bad binary data (0x93)");
908 ESP_LOGN(TAG, "proc: %s %zu %zu", to_process.c_str(), to_process_length, index);
909 break;
910 }
911
912 variable_name = to_process.substr(0, index);
913 ++index;
914
915 ESP_LOGN(TAG, "Binary sensor: %s=%s", variable_name.c_str(), ONOFF(to_process[index] != 0));
916
917#ifdef USE_NEXTION_TRIGGER_CUSTOM_BINARY_SENSOR
918 this->custom_binary_sensor_callback_.call(StringRef(variable_name), to_process[index] != 0);
919#endif // USE_NEXTION_TRIGGER_CUSTOM_BINARY_SENSOR
920
921 for (auto *binarysensortype : this->binarysensortype_) {
922 binarysensortype->process_bool(&variable_name[0], to_process[index] != 0);
923 }
924 break;
925 }
926 case 0xFD: { // data transparent transmit finished
927 ESP_LOGVV(TAG, "Data transmit done");
928#ifdef USE_NEXTION_WAVEFORM
930#endif // USE_NEXTION_WAVEFORM
931 break;
932 }
933 case 0xFE: { // data transparent transmit ready
934 ESP_LOGVV(TAG, "Ready for transmit");
935#ifdef USE_NEXTION_WAVEFORM
936 if (this->waveform_queue_.empty()) {
937 ESP_LOGE(TAG, "No waveforms queued");
938 break;
939 }
940 auto &nb = this->waveform_queue_.front();
941 auto *component = nb->component;
942 size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size() : 255;
943 this->write_array(component->get_wave_buffer().data(), static_cast<int>(buffer_to_send));
944 ESP_LOGN(TAG, "Send waveform: component id %d, waveform id %d, size %zu", component->get_component_id(),
945 component->get_wave_channel_id(), buffer_to_send);
946 component->clear_wave_buffer(buffer_to_send);
947 this->release_queue_entry_(nb);
948 this->waveform_queue_.pop();
949#else // USE_NEXTION_WAVEFORM
950 ESP_LOGW(TAG, "Waveform transmit ready but waveform not enabled");
951#endif // USE_NEXTION_WAVEFORM
952 break;
953 }
954 default:
955 ESP_LOGW(TAG, "Unknown event: 0x%02X", nextion_event);
956 break;
957 }
958
959 this->command_data_.erase(0, to_process_length + DELIMITER_SIZE + 1);
960 }
961
962 ESP_LOGN(TAG, "Loop end");
963 this->process_serial_();
964} // Nextion::process_nextion_commands_()
965
968
969 if (this->max_q_age_ms_ > 0 && !this->nextion_queue_.empty() &&
970 ms - this->nextion_queue_.front()->queue_time > this->max_q_age_ms_) {
971 for (auto it = this->nextion_queue_.begin(); it != this->nextion_queue_.end();) {
972 if (ms - (*it)->queue_time > this->max_q_age_ms_) {
973 NextionComponentBase *component = (*it)->component;
974 ESP_LOGV(TAG, "Remove old queue '%s':'%s'", LOG_STR_ARG(component->get_queue_type_string()),
975 component->get_variable_name().c_str());
976
977 if (is_sleep_wake_command(component)) {
978 this->is_sleeping_ = false;
979 }
980 this->release_queue_entry_(*it);
981 it = this->nextion_queue_.erase(it);
982
983 } else {
984 break;
985 }
986 }
987 }
988}
989
990void Nextion::set_nextion_sensor_state(int queue_type, const std::string &name, float state) {
991 this->set_nextion_sensor_state(static_cast<NextionQueueType>(queue_type), name, state);
992}
993
994void Nextion::set_nextion_sensor_state(NextionQueueType queue_type, const std::string &name, float state) {
995 ESP_LOGN(TAG, "State: %s=%lf (type %d)", name.c_str(), state, queue_type);
996
997 switch (queue_type) {
999 for (auto *sensor : this->sensortype_) {
1000 if (name == sensor->get_variable_name()) {
1001 sensor->set_state(state, true, true);
1002 break;
1003 }
1004 }
1005 break;
1006 }
1008 for (auto *sensor : this->binarysensortype_) {
1009 if (name == sensor->get_variable_name()) {
1010 sensor->set_state(state != 0, true, true);
1011 break;
1012 }
1013 }
1014 break;
1015 }
1017 for (auto *sensor : this->switchtype_) {
1018 if (name == sensor->get_variable_name()) {
1019 sensor->set_state(state != 0, true, true);
1020 break;
1021 }
1022 }
1023 break;
1024 }
1025 default: {
1026 ESP_LOGW(TAG, "set_sensor_state: bad type %d", queue_type);
1027 }
1028 }
1029}
1030
1031void Nextion::set_nextion_text_state(const std::string &name, const std::string &state) {
1032 ESP_LOGV(TAG, "State: %s='%s'", name.c_str(), state.c_str());
1033
1034 for (auto *sensor : this->textsensortype_) {
1035 if (name == sensor->get_variable_name()) {
1036 sensor->set_state(state, true, true);
1037 break;
1038 }
1039 }
1040}
1041
1042void Nextion::all_components_send_state_(bool force_update) {
1043 ESP_LOGV(TAG, "Send states");
1044 for (auto *binarysensortype : this->binarysensortype_) {
1045 if (force_update || binarysensortype->get_needs_to_send_update())
1046 binarysensortype->send_state_to_nextion();
1047 }
1048 for (auto *sensortype : this->sensortype_) {
1049#ifdef USE_NEXTION_WAVEFORM
1050 if ((force_update || sensortype->get_needs_to_send_update()) && sensortype->get_wave_channel_id() == UINT8_MAX) {
1051#else // USE_NEXTION_WAVEFORM
1052 if (force_update || sensortype->get_needs_to_send_update()) {
1053#endif // USE_NEXTION_WAVEFORM
1054 sensortype->send_state_to_nextion();
1055 }
1056 }
1057 for (auto *switchtype : this->switchtype_) {
1058 if (force_update || switchtype->get_needs_to_send_update())
1059 switchtype->send_state_to_nextion();
1060 }
1061 for (auto *textsensortype : this->textsensortype_) {
1062 if (force_update || textsensortype->get_needs_to_send_update())
1063 textsensortype->send_state_to_nextion();
1064 }
1065}
1066
1067void Nextion::update_components_by_prefix(const std::string &prefix) {
1068 for (auto *binarysensortype : this->binarysensortype_) {
1069 if (binarysensortype->get_variable_name().find(prefix, 0) != std::string::npos)
1070 binarysensortype->update_component_settings(true);
1071 }
1072 for (auto *sensortype : this->sensortype_) {
1073 if (sensortype->get_variable_name().find(prefix, 0) != std::string::npos)
1074 sensortype->update_component_settings(true);
1075 }
1076 for (auto *switchtype : this->switchtype_) {
1077 if (switchtype->get_variable_name().find(prefix, 0) != std::string::npos)
1078 switchtype->update_component_settings(true);
1079 }
1080 for (auto *textsensortype : this->textsensortype_) {
1081 if (textsensortype->get_variable_name().find(prefix, 0) != std::string::npos)
1082 textsensortype->update_component_settings(true);
1083 }
1084}
1085
1086uint16_t Nextion::recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag) {
1087 uint8_t c = 0;
1088 uint8_t nr_of_ff_bytes = 0;
1089 bool exit_flag = false;
1090 bool ff_flag = false;
1091
1092 const uint32_t start = millis();
1093
1094 while ((timeout == 0 && this->available()) || millis() - start <= timeout) {
1095 if (!this->available()) {
1096 App.feed_wdt();
1097 delay(1);
1098 continue;
1099 }
1100
1101 this->read_byte(&c);
1102 if (c == 0xFF) {
1103 nr_of_ff_bytes++;
1104 } else {
1105 nr_of_ff_bytes = 0;
1106 ff_flag = false;
1107 }
1108
1109 if (nr_of_ff_bytes >= 3)
1110 ff_flag = true;
1111
1112 response += (char) c;
1113 if (recv_flag) {
1114 if (response.find(0x05) != std::string::npos) {
1115 exit_flag = true;
1116 }
1117 }
1118 App.feed_wdt();
1119 delay(2);
1120
1121 if (exit_flag || ff_flag) {
1122 break;
1123 }
1124 }
1125
1126 if (ff_flag)
1127 response = response.substr(0, response.length() - 3); // Remove last 3 0xFF
1128
1129 return response.length();
1130}
1131
1132// Allocates a queue entry owning a bare NO_RESULT component; nullptr when the queue is full or memory is out
1133NextionQueue *Nextion::make_no_result_entry_(const std::string &variable_name) {
1134#ifdef USE_NEXTION_MAX_QUEUE_SIZE
1135 if (this->max_queue_size_ > 0 && this->nextion_queue_.size() >= this->max_queue_size_) {
1136 ESP_LOGW(TAG, "Queue full (%zu), drop: %s", this->nextion_queue_.size(), variable_name.c_str());
1137 return nullptr;
1138 }
1139#endif
1140
1141 auto *nextion_queue = RAMAllocator<nextion::NextionQueue>().allocate(1);
1142 if (nextion_queue == nullptr) {
1143 ESP_LOGW(TAG, "Queue alloc failed");
1144 return nullptr;
1145 }
1146 new (nextion_queue) nextion::NextionQueue;
1147
1148 nextion_queue->component = RAMAllocator<nextion::NextionComponentBase>().allocate(1);
1149 if (nextion_queue->component == nullptr) {
1150 ESP_LOGW(TAG, "Component alloc failed");
1151 this->release_queue_entry_(nextion_queue);
1152 return nullptr;
1153 }
1154 new (nextion_queue->component) nextion::NextionComponentBase;
1155 nextion_queue->component->set_variable_name(variable_name);
1156 nextion_queue->queue_time = App.get_loop_component_start_time();
1157 return nextion_queue;
1158}
1159
1170void Nextion::add_no_result_to_queue_(const std::string &variable_name) {
1171 auto *nextion_queue = this->make_no_result_entry_(variable_name);
1172 if (nextion_queue == nullptr)
1173 return;
1174 this->nextion_queue_.push_back(nextion_queue);
1175 ESP_LOGN(TAG, "Queue NORESULT: %s", variable_name.c_str());
1176}
1177
1192void Nextion::add_no_result_to_queue_with_command_(const std::string &variable_name, const std::string &command) {
1193 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || command.empty())
1194 return;
1195
1196 ESP_LOGV(TAG, "Queue NORESULT '%s': %s", variable_name.c_str(), command.c_str());
1197
1198#ifdef USE_NEXTION_COMMAND_SPACING
1199 // Sending now would overtake commands that are still waiting, so only send when
1200 // nothing is waiting. process_pending_in_queue_() transmits the rest in order.
1201 if (this->has_unsent_commands_()) {
1202 this->add_no_result_to_queue_with_pending_command_(variable_name, command);
1203 return;
1204 }
1205#endif // USE_NEXTION_COMMAND_SPACING
1206
1207 if (this->send_command_(command)) {
1208 this->add_no_result_to_queue_(variable_name);
1209#ifdef USE_NEXTION_COMMAND_SPACING
1210 } else {
1211 // Command blocked by spacing, add to queue WITH the command for retry
1212 this->add_no_result_to_queue_with_pending_command_(variable_name, command);
1213#endif // USE_NEXTION_COMMAND_SPACING
1214 }
1215}
1216
1217#ifdef USE_NEXTION_COMMAND_SPACING
1218void Nextion::add_no_result_to_queue_with_pending_command_(const std::string &variable_name,
1219 const std::string &command) {
1220 auto *nextion_queue = this->make_no_result_entry_(variable_name);
1221 if (nextion_queue == nullptr)
1222 return;
1223 nextion_queue->pending_command = command; // Store command for retry
1224 this->nextion_queue_.push_back(nextion_queue);
1225 ESP_LOGVV(TAG, "Queue with pending command: %s", variable_name.c_str());
1226}
1227#endif // USE_NEXTION_COMMAND_SPACING
1228
1229bool Nextion::add_no_result_to_queue_with_ignore_sleep_printf_(const std::string &variable_name, const char *format,
1230 ...) {
1231 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_))
1232 return false;
1233
1234 char buffer[256];
1235 va_list arg;
1236 va_start(arg, format);
1237 int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
1238 va_end(arg);
1239 if (ret <= 0) {
1240 ESP_LOGW(TAG, "Bad cmd format: '%s'", format);
1241 return false;
1242 }
1243
1244 this->add_no_result_to_queue_with_command_(variable_name, buffer);
1245 return true;
1246}
1247
1255bool Nextion::add_no_result_to_queue_with_printf_(const std::string &variable_name, const char *format, ...) {
1256 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping())
1257 return false;
1258
1259 char buffer[256];
1260 va_list arg;
1261 va_start(arg, format);
1262 int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
1263 va_end(arg);
1264 if (ret <= 0) {
1265 ESP_LOGW(TAG, "Bad cmd format: '%s'", format);
1266 return false;
1267 }
1268
1269 this->add_no_result_to_queue_with_command_(variable_name, buffer);
1270 return true;
1271}
1272
1282void Nextion::add_no_result_to_queue_with_set(NextionComponentBase *component, int32_t state_value) {
1283 this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(),
1284 state_value);
1285}
1286
1287void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name,
1288 const std::string &variable_name_to_send, int32_t state_value) {
1289 this->add_no_result_to_queue_with_set_internal_(variable_name, variable_name_to_send, state_value);
1290}
1291
1292void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name,
1293 const std::string &variable_name_to_send, int32_t state_value,
1294 bool is_sleep_safe) {
1295 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping()))
1296 return;
1297
1298 this->add_no_result_to_queue_with_ignore_sleep_printf_(variable_name, "%s=%" PRId32, variable_name_to_send.c_str(),
1299 state_value);
1300}
1301
1310void Nextion::add_no_result_to_queue_with_set(NextionComponentBase *component, const std::string &state_value) {
1311 this->add_no_result_to_queue_with_set(component->get_variable_name(), component->get_variable_name_to_send(),
1312 state_value);
1313}
1314void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name,
1315 const std::string &variable_name_to_send,
1316 const std::string &state_value) {
1317 this->add_no_result_to_queue_with_set_internal_(variable_name, variable_name_to_send, state_value);
1318}
1319
1320void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name,
1321 const std::string &variable_name_to_send,
1322 const std::string &state_value, bool is_sleep_safe) {
1323 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping()))
1324 return;
1325
1326 this->add_no_result_to_queue_with_printf_(variable_name, "%s=\"%s\"", variable_name_to_send.c_str(),
1327 state_value.c_str());
1328}
1329
1339void Nextion::add_to_get_queue(NextionComponentBase *component) {
1340 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_))
1341 return;
1342
1343#ifdef USE_NEXTION_MAX_QUEUE_SIZE
1344 if (this->max_queue_size_ > 0 && this->nextion_queue_.size() >= this->max_queue_size_) {
1345 ESP_LOGW(TAG, "Queue full (%zu), drop GET: %s", this->nextion_queue_.size(),
1346 component->get_variable_name().c_str());
1347 return;
1348 }
1349#endif
1350
1351 RAMAllocator<nextion::NextionQueue> allocator;
1352 nextion::NextionQueue *nextion_queue = allocator.allocate(1);
1353 if (nextion_queue == nullptr) {
1354 ESP_LOGW(TAG, "Queue alloc failed");
1355 return;
1356 }
1357 new (nextion_queue) nextion::NextionQueue;
1358
1359 nextion_queue->component = component;
1360 nextion_queue->queue_time = App.get_loop_component_start_time();
1361
1362 ESP_LOGN(TAG, "Queue %s: %s", LOG_STR_ARG(component->get_queue_type_string()),
1363 component->get_variable_name().c_str());
1364
1365 std::string command = "get " + component->get_variable_name_to_send();
1366
1367#ifdef USE_NEXTION_COMMAND_SPACING
1368 // Only send right away when nothing is waiting, otherwise this command would
1369 // overtake the ones still queued. Anything not sent here keeps its command for
1370 // process_pending_in_queue_() to transmit in order.
1371 if (this->has_unsent_commands_() || !this->send_command_(command)) {
1372 nextion_queue->pending_command = std::move(command);
1373 }
1374 this->nextion_queue_.push_back(nextion_queue);
1375#else // USE_NEXTION_COMMAND_SPACING
1376 if (this->send_command_(command)) {
1377 this->nextion_queue_.push_back(nextion_queue);
1378 } else {
1379 this->release_queue_entry_(nextion_queue);
1380 }
1381#endif // USE_NEXTION_COMMAND_SPACING
1382}
1383
1384#ifdef USE_NEXTION_WAVEFORM
1390void Nextion::add_addt_command_to_queue(NextionComponentBase *component) {
1391 if ((!this->is_setup() && !this->connection_state_.ignore_is_setup_) || this->is_sleeping())
1392 return;
1393
1394 RAMAllocator<nextion::NextionQueue> allocator;
1395 nextion::NextionQueue *nextion_queue = allocator.allocate(1);
1396 if (nextion_queue == nullptr) {
1397 ESP_LOGW(TAG, "Queue alloc failed");
1398 return;
1399 }
1400 new (nextion_queue) nextion::NextionQueue;
1401
1402 nextion_queue->component = component;
1403 nextion_queue->queue_time = App.get_loop_component_start_time();
1404
1405 if (!this->waveform_queue_.push(nextion_queue)) {
1406 ESP_LOGW(TAG, "Waveform queue full, drop");
1407 this->release_queue_entry_(nextion_queue);
1408 return;
1409 }
1410 if (this->waveform_queue_.size() == 1)
1412}
1413
1415 if (this->waveform_queue_.empty())
1416 return;
1417
1418 auto *nb = this->waveform_queue_.front();
1419 auto *component = nb->component;
1420 size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size() : 255;
1421
1422 char command[24]; // "addt " + uint8 + "," + uint8 + "," + uint8 + null = max 17 chars
1423 buf_append_printf(command, sizeof(command), 0, "addt %u,%u,%zu", component->get_component_id(),
1424 component->get_wave_channel_id(), buffer_to_send);
1425 // If spacing or setup state blocks the send, leave the entry at the front
1426 // of waveform_queue_ for retry on the next loop iteration via
1427 // check_pending_waveform_(). Only pop on a successful send.
1428 this->send_command_(command);
1429}
1430#endif // USE_NEXTION_WAVEFORM
1431
1432void Nextion::set_writer(const nextion_writer_t &writer) { this->writer_ = writer; }
1433
1434bool Nextion::is_updating() { return this->connection_state_.is_updating_; }
1435
1436} // namespace esphome::nextion
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.
uint8_t get_spacing() const
Get current command spacing.
Definition nextion.h:57
bool can_send(uint32_t now) const
Check if enough time has passed to send the next command.
Definition nextion.h:65
void mark_sent(uint32_t now)
Record the transmit timestamp for the most recently sent command.
Definition nextion.h:73
void set_variable_name(const std::string &variable_name, const std::string &variable_name_to_send="")
std::vector< NextionComponentBase * > touch_
Definition nextion.h:1633
std::vector< NextionComponentBase * > switchtype_
Definition nextion.h:1634
std::vector< NextionComponentBase * > binarysensortype_
Definition nextion.h:1637
StaticRingBuffer< NextionQueue *, 4 > waveform_queue_
Fixed-size ring buffer for waveform queue.
Definition nextion.h:1489
uint16_t max_q_age_ms_
Maximum age for queue items in ms.
Definition nextion.h:1681
bool send_command_(const std::string &command)
Manually send a raw command to the display and don't wait for an acknowledgement packet.
static constexpr size_t NEXTION_MODEL_MAX
Max observed ~18 chars from product numbering rules.
Definition nextion.h:1662
std::vector< NextionComponentBase * > textsensortype_
Definition nextion.h:1636
char firmware_version_[NEXTION_FW_MAX+1]
Definition nextion.h:1666
void purge_stale_queue_entries_()
Drop queue entries older than max_q_age_ms_.
CallbackManager< void(uint8_t)> page_callback_
Definition nextion.h:1641
CallbackManager< void(StringRef, int32_t)> custom_sensor_callback_
Definition nextion.h:1648
void set_wake_up_page(uint8_t wake_up_page=255)
Sets which page Nextion loads when exiting sleep mode.
void set_string_return_(const std::string &value)
NextionQueue * make_no_result_entry_(const std::string &variable_name)
void all_components_send_state_(bool force_update=false)
void set_nextion_sensor_state(int queue_type, const std::string &name, float state)
Set the nextion sensor state object.
char serial_number_[NEXTION_SERIAL_MAX+1]
Definition nextion.h:1667
void add_addt_command_to_queue(NextionComponentBase *component) override
uint32_t flash_size_
Flash size in bytes — plain integer, no string needed.
Definition nextion.h:1668
uint16_t max_commands_per_loop_
Definition nextion.h:1453
nextion_writer_t writer_
Definition nextion.h:1657
uint16_t startup_override_ms_
Timeout before forcing setup complete.
Definition nextion.h:1680
void add_to_get_queue(NextionComponentBase *component) override
bool send_command_printf(const char *format,...) __attribute__((format(printf
Manually send a raw formatted command to the display.
std::list< NextionQueue * > nextion_queue_
Definition nextion.h:1485
void set_auto_wake_on_touch(bool auto_wake_on_touch)
Sets if Nextion should auto-wake from sleep when touch press occurs.
bool remove_from_q_(bool report_empty=true)
std::vector< NextionComponentBase * > sensortype_
Definition nextion.h:1635
bool add_no_result_to_queue_with_printf_(const std::string &variable_name, const char *format,...) __attribute__((format(printf
void set_touch_sleep_timeout(uint16_t touch_sleep_timeout=0)
Set the touch sleep timeout of the display using the thsp command.
CallbackManager< void()> setup_callback_
Definition nextion.h:1638
std::string command_data_
Definition nextion.h:1677
optional< float > brightness_
Definition nextion.h:1658
CallbackManager< void()> wake_callback_
Definition nextion.h:1640
void release_queue_entry_(NextionQueue *nb)
bool is_updating() override
Check if the TFT update process is currently running.
uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag)
void goto_page(const char *page)
Show the page with a given name.
bool void add_no_result_to_queue_with_set_internal_(const std::string &variable_name, const std::string &variable_name_to_send, int32_t state_value, bool is_sleep_safe=false)
bool void add_no_result_to_queue_with_command_(const std::string &variable_name, const std::string &command)
CallbackManager< void(StringRef, bool)> custom_binary_sensor_callback_
Definition nextion.h:1645
bool send_command(const char *command)
Manually send a raw command to the display.
bool has_unsent_commands_() const
Whether the queue still holds a command that has not reached the wire.
Definition nextion.h:1479
void set_numeric_return_(int value)
struct esphome::nextion::Nextion::@156 connection_state_
Status flags for Nextion display state management.
CallbackManager< void()> sleep_callback_
Definition nextion.h:1639
void reset_(bool reset_nextion=true)
void process_pending_in_queue_()
Process any commands in the queue that are pending due to command spacing.
static constexpr size_t NEXTION_FW_MAX
'S' prefix + integer (e.g. 'S99' or 123)
Definition nextion.h:1663
void add_no_result_to_queue_(const std::string &variable_name)
CallbackManager< void(uint8_t, uint8_t, bool)> touch_callback_
Definition nextion.h:1642
void dump_config() override
NextionCommandPacer command_pacer_
Definition nextion.h:1460
void deliver_queue_response_(const LogString *response_name, const NextionQueueResponse &resp)
Deliver a 0x70/0x71 response to the first query in the queue that was sent and expects a value,...
void set_nextion_text_state(const std::string &name, const std::string &state)
bool add_no_result_to_queue_with_ignore_sleep_printf_(const std::string &variable_name, const char *format,...) __attribute__((format(printf
void update() override
CallbackManager< void()> buffer_overflow_callback_
Definition nextion.h:1643
void set_writer(const nextion_writer_t &writer)
char device_model_[NEXTION_MODEL_MAX+1]
Definition nextion.h:1665
CallbackManager< void(StringRef, StringRef)> custom_text_sensor_callback_
Definition nextion.h:1654
void add_no_result_to_queue_with_pending_command_(const std::string &variable_name, const std::string &command)
Add a command to the Nextion queue with a pending command for retry.
void add_no_result_to_queue_with_set(NextionComponentBase *component, int32_t state_value) override
static constexpr size_t NEXTION_SERIAL_MAX
Consistently 16 hex chars across all documented examples.
Definition nextion.h:1664
CallbackManager< void(StringRef, bool)> custom_switch_callback_
Definition nextion.h:1651
void update_components_by_prefix(const std::string &prefix)
uint32_t tft_upload_watchdog_timeout_
WDT timeout in ms (0 = no adjustment)
Definition nextion.h:1599
void set_backlight_brightness(float brightness)
Set the brightness of the backlight.
bool read_available_chunks(F &&on_chunk)
Pass the bytes available now to on_chunk(data, len) in N byte chunks; returning false stops.
Definition uart.h:56
void discard_available()
Read and drop every byte waiting in the receive buffer.
Definition uart.cpp:36
void write_str(const char *str)
Definition uart.h:37
bool read_byte(uint8_t *data)
Definition uart.h:39
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
const Component * component
Definition component.cpp:34
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
int ret
const char * format
ESPHOME_LOG_TAG(TAG, "nextion_binarysensor")
display::DisplayWriter< Nextion > nextion_writer_t
Definition nextion.h:36
uint32_t value
Definition hal.cpp:41
va_end(args)
const void size_t len
Definition hal.h:68
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
size_t size_t const char va_start(args, fmt)
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17
uint16_t x
Definition tt21100.cpp:5
uint16_t y
Definition tt21100.cpp:6