cycle_engine.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #pragma once
  2. #include <cstdint>
  3. #include <cstdio>
  4. #include "esphome/core/gpio.h"
  5. #include "esphome/core/hal.h"
  6. #include "esphome/core/log.h"
  7. #include "esphome/components/spi/spi.h"
  8. #include "epd_command.h"
  9. namespace esphome::gxepd2 {
  10. // Stock GxEPD2 vendor value (20MHz) for this panel. Was dropped to 10MHz
  11. // (matching epaper_spi) while chasing the solid-black/solid-red symptom,
  12. // which turned out to be unrelated - display.py never wired the configured
  13. // lambda to set_writer() at all, so nothing but auto_clear's default fill
  14. // ever rendered, regardless of SPI clock. Rolled back to test the stock
  15. // GxEPD2 clock now that the real bug is fixed.
  16. using EpdSPIDevice = spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING,
  17. spi::DATA_RATE_20MHZ>;
  18. // Mechanically replicates one GxEPD2 driver's refresh cycle - reset pulse,
  19. // init command table, RAM-window set, per-plane byte burst, refresh
  20. // trigger, busy-pin wait - as a state machine stepped from loop(), instead
  21. // of GxEPD2's own synchronous top-to-bottom call stack. See the plan this
  22. // was built from (and gxepd2_task_watchdog_status in project memory) for
  23. // why: that call stack has no yield points, so making it non-blocking used
  24. // to require running the whole thing on a separate FreeRTOS task, which
  25. // intermittently tripped the ESP-IDF watchdog anyway. step() never blocks -
  26. // every state does a small bounded unit of work and returns - so there is
  27. // nothing here that can starve another task or need a watchdog subscription
  28. // at all.
  29. class CycleEngine {
  30. public:
  31. void begin(const EpdPanelDescriptor *desc, GPIOPin *cs, GPIOPin *dc, GPIOPin *rst, GPIOPin *busy,
  32. EpdSPIDevice *spi) {
  33. this->desc_ = desc;
  34. this->cs_ = cs;
  35. this->dc_ = dc;
  36. this->rst_ = rst;
  37. this->busy_ = busy;
  38. this->spi_ = spi;
  39. this->cs_->setup();
  40. this->dc_->setup();
  41. if (this->rst_ != nullptr)
  42. this->rst_->setup();
  43. if (this->busy_ != nullptr)
  44. this->busy_->setup();
  45. this->cs_->digital_write(true);
  46. this->dc_->digital_write(true);
  47. }
  48. // Arms the state machine; returns immediately. planes[1] is ignored when
  49. // desc->plane_count == 1. Undefined to call while !idle().
  50. void request_full_update(const uint8_t *plane0, const uint8_t *plane1) {
  51. this->planes_[0] = plane0;
  52. this->planes_[1] = plane1;
  53. uint32_t w = this->desc_->window_per_plane ? this->desc_->plane_width : this->desc_->width;
  54. this->plane_bytes_ = this->desc_->packed_2bpp_plane ? (w * this->desc_->height) / 4
  55. : (w * this->desc_->height) / 8;
  56. this->cursor_ = 0;
  57. this->plane_ = 0;
  58. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  59. this->set_state_(this->rst_ != nullptr ? State::RESET_LOW : State::INIT_CMD);
  60. }
  61. bool idle() const { return this->state_ == State::IDLE; }
  62. // Called once per loop() tick. Does one bounded unit of work.
  63. void step() {
  64. switch (this->state_) {
  65. case State::IDLE:
  66. return;
  67. case State::RESET_LOW:
  68. this->rst_->digital_write(true); // preset high, then pulse low - see GxEPD2_EPD::_reset()
  69. this->deadline_ = millis() + 10;
  70. this->set_state_(State::RESET_LOW_WAIT);
  71. return;
  72. case State::RESET_LOW_WAIT:
  73. if (millis() < this->deadline_)
  74. return;
  75. this->rst_->digital_write(false);
  76. this->deadline_ = millis() + 10;
  77. this->set_state_(State::RESET_HIGH_WAIT);
  78. return;
  79. case State::RESET_HIGH_WAIT:
  80. if (millis() < this->deadline_)
  81. return;
  82. this->rst_->digital_write(true);
  83. this->deadline_ = millis() + 10;
  84. this->set_state_(State::RESET_SETTLE);
  85. return;
  86. case State::RESET_SETTLE:
  87. if (millis() < this->deadline_)
  88. return;
  89. this->cursor_ = 0;
  90. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  91. this->set_state_(State::INIT_CMD);
  92. return;
  93. case State::INIT_CMD:
  94. this->step_sequence_(this->desc_->init_sequence, this->desc_->init_sequence_len, State::INIT_CMD,
  95. State::SET_WINDOW);
  96. return;
  97. case State::SET_WINDOW:
  98. // window_sequence[this->plane_]: index 0 on the first entry
  99. // (plane_ reset to 0 in request_full_update()); when
  100. // window_per_plane is true, step_write_plane_() re-enters this
  101. // state with plane_ already advanced to 1 before the next plane's
  102. // byte burst, picking window_sequence[1] instead - see
  103. // panel_579c_gdey0579f51.h for why a panel needs that.
  104. this->step_sequence_(this->desc_->window_sequence[this->plane_], this->desc_->window_sequence_len[this->plane_],
  105. State::SET_WINDOW, State::WRITE_PLANE);
  106. return;
  107. case State::WRITE_PLANE:
  108. this->step_write_plane_();
  109. return;
  110. case State::REFRESH_CMD:
  111. this->step_sequence_(this->desc_->refresh_sequence, this->desc_->refresh_sequence_len, State::REFRESH_CMD,
  112. State::DONE);
  113. return;
  114. case State::POST_DELAY:
  115. if (millis() < this->deadline_)
  116. return;
  117. this->set_state_(this->delay_return_state_);
  118. return;
  119. case State::WAIT_BUSY:
  120. this->step_wait_busy_();
  121. return;
  122. case State::DONE:
  123. ESP_LOGD("gxepd2", "Display update finished");
  124. this->set_state_(State::IDLE);
  125. return;
  126. case State::ABORTED:
  127. // A busy timeout means the panel isn't behaving as wired/expected
  128. // (unplugged, dead, wrong busy polarity, ...) - pressing ahead
  129. // with the rest of the sequence (more command bytes, another
  130. // busy-wait) is very unlikely to "just work" and only obscures
  131. // which step actually failed. Bail the whole cycle here instead of
  132. // continuing to whatever state the timed-out wait was headed to.
  133. ESP_LOGE("gxepd2", "Aborting display update: busy timeout");
  134. this->cursor_ = 0;
  135. this->plane_ = 0;
  136. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  137. this->set_state_(State::IDLE);
  138. return;
  139. }
  140. }
  141. private:
  142. enum class State {
  143. IDLE,
  144. RESET_LOW,
  145. RESET_LOW_WAIT,
  146. RESET_HIGH_WAIT,
  147. RESET_SETTLE,
  148. INIT_CMD,
  149. SET_WINDOW,
  150. WRITE_PLANE,
  151. REFRESH_CMD,
  152. POST_DELAY,
  153. WAIT_BUSY,
  154. DONE,
  155. ABORTED,
  156. };
  157. enum class CmdPhase { BEFORE_DELAY, ISSUE };
  158. // Every command byte and every data byte is its own SPI transaction, CS
  159. // toggled around each one - this looks wasteful, but it's mechanically
  160. // what GxEPD2_EPD::_writeCommand()/_writeData(uint8_t) do (see
  161. // vendor/src/GxEPD2_EPD.cpp), and matching the vendor cycle byte-for-byte
  162. // is the point of this engine.
  163. void write_byte_(uint8_t b, bool dc_high) {
  164. this->dc_->digital_write(dc_high);
  165. this->spi_->enable();
  166. this->cs_->digital_write(false);
  167. this->spi_->write_byte(b);
  168. this->cs_->digital_write(true);
  169. this->spi_->disable();
  170. }
  171. void write_command_(uint8_t cmd, const uint8_t *data, uint8_t data_len) {
  172. #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
  173. // Command-level skeleton trace - deliberately left in (not gated to
  174. // VERY_VERBOSE) while diagnosing a real-hardware content bug: this is
  175. // the exact byte-for-byte counterpart to compare against a captured
  176. // epaper_spi trace on the same panel. Bulk plane data isn't logged
  177. // here (see step_write_plane_) - only the command skeleton matters for
  178. // that comparison.
  179. char buf[32] = {0};
  180. int n = 0;
  181. for (uint8_t i = 0; i < data_len && n < (int) sizeof(buf) - 3; i++)
  182. n += snprintf(buf + n, sizeof(buf) - n, "%02X ", data[i]);
  183. ESP_LOGD("gxepd2", "cmd 0x%02X data[%u]: %s", cmd, data_len, buf);
  184. #endif
  185. this->write_byte_(cmd, false);
  186. for (uint8_t i = 0; i < data_len; i++)
  187. this->write_byte_(data[i], true);
  188. }
  189. // Steps through one EpdCommand table one entry (and one delay/busy-wait,
  190. // if that entry has one) at a time, resuming in self_state after any
  191. // wait so the same call re-enters here for the next entry. Shared by
  192. // INIT_CMD and REFRESH_CMD - which table is being stepped is entirely
  193. // determined by which state called this.
  194. void step_sequence_(const EpdCommand *seq, uint8_t len, State self_state, State done_state) {
  195. if (this->cursor_ >= len) {
  196. this->cursor_ = 0;
  197. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  198. this->set_state_(done_state);
  199. return;
  200. }
  201. const EpdCommand &c = seq[this->cursor_];
  202. if (this->cmd_phase_ == CmdPhase::BEFORE_DELAY) {
  203. this->cmd_phase_ = CmdPhase::ISSUE;
  204. if (c.delay_before_ms > 0) {
  205. this->start_delay_(c.delay_before_ms, self_state);
  206. return;
  207. }
  208. }
  209. this->write_command_(c.cmd, c.data, c.data_len);
  210. this->cursor_++;
  211. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  212. if (c.wait_busy_after) {
  213. this->start_busy_wait_(self_state);
  214. } else if (c.delay_after_ms > 0) {
  215. this->start_delay_(c.delay_after_ms, self_state);
  216. }
  217. // else: stays in self_state; the next step() call processes the next entry.
  218. }
  219. // Writes up to BYTE_BUDGET bytes of the current plane per call, then
  220. // returns - this bound is what keeps a full-frame write (thousands of
  221. // bytes) from ever making one loop() tick run long, replacing the old
  222. // per-256-byte esp_task_wdt_reset()+delay(1) throttle with simply not
  223. // doing enough work in one call to need it.
  224. static constexpr uint32_t BYTE_BUDGET = 64;
  225. void step_write_plane_() {
  226. if (this->cursor_ == 0) {
  227. const uint8_t *buf = this->planes_[this->plane_];
  228. uint32_t histo[3] = {0, 0, 0}; // [0]=0x00, [1]=0xFF, [2]=other
  229. if (buf != nullptr) {
  230. for (uint32_t i = 0; i < this->plane_bytes_; i++) {
  231. if (buf[i] == 0x00)
  232. histo[0]++;
  233. else if (buf[i] == 0xFF)
  234. histo[1]++;
  235. else
  236. histo[2]++;
  237. }
  238. }
  239. ESP_LOGD("gxepd2", "plane %u: cmd 0x%02X, %u bytes, invert=%d, buf[0]=0x%02X buf[last]=0x%02X, histo(00/FF/other)=%u/%u/%u",
  240. this->plane_, this->desc_->plane_write_cmd[this->plane_], (unsigned) this->plane_bytes_,
  241. this->desc_->plane_invert[this->plane_], buf != nullptr ? buf[0] : 0,
  242. buf != nullptr ? buf[this->plane_bytes_ - 1] : 0, (unsigned) histo[0], (unsigned) histo[1],
  243. (unsigned) histo[2]);
  244. this->write_byte_(this->desc_->plane_write_cmd[this->plane_], false);
  245. }
  246. const uint8_t *buf = this->planes_[this->plane_];
  247. bool invert = this->desc_->plane_invert[this->plane_];
  248. uint32_t end = this->cursor_ + BYTE_BUDGET;
  249. if (end > this->plane_bytes_)
  250. end = this->plane_bytes_;
  251. for (; this->cursor_ < end; this->cursor_++) {
  252. uint8_t b = buf != nullptr ? buf[this->cursor_] : 0xFF;
  253. this->write_byte_(invert ? static_cast<uint8_t>(~b) : b, true);
  254. }
  255. if (this->cursor_ >= this->plane_bytes_) {
  256. this->cursor_ = 0;
  257. this->plane_++;
  258. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  259. if (this->plane_ >= this->desc_->plane_count) {
  260. this->plane_ = 0;
  261. this->set_state_(State::REFRESH_CMD);
  262. } else if (this->desc_->window_per_plane) {
  263. // Another plane to go and it needs its own window-set first (a
  264. // genuinely separate physical RAM region, not just another color
  265. // plane sharing the window already set) - re-enter SET_WINDOW,
  266. // which will pick window_sequence[this->plane_] now that plane_
  267. // has already advanced.
  268. this->set_state_(State::SET_WINDOW);
  269. }
  270. // else: more planes, sharing one window already set - stay in
  271. // WRITE_PLANE, next step() call starts the next plane's byte burst.
  272. }
  273. }
  274. void start_delay_(uint16_t delay_ms, State return_to) {
  275. this->deadline_ = millis() + delay_ms;
  276. this->delay_return_state_ = return_to;
  277. this->set_state_(State::POST_DELAY);
  278. }
  279. void start_busy_wait_(State next) {
  280. this->busy_wait_next_ = next;
  281. this->busy_wait_deadline_ = millis() + this->desc_->busy_timeout_ms;
  282. this->set_state_(State::WAIT_BUSY);
  283. }
  284. void step_wait_busy_() {
  285. if (this->busy_ == nullptr) {
  286. this->set_state_(this->busy_wait_next_);
  287. return;
  288. }
  289. bool busy = this->busy_->digital_read() == this->desc_->busy_active_level;
  290. if (!busy) {
  291. this->set_state_(this->busy_wait_next_);
  292. return;
  293. }
  294. if (millis() >= this->busy_wait_deadline_) {
  295. ESP_LOGW("gxepd2", "Busy timeout waiting for panel");
  296. this->set_state_(State::ABORTED);
  297. }
  298. }
  299. // Logs every state transition (only when the state actually changes -
  300. // WAIT_BUSY and POST_DELAY re-enter their own case on every step() call
  301. // while polling, which would otherwise spam this at loop() rate) so a
  302. // first hardware run can be checked against the vendor cycle it's meant
  303. // to replicate before this gets dialed back to WARN-only.
  304. void set_state_(State s) {
  305. if (s != this->state_)
  306. ESP_LOGD("gxepd2", "state: %s -> %s", state_name_(this->state_), state_name_(s));
  307. this->state_ = s;
  308. }
  309. static const char *state_name_(State s) {
  310. switch (s) {
  311. case State::IDLE:
  312. return "IDLE";
  313. case State::RESET_LOW:
  314. return "RESET_LOW";
  315. case State::RESET_LOW_WAIT:
  316. return "RESET_LOW_WAIT";
  317. case State::RESET_HIGH_WAIT:
  318. return "RESET_HIGH_WAIT";
  319. case State::RESET_SETTLE:
  320. return "RESET_SETTLE";
  321. case State::INIT_CMD:
  322. return "INIT_CMD";
  323. case State::SET_WINDOW:
  324. return "SET_WINDOW";
  325. case State::WRITE_PLANE:
  326. return "WRITE_PLANE";
  327. case State::REFRESH_CMD:
  328. return "REFRESH_CMD";
  329. case State::POST_DELAY:
  330. return "POST_DELAY";
  331. case State::WAIT_BUSY:
  332. return "WAIT_BUSY";
  333. case State::DONE:
  334. return "DONE";
  335. case State::ABORTED:
  336. return "ABORTED";
  337. }
  338. return "?";
  339. }
  340. const EpdPanelDescriptor *desc_{nullptr};
  341. GPIOPin *cs_{nullptr};
  342. GPIOPin *dc_{nullptr};
  343. GPIOPin *rst_{nullptr};
  344. GPIOPin *busy_{nullptr};
  345. EpdSPIDevice *spi_{nullptr};
  346. State state_{State::IDLE};
  347. uint32_t cursor_{0};
  348. CmdPhase cmd_phase_{CmdPhase::BEFORE_DELAY};
  349. uint8_t plane_{0};
  350. const uint8_t *planes_[2]{nullptr, nullptr};
  351. uint32_t plane_bytes_{0};
  352. uint32_t deadline_{0};
  353. State delay_return_state_{State::DONE};
  354. uint32_t busy_wait_deadline_{0};
  355. State busy_wait_next_{State::DONE};
  356. };
  357. } // namespace esphome::gxepd2