gxepd2_display.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #pragma once
  2. #include "esphome/core/component.h"
  3. #include "esphome/core/helpers.h"
  4. #include "esphome/components/display/display_buffer.h"
  5. #include "esphome/components/spi/spi.h"
  6. #include "cycle_engine.h"
  7. #include "panel_213_z98c.h"
  8. #include "panel_290c_gdey029f51.h"
  9. #include "panel_426_gdeq0426t82.h"
  10. #include "panel_579c_gdey0579f51.h"
  11. #include "panel_579c_gdey0579f51_master_only.h"
  12. #include "panel_583_gdeq0583t31.h"
  13. namespace esphome::gxepd2 {
  14. static const char *const TAG = "gxepd2";
  15. // Native chunked-engine replacement for the old GxEPD2-template/FreeRTOS-task
  16. // component - see the plan this was built from (and project memory entry
  17. // gxepd2_task_watchdog_status) for why. Panels arrive as hand-written
  18. // (later, extracted) descriptors selected at runtime via set_descriptor(),
  19. // not by templating this class over GxEPD2's own driver classes.
  20. class GxEPD2Display : public display::DisplayBuffer {
  21. public:
  22. void set_cs_pin(GPIOPin *pin) { this->cs_ = pin; }
  23. void set_dc_pin(GPIOPin *pin) { this->dc_ = pin; }
  24. void set_reset_pin(GPIOPin *pin) { this->rst_ = pin; }
  25. void set_busy_pin(GPIOPin *pin) { this->busy_ = pin; }
  26. void set_spi_parent(spi::SPIComponent *parent) { this->spi_.set_spi_parent(parent); }
  27. void set_descriptor(const EpdPanelDescriptor *desc) { this->desc_ = desc; }
  28. void set_invert_mono(bool invert) { this->invert_mono_ = invert; }
  29. // Model trailer (e.g. "GDEQ0583T31", not the full "GxEPD2_583_..." id) and
  30. // an optional font, both for test_pattern()'s on-screen panel label. Set
  31. // from display.py: the name is derived from model:, the font is a normal
  32. // ESPHome font: the builder can pull from gfonts://. See test_pattern().
  33. void set_model_name(const char *name) { this->model_name_ = name; }
  34. void set_name_font(display::BaseFont *font) { this->name_font_ = font; }
  35. // Bench visual-check pattern, bit-depth aware. Everything scales to what
  36. // THIS panel can actually show (see test_colors_): the color-bar count,
  37. // the ladder color cycle and the corner markers all follow the panel's
  38. // real color set instead of a hardcoded 4, so the drawn pattern doubles as
  39. // a statement of what the driver expects of the panel. Adds a dithered
  40. // grey ramp (so a 1bpp panel shows a graded sweep, not just two flat
  41. // blocks) and, when a name font is set and the panel can spare the room, a
  42. // model-trailer label so a tested panel says what it is on the shelf.
  43. // Call it from the display lambda: `id(<display_id>).test_pattern();`.
  44. void test_pattern() {
  45. const int w = this->get_width();
  46. const int h = this->get_height();
  47. Color colors[8];
  48. const int n = this->test_colors_(colors, 8);
  49. this->fill(Color(0xFF, 0xFF, 0xFF));
  50. const int smin = w < h ? w : h;
  51. const int border = smin / 100 > 1 ? smin / 100 : 1;
  52. const int x0 = border;
  53. int y0 = border;
  54. const int iw = w - 2 * border;
  55. int ih = h - 2 * border;
  56. // Name band, above every test zone. Drawn only when a font is set and
  57. // the panel is tall enough to give it a fifth of the interior without
  58. // crowding the zones below - the "skip the name on panels too short to
  59. // spare ~10px above the bar" rule, sized to the actual font.
  60. if (this->name_font_ != nullptr && this->model_name_ != nullptr && this->model_name_[0] != '\0') {
  61. int tw, xoff, baseline, th;
  62. this->name_font_->measure(this->model_name_, &tw, &xoff, &baseline, &th);
  63. const int band = th + 4;
  64. if (band <= ih / 5) {
  65. this->print(w / 2, y0 + band / 2, this->name_font_, Color(0x00, 0x00, 0x00),
  66. display::TextAlign::CENTER, this->model_name_);
  67. y0 += band;
  68. ih -= band;
  69. }
  70. }
  71. // Vertical budget for the four zones below any name band.
  72. const int bars_h = ih * 34 / 100;
  73. int dither_h = ih * 12 / 100;
  74. if (dither_h < 8) dither_h = 8;
  75. const int row_h = ih * 18 / 100 > 2 ? ih * 18 / 100 : 2;
  76. const int dy = y0 + bars_h;
  77. const int ry = dy + dither_h;
  78. const int col_y = ry + row_h;
  79. const int col_h = (y0 + ih) - col_y;
  80. // Color bars: one solid block per available color, in palette/wire-code
  81. // order (black, white, then the accents). A wrong or missing block
  82. // points straight at the color - or the wire code - it stands for.
  83. const int bar_w = iw / n;
  84. for (int i = 0; i < n; i++) {
  85. const int bx = x0 + i * bar_w;
  86. const int bw = (i == n - 1) ? (x0 + iw - bx) : bar_w;
  87. this->filled_rectangle(bx, y0, bw, bars_h, colors[i]);
  88. }
  89. // Dithered grey ramp: brightness 255 (left) -> 0 (right) via an ordered
  90. // 4x4 Bayer threshold. On a 1bpp panel this is the only zone that shows
  91. // a graded sweep; on deeper panels it's a quick mono/uniformity check.
  92. static const uint8_t BAYER4[4][4] = {
  93. {0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};
  94. for (int yy = 0; yy < dither_h; yy++) {
  95. for (int xx = 0; xx < iw; xx++) {
  96. const int bright = (iw <= 1) ? 255 : 255 - xx * 255 / (iw - 1);
  97. const int thr = (BAYER4[yy & 3][xx & 3] * 2 + 1) * 255 / 32;
  98. if (bright <= thr)
  99. this->draw_pixel_at(x0 + xx, dy + yy, Color(0x00, 0x00, 0x00));
  100. }
  101. }
  102. // Row ladder: 1px rows cycling the full color set - a dropped, doubled
  103. // or reordered row breaks the N-row cadence.
  104. for (int yy = 0; yy < row_h; yy++)
  105. this->horizontal_line(x0, ry + yy, iw, colors[yy % n]);
  106. // Column ladder: the same rotated 90 degrees, catching nibble/column
  107. // order bugs the row ladder can't (packed formats put several pixels per
  108. // byte, so a column-order fault can leave every row looking fine).
  109. for (int xx = 0; xx < iw; xx++)
  110. this->vertical_line(x0 + xx, col_y, col_h, colors[xx % n]);
  111. // Corner markers for orientation, using the panel's ink colors (every
  112. // color but white). BL is always black; TL/TR take the next inks when
  113. // the panel has them; BR is left blank as the distinct "no marker"
  114. // state. A 90/180 rotation or mirror can't survive this even though the
  115. // bars and ladders are otherwise symmetric.
  116. Color ink[8];
  117. int ni = 0;
  118. for (int i = 0; i < n; i++) {
  119. if (colors[i].red == 0xFF && colors[i].green == 0xFF && colors[i].blue == 0xFF)
  120. continue; // skip white - a white marker is invisible
  121. ink[ni++] = colors[i];
  122. }
  123. const int mk = smin / 12 > 3 ? smin / 12 : 3;
  124. if (ni > 0) this->filled_rectangle(x0, y0 + ih - mk, mk, mk, ink[0]); // BL
  125. if (ni > 1) this->filled_rectangle(x0, y0, mk, mk, ink[1]); // TL
  126. if (ni > 2) this->filled_rectangle(x0 + iw - mk, y0, mk, mk, ink[2]); // TR
  127. // Corner-to-corner diagonals over everything: the cheapest coordinate-
  128. // transform check - a clean line means no row/column reordering.
  129. this->line(0, 0, w - 1, h - 1, Color(0x00, 0x00, 0x00));
  130. this->line(w - 1, 0, 0, h - 1, Color(0x00, 0x00, 0x00));
  131. // Border frame last, so it stays an unbroken rectangle on all four edges
  132. // even where a zone fills to the edge - catches a clipped/offset origin.
  133. this->rectangle(0, 0, w, h, Color(0x00, 0x00, 0x00));
  134. }
  135. void setup() override {
  136. const auto *desc = this->desc_;
  137. // window_per_plane panels (GDEY0579F51's master+slave) size each
  138. // plane's own buffer from plane_width (each region's own local
  139. // width), not the descriptor's overall width (the full logical canvas
  140. // ESPHome draws into) - both regions are the same size here, so one
  141. // plane_bytes_ value covers both buffers.
  142. uint32_t w = desc->window_per_plane ? desc->plane_width : desc->width;
  143. // width*height*bpp/8: /8 at 1bpp, /4 at 2bpp (4-color), /2 at 4bpp (7-color).
  144. this->plane_bytes_ = (uint32_t) w * desc->height * desc->bits_per_pixel / 8;
  145. RAMAllocator<uint8_t> allocator;
  146. this->plane0_ = allocator.allocate(this->plane_bytes_);
  147. bool need_plane1 = desc->plane_count > 1;
  148. this->plane1_ = need_plane1 ? allocator.allocate(this->plane_bytes_) : nullptr;
  149. if (this->plane0_ == nullptr || (need_plane1 && this->plane1_ == nullptr)) {
  150. ESP_LOGE(TAG, "Failed to allocate %u-byte plane buffer(s)", (unsigned) this->plane_bytes_);
  151. this->mark_failed();
  152. return;
  153. }
  154. if (desc->bits_per_pixel > 1) {
  155. // Packed modes: clear every pixel to the panel's white/blank code,
  156. // replicated across the byte - e.g. 4-color white=0x01 -> 0x55, 7-color
  157. // white=0x01 -> 0x11, matching GxEPD2's own writeScreenBuffer() fill
  158. // (color4()*0x55 / color7()|<<4). Both regions of a window_per_plane
  159. // panel (master/slave) get the same blank fill.
  160. uint8_t fill = replicate_code_(desc->blank_code, desc->bits_per_pixel);
  161. memset(this->plane0_, fill, this->plane_bytes_);
  162. if (this->plane1_ != nullptr)
  163. memset(this->plane1_, fill, this->plane_bytes_);
  164. } else {
  165. // 1bpp plane model: plane0 white = all bits set (0xFF); plane1 (the
  166. // accent/red plane, when present) = 0 = not-red.
  167. memset(this->plane0_, 0xFF, this->plane_bytes_);
  168. if (this->plane1_ != nullptr)
  169. memset(this->plane1_, 0x00, this->plane_bytes_);
  170. }
  171. this->spi_.spi_setup();
  172. this->engine_.begin(desc, this->cs_, this->dc_, this->rst_, this->busy_, &this->spi_);
  173. }
  174. // Arms the state machine and returns immediately - the real several-
  175. // seconds-long write/refresh/busy-wait cycle happens across many
  176. // subsequent loop() ticks, not before this call returns.
  177. void update() override {
  178. if (!this->engine_.idle()) {
  179. ESP_LOGW(TAG, "Skipping update: previous display refresh is still running");
  180. return;
  181. }
  182. this->do_update_();
  183. this->engine_.request_full_update(this->plane0_, this->plane1_);
  184. }
  185. void loop() override { this->engine_.step(); }
  186. void dump_config() override {
  187. ESP_LOGCONFIG(TAG, "GxEPD2 Display:");
  188. ESP_LOGCONFIG(TAG, " Dimensions: %ux%u", (unsigned) this->desc_->width, (unsigned) this->desc_->height);
  189. ESP_LOGCONFIG(TAG, " Bits/pixel: %u (%s)", (unsigned) this->desc_->bits_per_pixel,
  190. this->desc_->bits_per_pixel == 1 ? "mono/plane" : "packed palette");
  191. ESP_LOGCONFIG(TAG, " Planes/regions: %u", (unsigned) this->desc_->plane_count);
  192. ESP_LOGCONFIG(TAG, " Busy active level: %s", this->desc_->busy_active_level ? "HIGH" : "LOW");
  193. if (this->desc_->bits_per_pixel == 1)
  194. ESP_LOGCONFIG(TAG, " invert_mono: %s", YESNO(this->invert_mono_));
  195. LOG_UPDATE_INTERVAL(this);
  196. }
  197. display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
  198. protected:
  199. // Replicates a packed wire code across a whole byte (one code per pixel
  200. // slot), e.g. 2bpp code 0x01 -> 0x55, 4bpp code 0x01 -> 0x11.
  201. static uint8_t replicate_code_(uint8_t code, uint8_t bpp) {
  202. uint8_t mask = static_cast<uint8_t>((1u << bpp) - 1);
  203. uint8_t out = 0;
  204. for (uint8_t i = 0; i < 8 / bpp; i++)
  205. out = static_cast<uint8_t>((out << bpp) | (code & mask));
  206. return out;
  207. }
  208. // Maps a drawn RGB color to its panel wire code via the descriptor's
  209. // palette: exact matches win (so named colors are deterministic, like
  210. // GxEPD2's color4()/color7() switch), otherwise nearest in RGB space.
  211. static uint8_t classify_(Color c, const EpdPaletteEntry *pal, uint8_t len) {
  212. if (pal == nullptr || len == 0)
  213. return 0;
  214. uint8_t best = 0;
  215. long best_d = -1;
  216. for (uint8_t i = 0; i < len; i++) {
  217. long dr = static_cast<long>(c.red) - pal[i].r;
  218. long dg = static_cast<long>(c.green) - pal[i].g;
  219. long db = static_cast<long>(c.blue) - pal[i].b;
  220. long d = dr * dr + dg * dg + db * db;
  221. if (d == 0)
  222. return pal[i].code;
  223. if (best_d < 0 || d < best_d) {
  224. best_d = d;
  225. best = i;
  226. }
  227. }
  228. return pal[best].code;
  229. }
  230. // Packed code-per-pixel model (bits_per_pixel > 1): N bits/pixel, MSB
  231. // first, matching GxEPD2's own out_data packing in writeImage (4-color
  232. // 4px/byte, 7-color 2px/byte). Routes to the correct region for a
  233. // window_per_plane (master/slave) panel the same way the mono path does.
  234. void draw_packed_(int x, int y, Color color) {
  235. const uint8_t bpp = this->desc_->bits_per_pixel;
  236. uint8_t code = classify_(color, this->desc_->palette, this->desc_->palette_len);
  237. uint16_t stride = this->desc_->width;
  238. uint8_t *buf = this->plane0_;
  239. int local_x = x;
  240. if (this->desc_->window_per_plane && this->desc_->plane_count > 1) {
  241. stride = this->desc_->plane_width;
  242. if (x >= stride) {
  243. buf = this->plane1_;
  244. local_x = x - stride;
  245. }
  246. }
  247. uint32_t px = static_cast<uint32_t>(y) * stride + local_x;
  248. const uint8_t ppb = 8 / bpp;
  249. uint32_t idx = px / ppb;
  250. uint8_t shift = static_cast<uint8_t>((ppb - 1 - (px % ppb)) * bpp);
  251. uint8_t mask = static_cast<uint8_t>((1u << bpp) - 1);
  252. buf[idx] = static_cast<uint8_t>((buf[idx] & ~(mask << shift)) | ((code & mask) << shift));
  253. }
  254. void draw_absolute_pixel_internal(int x, int y, Color color) override {
  255. if (x < 0 || y < 0 || x >= this->desc_->width || y >= this->desc_->height)
  256. return;
  257. if (this->desc_->bits_per_pixel > 1) {
  258. this->draw_packed_(x, y, color);
  259. return;
  260. }
  261. bool red = color.red > color.green && color.red > color.blue && color.red > 0x7f;
  262. bool bright = color.red > 0x7f || color.green > 0x7f || color.blue > 0x7f;
  263. uint32_t idx = (static_cast<uint32_t>(y) * this->desc_->width + x) / 8;
  264. uint8_t mask = 0x80 >> (x % 8);
  265. // Same classification the old task-based component used: red/accent
  266. // pixels go to the color plane (when the panel has one), everything
  267. // else is black/white on the black plane. get_display_type() reports
  268. // DISPLAY_TYPE_COLOR, so callers draw literal RGB colors, not the
  269. // on/off is_on() convention, even on a plane_count==1 (BW-only) panel -
  270. // there just is no color plane for a "red" classification to land on.
  271. //
  272. // Buffer convention here is 1=red/0=not-red (matching the reference
  273. // epaper_spi driver's EPaperWeAct3C internal convention), transformed
  274. // to the wire value by plane_invert[1] - see PANEL_213_Z98C's comment
  275. // for why that inversion flag and this buffer convention are coupled,
  276. // not independent facts.
  277. if (red && this->plane1_ != nullptr) {
  278. this->plane1_[idx] |= mask;
  279. } else {
  280. if (this->plane1_ != nullptr)
  281. this->plane1_[idx] &= ~mask;
  282. // plane0 bit set = white/blank. invert_mono_ flips the mono sense so a
  283. // bright color (e.g. ESPHome's default COLOR_ON) becomes ink, not blank
  284. // - see display.py's CONF_INVERT_MONO. Red classification is unaffected.
  285. if (bright ^ this->invert_mono_) {
  286. this->plane0_[idx] |= mask;
  287. } else {
  288. this->plane0_[idx] &= ~mask;
  289. }
  290. }
  291. }
  292. int get_width_internal() override { return this->desc_->width; }
  293. int get_height_internal() override { return this->desc_->height; }
  294. // The colors this panel can actually show, each as a representative RGB, in
  295. // a stable order (black, white, then accents). Packed panels (>1bpp): one
  296. // entry per distinct palette wire code, first RGB seen for each. 1bpp:
  297. // black + white, plus red when a second plane exists for the accent (only
  298. // red-classified pixels reach it - see draw_absolute_pixel_internal). This
  299. // is what makes test_pattern() bit-depth aware. Returns the count.
  300. int test_colors_(Color *out, int max) {
  301. int n = 0;
  302. if (this->desc_->bits_per_pixel > 1 && this->desc_->palette != nullptr) {
  303. uint8_t seen[16];
  304. int seen_n = 0;
  305. for (int i = 0; i < this->desc_->palette_len && n < max; i++) {
  306. const uint8_t code = this->desc_->palette[i].code;
  307. bool dup = false;
  308. for (int j = 0; j < seen_n; j++)
  309. if (seen[j] == code) { dup = true; break; }
  310. if (dup) continue;
  311. if (seen_n < (int) sizeof(seen)) seen[seen_n++] = code;
  312. const auto &e = this->desc_->palette[i];
  313. out[n++] = Color(e.r, e.g, e.b);
  314. }
  315. } else {
  316. if (n < max) out[n++] = Color(0x00, 0x00, 0x00); // black
  317. if (n < max) out[n++] = Color(0xFF, 0xFF, 0xFF); // white
  318. if (this->desc_->plane_count >= 2 && n < max) out[n++] = Color(0xFF, 0x00, 0x00); // accent
  319. }
  320. return n;
  321. }
  322. const EpdPanelDescriptor *desc_{nullptr};
  323. const char *model_name_{nullptr};
  324. display::BaseFont *name_font_{nullptr};
  325. GPIOPin *cs_{nullptr};
  326. GPIOPin *dc_{nullptr};
  327. GPIOPin *rst_{nullptr};
  328. GPIOPin *busy_{nullptr};
  329. EpdSPIDevice spi_;
  330. CycleEngine engine_;
  331. uint8_t *plane0_{nullptr};
  332. uint8_t *plane1_{nullptr};
  333. uint32_t plane_bytes_{0};
  334. bool invert_mono_{false};
  335. };
  336. } // namespace esphome::gxepd2