emit_descriptor.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. #pragma once
  2. // Prototype: emit a candidate panel_*.h EpdPanelDescriptor by *observing* a
  3. // real vendor GxEPD2 driver run, instead of hand-transcribing its C++. This
  4. // closes the hand-derivation gap for the straight-line parts of a descriptor
  5. // (init / window / refresh command sequences + the plane-write command) by
  6. // phase-segmenting the captured event stream at the public-API boundary - no
  7. // edits to the vendor source.
  8. //
  9. // Staging (the trick that separates the phases without instrumenting the
  10. // vendor's private methods):
  11. // writeScreenBuffer() -> lazy _InitDisplay() + a plane-write burst (clear).
  12. // Everything before that burst is the INIT sequence;
  13. // the command right before it is the PLANE-WRITE cmd.
  14. // writeImage(pattern) -> init already done, so this is just the WINDOW set
  15. // (commands before the pattern burst) + plane write.
  16. // refresh() -> re-sets the window then triggers; dropping the
  17. // duplicate window command leaves the REFRESH seq.
  18. //
  19. // Out of scope here (comes from the diag Pattern A/B passes, not one capture):
  20. // bits_per_pixel / palette / plane_invert / line_order. Those are emitted
  21. // as TODO placeholders so the diff against the hand file is about segmentation.
  22. #include <cstdint>
  23. #include <cstdio>
  24. #include <cstdlib>
  25. #include <functional>
  26. #include <set>
  27. #include <string>
  28. #include <type_traits>
  29. #include <utility>
  30. #include <vector>
  31. #include "spy/Arduino.h"
  32. #include "spy/SPI.h"
  33. #include "trace.h"
  34. namespace emit {
  35. // A data burst at least this long is a pixel-plane write, not config data.
  36. constexpr size_t PLANE_BURST_MIN = 256;
  37. struct Cmd {
  38. uint8_t cmd;
  39. std::vector<uint8_t> data;
  40. bool wait_busy = false;
  41. unsigned long delay_after = 0;
  42. };
  43. // Expose GxEPD2_EPD's protected busy level without parsing (same trick as
  44. // run_harness.h's Peek).
  45. template<typename Driver> struct Peek : Driver {
  46. using Driver::Driver;
  47. int busy_level() const { return this->_busy_level; }
  48. };
  49. // Group a slice of the event stream into EpdCommand-shaped records. Events
  50. // before the first SPI *command* (the reset pulse + its delays) are skipped -
  51. // the engine owns the hardware reset, so it never belongs in a descriptor.
  52. inline std::vector<Cmd> group(size_t lo, size_t hi) {
  53. std::vector<Cmd> cmds;
  54. bool started = false;
  55. for (size_t i = lo; i < hi; i++) {
  56. const auto &e = Trace::events[i];
  57. switch (e.kind) {
  58. case EventKind::SPI_TRANSFER:
  59. if (e.is_command) {
  60. cmds.push_back(Cmd{e.byte});
  61. started = true;
  62. } else if (started) {
  63. cmds.back().data.push_back(e.byte);
  64. }
  65. break;
  66. case EventKind::DELAY:
  67. if (started)
  68. cmds.back().delay_after += e.ms;
  69. break;
  70. case EventKind::DIGITAL_READ: // the only reads are busy-pin polls
  71. if (started) {
  72. cmds.back().wait_busy = true;
  73. // The delay(1) GxEPD2_EPD::_waitWhileBusy() runs inside its poll
  74. // loop lands right before this read and is part of the busy-wait,
  75. // not an inter-command delay - our engine owns busy-waiting, so
  76. // fold it in rather than emit it. (This also absorbs a vendor's own
  77. // tiny settle delay right before a refresh trigger, e.g. 290c's
  78. // _refresh delay(1); immaterial, the panel asserts busy regardless.)
  79. cmds.back().delay_after = 0;
  80. }
  81. break;
  82. default:
  83. break; // DIGITAL_WRITE = reset/CS/DC toggles: engine's job, not data
  84. }
  85. }
  86. return cmds;
  87. }
  88. // Index of the first command whose data burst marks a plane write, or np
  89. // (cmds.size()) if there's none in this slice.
  90. inline size_t plane_index(const std::vector<Cmd> &cmds) {
  91. for (size_t i = 0; i < cmds.size(); i++)
  92. if (cmds[i].data.size() >= PLANE_BURST_MIN)
  93. return i;
  94. return cmds.size();
  95. }
  96. inline void print_data_array(const char *macro, const char *suffix, const std::vector<uint8_t> &d) {
  97. printf("inline const uint8_t %s_%s[] = {", macro, suffix);
  98. for (size_t i = 0; i < d.size(); i++)
  99. printf("%s0x%02X", i ? ", " : "", d[i]);
  100. printf("};\n");
  101. }
  102. // Print one EpdCommand{} initializer line, with the optional fields only when
  103. // they're non-default (matches the hand files' style).
  104. inline void print_cmd(const char *macro, const char *suffix, const Cmd &c) {
  105. if (c.data.empty() && !c.wait_busy && c.delay_after == 0) {
  106. printf(" {0x%02X, nullptr, 0},\n", c.cmd);
  107. return;
  108. }
  109. const char *dataref = c.data.empty() ? "nullptr" : nullptr;
  110. if (dataref)
  111. printf(" {0x%02X, nullptr, 0", c.cmd);
  112. else
  113. printf(" {0x%02X, %s_%s, %u", c.cmd, macro, suffix, (unsigned) c.data.size());
  114. if (c.wait_busy || c.delay_after)
  115. printf(", /*delay_before_ms=*/0, /*delay_after_ms=*/%lu, /*wait_busy_after=*/%s", c.delay_after,
  116. c.wait_busy ? "true" : "false");
  117. printf("},\n");
  118. }
  119. // First data byte of the burst written right after command `op`, or -1.
  120. inline int burst_byte_after(const std::vector<Cmd> &cmds, uint8_t op) {
  121. for (const auto &c : cmds)
  122. if (c.cmd == op && c.data.size() >= PLANE_BURST_MIN)
  123. return c.data[0];
  124. return -1;
  125. }
  126. // Detects the two-arg writeScreenBuffer(black_value, color_value) that colour
  127. // (plane_count > 1) drivers have and mono drivers don't.
  128. template<typename T, typename = void> struct has_wsb2 : std::false_type {};
  129. template<typename T>
  130. struct has_wsb2<T, std::void_t<decltype(std::declval<T &>().writeScreenBuffer(uint8_t{}, uint8_t{}))>>
  131. : std::true_type {};
  132. struct PlaneInvert {
  133. bool inv0 = false, inv1 = false;
  134. bool plane1_valid = false;
  135. bool is_1bpp = false; // white fill => an all-bits-same wire byte (not packed)
  136. int w0_white = -1, w1_red = -1;
  137. };
  138. // A packed panel's depth / palette / blank code, resolved by observation for
  139. // the panel families the emitter knows how to probe (currently 4-colour, via
  140. // emit_palette_4c.h). `emit_descriptor_impl` calls a resolver of this shape
  141. // only for a packed panel (the plane-invert probe said white fill isn't an
  142. // all-bits wire byte); a null or unresolved result keeps the old TODO fields,
  143. // so an unknown packed family still emits a reviewable placeholder rather than
  144. // a wrong palette.
  145. struct PackedResolved {
  146. bool resolved = false; // false => emit TODO placeholders
  147. int bits_per_pixel = 2; // 2 (4-colour) or 4 (7-colour)
  148. const char *palette_expr = "nullptr"; // e.g. "GXEPD2_PALETTE_4C"
  149. const char *palette_len_expr = "0"; // e.g. "GXEPD2_PALETTE_4C_LEN"
  150. int blank_code = 0; // per-pixel clear code (observed white)
  151. int color_count = -1; // actual distinct colours probed; -1 => assume 1<<bits_per_pixel
  152. std::string note; // appended as a comment (observed table, or why unresolved)
  153. };
  154. using PackedResolverFn = std::function<PackedResolved(uint8_t clear_fill, const PlaneInvert &pv)>;
  155. // A generous, class-aware default for busy_timeout_ms. The timeout is only a
  156. // diagnostic ceiling - the engine hard-aborts a busy-wait that runs past it and
  157. // logs a failure, where GxEPD2 itself just keeps polling - so erring long costs
  158. // nothing on a healthy panel and the exact number is meant to be dev-tuned. The
  159. // vendor full_refresh_time is a soft estimate, so we take 2x it, then clamp up
  160. // to a per-depth floor so a panel that under-reports (or whose colour pass is
  161. // genuinely slow) still gets room: mono/3-colour fail fast, 4-colour and
  162. // 7-colour (ACeP) get progressively more headroom.
  163. inline uint32_t default_busy_timeout_ms(unsigned full_refresh_time, int bits_per_pixel) {
  164. uint32_t headroom = static_cast<uint32_t>(full_refresh_time) * 2;
  165. uint32_t floor = bits_per_pixel >= 4 ? 60000u : bits_per_pixel == 2 ? 45000u : 15000u;
  166. return headroom > floor ? headroom : floor;
  167. }
  168. // plane_invert by capture (see probe_plane_invert.h for the rationale): drive
  169. // known full-screen fills and read each plane's wire byte, reconciling against
  170. // the engine's fixed buffer convention (plane0 bit=white, plane1 bit=red). A
  171. // white-fill plane0 wire that isn't 0x00/0xFF means a packed (>1bpp) panel,
  172. // where plane_invert is unused and bits_per_pixel/palette come from the diag
  173. // pass instead.
  174. template<typename Driver> PlaneInvert probe_plane_invert_values(uint8_t p0cmd, uint8_t p1cmd, size_t plane_count) {
  175. constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
  176. Trace::set_dc_pin(DC);
  177. Peek<Driver> d(CS, DC, RST, BUSY);
  178. Trace::last_busy_release_value = d.busy_level() == HIGH ? LOW : HIGH;
  179. d.selectSPI(SPI, SPISettings());
  180. d.init(0);
  181. PlaneInvert r;
  182. auto cap0 = [&](uint8_t value) -> int {
  183. Trace::start_event_record();
  184. d.writeScreenBuffer(value); // 1-arg form all drivers have; colour defaults blank
  185. Trace::stop_event_record();
  186. return burst_byte_after(group(0, Trace::events.size()), p0cmd);
  187. };
  188. r.w0_white = cap0(0xFF);
  189. r.is_1bpp = (r.w0_white == 0x00 || r.w0_white == 0xFF);
  190. r.inv0 = (r.w0_white == 0x00); // engine plane0 bit=white; white wire 0x00 => invert
  191. if (plane_count > 1) {
  192. if constexpr (has_wsb2<Driver>::value) {
  193. Trace::start_event_record();
  194. d.writeScreenBuffer((uint8_t) 0xFF, (uint8_t) 0x00); // all-red fill
  195. Trace::stop_event_record();
  196. r.w1_red = burst_byte_after(group(0, Trace::events.size()), p1cmd);
  197. r.plane1_valid = (r.w1_red == 0x00 || r.w1_red == 0xFF);
  198. r.inv1 = (r.w1_red == 0x00); // engine plane1 bit=red; red wire 0x00 => invert
  199. }
  200. }
  201. return r;
  202. }
  203. template<typename Driver>
  204. void emit_descriptor_impl(const char *class_name, const char *macro, const PackedResolverFn &resolve_packed) {
  205. constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
  206. Trace::set_dc_pin(DC);
  207. Peek<Driver> driver(CS, DC, RST, BUSY);
  208. const int bl = driver.busy_level();
  209. Trace::last_busy_release_value = bl == HIGH ? LOW : HIGH;
  210. driver.selectSPI(SPI, SPISettings());
  211. driver.init(0);
  212. const uint32_t plane_bytes = (static_cast<uint32_t>(Driver::WIDTH) * Driver::HEIGHT) / 8;
  213. auto *black = new uint8_t[plane_bytes];
  214. auto *color = new uint8_t[plane_bytes];
  215. for (uint32_t i = 0; i < plane_bytes; i++) {
  216. black[i] = 0xA5;
  217. color[i] = 0xA5;
  218. }
  219. Trace::start_event_record();
  220. const size_t s0 = 0;
  221. driver.writeScreenBuffer(); // init + clear burst
  222. const size_t s1 = Trace::events.size();
  223. driver.writeImage(black, color, 0, 0, Driver::WIDTH, Driver::HEIGHT); // window + plane
  224. const size_t s2 = Trace::events.size();
  225. driver.refresh(false); // window-again + trigger
  226. const size_t s3 = Trace::events.size();
  227. Trace::stop_event_record();
  228. delete[] black;
  229. delete[] color;
  230. // --- segment ---
  231. auto init_stage = group(s0, s1);
  232. auto image_stage = group(s1, s2);
  233. auto refresh_stage = group(s2, s3);
  234. auto cmds_equal = [](const std::vector<Cmd> &a, const std::vector<Cmd> &b) {
  235. if (a.size() != b.size())
  236. return false;
  237. for (size_t i = 0; i < a.size(); i++)
  238. if (a[i].cmd != b[i].cmd || a[i].data != b[i].data)
  239. return false;
  240. return true;
  241. };
  242. // Every pixel-plane burst in the image call. One => single-plane panel;
  243. // N => N planes (two colour planes sharing a region, or two physical
  244. // regions - told apart below by whether their window-sets match).
  245. std::vector<size_t> bursts;
  246. for (size_t i = 0; i < image_stage.size(); i++)
  247. if (image_stage[i].data.size() >= PLANE_BURST_MIN)
  248. bursts.push_back(i);
  249. const size_t nplanes = bursts.empty() ? 1 : bursts.size();
  250. if (getenv("EMIT_DEBUG")) {
  251. fprintf(stderr, "image_stage %zu cmds; bursts:", image_stage.size());
  252. for (auto b : bursts)
  253. fprintf(stderr, " [%zu]=0x%02X", b, image_stage[b].cmd);
  254. fprintf(stderr, "\n");
  255. for (size_t i = 0; i < image_stage.size(); i++)
  256. fprintf(stderr, " [%zu] 0x%02X data=%zu\n", i, image_stage[i].cmd, image_stage[i].data.size());
  257. }
  258. // pre_block(k) = commands after burst k-1 (or the start) up to, but not
  259. // including, burst k's own plane-write command - i.e. the window set for
  260. // plane k, possibly with the lazily-run _InitDisplay in front for k==0.
  261. auto pre_block = [&](size_t k) {
  262. size_t lo = (k == 0) ? 0 : bursts[k - 1] + 1;
  263. return std::vector<Cmd>(image_stage.begin() + lo, image_stage.begin() + bursts[k]);
  264. };
  265. std::vector<Cmd> init_seq, window0, window1;
  266. std::vector<uint8_t> plane_cmds;
  267. bool per_plane = false;
  268. bool dual_region = false; // two physical regions (per-region select + window)
  269. int plane_width_val = 0; // decoded per-region width (dual_region only)
  270. uint32_t region0_burst = 0; // region 0's image burst length, for line-order detection
  271. if (bursts.size() >= 2) {
  272. // Multi-plane. Two observed layouts:
  273. // interleaved: [init][W0][burst0][W1][burst1] - each plane's window
  274. // sits between its burst and the previous one (dual region);
  275. // batched: [init][W][W][burst0][burst1] - all windows precede all
  276. // bursts (SSD1680 3-colour: writeImage sets the black and
  277. // red RAM windows, then bursts both planes).
  278. for (size_t k = 0; k < bursts.size(); k++)
  279. plane_cmds.push_back(image_stage[bursts[k]].cmd);
  280. const size_t n = bursts.size();
  281. std::vector<Cmd> pre = pre_block(0);
  282. std::vector<std::vector<Cmd>> windows;
  283. bool interleaved = false;
  284. for (size_t k = 1; k < n; k++)
  285. if (bursts[k] - bursts[k - 1] > 1) {
  286. interleaved = true;
  287. break;
  288. }
  289. if (interleaved) {
  290. std::vector<Cmd> gap0(image_stage.begin() + bursts[0] + 1, image_stage.begin() + bursts[1]);
  291. const size_t wl = gap0.size();
  292. if (wl <= pre.size()) {
  293. windows.push_back(std::vector<Cmd>(pre.end() - wl, pre.end()));
  294. init_seq.assign(pre.begin(), pre.end() - wl);
  295. } else {
  296. windows.push_back({});
  297. init_seq = pre;
  298. }
  299. for (size_t k = 1; k < n; k++)
  300. windows.push_back(std::vector<Cmd>(image_stage.begin() + bursts[k - 1] + 1, image_stage.begin() + bursts[k]));
  301. } else {
  302. // Batched: pre = init + n copies of the window. Peel the smallest block
  303. // that repeats n times at the tail; the remainder is init.
  304. size_t L = 0;
  305. for (size_t cand = 1; cand * n <= pre.size(); cand++) {
  306. bool ok = true;
  307. for (size_t b = 0; b < n && ok; b++)
  308. for (size_t j = 0; j < cand && ok; j++) {
  309. const Cmd &a = pre[pre.size() - cand * n + b * cand + j];
  310. const Cmd &c = pre[pre.size() - cand + j];
  311. if (a.cmd != c.cmd || a.data != c.data)
  312. ok = false;
  313. }
  314. if (ok) {
  315. L = cand;
  316. break;
  317. }
  318. }
  319. if (L > 0) {
  320. for (size_t b = 0; b < n; b++)
  321. windows.push_back(std::vector<Cmd>(pre.end() - L * (n - b), pre.end() - L * (n - b - 1)));
  322. init_seq.assign(pre.begin(), pre.end() - L * n);
  323. } else {
  324. windows.push_back({});
  325. init_seq = pre;
  326. }
  327. }
  328. window0 = windows.empty() ? std::vector<Cmd>{} : windows[0];
  329. window1 = windows.size() > 1 ? windows[1] : std::vector<Cmd>{};
  330. for (size_t k = 1; k < windows.size(); k++)
  331. if (!cmds_equal(windows[0], windows[k]))
  332. per_plane = true; // per-plane windows differ => separate regions
  333. // Dual-region refinement (e.g. GDEY0579F51 / HX8717: a two-chip panel whose
  334. // "planes" are two physical half-width regions, each gated by a region-
  335. // select command before its own window + burst). The generic interleaved
  336. // path above already recovers the per-region windows and plane commands;
  337. // three things it can't are filled here.
  338. if (interleaved && per_plane) {
  339. dual_region = true;
  340. std::set<uint8_t> wops; // region-select + window-set opcodes
  341. for (const auto &c : window0)
  342. wops.insert(c.cmd);
  343. for (const auto &c : window1)
  344. wops.insert(c.cmd);
  345. // (1) INIT. A dual-region panel runs its whole _InitDisplay during the
  346. // earlier writeScreenBuffer clear, and that init REUSES the region-select
  347. // opcode (select master/slave for each region's PSR), so the single-plane
  348. // "cut at the first window opcode" rule would cut at the very first init
  349. // command. Instead take init from the clear stage and drop only the
  350. // CONTIGUOUS trailing run of window-set commands before the first clear
  351. // burst (the both-/first-region window-sets); the select/PSR pairs earlier
  352. // in init survive because a non-window command (BTST, power-on, ...)
  353. // separates them from that trailing run.
  354. const size_t cb = plane_index(init_stage); // first clear burst
  355. size_t cut = cb;
  356. while (cut > 0 && wops.count(init_stage[cut - 1].cmd))
  357. cut--;
  358. init_seq.assign(init_stage.begin(), init_stage.begin() + cut);
  359. // (2) plane_width: each region addresses its own half. Decode it from the
  360. // window-set command's payload - first two big-endian 16-bit fields are
  361. // x and x_end, as every window encoder observed so far lays them out.
  362. for (const auto &c : window0)
  363. if (c.data.size() >= 4) {
  364. int x = (c.data[0] << 8) | c.data[1];
  365. int xe = (c.data[2] << 8) | c.data[3];
  366. plane_width_val = xe - x + 1;
  367. break;
  368. }
  369. // (3) line doubling: region 0's burst length, compared in the emit stage
  370. // against plane_width*height*bpp/8 to flag PAIRED_EDGES.
  371. region0_burst = (uint32_t) image_stage[bursts[0]].data.size();
  372. }
  373. } else {
  374. // Single plane: window = the image call's pre-burst block; init comes
  375. // from the writeScreenBuffer stage, cut at the first window-set command
  376. // (SSD16xx sets the window there too - that belongs in window_sequence).
  377. const size_t wp = plane_index(image_stage);
  378. window0.assign(image_stage.begin(), image_stage.begin() + wp);
  379. std::set<uint8_t> wops;
  380. for (const auto &c : window0)
  381. wops.insert(c.cmd);
  382. const size_t ip = plane_index(init_stage);
  383. size_t cut = ip;
  384. for (size_t i = 0; i < ip; i++)
  385. if (wops.count(init_stage[i].cmd)) {
  386. cut = i;
  387. break;
  388. }
  389. init_seq.assign(init_stage.begin(), init_stage.begin() + cut);
  390. plane_cmds.push_back(wp < image_stage.size() ? image_stage[wp].cmd : 0x00);
  391. }
  392. // blank/clear fill byte, observed from the writeScreenBuffer clear burst.
  393. const size_t cip = plane_index(init_stage);
  394. const uint8_t clear_fill = (cip < init_stage.size() && !init_stage[cip].data.empty()) ? init_stage[cip].data[0] : 0x00;
  395. // plane_invert + 1bpp/packed detection, derived by the fill-capture probe.
  396. const uint8_t p0cmd = plane_cmds.empty() ? 0x00 : plane_cmds[0];
  397. const uint8_t p1cmd = plane_cmds.size() > 1 ? plane_cmds[1] : 0x00;
  398. const PlaneInvert pv = probe_plane_invert_values<Driver>(p0cmd, p1cmd, nplanes);
  399. // Packed-family resolution (4-colour palette etc.), run once here so both the
  400. // busy-timeout class and the packed fields below use the same answer. 1bpp
  401. // panels skip it. An unresolved packed panel (no family resolver, e.g.
  402. // 7-colour) is treated as the slow class for the timeout floor.
  403. const PackedResolved pr =
  404. (!pv.is_1bpp && resolve_packed) ? resolve_packed(clear_fill, pv) : PackedResolved{};
  405. const int depth_bpp = pv.is_1bpp ? 1 : (pr.resolved ? pr.bits_per_pixel : 4);
  406. // Refresh = post-write commands after the LAST burst (e.g. UC8179's 0x92),
  407. // then the refresh call minus any window-set it repeats.
  408. std::set<uint8_t> all_wops;
  409. for (const auto &c : window0)
  410. all_wops.insert(c.cmd);
  411. for (const auto &c : window1)
  412. all_wops.insert(c.cmd);
  413. std::vector<Cmd> refresh_seq;
  414. if (!bursts.empty())
  415. for (size_t i = bursts.back() + 1; i < image_stage.size() && image_stage[i].data.size() < PLANE_BURST_MIN; i++)
  416. refresh_seq.push_back(image_stage[i]);
  417. // A shared-region panel re-sets its one window in refresh() and we drop that
  418. // duplicate; a dual-region panel's refresh instead sets a DISTINCT both-region
  419. // window (its own select payload), which is part of the refresh - keep it.
  420. for (const auto &c : refresh_stage)
  421. if (dual_region || !all_wops.count(c.cmd))
  422. refresh_seq.push_back(c);
  423. // The refresh ends at its trigger (the command we busy-wait on). A dual-region
  424. // driver re-sets the window AFTER the trigger to prime its own next writeImage;
  425. // our engine always sets its own window per cycle, so that trailing window is
  426. // dead in replay - trim anything past the last busy-wait.
  427. if (dual_region) {
  428. size_t last_wait = refresh_seq.size();
  429. for (size_t i = 0; i < refresh_seq.size(); i++)
  430. if (refresh_seq[i].wait_busy)
  431. last_wait = i;
  432. if (last_wait < refresh_seq.size())
  433. refresh_seq.resize(last_wait + 1);
  434. }
  435. // --- emit ---
  436. printf("// GENERATED by emit_descriptor from %s - candidate.\n", class_name);
  437. printf("// Command sequences, plane layout and plane_invert are observed here;\n");
  438. printf("// for a packed panel bits_per_pixel/palette/blank_code are probe-filled\n");
  439. printf("// when the colour family is recognised (4-colour/7-colour), else left TODO. A\n");
  440. printf("// dual-region panel also gets plane_width and a candidate line_order; the\n");
  441. printf("// exact PAIRED_EDGES row order still wants diag/driver confirmation.\n");
  442. printf("#pragma once\n#include \"epd_command.h\"\n\nnamespace esphome::gxepd2 {\n\n");
  443. auto emit_seq = [&](const char *seqsuffix, std::vector<Cmd> &cmds) {
  444. for (size_t i = 0; i < cmds.size(); i++)
  445. if (!cmds[i].data.empty()) {
  446. char suf[64];
  447. snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
  448. print_data_array(macro, suf, cmds[i].data);
  449. }
  450. printf("\ninline const EpdCommand %s_%s[] = {\n", macro, seqsuffix);
  451. for (size_t i = 0; i < cmds.size(); i++) {
  452. char suf[64];
  453. snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
  454. print_cmd(macro, suf, cmds[i]);
  455. }
  456. printf("};\n\n");
  457. };
  458. const bool w0_empty = window0.empty(); // e.g. OTP-default panels (F52) set no window
  459. emit_seq("INIT", init_seq);
  460. if (!w0_empty)
  461. emit_seq("WINDOW_SEQ0", window0);
  462. if (per_plane)
  463. emit_seq("WINDOW_SEQ1", window1);
  464. emit_seq("REFRESH", refresh_seq);
  465. printf("inline const EpdPanelDescriptor %s = {\n", macro);
  466. printf(" .width = %u,\n", (unsigned) Driver::WIDTH);
  467. printf(" .height = %u,\n", (unsigned) Driver::HEIGHT);
  468. printf(" .busy_active_level = %s,\n", bl == HIGH ? "true" : "false");
  469. const char *depth_class = depth_bpp >= 4 ? "4bpp 7-colour" : depth_bpp == 2 ? "2bpp 4-colour" : "1bpp mono/3-colour";
  470. printf(" .busy_timeout_ms = %u, // generous diagnostic ceiling (vendor full_refresh_time %ums, "
  471. "%s class); dev-tunable\n",
  472. (unsigned) default_busy_timeout_ms(Driver::full_refresh_time, depth_bpp),
  473. (unsigned) Driver::full_refresh_time, depth_class);
  474. printf(" .init_sequence = %s_INIT,\n", macro);
  475. printf(" .init_sequence_len = sizeof(%s_INIT) / sizeof(%s_INIT[0]),\n", macro, macro);
  476. if (per_plane) {
  477. printf(" .window_sequence = {%s_WINDOW_SEQ0, %s_WINDOW_SEQ1},\n", macro, macro);
  478. printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), "
  479. "sizeof(%s_WINDOW_SEQ1) / sizeof(%s_WINDOW_SEQ1[0])},\n",
  480. macro, macro, macro, macro);
  481. printf(" .window_per_plane = true, // per-plane windows differ => separate regions\n");
  482. } else if (w0_empty) {
  483. printf(" .window_sequence = {nullptr, nullptr}, // panel sets no window (OTP-default frame)\n");
  484. printf(" .window_sequence_len = {0, 0},\n");
  485. } else {
  486. printf(" .window_sequence = {%s_WINDOW_SEQ0, nullptr},\n", macro);
  487. printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), 0},\n", macro, macro);
  488. }
  489. printf(" .plane_count = %zu,\n", nplanes);
  490. printf(" .plane_write_cmd = {0x%02X, 0x%02X},\n", p0cmd, p1cmd);
  491. // Fields below are emitted in struct-declaration order (plane_invert,
  492. // plane_width, line_order, bits_per_pixel, palette, palette_len,
  493. // blank_code) so the designated initializer stays well-formed.
  494. if (pv.is_1bpp) {
  495. const bool i1 = (nplanes > 1 && pv.plane1_valid) ? pv.inv1 : false;
  496. printf(" .plane_invert = {%s, %s}, // probe-derived\n", pv.inv0 ? "true" : "false", i1 ? "true" : "false");
  497. } else {
  498. printf(" .plane_invert = {false, false}, // unused: packed panel\n");
  499. }
  500. if (per_plane) {
  501. if (dual_region && plane_width_val > 0)
  502. printf(" .plane_width = %d, // decoded from the region window-set (x_end-x+1); sanity-check\n",
  503. plane_width_val);
  504. else
  505. printf(" .plane_width = 0, // TODO: diag pass (separate-region width)\n");
  506. }
  507. // line_order: a dual-region panel whose per-region burst is twice the region's
  508. // own pixel bytes is sending two wire lines per row (GxEPD2 writeNative's
  509. // doubled, both-edges-to-middle emission). The doubling is observable here;
  510. // the exact row order that PAIRED_EDGES encodes is NOT (a uniform fill can't
  511. // show which buffer row each line carries), so emit it as a candidate the
  512. // diag native-path pass / driver source confirms.
  513. if (dual_region && plane_width_val > 0 && depth_bpp > 0) {
  514. uint32_t expect = (uint32_t) plane_width_val * Driver::HEIGHT * depth_bpp / 8;
  515. if (expect && region0_burst == 2u * expect)
  516. printf(" .line_order = LineOrder::PAIRED_EDGES, // region burst %u B = 2x %u B (2 lines/row); "
  517. "confirm edges-to-middle order via the diag native-path pass\n",
  518. region0_burst, expect);
  519. else if (expect && region0_burst != expect)
  520. printf(" // NOTE: region burst %u B vs expected %u B (1 line/row) - line order unclear, "
  521. "check with the diag native-path pass\n",
  522. region0_burst, expect);
  523. }
  524. if (pv.is_1bpp) {
  525. // 1bpp plane model: depth confirmed by the probe; palette/blank_code unused.
  526. printf(" .bits_per_pixel = 1, // probe: white fill => all-bits wire byte 0x%02X\n", pv.w0_white & 0xFF);
  527. printf(" .palette = nullptr,\n");
  528. printf(" .palette_len = 0,\n");
  529. } else {
  530. // Packed panel. If a family resolver recognised it (4-colour, via
  531. // emit_palette_4c.h), it derived depth/palette/blank_code by observing the
  532. // driver's own colour fills - emit those (computed once, above). Otherwise
  533. // fall back to a TODO the diag pass fills in by hand (an unknown packed
  534. // family, e.g. a packed panel outside the 4-colour/7-colour resolvers).
  535. if (pr.resolved) {
  536. const int shown_colors = pr.color_count >= 0 ? pr.color_count : (1 << pr.bits_per_pixel);
  537. printf(" .bits_per_pixel = %d, // probe: %d-colour packed%s%s\n", pr.bits_per_pixel,
  538. shown_colors, pr.note.empty() ? "" : " - ", pr.note.c_str());
  539. printf(" .palette = %s,\n", pr.palette_expr);
  540. printf(" .palette_len = %s,\n", pr.palette_len_expr);
  541. printf(" .blank_code = 0x%02X, // observed white fill code\n", pr.blank_code & 0xFF);
  542. } else {
  543. printf(" .bits_per_pixel = 2, // TODO: diag pass - PACKED (white fill wire 0x%02X, not 1bpp)%s%s\n",
  544. pv.w0_white & 0xFF, pr.note.empty() ? "" : " - ", pr.note.c_str());
  545. printf(" .palette = nullptr, // TODO: diag pass\n");
  546. printf(" .palette_len = 0,\n");
  547. printf(" .blank_code = 0x00, // TODO: diag pass (clear fill observed 0x%02X)\n", clear_fill);
  548. }
  549. }
  550. printf(" .refresh_sequence = %s_REFRESH,\n", macro);
  551. printf(" .refresh_sequence_len = sizeof(%s_REFRESH) / sizeof(%s_REFRESH[0]),\n", macro, macro);
  552. printf("};\n\n} // namespace esphome::gxepd2\n");
  553. }
  554. // Generic entry: no packed-family resolver, so a packed panel's
  555. // depth/palette/blank_code emit as TODO placeholders (the pre-resolver
  556. // behaviour). The 4-colour entry is emit_descriptor_4c() in emit_palette_4c.h.
  557. template<typename Driver> void emit_descriptor(const char *class_name, const char *macro) {
  558. emit_descriptor_impl<Driver>(class_name, macro, nullptr);
  559. }
  560. } // namespace emit