cycle_engine.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. // Replays one GxEPD2 driver's refresh cycle - reset pulse, init command table,
  19. // RAM-window set, per-plane byte burst, refresh trigger, busy-pin wait - as a
  20. // state machine stepped from loop(), instead of GxEPD2's own synchronous
  21. // top-to-bottom call stack. step() never blocks: every state does a small
  22. // bounded unit of work and returns, so nothing here can starve another task or
  23. // need a watchdog subscription.
  24. class CycleEngine {
  25. public:
  26. void begin(const EpdPanelDescriptor *desc, GPIOPin *cs, GPIOPin *dc, GPIOPin *rst, GPIOPin *busy,
  27. EpdSPIDevice *spi) {
  28. this->desc_ = desc;
  29. this->cs_ = cs;
  30. this->dc_ = dc;
  31. this->rst_ = rst;
  32. this->busy_ = busy;
  33. this->spi_ = spi;
  34. this->cs_->setup();
  35. this->dc_->setup();
  36. if (this->rst_ != nullptr)
  37. this->rst_->setup();
  38. if (this->busy_ != nullptr)
  39. this->busy_->setup();
  40. this->cs_->digital_write(true);
  41. this->dc_->digital_write(true);
  42. }
  43. // Arms the state machine; returns immediately. planes[1] is ignored when
  44. // desc->plane_count == 1. Undefined to call while !idle().
  45. void request_full_update(const uint8_t *plane0, const uint8_t *plane1) {
  46. this->planes_[0] = plane0;
  47. this->planes_[1] = plane1;
  48. uint32_t w = this->desc_->window_per_plane ? this->desc_->plane_width : this->desc_->width;
  49. // width*height*bpp/8: /8 at 1bpp, /4 at 2bpp, /2 at 4bpp.
  50. this->plane_bytes_ = (uint32_t) w * this->desc_->height * this->desc_->bits_per_pixel / 8;
  51. this->bytes_per_row_ = this->plane_bytes_ / this->desc_->height;
  52. // Wire length can exceed the buffer: PAIRED_EDGES sends each row twice
  53. // (2x-height RAM). plane_bytes_ stays the real buffer size; wire_bytes_
  54. // is what actually goes out on 0x10/0x24/... per plane.
  55. uint32_t wire_lines = this->desc_->height;
  56. if (this->desc_->line_order == LineOrder::PAIRED_EDGES)
  57. wire_lines *= 2;
  58. this->wire_bytes_ = wire_lines * this->bytes_per_row_;
  59. this->cursor_ = 0;
  60. this->plane_ = 0;
  61. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  62. this->set_state_(this->rst_ != nullptr ? State::RESET_LOW : State::INIT_CMD);
  63. }
  64. bool idle() const { return this->state_ == State::IDLE; }
  65. // Called once per loop() tick. Does one bounded unit of work.
  66. void step() {
  67. switch (this->state_) {
  68. case State::IDLE:
  69. return;
  70. case State::RESET_LOW:
  71. this->rst_->digital_write(true); // preset high, then pulse low - see GxEPD2_EPD::_reset()
  72. this->deadline_ = millis() + 10;
  73. this->set_state_(State::RESET_LOW_WAIT);
  74. return;
  75. case State::RESET_LOW_WAIT:
  76. if (millis() < this->deadline_)
  77. return;
  78. this->rst_->digital_write(false);
  79. this->deadline_ = millis() + 10;
  80. this->set_state_(State::RESET_HIGH_WAIT);
  81. return;
  82. case State::RESET_HIGH_WAIT:
  83. if (millis() < this->deadline_)
  84. return;
  85. this->rst_->digital_write(true);
  86. this->deadline_ = millis() + 10;
  87. this->set_state_(State::RESET_SETTLE);
  88. return;
  89. case State::RESET_SETTLE:
  90. if (millis() < this->deadline_)
  91. return;
  92. this->cursor_ = 0;
  93. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  94. // Post-reset busy wait, matching every vendor _InitDisplay()'s
  95. // _waitWhileBusy() right after the reset pulse. Some controllers hold
  96. // BUSY while they load settings/waveforms from OTP after a hardware
  97. // reset (notably JD79676 / GDEY0213F52, whose init is otherwise just
  98. // 0xE9 + power-on) - issuing any command before that clears gets it
  99. // silently dropped, so the panel never refreshes. Panels that don't
  100. // assert BUSY post-reset read "not busy" on the first poll and fall
  101. // straight through to INIT_CMD, so this is safe for all of them.
  102. this->start_busy_wait_(State::INIT_CMD);
  103. return;
  104. case State::INIT_CMD:
  105. this->step_sequence_(this->desc_->init_sequence, this->desc_->init_sequence_len, State::INIT_CMD,
  106. State::SET_WINDOW);
  107. return;
  108. case State::SET_WINDOW:
  109. // window_sequence[this->plane_]: index 0 on the first entry
  110. // (plane_ reset to 0 in request_full_update()); when
  111. // window_per_plane is true, step_write_plane_() re-enters this
  112. // state with plane_ already advanced to 1 before the next plane's
  113. // byte burst, picking window_sequence[1] instead - see
  114. // panel_579c_gdey0579f51.h for why a panel needs that.
  115. this->step_sequence_(this->desc_->window_sequence[this->plane_], this->desc_->window_sequence_len[this->plane_],
  116. State::SET_WINDOW, State::WRITE_PLANE);
  117. return;
  118. case State::WRITE_PLANE:
  119. this->step_write_plane_();
  120. return;
  121. case State::REFRESH_CMD:
  122. this->step_sequence_(this->desc_->refresh_sequence, this->desc_->refresh_sequence_len, State::REFRESH_CMD,
  123. State::DONE);
  124. return;
  125. case State::POST_DELAY:
  126. if (millis() < this->deadline_)
  127. return;
  128. this->set_state_(this->delay_return_state_);
  129. return;
  130. case State::WAIT_BUSY:
  131. this->step_wait_busy_();
  132. return;
  133. case State::DONE:
  134. ESP_LOGD("gxepd2", "Display update finished");
  135. this->set_state_(State::IDLE);
  136. return;
  137. case State::ABORTED:
  138. // A busy timeout means the panel isn't behaving as wired/expected
  139. // (unplugged, dead, wrong busy polarity, ...) - pressing ahead
  140. // with the rest of the sequence (more command bytes, another
  141. // busy-wait) is very unlikely to "just work" and only obscures
  142. // which step actually failed. Bail the whole cycle here instead of
  143. // continuing to whatever state the timed-out wait was headed to.
  144. ESP_LOGE("gxepd2", "Aborting display update: busy timeout");
  145. this->cursor_ = 0;
  146. this->plane_ = 0;
  147. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  148. this->set_state_(State::IDLE);
  149. return;
  150. }
  151. }
  152. private:
  153. enum class State {
  154. IDLE,
  155. RESET_LOW,
  156. RESET_LOW_WAIT,
  157. RESET_HIGH_WAIT,
  158. RESET_SETTLE,
  159. INIT_CMD,
  160. SET_WINDOW,
  161. WRITE_PLANE,
  162. REFRESH_CMD,
  163. POST_DELAY,
  164. WAIT_BUSY,
  165. DONE,
  166. ABORTED,
  167. };
  168. enum class CmdPhase { BEFORE_DELAY, ISSUE };
  169. // Every command byte and every data byte is its own SPI transaction, CS
  170. // toggled around each one - this looks wasteful, but it's mechanically
  171. // what GxEPD2_EPD::_writeCommand()/_writeData(uint8_t) do (see
  172. // third_party/GxEPD2/src/GxEPD2_EPD.cpp), and matching the vendor cycle byte-for-byte
  173. // is the point of this engine.
  174. void write_byte_(uint8_t b, bool dc_high) {
  175. this->dc_->digital_write(dc_high);
  176. this->spi_->enable();
  177. this->cs_->digital_write(false);
  178. this->spi_->write_byte(b);
  179. this->cs_->digital_write(true);
  180. this->spi_->disable();
  181. }
  182. void write_command_(uint8_t cmd, const uint8_t *data, uint8_t data_len) {
  183. #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
  184. // Command-level skeleton trace - deliberately left in (not gated to
  185. // VERY_VERBOSE) while diagnosing a real-hardware content bug: this is
  186. // the exact byte-for-byte counterpart to compare against a captured
  187. // epaper_spi trace on the same panel. Bulk plane data isn't logged
  188. // here (see step_write_plane_) - only the command skeleton matters for
  189. // that comparison.
  190. char buf[32] = {0};
  191. int n = 0;
  192. for (uint8_t i = 0; i < data_len && n < (int) sizeof(buf) - 3; i++)
  193. n += snprintf(buf + n, sizeof(buf) - n, "%02X ", data[i]);
  194. ESP_LOGD("gxepd2", "cmd 0x%02X data[%u]: %s", cmd, data_len, buf);
  195. #endif
  196. this->write_byte_(cmd, false);
  197. for (uint8_t i = 0; i < data_len; i++)
  198. this->write_byte_(data[i], true);
  199. }
  200. // Steps through one EpdCommand table one entry (and one delay/busy-wait,
  201. // if that entry has one) at a time, resuming in self_state after any
  202. // wait so the same call re-enters here for the next entry. Shared by
  203. // INIT_CMD and REFRESH_CMD - which table is being stepped is entirely
  204. // determined by which state called this.
  205. void step_sequence_(const EpdCommand *seq, uint8_t len, State self_state, State done_state) {
  206. if (this->cursor_ >= len) {
  207. this->cursor_ = 0;
  208. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  209. this->set_state_(done_state);
  210. return;
  211. }
  212. const EpdCommand &c = seq[this->cursor_];
  213. if (this->cmd_phase_ == CmdPhase::BEFORE_DELAY) {
  214. this->cmd_phase_ = CmdPhase::ISSUE;
  215. if (c.delay_before_ms > 0) {
  216. this->start_delay_(c.delay_before_ms, self_state);
  217. return;
  218. }
  219. }
  220. this->write_command_(c.cmd, c.data, c.data_len);
  221. this->cursor_++;
  222. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  223. if (c.wait_busy_after) {
  224. this->start_busy_wait_(self_state);
  225. } else if (c.delay_after_ms > 0) {
  226. this->start_delay_(c.delay_after_ms, self_state);
  227. }
  228. // else: stays in self_state; the next step() call processes the next entry.
  229. }
  230. // Writes up to BYTE_BUDGET bytes of the current plane per call, then
  231. // returns - this bound is what keeps a full-frame write (thousands of
  232. // bytes) from ever making one loop() tick run long, replacing the old
  233. // per-256-byte esp_task_wdt_reset()+delay(1) throttle with simply not
  234. // doing enough work in one call to need it.
  235. //
  236. // 64 was overly conservative: at 20MHz SPI that's ~25us of actual bus
  237. // time, so a 426T82 full-plane write (48000 bytes) was bottlenecked
  238. // almost entirely on loop() scheduling overhead (~17ms/step observed),
  239. // not SPI - ~12.7s for one plane. Raised to 16384 (up to ~25ms of
  240. // blocking per step is fine here), cutting that to 3 steps instead of
  241. // 750 - measured ~1.07s for the plane write on hardware. The remaining
  242. // time is dominated by write_byte_()'s per-byte SPI enable()/disable()
  243. // (ESP-IDF transaction setup/teardown, ~21.7us/byte vs ~0.4us raw
  244. // transfer), which is intentionally NOT batched away: it lets other
  245. // devices on a shared spi: bus interleave between our bytes instead of
  246. // being locked out for the whole burst. 1s is well under half this
  247. // panel's own multi-second refresh time anyway, so it wasn't worth
  248. // trading that fairness for more throughput.
  249. static constexpr uint32_t BYTE_BUDGET = 16384;
  250. void step_write_plane_() {
  251. if (this->cursor_ == 0) {
  252. const uint8_t *buf = this->planes_[this->plane_];
  253. uint32_t histo[3] = {0, 0, 0}; // [0]=0x00, [1]=0xFF, [2]=other
  254. if (buf != nullptr) {
  255. for (uint32_t i = 0; i < this->plane_bytes_; i++) {
  256. if (buf[i] == 0x00)
  257. histo[0]++;
  258. else if (buf[i] == 0xFF)
  259. histo[1]++;
  260. else
  261. histo[2]++;
  262. }
  263. }
  264. ESP_LOGD("gxepd2", "plane %u: cmd 0x%02X, %u wire bytes (buf %u), invert=%d, buf[0]=0x%02X buf[last]=0x%02X, histo(00/FF/other)=%u/%u/%u",
  265. this->plane_, this->desc_->plane_write_cmd[this->plane_], (unsigned) this->wire_bytes_,
  266. (unsigned) this->plane_bytes_, this->desc_->plane_invert[this->plane_], buf != nullptr ? buf[0] : 0,
  267. buf != nullptr ? buf[this->plane_bytes_ - 1] : 0, (unsigned) histo[0], (unsigned) histo[1],
  268. (unsigned) histo[2]);
  269. this->write_byte_(this->desc_->plane_write_cmd[this->plane_], false);
  270. }
  271. const uint8_t *buf = this->planes_[this->plane_];
  272. bool invert = this->desc_->plane_invert[this->plane_];
  273. uint32_t end = this->cursor_ + BYTE_BUDGET;
  274. if (end > this->wire_bytes_)
  275. end = this->wire_bytes_;
  276. for (; this->cursor_ < end; this->cursor_++) {
  277. uint32_t src = this->line_src_index_(this->cursor_);
  278. uint8_t b = buf != nullptr ? buf[src] : 0xFF;
  279. this->write_byte_(invert ? static_cast<uint8_t>(~b) : b, true);
  280. }
  281. if (this->cursor_ >= this->wire_bytes_) {
  282. this->cursor_ = 0;
  283. this->plane_++;
  284. this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
  285. if (this->plane_ >= this->desc_->plane_count) {
  286. this->plane_ = 0;
  287. this->set_state_(State::REFRESH_CMD);
  288. } else if (this->desc_->window_per_plane) {
  289. // Another plane to go and it needs its own window-set first (a
  290. // genuinely separate physical RAM region, not just another color
  291. // plane sharing the window already set) - re-enter SET_WINDOW,
  292. // which will pick window_sequence[this->plane_] now that plane_
  293. // has already advanced.
  294. this->set_state_(State::SET_WINDOW);
  295. }
  296. // else: more planes, sharing one window already set - stay in
  297. // WRITE_PLANE, next step() call starts the next plane's byte burst.
  298. }
  299. }
  300. // Maps a wire-transmission-order byte position (0..wire_bytes_-1) to the
  301. // buffer byte it reads. The wire is a sequence of lines, each bytes_per_row_
  302. // bytes from one buffer row; line_order picks which buffer row each wire
  303. // line carries (and, for PAIRED_EDGES, there are 2x as many wire lines as
  304. // buffer rows). SEQUENTIAL is the identity (wire line i -> row i).
  305. uint32_t line_src_index_(uint32_t wire_pos) const {
  306. uint32_t wire_line = wire_pos / this->bytes_per_row_;
  307. uint32_t byte_in_line = wire_pos % this->bytes_per_row_;
  308. uint32_t buf_row;
  309. switch (this->desc_->line_order) {
  310. case LineOrder::PAIRED_EDGES: {
  311. // wire lines come in pairs: for i in [0,H), line 2i = row (H-1-i),
  312. // line 2i+1 = row i. Matches GxEPD2 writeNative's emission exactly.
  313. uint32_t i = wire_line / 2;
  314. buf_row = (wire_line % 2 == 0) ? (this->desc_->height - 1 - i) : i;
  315. break;
  316. }
  317. case LineOrder::SEQUENTIAL:
  318. default:
  319. buf_row = wire_line;
  320. break;
  321. }
  322. return buf_row * this->bytes_per_row_ + byte_in_line;
  323. }
  324. void start_delay_(uint16_t delay_ms, State return_to) {
  325. this->deadline_ = millis() + delay_ms;
  326. this->delay_return_state_ = return_to;
  327. this->set_state_(State::POST_DELAY);
  328. }
  329. void start_busy_wait_(State next) {
  330. this->busy_wait_next_ = next;
  331. this->busy_wait_deadline_ = millis() + this->desc_->busy_timeout_ms;
  332. this->set_state_(State::WAIT_BUSY);
  333. }
  334. void step_wait_busy_() {
  335. if (this->busy_ == nullptr) {
  336. this->set_state_(this->busy_wait_next_);
  337. return;
  338. }
  339. bool busy = this->busy_->digital_read() == this->desc_->busy_active_level;
  340. if (!busy) {
  341. this->set_state_(this->busy_wait_next_);
  342. return;
  343. }
  344. if (millis() >= this->busy_wait_deadline_) {
  345. ESP_LOGW("gxepd2", "Busy timeout waiting for panel");
  346. this->set_state_(State::ABORTED);
  347. }
  348. }
  349. // Logs every state transition (only when the state actually changes -
  350. // WAIT_BUSY and POST_DELAY re-enter their own case on every step() call
  351. // while polling, which would otherwise spam this at loop() rate) so a
  352. // first hardware run can be checked against the vendor cycle it's meant
  353. // to replicate before this gets dialed back to WARN-only.
  354. void set_state_(State s) {
  355. if (s != this->state_)
  356. ESP_LOGD("gxepd2", "state: %s -> %s", state_name_(this->state_), state_name_(s));
  357. this->state_ = s;
  358. }
  359. static const char *state_name_(State s) {
  360. switch (s) {
  361. case State::IDLE:
  362. return "IDLE";
  363. case State::RESET_LOW:
  364. return "RESET_LOW";
  365. case State::RESET_LOW_WAIT:
  366. return "RESET_LOW_WAIT";
  367. case State::RESET_HIGH_WAIT:
  368. return "RESET_HIGH_WAIT";
  369. case State::RESET_SETTLE:
  370. return "RESET_SETTLE";
  371. case State::INIT_CMD:
  372. return "INIT_CMD";
  373. case State::SET_WINDOW:
  374. return "SET_WINDOW";
  375. case State::WRITE_PLANE:
  376. return "WRITE_PLANE";
  377. case State::REFRESH_CMD:
  378. return "REFRESH_CMD";
  379. case State::POST_DELAY:
  380. return "POST_DELAY";
  381. case State::WAIT_BUSY:
  382. return "WAIT_BUSY";
  383. case State::DONE:
  384. return "DONE";
  385. case State::ABORTED:
  386. return "ABORTED";
  387. }
  388. return "?";
  389. }
  390. const EpdPanelDescriptor *desc_{nullptr};
  391. GPIOPin *cs_{nullptr};
  392. GPIOPin *dc_{nullptr};
  393. GPIOPin *rst_{nullptr};
  394. GPIOPin *busy_{nullptr};
  395. EpdSPIDevice *spi_{nullptr};
  396. State state_{State::IDLE};
  397. uint32_t cursor_{0};
  398. CmdPhase cmd_phase_{CmdPhase::BEFORE_DELAY};
  399. uint8_t plane_{0};
  400. const uint8_t *planes_[2]{nullptr, nullptr};
  401. uint32_t plane_bytes_{0}; // real buffer size per plane
  402. uint32_t wire_bytes_{0}; // bytes actually sent per plane (>= plane_bytes_)
  403. uint32_t bytes_per_row_{0};
  404. uint32_t deadline_{0};
  405. State delay_return_state_{State::DONE};
  406. uint32_t busy_wait_deadline_{0};
  407. State busy_wait_next_{State::DONE};
  408. };
  409. } // namespace esphome::gxepd2