ESPHome  2024.4.0
nextion.cpp
Go to the documentation of this file.
1 #include "nextion.h"
2 #include "esphome/core/util.h"
3 #include "esphome/core/log.h"
5 #include <cinttypes>
6 
7 namespace esphome {
8 namespace nextion {
9 
10 static const char *const TAG = "nextion";
11 
13  this->is_setup_ = false;
14  this->ignore_is_setup_ = true;
15 
16  // Wake up the nextion
17  this->send_command_("bkcmd=0");
18  this->send_command_("sleep=0");
19 
20  this->send_command_("bkcmd=0");
21  this->send_command_("sleep=0");
22 
23  // Reboot it
24  this->send_command_("rest");
25 
26  this->ignore_is_setup_ = false;
27 }
28 
29 bool Nextion::send_command_(const std::string &command) {
30  if (!this->ignore_is_setup_ && !this->is_setup()) {
31  return false;
32  }
33 
34  ESP_LOGN(TAG, "send_command %s", command.c_str());
35 
36  this->write_str(command.c_str());
37  const uint8_t to_send[3] = {0xFF, 0xFF, 0xFF};
38  this->write_array(to_send, sizeof(to_send));
39  return true;
40 }
41 
43  if (this->get_is_connected_())
44  return true;
45 
46  if (this->comok_sent_ == 0) {
47  this->reset_(false);
48 
49  this->ignore_is_setup_ = true;
50  this->send_command_("boguscommand=0"); // bogus command. needed sometimes after updating
51  if (this->exit_reparse_on_start_) {
52  this->send_command_("DRAKJHSUYDGBNCJHGJKSHBDN");
53  }
54  this->send_command_("connect");
55 
56  this->comok_sent_ = millis();
57  this->ignore_is_setup_ = false;
58 
59  return false;
60  }
61 
62  if (millis() - this->comok_sent_ <= 500) // Wait 500 ms
63  return false;
64 
65  std::string response;
66 
67  this->recv_ret_string_(response, 0, false);
68  if (!response.empty() && response[0] == 0x1A) {
69  // Swallow invalid variable name responses that may be caused by the above commands
70  ESP_LOGD(TAG, "0x1A error ignored during setup");
71  return false;
72  }
73  if (response.empty() || response.find("comok") == std::string::npos) {
74 #ifdef NEXTION_PROTOCOL_LOG
75  ESP_LOGN(TAG, "Bad connect request %s", response.c_str());
76  for (size_t i = 0; i < response.length(); i++) {
77  ESP_LOGN(TAG, "response %s %d %d %c", response.c_str(), i, response[i], response[i]);
78  }
79 #endif
80 
81  ESP_LOGW(TAG, "Nextion is not connected! ");
82  comok_sent_ = 0;
83  return false;
84  }
85 
86  this->ignore_is_setup_ = true;
87  ESP_LOGI(TAG, "Nextion is connected");
88  this->is_connected_ = true;
89 
90  ESP_LOGN(TAG, "connect request %s", response.c_str());
91 
92  size_t start;
93  size_t end = 0;
94  std::vector<std::string> connect_info;
95  while ((start = response.find_first_not_of(',', end)) != std::string::npos) {
96  end = response.find(',', start);
97  connect_info.push_back(response.substr(start, end - start));
98  }
99 
100  this->is_detected_ = (connect_info.size() == 7);
101  if (this->is_detected_) {
102  ESP_LOGN(TAG, "Received connect_info %zu", connect_info.size());
103 
104  this->device_model_ = connect_info[2];
105  this->firmware_version_ = connect_info[3];
106  this->serial_number_ = connect_info[5];
107  this->flash_size_ = connect_info[6];
108  } else {
109  ESP_LOGE(TAG, "Nextion returned bad connect value \"%s\"", response.c_str());
110  }
111 
112  this->ignore_is_setup_ = false;
113  this->dump_config();
114  return true;
115 }
116 
117 void Nextion::reset_(bool reset_nextion) {
118  uint8_t d;
119 
120  while (this->available()) { // Clear receive buffer
121  this->read_byte(&d);
122  };
123  this->nextion_queue_.clear();
124  this->waveform_queue_.clear();
125 }
126 
128  ESP_LOGCONFIG(TAG, "Nextion:");
129  ESP_LOGCONFIG(TAG, " Device Model: %s", this->device_model_.c_str());
130  ESP_LOGCONFIG(TAG, " Firmware Version: %s", this->firmware_version_.c_str());
131  ESP_LOGCONFIG(TAG, " Serial Number: %s", this->serial_number_.c_str());
132  ESP_LOGCONFIG(TAG, " Flash Size: %s", this->flash_size_.c_str());
133  ESP_LOGCONFIG(TAG, " Wake On Touch: %s", YESNO(this->auto_wake_on_touch_));
134  ESP_LOGCONFIG(TAG, " Exit reparse: %s", YESNO(this->exit_reparse_on_start_));
135 
136  if (this->touch_sleep_timeout_ != 0) {
137  ESP_LOGCONFIG(TAG, " Touch Timeout: %" PRIu32, this->touch_sleep_timeout_);
138  }
139 
140  if (this->wake_up_page_ != -1) {
141  ESP_LOGCONFIG(TAG, " Wake Up Page: %d", this->wake_up_page_);
142  }
143 
144  if (this->start_up_page_ != -1) {
145  ESP_LOGCONFIG(TAG, " Start Up Page: %d", this->start_up_page_);
146  }
147 }
148 
151  if (!this->is_setup()) {
152  return;
153  }
154  if (this->writer_.has_value()) {
155  (*this->writer_)(*this);
156  }
157 }
158 
159 void Nextion::add_sleep_state_callback(std::function<void()> &&callback) {
160  this->sleep_callback_.add(std::move(callback));
161 }
162 
163 void Nextion::add_wake_state_callback(std::function<void()> &&callback) {
164  this->wake_callback_.add(std::move(callback));
165 }
166 
167 void Nextion::add_setup_state_callback(std::function<void()> &&callback) {
168  this->setup_callback_.add(std::move(callback));
169 }
170 
171 void Nextion::add_new_page_callback(std::function<void(uint8_t)> &&callback) {
172  this->page_callback_.add(std::move(callback));
173 }
174 
175 void Nextion::add_touch_event_callback(std::function<void(uint8_t, uint8_t, bool)> &&callback) {
176  this->touch_callback_.add(std::move(callback));
177 }
178 
180  if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping())
181  return;
182 
183  for (auto *binarysensortype : this->binarysensortype_) {
184  binarysensortype->update_component();
185  }
186  for (auto *sensortype : this->sensortype_) {
187  sensortype->update_component();
188  }
189  for (auto *switchtype : this->switchtype_) {
190  switchtype->update_component();
191  }
192  for (auto *textsensortype : this->textsensortype_) {
193  textsensortype->update_component();
194  }
195 }
196 
197 bool Nextion::send_command_printf(const char *format, ...) {
198  if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping())
199  return false;
200 
201  char buffer[256];
202  va_list arg;
203  va_start(arg, format);
204  int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
205  va_end(arg);
206  if (ret <= 0) {
207  ESP_LOGW(TAG, "Building command for format '%s' failed!", format);
208  return false;
209  }
210 
211  if (this->send_command_(buffer)) {
212  this->add_no_result_to_queue_("send_command_printf");
213  return true;
214  }
215  return false;
216 }
217 
218 #ifdef NEXTION_PROTOCOL_LOG
220  ESP_LOGN(TAG, "print_queue_members_ (top 10) size %zu", this->nextion_queue_.size());
221  ESP_LOGN(TAG, "*******************************************");
222  int count = 0;
223  for (auto *i : this->nextion_queue_) {
224  if (count++ == 10)
225  break;
226 
227  if (i == nullptr) {
228  ESP_LOGN(TAG, "Nextion queue is null");
229  } else {
230  ESP_LOGN(TAG, "Nextion queue type: %d:%s , name: %s", i->component->get_queue_type(),
231  i->component->get_queue_type_string().c_str(), i->component->get_variable_name().c_str());
232  }
233  }
234  ESP_LOGN(TAG, "*******************************************");
235 }
236 #endif
237 
239  if (!this->check_connect_() || this->is_updating_)
240  return;
241 
242  if (this->nextion_reports_is_setup_ && !this->sent_setup_commands_) {
243  this->ignore_is_setup_ = true;
244  this->sent_setup_commands_ = true;
245  this->send_command_("bkcmd=3"); // Always, returns 0x00 to 0x23 result of serial command.
246 
248 
249  // Check if a startup page has been set and send the command
250  if (this->start_up_page_ != -1) {
251  this->goto_page(this->start_up_page_);
252  }
253 
256 
257  if (this->touch_sleep_timeout_ != 0) {
259  }
260 
261  if (this->wake_up_page_ != -1) {
262  this->set_wake_up_page(this->wake_up_page_);
263  }
264 
265  this->ignore_is_setup_ = false;
266  }
267 
268  this->process_serial_(); // Receive serial data
269  this->process_nextion_commands_(); // Process nextion return commands
270 
271  if (!this->nextion_reports_is_setup_) {
272  if (this->started_ms_ == 0)
273  this->started_ms_ = millis();
274 
275  if (this->started_ms_ + this->startup_override_ms_ < millis()) {
276  ESP_LOGD(TAG, "Manually set nextion report ready");
277  this->nextion_reports_is_setup_ = true;
278  }
279  }
280 }
281 
282 bool Nextion::remove_from_q_(bool report_empty) {
283  if (this->nextion_queue_.empty()) {
284  if (report_empty) {
285  ESP_LOGE(TAG, "Nextion queue is empty!");
286  }
287  return false;
288  }
289 
290  NextionQueue *nb = this->nextion_queue_.front();
291  NextionComponentBase *component = nb->component;
292 
293  ESP_LOGN(TAG, "Removing %s from the queue", component->get_variable_name().c_str());
294 
295  if (component->get_queue_type() == NextionQueueType::NO_RESULT) {
296  if (component->get_variable_name() == "sleep_wake") {
297  this->is_sleeping_ = false;
298  }
299  delete component; // NOLINT(cppcoreguidelines-owning-memory)
300  }
301  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
302  this->nextion_queue_.pop_front();
303  return true;
304 }
305 
307  uint8_t d;
308 
309  while (this->available()) {
310  read_byte(&d);
311  this->command_data_ += d;
312  }
313 }
314 // nextion.tech/instruction-set/
316  if (this->command_data_.length() == 0) {
317  return;
318  }
319 
320  size_t to_process_length = 0;
321  std::string to_process;
322 
323  ESP_LOGN(TAG, "this->command_data_ %s length %d", this->command_data_.c_str(), this->command_data_.length());
324 #ifdef NEXTION_PROTOCOL_LOG
325  this->print_queue_members_();
326 #endif
327  while ((to_process_length = this->command_data_.find(COMMAND_DELIMITER)) != std::string::npos) {
328  ESP_LOGN(TAG, "print_queue_members_ size %zu", this->nextion_queue_.size());
329  while (to_process_length + COMMAND_DELIMITER.length() < this->command_data_.length() &&
330  static_cast<uint8_t>(this->command_data_[to_process_length + COMMAND_DELIMITER.length()]) == 0xFF) {
331  ++to_process_length;
332  ESP_LOGN(TAG, "Add extra 0xFF to process");
333  }
334 
335  this->nextion_event_ = this->command_data_[0];
336 
337  to_process_length -= 1;
338  to_process = this->command_data_.substr(1, to_process_length);
339 
340  switch (this->nextion_event_) {
341  case 0x00: // instruction sent by user has failed
342  ESP_LOGW(TAG, "Nextion reported invalid instruction!");
343  this->remove_from_q_();
344 
345  break;
346  case 0x01: // instruction sent by user was successful
347 
348  ESP_LOGVV(TAG, "instruction sent by user was successful");
349  ESP_LOGN(TAG, "this->nextion_queue_.empty() %s", this->nextion_queue_.empty() ? "True" : "False");
350 
351  this->remove_from_q_();
352  if (!this->is_setup_) {
353  if (this->nextion_queue_.empty()) {
354  ESP_LOGD(TAG, "Nextion is setup");
355  this->is_setup_ = true;
356  this->setup_callback_.call();
357  }
358  }
359 
360  break;
361  case 0x02: // invalid Component ID or name was used
362  ESP_LOGW(TAG, "Nextion reported component ID or name invalid!");
363  this->remove_from_q_();
364  break;
365  case 0x03: // invalid Page ID or name was used
366  ESP_LOGW(TAG, "Nextion reported page ID invalid!");
367  this->remove_from_q_();
368  break;
369  case 0x04: // invalid Picture ID was used
370  ESP_LOGW(TAG, "Nextion reported picture ID invalid!");
371  this->remove_from_q_();
372  break;
373  case 0x05: // invalid Font ID was used
374  ESP_LOGW(TAG, "Nextion reported font ID invalid!");
375  this->remove_from_q_();
376  break;
377  case 0x06: // File operation fails
378  ESP_LOGW(TAG, "Nextion File operation fail!");
379  break;
380  case 0x09: // Instructions with CRC validation fails their CRC check
381  ESP_LOGW(TAG, "Nextion Instructions with CRC validation fails their CRC check!");
382  break;
383  case 0x11: // invalid Baud rate was used
384  ESP_LOGW(TAG, "Nextion reported baud rate invalid!");
385  break;
386  case 0x12: // invalid Waveform ID or Channel # was used
387  if (this->waveform_queue_.empty()) {
388  ESP_LOGW(TAG,
389  "Nextion reported invalid Waveform ID or Channel # was used but no waveform sensor in queue found!");
390  } else {
391  auto &nb = this->waveform_queue_.front();
392  NextionComponentBase *component = nb->component;
393 
394  ESP_LOGW(TAG, "Nextion reported invalid Waveform ID %d or Channel # %d was used!",
395  component->get_component_id(), component->get_wave_channel_id());
396 
397  ESP_LOGN(TAG, "Removing waveform from queue with component id %d and waveform id %d",
398  component->get_component_id(), component->get_wave_channel_id());
399 
400  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
401  this->waveform_queue_.pop_front();
402  }
403  break;
404  case 0x1A: // variable name invalid
405  ESP_LOGW(TAG, "Nextion reported variable name invalid!");
406  this->remove_from_q_();
407  break;
408  case 0x1B: // variable operation invalid
409  ESP_LOGW(TAG, "Nextion reported variable operation invalid!");
410  this->remove_from_q_();
411  break;
412  case 0x1C: // failed to assign
413  ESP_LOGW(TAG, "Nextion reported failed to assign variable!");
414  this->remove_from_q_();
415  break;
416  case 0x1D: // operate EEPROM failed
417  ESP_LOGW(TAG, "Nextion reported operating EEPROM failed!");
418  break;
419  case 0x1E: // parameter quantity invalid
420  ESP_LOGW(TAG, "Nextion reported parameter quantity invalid!");
421  this->remove_from_q_();
422  break;
423  case 0x1F: // IO operation failed
424  ESP_LOGW(TAG, "Nextion reported component I/O operation invalid!");
425  break;
426  case 0x20: // undefined escape characters
427  ESP_LOGW(TAG, "Nextion reported undefined escape characters!");
428  this->remove_from_q_();
429  break;
430  case 0x23: // too long variable name
431  ESP_LOGW(TAG, "Nextion reported too long variable name!");
432  this->remove_from_q_();
433  break;
434  case 0x24: // Serial Buffer overflow occurs
435  ESP_LOGW(TAG, "Nextion reported Serial Buffer overflow!");
436  break;
437  case 0x65: { // touch event return data
438  if (to_process_length != 3) {
439  ESP_LOGW(TAG, "Touch event data is expecting 3, received %zu", to_process_length);
440  break;
441  }
442 
443  uint8_t page_id = to_process[0];
444  uint8_t component_id = to_process[1];
445  uint8_t touch_event = to_process[2]; // 0 -> release, 1 -> press
446  ESP_LOGD(TAG, "Got touch event:");
447  ESP_LOGD(TAG, " page_id: %u", page_id);
448  ESP_LOGD(TAG, " component_id: %u", component_id);
449  ESP_LOGD(TAG, " event type: %s", touch_event ? "PRESS" : "RELEASE");
450  for (auto *touch : this->touch_) {
451  touch->process_touch(page_id, component_id, touch_event != 0);
452  }
453  this->touch_callback_.call(page_id, component_id, touch_event != 0);
454  break;
455  }
456  case 0x66: { // Nextion initiated new page event return data.
457  // Also is used for sendme command which we never explicitly initiate
458  if (to_process_length != 1) {
459  ESP_LOGW(TAG, "New page event data is expecting 1, received %zu", to_process_length);
460  break;
461  }
462 
463  uint8_t page_id = to_process[0];
464  ESP_LOGD(TAG, "Got new page: %u", page_id);
465  this->page_callback_.call(page_id);
466  break;
467  }
468  case 0x67: { // Touch Coordinate (awake)
469  break;
470  }
471  case 0x68: { // touch coordinate data (sleep)
472 
473  if (to_process_length != 5) {
474  ESP_LOGW(TAG, "Touch coordinate data is expecting 5, received %zu", to_process_length);
475  ESP_LOGW(TAG, "%s", to_process.c_str());
476  break;
477  }
478 
479  uint16_t x = (uint16_t(to_process[0]) << 8) | to_process[1];
480  uint16_t y = (uint16_t(to_process[2]) << 8) | to_process[3];
481  uint8_t touch_event = to_process[4]; // 0 -> release, 1 -> press
482  ESP_LOGD(TAG, "Got touch event:");
483  ESP_LOGD(TAG, " x: %u", x);
484  ESP_LOGD(TAG, " y: %u", y);
485  ESP_LOGD(TAG, " type: %s", touch_event ? "PRESS" : "RELEASE");
486  break;
487  }
488 
489  // 0x70 0x61 0x62 0x31 0x32 0x33 0xFF 0xFF 0xFF
490  // Returned when using get command for a string.
491  // Each byte is converted to char.
492  // data: ab123
493  case 0x70: // string variable data return
494  {
495  if (this->nextion_queue_.empty()) {
496  ESP_LOGW(TAG, "ERROR: Received string return but the queue is empty");
497  break;
498  }
499 
500  NextionQueue *nb = this->nextion_queue_.front();
501  NextionComponentBase *component = nb->component;
502 
503  if (component->get_queue_type() != NextionQueueType::TEXT_SENSOR) {
504  ESP_LOGE(TAG, "ERROR: Received string return but next in queue \"%s\" is not a text sensor",
505  component->get_variable_name().c_str());
506  } else {
507  ESP_LOGN(TAG, "Received get_string response: \"%s\" for component id: %s, type: %s", to_process.c_str(),
508  component->get_variable_name().c_str(), component->get_queue_type_string().c_str());
509  component->set_state_from_string(to_process, true, false);
510  }
511 
512  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
513  this->nextion_queue_.pop_front();
514 
515  break;
516  }
517  // 0x71 0x01 0x02 0x03 0x04 0xFF 0xFF 0xFF
518  // Returned when get command to return a number
519  // 4 byte 32-bit value in little endian order.
520  // (0x01+0x02*256+0x03*65536+0x04*16777216)
521  // data: 67305985
522  case 0x71: // numeric variable data return
523  {
524  if (this->nextion_queue_.empty()) {
525  ESP_LOGE(TAG, "ERROR: Received numeric return but the queue is empty");
526  break;
527  }
528 
529  if (to_process_length == 0) {
530  ESP_LOGE(TAG, "ERROR: Received numeric return but no data!");
531  break;
532  }
533 
534  int dataindex = 0;
535 
536  int value = 0;
537 
538  for (int i = 0; i < 4; ++i) {
539  value += to_process[i] << (8 * i);
540  ++dataindex;
541  }
542 
543  NextionQueue *nb = this->nextion_queue_.front();
544  NextionComponentBase *component = nb->component;
545 
546  if (component->get_queue_type() != NextionQueueType::SENSOR &&
548  component->get_queue_type() != NextionQueueType::SWITCH) {
549  ESP_LOGE(TAG, "ERROR: Received numeric return but next in queue \"%s\" is not a valid sensor type %d",
550  component->get_variable_name().c_str(), component->get_queue_type());
551  } else {
552  ESP_LOGN(TAG, "Received numeric return for variable %s, queue type %d:%s, value %d",
553  component->get_variable_name().c_str(), component->get_queue_type(),
554  component->get_queue_type_string().c_str(), value);
555  component->set_state_from_int(value, true, false);
556  }
557 
558  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
559  this->nextion_queue_.pop_front();
560 
561  break;
562  }
563 
564  case 0x86: { // device automatically enters into sleep mode
565  ESP_LOGVV(TAG, "Received Nextion entering sleep automatically");
566  this->is_sleeping_ = true;
567  this->sleep_callback_.call();
568  break;
569  }
570  case 0x87: // device automatically wakes up
571  {
572  ESP_LOGVV(TAG, "Received Nextion leaves sleep automatically");
573  this->is_sleeping_ = false;
574  this->wake_callback_.call();
575  this->all_components_send_state_(false);
576  break;
577  }
578  case 0x88: // system successful start up
579  {
580  ESP_LOGD(TAG, "system successful start up %zu", to_process_length);
581  this->nextion_reports_is_setup_ = true;
582  break;
583  }
584  case 0x89: { // start SD card upgrade
585  break;
586  }
587  // Data from nextion is
588  // 0x90 - Start
589  // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
590  // 00 - NULL
591  // 00/01 - Single byte for on/off
592  // FF FF FF - End
593  case 0x90: { // Switched component
594  std::string variable_name;
595 
596  // Get variable name
597  auto index = to_process.find('\0');
598  if (index == std::string::npos || (to_process_length - index - 1) < 1) {
599  ESP_LOGE(TAG, "Bad switch component data received for 0x90 event!");
600  ESP_LOGN(TAG, "to_process %s %zu %d", to_process.c_str(), to_process_length, index);
601  break;
602  }
603 
604  variable_name = to_process.substr(0, index);
605  ++index;
606 
607  ESP_LOGN(TAG, "Got Switch:");
608  ESP_LOGN(TAG, " variable_name: %s", variable_name.c_str());
609  ESP_LOGN(TAG, " value: %d", to_process[0] != 0);
610 
611  for (auto *switchtype : this->switchtype_) {
612  switchtype->process_bool(variable_name, to_process[index] != 0);
613  }
614  break;
615  }
616  // Data from nextion is
617  // 0x91 - Start
618  // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
619  // 00 - NULL
620  // variable length of 0x71 return data: prints temp1.val,0
621  // FF FF FF - End
622  case 0x91: { // Sensor component
623  std::string variable_name;
624 
625  auto index = to_process.find('\0');
626  if (index == std::string::npos || (to_process_length - index - 1) != 4) {
627  ESP_LOGE(TAG, "Bad sensor component data received for 0x91 event!");
628  ESP_LOGN(TAG, "to_process %s %zu %d", to_process.c_str(), to_process_length, index);
629  break;
630  }
631 
632  index = to_process.find('\0');
633  variable_name = to_process.substr(0, index);
634  // // Get variable name
635  int value = 0;
636  for (int i = 0; i < 4; ++i) {
637  value += to_process[i + index + 1] << (8 * i);
638  }
639 
640  ESP_LOGN(TAG, "Got sensor:");
641  ESP_LOGN(TAG, " variable_name: %s", variable_name.c_str());
642  ESP_LOGN(TAG, " value: %d", value);
643 
644  for (auto *sensor : this->sensortype_) {
645  sensor->process_sensor(variable_name, value);
646  }
647  break;
648  }
649 
650  // Data from nextion is
651  // 0x92 - Start
652  // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
653  // 00 - NULL
654  // variable length of 0x70 return formatted data (bytes) that contain the text prints temp1.txt,0
655  // 00 - NULL
656  // FF FF FF - End
657  case 0x92: { // Text Sensor Component
658  std::string variable_name;
659  std::string text_value;
660 
661  // Get variable name
662  auto index = to_process.find('\0');
663  if (index == std::string::npos || (to_process_length - index - 1) < 1) {
664  ESP_LOGE(TAG, "Bad text sensor component data received for 0x92 event!");
665  ESP_LOGN(TAG, "to_process %s %zu %d", to_process.c_str(), to_process_length, index);
666  break;
667  }
668 
669  variable_name = to_process.substr(0, index);
670  ++index;
671 
672  text_value = to_process.substr(index);
673 
674  ESP_LOGN(TAG, "Got Text Sensor:");
675  ESP_LOGN(TAG, " variable_name: %s", variable_name.c_str());
676  ESP_LOGN(TAG, " value: %s", text_value.c_str());
677 
678  // NextionTextSensorResponseQueue *nq = new NextionTextSensorResponseQueue;
679  // nq->variable_name = variable_name;
680  // nq->state = text_value;
681  // this->textsensorq_.push_back(nq);
682  for (auto *textsensortype : this->textsensortype_) {
683  textsensortype->process_text(variable_name, text_value);
684  }
685  break;
686  }
687  // Data from nextion is
688  // 0x93 - Start
689  // variable length of 0x70 return formatted data (bytes) that contain the variable name: prints "temp1",0
690  // 00 - NULL
691  // 00/01 - Single byte for on/off
692  // FF FF FF - End
693  case 0x93: { // Binary Sensor component
694  std::string variable_name;
695 
696  // Get variable name
697  auto index = to_process.find('\0');
698  if (index == std::string::npos || (to_process_length - index - 1) < 1) {
699  ESP_LOGE(TAG, "Bad binary sensor component data received for 0x92 event!");
700  ESP_LOGN(TAG, "to_process %s %zu %d", to_process.c_str(), to_process_length, index);
701  break;
702  }
703 
704  variable_name = to_process.substr(0, index);
705  ++index;
706 
707  ESP_LOGN(TAG, "Got Binary Sensor:");
708  ESP_LOGN(TAG, " variable_name: %s", variable_name.c_str());
709  ESP_LOGN(TAG, " value: %d", to_process[index] != 0);
710 
711  for (auto *binarysensortype : this->binarysensortype_) {
712  binarysensortype->process_bool(&variable_name[0], to_process[index] != 0);
713  }
714  break;
715  }
716  case 0xFD: { // data transparent transmit finished
717  ESP_LOGVV(TAG, "Nextion reported data transmit finished!");
718  this->check_pending_waveform_();
719  break;
720  }
721  case 0xFE: { // data transparent transmit ready
722  ESP_LOGVV(TAG, "Nextion reported ready for transmit!");
723  if (this->waveform_queue_.empty()) {
724  ESP_LOGE(TAG, "No waveforms in queue to send data!");
725  break;
726  }
727 
728  auto &nb = this->waveform_queue_.front();
729  auto *component = nb->component;
730  size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size()
731  : 255; // ADDT command can only send 255
732 
733  this->write_array(component->get_wave_buffer().data(), static_cast<int>(buffer_to_send));
734 
735  ESP_LOGN(TAG, "Nextion sending waveform data for component id %d and waveform id %d, size %zu",
736  component->get_component_id(), component->get_wave_channel_id(), buffer_to_send);
737 
738  component->clear_wave_buffer(buffer_to_send);
739  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
740  this->waveform_queue_.pop_front();
741  break;
742  }
743  default:
744  ESP_LOGW(TAG, "Received unknown event from nextion: 0x%02X", this->nextion_event_);
745  break;
746  }
747 
748  // ESP_LOGN(TAG, "nextion_event_ deleting from 0 to %d", to_process_length + COMMAND_DELIMITER.length() + 1);
749  this->command_data_.erase(0, to_process_length + COMMAND_DELIMITER.length() + 1);
750  // App.feed_wdt(); Remove before master merge
751  this->process_serial_();
752  }
753 
754  uint32_t ms = millis();
755 
756  if (!this->nextion_queue_.empty() && this->nextion_queue_.front()->queue_time + this->max_q_age_ms_ < ms) {
757  for (size_t i = 0; i < this->nextion_queue_.size(); i++) {
758  NextionComponentBase *component = this->nextion_queue_[i]->component;
759  if (this->nextion_queue_[i]->queue_time + this->max_q_age_ms_ < ms) {
760  if (this->nextion_queue_[i]->queue_time == 0) {
761  ESP_LOGD(TAG, "Removing old queue type \"%s\" name \"%s\" queue_time 0",
762  component->get_queue_type_string().c_str(), component->get_variable_name().c_str());
763  }
764 
765  if (component->get_variable_name() == "sleep_wake") {
766  this->is_sleeping_ = false;
767  }
768 
769  ESP_LOGD(TAG, "Removing old queue type \"%s\" name \"%s\"", component->get_queue_type_string().c_str(),
770  component->get_variable_name().c_str());
771 
772  if (component->get_queue_type() == NextionQueueType::NO_RESULT) {
773  if (component->get_variable_name() == "sleep_wake") {
774  this->is_sleeping_ = false;
775  }
776  delete component; // NOLINT(cppcoreguidelines-owning-memory)
777  }
778 
779  delete this->nextion_queue_[i]; // NOLINT(cppcoreguidelines-owning-memory)
780 
781  this->nextion_queue_.erase(this->nextion_queue_.begin() + i);
782  i--;
783 
784  } else {
785  break;
786  }
787  }
788  }
789  ESP_LOGN(TAG, "Loop End");
790  // App.feed_wdt(); Remove before master merge
791  this->process_serial_();
792 } // namespace nextion
793 
794 void Nextion::set_nextion_sensor_state(int queue_type, const std::string &name, float state) {
795  this->set_nextion_sensor_state(static_cast<NextionQueueType>(queue_type), name, state);
796 }
797 
798 void Nextion::set_nextion_sensor_state(NextionQueueType queue_type, const std::string &name, float state) {
799  ESP_LOGN(TAG, "Received state:");
800  ESP_LOGN(TAG, " variable: %s", name.c_str());
801  ESP_LOGN(TAG, " state: %lf", state);
802  ESP_LOGN(TAG, " queue type: %d", queue_type);
803 
804  switch (queue_type) {
806  for (auto *sensor : this->sensortype_) {
807  if (name == sensor->get_variable_name()) {
808  sensor->set_state(state, true, true);
809  break;
810  }
811  }
812  break;
813  }
815  for (auto *sensor : this->binarysensortype_) {
816  if (name == sensor->get_variable_name()) {
817  sensor->set_state(state != 0, true, true);
818  break;
819  }
820  }
821  break;
822  }
824  for (auto *sensor : this->switchtype_) {
825  if (name == sensor->get_variable_name()) {
826  sensor->set_state(state != 0, true, true);
827  break;
828  }
829  }
830  break;
831  }
832  default: {
833  ESP_LOGW(TAG, "set_nextion_sensor_state does not support a queue type %d", queue_type);
834  }
835  }
836 }
837 
838 void Nextion::set_nextion_text_state(const std::string &name, const std::string &state) {
839  ESP_LOGD(TAG, "Received state:");
840  ESP_LOGD(TAG, " variable: %s", name.c_str());
841  ESP_LOGD(TAG, " state: %s", state.c_str());
842 
843  for (auto *sensor : this->textsensortype_) {
844  if (name == sensor->get_variable_name()) {
845  sensor->set_state(state, true, true);
846  break;
847  }
848  }
849 }
850 
851 void Nextion::all_components_send_state_(bool force_update) {
852  ESP_LOGD(TAG, "all_components_send_state_ ");
853  for (auto *binarysensortype : this->binarysensortype_) {
854  if (force_update || binarysensortype->get_needs_to_send_update())
855  binarysensortype->send_state_to_nextion();
856  }
857  for (auto *sensortype : this->sensortype_) {
858  if ((force_update || sensortype->get_needs_to_send_update()) && sensortype->get_wave_chan_id() == 0)
859  sensortype->send_state_to_nextion();
860  }
861  for (auto *switchtype : this->switchtype_) {
862  if (force_update || switchtype->get_needs_to_send_update())
863  switchtype->send_state_to_nextion();
864  }
865  for (auto *textsensortype : this->textsensortype_) {
866  if (force_update || textsensortype->get_needs_to_send_update())
867  textsensortype->send_state_to_nextion();
868  }
869 }
870 
871 void Nextion::update_components_by_prefix(const std::string &prefix) {
872  for (auto *binarysensortype : this->binarysensortype_) {
873  if (binarysensortype->get_variable_name().find(prefix, 0) != std::string::npos)
874  binarysensortype->update_component_settings(true);
875  }
876  for (auto *sensortype : this->sensortype_) {
877  if (sensortype->get_variable_name().find(prefix, 0) != std::string::npos)
878  sensortype->update_component_settings(true);
879  }
880  for (auto *switchtype : this->switchtype_) {
881  if (switchtype->get_variable_name().find(prefix, 0) != std::string::npos)
882  switchtype->update_component_settings(true);
883  }
884  for (auto *textsensortype : this->textsensortype_) {
885  if (textsensortype->get_variable_name().find(prefix, 0) != std::string::npos)
886  textsensortype->update_component_settings(true);
887  }
888 }
889 
890 uint16_t Nextion::recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag) {
891  uint16_t ret = 0;
892  uint8_t c = 0;
893  uint8_t nr_of_ff_bytes = 0;
894  uint64_t start;
895  bool exit_flag = false;
896  bool ff_flag = false;
897 
898  start = millis();
899 
900  while ((timeout == 0 && this->available()) || millis() - start <= timeout) {
901  if (!this->available()) {
902  App.feed_wdt();
903  delay(1);
904  continue;
905  }
906 
907  this->read_byte(&c);
908  if (c == 0xFF) {
909  nr_of_ff_bytes++;
910  } else {
911  nr_of_ff_bytes = 0;
912  ff_flag = false;
913  }
914 
915  if (nr_of_ff_bytes >= 3)
916  ff_flag = true;
917 
918  response += (char) c;
919  if (recv_flag) {
920  if (response.find(0x05) != std::string::npos) {
921  exit_flag = true;
922  }
923  }
924  App.feed_wdt();
925  delay(2);
926 
927  if (exit_flag || ff_flag) {
928  break;
929  }
930  }
931 
932  if (ff_flag)
933  response = response.substr(0, response.length() - 3); // Remove last 3 0xFF
934 
935  ret = response.length();
936  return ret;
937 }
938 
944 void Nextion::add_no_result_to_queue_(const std::string &variable_name) {
945  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
946  nextion::NextionQueue *nextion_queue = new nextion::NextionQueue;
947 
948  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
949  nextion_queue->component = new nextion::NextionComponentBase;
950  nextion_queue->component->set_variable_name(variable_name);
951 
952  nextion_queue->queue_time = millis();
953 
954  this->nextion_queue_.push_back(nextion_queue);
955 
956  ESP_LOGN(TAG, "Add to queue type: NORESULT component %s", nextion_queue->component->get_variable_name().c_str());
957 }
958 
965 void Nextion::add_no_result_to_queue_with_command_(const std::string &variable_name, const std::string &command) {
966  if ((!this->is_setup() && !this->ignore_is_setup_) || command.empty())
967  return;
968 
969  if (this->send_command_(command)) {
970  this->add_no_result_to_queue_(variable_name);
971  }
972 }
973 
974 bool Nextion::add_no_result_to_queue_with_ignore_sleep_printf_(const std::string &variable_name, const char *format,
975  ...) {
976  if ((!this->is_setup() && !this->ignore_is_setup_))
977  return false;
978 
979  char buffer[256];
980  va_list arg;
981  va_start(arg, format);
982  int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
983  va_end(arg);
984  if (ret <= 0) {
985  ESP_LOGW(TAG, "Building command for format '%s' failed!", format);
986  return false;
987  }
988 
989  this->add_no_result_to_queue_with_command_(variable_name, buffer);
990  return true;
991 }
992 
1000 bool Nextion::add_no_result_to_queue_with_printf_(const std::string &variable_name, const char *format, ...) {
1001  if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping())
1002  return false;
1003 
1004  char buffer[256];
1005  va_list arg;
1006  va_start(arg, format);
1007  int ret = vsnprintf(buffer, sizeof(buffer), format, arg);
1008  va_end(arg);
1009  if (ret <= 0) {
1010  ESP_LOGW(TAG, "Building command for format '%s' failed!", format);
1011  return false;
1012  }
1013 
1014  this->add_no_result_to_queue_with_command_(variable_name, buffer);
1015  return true;
1016 }
1017 
1029  state_value);
1030 }
1031 
1032 void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name,
1033  const std::string &variable_name_to_send, int state_value) {
1034  this->add_no_result_to_queue_with_set_internal_(variable_name, variable_name_to_send, state_value);
1035 }
1036 
1037 void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name,
1038  const std::string &variable_name_to_send, int state_value,
1039  bool is_sleep_safe) {
1040  if ((!this->is_setup() && !this->ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping()))
1041  return;
1042 
1043  this->add_no_result_to_queue_with_ignore_sleep_printf_(variable_name, "%s=%d", variable_name_to_send.c_str(),
1044  state_value);
1045 }
1046 
1055 void Nextion::add_no_result_to_queue_with_set(NextionComponentBase *component, const std::string &state_value) {
1057  state_value);
1058 }
1059 void Nextion::add_no_result_to_queue_with_set(const std::string &variable_name,
1060  const std::string &variable_name_to_send,
1061  const std::string &state_value) {
1062  this->add_no_result_to_queue_with_set_internal_(variable_name, variable_name_to_send, state_value);
1063 }
1064 
1065 void Nextion::add_no_result_to_queue_with_set_internal_(const std::string &variable_name,
1066  const std::string &variable_name_to_send,
1067  const std::string &state_value, bool is_sleep_safe) {
1068  if ((!this->is_setup() && !this->ignore_is_setup_) || (!is_sleep_safe && this->is_sleeping()))
1069  return;
1070 
1071  this->add_no_result_to_queue_with_printf_(variable_name, "%s=\"%s\"", variable_name_to_send.c_str(),
1072  state_value.c_str());
1073 }
1074 
1076  if ((!this->is_setup() && !this->ignore_is_setup_))
1077  return;
1078 
1079  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1080  nextion::NextionQueue *nextion_queue = new nextion::NextionQueue;
1081 
1082  nextion_queue->component = component;
1083  nextion_queue->queue_time = millis();
1084 
1085  ESP_LOGN(TAG, "Add to queue type: %s component %s", component->get_queue_type_string().c_str(),
1086  component->get_variable_name().c_str());
1087 
1088  std::string command = "get " + component->get_variable_name_to_send();
1089 
1090  if (this->send_command_(command)) {
1091  this->nextion_queue_.push_back(nextion_queue);
1092  }
1093 }
1094 
1104  if ((!this->is_setup() && !this->ignore_is_setup_) || this->is_sleeping())
1105  return;
1106 
1107  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1108  nextion::NextionQueue *nextion_queue = new nextion::NextionQueue;
1109 
1110  nextion_queue->component = component;
1111  nextion_queue->queue_time = millis();
1112 
1113  this->waveform_queue_.push_back(nextion_queue);
1114  if (this->waveform_queue_.size() == 1)
1115  this->check_pending_waveform_();
1116 }
1117 
1119  if (this->waveform_queue_.empty())
1120  return;
1121 
1122  auto *nb = this->waveform_queue_.front();
1123  auto *component = nb->component;
1124  size_t buffer_to_send = component->get_wave_buffer_size() < 255 ? component->get_wave_buffer_size()
1125  : 255; // ADDT command can only send 255
1126 
1127  std::string command = "addt " + to_string(component->get_component_id()) + "," +
1128  to_string(component->get_wave_channel_id()) + "," + to_string(buffer_to_send);
1129  if (!this->send_command_(command)) {
1130  delete nb; // NOLINT(cppcoreguidelines-owning-memory)
1131  this->waveform_queue_.pop_front();
1132  }
1133 }
1134 
1135 void Nextion::set_writer(const nextion_writer_t &writer) { this->writer_ = writer; }
1136 
1137 ESPDEPRECATED("set_wait_for_ack(bool) is deprecated and has no effect", "v1.20")
1138 void Nextion::set_wait_for_ack(bool wait_for_ack) { ESP_LOGE(TAG, "This command is deprecated"); }
1139 
1140 } // namespace nextion
1141 } // namespace esphome
void goto_page(const char *page)
Show the page with a given name.
bool ignore_is_setup_
Sends commands ignoring of the Nextion has been setup.
Definition: nextion.h:1033
void write_str(const char *str)
Definition: uart.h:27
void all_components_send_state_(bool force_update=false)
Definition: nextion.cpp:851
CallbackManager< void(uint8_t)> page_callback_
Definition: nextion.h:1136
CallbackManager< void()> sleep_callback_
Definition: nextion.h:1134
const char * name
Definition: stm32flash.h:78
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
void add_new_page_callback(std::function< void(uint8_t)> &&callback)
Add a callback to be notified when the nextion changes pages.
Definition: nextion.cpp:171
void write_array(const uint8_t *data, size_t len)
Definition: uart.h:21
void add_wake_state_callback(std::function< void()> &&callback)
Add a callback to be notified of wake state changes.
Definition: nextion.cpp:163
bool send_command_printf(const char *format,...) __attribute__((format(printf
Manually send a raw formatted command to the display.
Definition: nextion.cpp:197
void add_no_result_to_queue_with_set(NextionComponentBase *component, int state_value) override
Definition: nextion.cpp:1027
void add_addt_command_to_queue(NextionComponentBase *component) override
Add addt command to the queue.
Definition: nextion.cpp:1103
uint32_t startup_override_ms_
Definition: nextion.h:1163
void add_to_get_queue(NextionComponentBase *component) override
Definition: nextion.cpp:1075
std::vector< NextionComponentBase * > touch_
Definition: nextion.h:1128
optional< nextion_writer_t > writer_
Definition: nextion.h:1139
uint16_t x
Definition: tt21100.cpp:17
void add_setup_state_callback(std::function< void()> &&callback)
Add a callback to be notified when the nextion completes its initialize setup.
Definition: nextion.cpp:167
bool send_command_(const std::string &command)
Manually send a raw command to the display and don&#39;t wait for an acknowledgement packet.
Definition: nextion.cpp:29
float get_setup_priority() const override
Definition: nextion.cpp:149
void setup() override
Definition: nextion.cpp:12
std::string serial_number_
Definition: nextion.h:1144
CallbackManager< void(uint8_t, uint8_t, bool)> touch_callback_
Definition: nextion.h:1137
bool has_value() const
Definition: optional.h:87
bool void add_no_result_to_queue_with_set_internal_(const std::string &variable_name, const std::string &variable_name_to_send, int state_value, bool is_sleep_safe=false)
Definition: nextion.cpp:1037
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
void set_exit_reparse_on_start(bool exit_reparse)
Sets if Nextion should exit the active reparse mode before the "connect" command is sent...
uint16_t y
Definition: tt21100.cpp:18
bool add_no_result_to_queue_with_printf_(const std::string &variable_name, const char *format,...) __attribute__((format(printf
Sends a formatted command to the nextion.
Definition: nextion.cpp:1000
void add_sleep_state_callback(std::function< void()> &&callback)
Add a callback to be notified of sleep state changes.
Definition: nextion.cpp:159
virtual void set_state_from_string(const std::string &state_value, bool publish, bool send_to_nextion)
std::string flash_size_
Definition: nextion.h:1145
void set_nextion_sensor_state(int queue_type, const std::string &name, float state)
Set the nextion sensor state object.
Definition: nextion.cpp:794
CallbackManager< void()> setup_callback_
Definition: nextion.h:1133
bool read_byte(uint8_t *data)
Definition: uart.h:29
void set_nextion_text_state(const std::string &name, const std::string &state)
Definition: nextion.cpp:838
void set_wait_for_ack(bool wait_for_ack)
void loop() override
Definition: nextion.cpp:238
std::deque< NextionQueue * > nextion_queue_
Definition: nextion.h:1023
CallbackManager< void()> wake_callback_
Definition: nextion.h:1135
Application App
Global storage of Application pointer - only one Application can exist.
void add_no_result_to_queue_(const std::string &variable_name)
Definition: nextion.cpp:944
std::deque< NextionQueue * > waveform_queue_
Definition: nextion.h:1024
std::string command_data_
Definition: nextion.h:1161
bool remove_from_q_(bool report_empty=true)
Definition: nextion.cpp:282
void set_backlight_brightness(float brightness)
Set the brightness of the backlight.
std::string device_model_
Definition: nextion.h:1142
bool add_no_result_to_queue_with_ignore_sleep_printf_(const std::string &variable_name, const char *format,...) __attribute__((format(printf
Definition: nextion.cpp:974
void set_touch_sleep_timeout(uint16_t timeout)
Set the touch sleep timeout of the display.
std::vector< NextionComponentBase * > textsensortype_
Definition: nextion.h:1131
ESPDEPRECATED("set_wait_for_ack(bool) is deprecated and has no effect", "v1.20") void Nextion
Definition: nextion.cpp:1137
void add_touch_event_callback(std::function< void(uint8_t, uint8_t, bool)> &&callback)
Add a callback to be notified when Nextion has a touch event.
Definition: nextion.cpp:175
void set_wake_up_page(uint8_t page_id=255)
Sets which page Nextion loads when exiting sleep mode.
std::vector< NextionComponentBase * > sensortype_
Definition: nextion.h:1130
void dump_config() override
Definition: nextion.cpp:127
std::string to_string(int value)
Definition: helpers.cpp:82
std::vector< NextionComponentBase * > switchtype_
Definition: nextion.h:1129
void set_auto_wake_on_touch(bool auto_wake)
Sets if Nextion should auto-wake from sleep when touch press occurs.
virtual void set_state_from_int(int state_value, bool publish, bool send_to_nextion)
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
bool void add_no_result_to_queue_with_command_(const std::string &variable_name, const std::string &command)
Definition: nextion.cpp:965
void reset_(bool reset_nextion=true)
Definition: nextion.cpp:117
void update_components_by_prefix(const std::string &prefix)
Definition: nextion.cpp:871
void update() override
Definition: nextion.cpp:150
uint8_t end[39]
Definition: sun_gtil2.cpp:31
std::string firmware_version_
Definition: nextion.h:1143
void set_variable_name(const std::string &variable_name, const std::string &variable_name_to_send="")
uint32_t touch_sleep_timeout_
Definition: nextion.h:1040
uint16_t recv_ret_string_(std::string &response, uint32_t timeout, bool recv_flag)
Definition: nextion.cpp:890
std::function< void(Nextion &)> nextion_writer_t
Definition: nextion.h:34
std::vector< NextionComponentBase * > binarysensortype_
Definition: nextion.h:1132
bool state
Definition: fan.h:34
void set_writer(const nextion_writer_t &writer)
Definition: nextion.cpp:1135
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26