gxepd2_display.h 13 KB

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