gxepd2_display.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. // update_task_loop_() suspends this exact task around every later
  137. // page's draw lambda too (see there) - it needs to know who to
  138. // suspend, since after this call returns nothing keeps it waiting for
  139. // update_task_ to signal it.
  140. this->caller_task_ = xTaskGetCurrentTaskHandle();
  141. xTaskNotifyGive(this->update_task_);
  142. // Block only through this frame's draw lambda - not through the SPI
  143. // write / physical refresh that follows, which continues on
  144. // update_task_ after we return. For a paged (height_divisor > 1) model
  145. // this covers only the first page's lambda call synchronously; later
  146. // pages' lambda calls happen after we've returned, protected instead
  147. // by briefly suspending this task around each one (below).
  148. xSemaphoreTake(this->lambda_done_sem_, portMAX_DELAY);
  149. }
  150. void dump_config() override {
  151. ESP_LOGCONFIG(TAG, "GxEPD2 Display");
  152. LOG_UPDATE_INTERVAL(this);
  153. }
  154. display::DisplayType get_display_type() override {
  155. if constexpr (ColorMode == GxEPD2ColorMode::BW) {
  156. return display::DisplayType::DISPLAY_TYPE_BINARY;
  157. } else {
  158. return display::DisplayType::DISPLAY_TYPE_COLOR;
  159. }
  160. }
  161. protected:
  162. void draw_absolute_pixel_internal(int x, int y, Color color) override {
  163. if constexpr (ColorMode == GxEPD2ColorMode::BW) {
  164. this->driver_->drawPixel(x, y, color.is_on() ? GxEPD_BLACK : GxEPD_WHITE);
  165. } else if constexpr (ColorMode == GxEPD2ColorMode::THREE_COLOR) {
  166. if (color.red > color.green && color.red > color.blue && color.red > 0x7f) {
  167. this->driver_->drawPixel(x, y, GxEPD_RED);
  168. } else {
  169. // get_display_type() reports DISPLAY_TYPE_COLOR for this mode, so
  170. // callers draw with literal RGB colors (Color(255,255,255,...) for
  171. // white, Color(0,0,0,...) for black) - not the on/off convention
  172. // is_on() (raw_32 != 0) assumes, which is only correct for the BW
  173. // path above (DISPLAY_TYPE_BINARY). Using is_on() here inverted
  174. // black and white for any lambda drawing literal colors.
  175. bool bright = color.red > 0x7f || color.green > 0x7f || color.blue > 0x7f;
  176. this->driver_->drawPixel(x, y, bright ? GxEPD_WHITE : GxEPD_BLACK);
  177. }
  178. } else {
  179. uint16_t rgb565 = ((color.red & 0xF8) << 8) | ((color.green & 0xFC) << 3) | (color.blue >> 3);
  180. this->driver_->drawPixel(x, y, rgb565);
  181. }
  182. }
  183. int get_width_internal() override { return this->driver_->width(); }
  184. int get_height_internal() override { return this->driver_->height(); }
  185. int16_t cs_;
  186. int16_t dc_;
  187. int16_t rst_;
  188. int16_t busy_;
  189. int16_t cs2_{-1};
  190. DisplayT *driver_{nullptr};
  191. SPIClass spi_;
  192. private:
  193. static void update_task_trampoline_(void *param) { static_cast<GxEPD2Display *>(param)->update_task_loop_(); }
  194. // Blocks (cooperatively - ulTaskNotifyTake sleeps this task, not the CPU)
  195. // until update() wakes it, runs one full refresh, then goes back to
  196. // sleep. Never returns; this is the task's entire body for its lifetime.
  197. [[noreturn]] void update_task_loop_() {
  198. while (true) {
  199. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  200. uint32_t start = millis();
  201. this->driver_->setFullWindow();
  202. this->driver_->firstPage();
  203. bool first_page = true;
  204. do {
  205. if (!first_page) {
  206. // update() already returned after the first page, so the caller
  207. // task is off running its own thing again - nothing keeps this
  208. // page's draw lambda from racing whatever it's doing (reading a
  209. // sensor, updating a global, ...). Freeze it just long enough to
  210. // draw this page too, so every page's lambda gets the same
  211. // "nothing else is running" guarantee the first one had for
  212. // free, not just the first. Resumed right after, before the
  213. // (slow) hardware write below, so the caller stays responsive
  214. // through the part that actually takes a while.
  215. vTaskSuspend(this->caller_task_);
  216. }
  217. this->do_update_();
  218. if (first_page) {
  219. // update() is waiting on exactly this: the draw lambda for the
  220. // first (often only) page has finished, so the caller can
  221. // proceed while the SPI write and physical refresh below run
  222. // without it.
  223. xSemaphoreGive(this->lambda_done_sem_);
  224. first_page = false;
  225. } else {
  226. vTaskResume(this->caller_task_);
  227. }
  228. } while (this->driver_->nextPage());
  229. ESP_LOGD(TAG, "Display update took %u ms", (unsigned) (millis() - start));
  230. this->update_running_.store(false, std::memory_order_release);
  231. }
  232. }
  233. TaskHandle_t update_task_{nullptr};
  234. // Set fresh by update() every call, before update_task_ can possibly read
  235. // it (it's blocked on lambda_done_sem_ until the first page finishes) -
  236. // safe without extra synchronization since update_running_ already
  237. // guarantees only one update cycle, and thus only one writer/reader pair
  238. // for this field, is ever in flight at a time.
  239. TaskHandle_t caller_task_{nullptr};
  240. SemaphoreHandle_t lambda_done_sem_{nullptr};
  241. std::atomic<bool> update_running_{false};
  242. };
  243. } // namespace esphome::gxepd2