gxepd2_display.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #pragma once
  2. #include <atomic>
  3. #include <freertos/FreeRTOS.h>
  4. #include <freertos/semphr.h>
  5. #include <freertos/task.h>
  6. #include "esphome/core/component.h"
  7. #include "esphome/core/helpers.h"
  8. #include "esphome/components/display/display_buffer.h"
  9. #include "esphome/components/spi/spi.h"
  10. #include "pin_registry.h"
  11. // Only the wrapper the configured model needs gets included - see
  12. // display.py's USE_GXEPD2_* defines. Including all four unconditionally
  13. // fails to parse under ESP-IDF's toolchain: the un-instantiated template
  14. // bodies of the unused ones hit the same bare WIDTH/HEIGHT names, and
  15. // GCC's two-phase lookup only resolves those once instantiated.
  16. #ifdef USE_GXEPD2_BW
  17. #include <GxEPD2_BW.h>
  18. #endif
  19. #ifdef USE_GXEPD2_3C
  20. #include <GxEPD2_3C.h>
  21. #endif
  22. #ifdef USE_GXEPD2_4C
  23. #include <GxEPD2_4C.h>
  24. #endif
  25. #ifdef USE_GXEPD2_7C
  26. #include <GxEPD2_7C.h>
  27. #endif
  28. namespace esphome::gxepd2 {
  29. static const char *const TAG = "gxepd2";
  30. // Selected by codegen from catalog.json's "wrapper" field.
  31. enum class GxEPD2ColorMode {
  32. BW,
  33. THREE_COLOR, // black/white plus one accent ink (red or yellow panels alike)
  34. FOUR_COLOR, // black/white/red/yellow(-ish) 4-ink panels
  35. SEVEN_COLOR, // full ACeP-style palette
  36. };
  37. // DriverT: a GxEPD2 panel driver class (e.g. GxEPD2_290_T94).
  38. // DisplayT: that driver wrapped in its GxEPD2 color-depth template (e.g.
  39. // GxEPD2_BW<GxEPD2_290_T94, GxEPD2_290_T94::HEIGHT>).
  40. // DualCS: whether DriverT takes 5 constructor args (cs, dc, rst, busy, cs2)
  41. // instead of 4. All four are chosen by codegen from catalog.json.
  42. //
  43. // cs_pin/dc_pin/reset_pin/busy_pin(/cs2_pin) are synthetic PinRegistry ids,
  44. // not real esphome::GPIOPin; digitalWrite()/digitalRead()/pinMode() in
  45. // arduino_compat/Arduino.h resolve them back to the real pin.
  46. //
  47. // display::DisplayBuffer already derives PollingComponent via Display - do
  48. // not add PollingComponent again here, it creates an ambiguous base.
  49. template<typename DriverT, typename DisplayT, GxEPD2ColorMode ColorMode, bool DualCS>
  50. class GxEPD2Display : public display::DisplayBuffer {
  51. public:
  52. GxEPD2Display(int16_t cs_pin, int16_t dc_pin, int16_t reset_pin, int16_t busy_pin)
  53. : cs_(cs_pin), dc_(dc_pin), rst_(reset_pin), busy_(busy_pin) {
  54. static_assert(!DualCS, "use the 5-pin constructor for a dual-CS model");
  55. }
  56. GxEPD2Display(int16_t cs_pin, int16_t dc_pin, int16_t reset_pin, int16_t busy_pin, int16_t cs2_pin)
  57. : cs_(cs_pin), dc_(dc_pin), rst_(reset_pin), busy_(busy_pin), cs2_(cs2_pin) {
  58. static_assert(DualCS, "the 5-pin constructor is only for a dual-CS model");
  59. }
  60. ~GxEPD2Display() {
  61. if (this->update_task_ != nullptr) {
  62. vTaskDelete(this->update_task_);
  63. }
  64. if (this->driver_ != nullptr) {
  65. this->driver_->~DisplayT();
  66. RAMAllocator<uint8_t>().deallocate(reinterpret_cast<uint8_t *>(this->driver_), 0);
  67. }
  68. }
  69. void set_pin(int16_t id, GPIOPin *pin) { PinRegistry::set(id, pin); }
  70. void set_spi_parent(spi::SPIComponent *parent) { this->spi_.set_spi_parent(parent); }
  71. // DisplayT (holds the page buffer, by far the biggest thing in this
  72. // component) is allocated here via RAMAllocator, not as a plain member -
  73. // ESPHome's Pvariable placement-news components into static storage, so
  74. // this is the one deliberate, explicitly-sized dynamic allocation that
  75. // lets the buffer prefer PSRAM when available, made once at boot and
  76. // never freed.
  77. void setup() override {
  78. RAMAllocator<uint8_t> allocator;
  79. void *mem = allocator.allocate(sizeof(DisplayT));
  80. if (mem == nullptr) {
  81. ESP_LOGE(TAG, "Failed to allocate %u bytes for display buffer", (unsigned) sizeof(DisplayT));
  82. this->mark_failed();
  83. return;
  84. }
  85. if constexpr (DualCS) {
  86. this->driver_ = new (mem) DisplayT(DriverT(this->cs_, this->dc_, this->rst_, this->busy_, this->cs2_));
  87. } else {
  88. this->driver_ = new (mem) DisplayT(DriverT(this->cs_, this->dc_, this->rst_, this->busy_));
  89. }
  90. this->spi_.spi_setup();
  91. this->driver_->epd2.selectSPI(this->spi_, SPISettings());
  92. // GxEPD2's init() does a real panel clear/refresh, blocking on busy just
  93. // like a full update does - it runs during ESPHome's synchronous setup()
  94. // phase, before any component's dump_config() is called, which is why
  95. // the whole boot log can appear to stall here.
  96. uint32_t init_start = millis();
  97. this->driver_->init(0);
  98. ESP_LOGD(TAG, "GxEPD2 init took %u ms", (unsigned) (millis() - init_start));
  99. // GxEPD2's own refresh cycle - draw callbacks, the SPI write burst, and
  100. // above all the busy-pin wait - is synchronous top to bottom, with no
  101. // yield points we can hook to turn it into the kind of chunked,
  102. // resumable loop() state machine ESPHome components are expected to be
  103. // (that's how esphome's own epaper_spi avoids ever blocking: its
  104. // update() just arms a flag and returns, and loop() polls busy
  105. // non-blockingly on every main-loop tick). Rewriting GxEPD2 itself to
  106. // work that way is out of reach here, so instead the whole sequence
  107. // runs on its own FreeRTOS task: update() just wakes this task and
  108. // returns immediately, so the real several-seconds-long wait happens
  109. // off the main loop entirely, and WiFi/API/every other component stay
  110. // responsive through a refresh instead of stalling with it.
  111. //
  112. // Caveats accepted for now, matching this project's actual constraint
  113. // (an update() that blocks the whole app is a non-starter, full stop):
  114. // - The draw lambda (and anything it reads - sensors, globals, other
  115. // components) now runs off the main loop's thread. ESPHome code is
  116. // generally written assuming single-threaded access; simple POD
  117. // reads (numbers, bools) are practically fine, but this is a real
  118. // departure from the norm worth keeping in mind for anything richer.
  119. // - A second update() call while one is still running is rejected
  120. // outright (logged, not queued) via update_running_ below - no
  121. // attempt to serialize or coalesce them.
  122. // - The SPI bus is only actually held (bus acquired, CS asserted) for
  123. // the write bursts, not for the busy-pin wait in between, so a
  124. // shared spi: bus should mostly be fine - but that's about the
  125. // write phase, not this task boundary, and hasn't been stress-tested
  126. // against another device on the same bus mid-refresh.
  127. this->lambda_done_sem_ = xSemaphoreCreateBinary();
  128. xTaskCreate(&GxEPD2Display::update_task_trampoline_, "gxepd2_update", 4096, this, 1, &this->update_task_);
  129. }
  130. void update() override {
  131. bool expected = false;
  132. if (!this->update_running_.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) {
  133. ESP_LOGW(TAG, "Skipping update: previous display refresh is still running");
  134. return;
  135. }
  136. xTaskNotifyGive(this->update_task_);
  137. // Block only through this frame's draw lambda - not through the SPI
  138. // write / physical refresh that follows, which continues on
  139. // update_task_ after we return. For a paged (height_divisor > 1) model
  140. // this only covers the first page: the lambda runs again per
  141. // subsequent page, interleaved with that page's hardware write, fully
  142. // in the background. Most models are single-page, where this is the
  143. // entire draw phase.
  144. xSemaphoreTake(this->lambda_done_sem_, portMAX_DELAY);
  145. }
  146. void dump_config() override {
  147. ESP_LOGCONFIG(TAG, "GxEPD2 Display");
  148. LOG_UPDATE_INTERVAL(this);
  149. }
  150. display::DisplayType get_display_type() override {
  151. if constexpr (ColorMode == GxEPD2ColorMode::BW) {
  152. return display::DisplayType::DISPLAY_TYPE_BINARY;
  153. } else {
  154. return display::DisplayType::DISPLAY_TYPE_COLOR;
  155. }
  156. }
  157. protected:
  158. void draw_absolute_pixel_internal(int x, int y, Color color) override {
  159. if constexpr (ColorMode == GxEPD2ColorMode::BW) {
  160. this->driver_->drawPixel(x, y, color.is_on() ? GxEPD_BLACK : GxEPD_WHITE);
  161. } else if constexpr (ColorMode == GxEPD2ColorMode::THREE_COLOR) {
  162. if (color.red > color.green && color.red > color.blue && color.red > 0x7f) {
  163. this->driver_->drawPixel(x, y, GxEPD_RED);
  164. } else {
  165. // get_display_type() reports DISPLAY_TYPE_COLOR for this mode, so
  166. // callers draw with literal RGB colors (Color(255,255,255,...) for
  167. // white, Color(0,0,0,...) for black) - not the on/off convention
  168. // is_on() (raw_32 != 0) assumes, which is only correct for the BW
  169. // path above (DISPLAY_TYPE_BINARY). Using is_on() here inverted
  170. // black and white for any lambda drawing literal colors.
  171. bool bright = color.red > 0x7f || color.green > 0x7f || color.blue > 0x7f;
  172. this->driver_->drawPixel(x, y, bright ? GxEPD_WHITE : GxEPD_BLACK);
  173. }
  174. } else {
  175. uint16_t rgb565 = ((color.red & 0xF8) << 8) | ((color.green & 0xFC) << 3) | (color.blue >> 3);
  176. this->driver_->drawPixel(x, y, rgb565);
  177. }
  178. }
  179. int get_width_internal() override { return this->driver_->width(); }
  180. int get_height_internal() override { return this->driver_->height(); }
  181. int16_t cs_;
  182. int16_t dc_;
  183. int16_t rst_;
  184. int16_t busy_;
  185. int16_t cs2_{-1};
  186. DisplayT *driver_{nullptr};
  187. SPIClass spi_;
  188. private:
  189. static void update_task_trampoline_(void *param) { static_cast<GxEPD2Display *>(param)->update_task_loop_(); }
  190. // Blocks (cooperatively - ulTaskNotifyTake sleeps this task, not the CPU)
  191. // until update() wakes it, runs one full refresh, then goes back to
  192. // sleep. Never returns; this is the task's entire body for its lifetime.
  193. [[noreturn]] void update_task_loop_() {
  194. while (true) {
  195. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  196. uint32_t start = millis();
  197. this->driver_->setFullWindow();
  198. this->driver_->firstPage();
  199. bool first_page = true;
  200. do {
  201. this->do_update_();
  202. if (first_page) {
  203. // update() is waiting on exactly this: the draw lambda for the
  204. // first (often only) page has finished, so the caller can
  205. // proceed while the SPI write and physical refresh below run
  206. // without it.
  207. xSemaphoreGive(this->lambda_done_sem_);
  208. first_page = false;
  209. }
  210. } while (this->driver_->nextPage());
  211. ESP_LOGD(TAG, "Display update took %u ms", (unsigned) (millis() - start));
  212. this->update_running_.store(false, std::memory_order_release);
  213. }
  214. }
  215. TaskHandle_t update_task_{nullptr};
  216. SemaphoreHandle_t lambda_done_sem_{nullptr};
  217. std::atomic<bool> update_running_{false};
  218. };
  219. } // namespace esphome::gxepd2