emit_descriptor.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 / row_interleave. 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 <set>
  26. #include <type_traits>
  27. #include <utility>
  28. #include <vector>
  29. #include "spy/Arduino.h"
  30. #include "spy/SPI.h"
  31. #include "trace.h"
  32. namespace emit {
  33. // A data burst at least this long is a pixel-plane write, not config data.
  34. constexpr size_t PLANE_BURST_MIN = 256;
  35. struct Cmd {
  36. uint8_t cmd;
  37. std::vector<uint8_t> data;
  38. bool wait_busy = false;
  39. unsigned long delay_after = 0;
  40. };
  41. // Expose GxEPD2_EPD's protected busy level without parsing (same trick as
  42. // run_harness.h's Peek).
  43. template<typename Driver> struct Peek : Driver {
  44. using Driver::Driver;
  45. int busy_level() const { return this->_busy_level; }
  46. };
  47. // Group a slice of the event stream into EpdCommand-shaped records. Events
  48. // before the first SPI *command* (the reset pulse + its delays) are skipped -
  49. // the engine owns the hardware reset, so it never belongs in a descriptor.
  50. inline std::vector<Cmd> group(size_t lo, size_t hi) {
  51. std::vector<Cmd> cmds;
  52. bool started = false;
  53. for (size_t i = lo; i < hi; i++) {
  54. const auto &e = Trace::events[i];
  55. switch (e.kind) {
  56. case EventKind::SPI_TRANSFER:
  57. if (e.is_command) {
  58. cmds.push_back(Cmd{e.byte});
  59. started = true;
  60. } else if (started) {
  61. cmds.back().data.push_back(e.byte);
  62. }
  63. break;
  64. case EventKind::DELAY:
  65. if (started)
  66. cmds.back().delay_after += e.ms;
  67. break;
  68. case EventKind::DIGITAL_READ: // the only reads are busy-pin polls
  69. if (started) {
  70. cmds.back().wait_busy = true;
  71. // The delay(1) GxEPD2_EPD::_waitWhileBusy() runs inside its poll
  72. // loop lands right before this read and is part of the busy-wait,
  73. // not an inter-command delay - our engine owns busy-waiting, so
  74. // fold it in rather than emit it. (This also absorbs a vendor's own
  75. // tiny settle delay right before a refresh trigger, e.g. 290c's
  76. // _refresh delay(1); immaterial, the panel asserts busy regardless.)
  77. cmds.back().delay_after = 0;
  78. }
  79. break;
  80. default:
  81. break; // DIGITAL_WRITE = reset/CS/DC toggles: engine's job, not data
  82. }
  83. }
  84. return cmds;
  85. }
  86. // Index of the first command whose data burst marks a plane write, or np
  87. // (cmds.size()) if there's none in this slice.
  88. inline size_t plane_index(const std::vector<Cmd> &cmds) {
  89. for (size_t i = 0; i < cmds.size(); i++)
  90. if (cmds[i].data.size() >= PLANE_BURST_MIN)
  91. return i;
  92. return cmds.size();
  93. }
  94. inline void print_data_array(const char *macro, const char *suffix, const std::vector<uint8_t> &d) {
  95. printf("inline const uint8_t %s_%s[] = {", macro, suffix);
  96. for (size_t i = 0; i < d.size(); i++)
  97. printf("%s0x%02X", i ? ", " : "", d[i]);
  98. printf("};\n");
  99. }
  100. // Print one EpdCommand{} initializer line, with the optional fields only when
  101. // they're non-default (matches the hand files' style).
  102. inline void print_cmd(const char *macro, const char *suffix, const Cmd &c) {
  103. if (c.data.empty() && !c.wait_busy && c.delay_after == 0) {
  104. printf(" {0x%02X, nullptr, 0},\n", c.cmd);
  105. return;
  106. }
  107. const char *dataref = c.data.empty() ? "nullptr" : nullptr;
  108. if (dataref)
  109. printf(" {0x%02X, nullptr, 0", c.cmd);
  110. else
  111. printf(" {0x%02X, %s_%s, %u", c.cmd, macro, suffix, (unsigned) c.data.size());
  112. if (c.wait_busy || c.delay_after)
  113. printf(", /*delay_before_ms=*/0, /*delay_after_ms=*/%lu, /*wait_busy_after=*/%s", c.delay_after,
  114. c.wait_busy ? "true" : "false");
  115. printf("},\n");
  116. }
  117. // First data byte of the burst written right after command `op`, or -1.
  118. inline int burst_byte_after(const std::vector<Cmd> &cmds, uint8_t op) {
  119. for (const auto &c : cmds)
  120. if (c.cmd == op && c.data.size() >= PLANE_BURST_MIN)
  121. return c.data[0];
  122. return -1;
  123. }
  124. // Detects the two-arg writeScreenBuffer(black_value, color_value) that colour
  125. // (plane_count > 1) drivers have and mono drivers don't.
  126. template<typename T, typename = void> struct has_wsb2 : std::false_type {};
  127. template<typename T>
  128. struct has_wsb2<T, std::void_t<decltype(std::declval<T &>().writeScreenBuffer(uint8_t{}, uint8_t{}))>>
  129. : std::true_type {};
  130. struct PlaneInvert {
  131. bool inv0 = false, inv1 = false;
  132. bool plane1_valid = false;
  133. bool is_1bpp = false; // white fill => an all-bits-same wire byte (not packed)
  134. int w0_white = -1, w1_red = -1;
  135. };
  136. // plane_invert by capture (see probe_plane_invert.h for the rationale): drive
  137. // known full-screen fills and read each plane's wire byte, reconciling against
  138. // the engine's fixed buffer convention (plane0 bit=white, plane1 bit=red). A
  139. // white-fill plane0 wire that isn't 0x00/0xFF means a packed (>1bpp) panel,
  140. // where plane_invert is unused and bits_per_pixel/palette come from the diag
  141. // pass instead.
  142. template<typename Driver> PlaneInvert probe_plane_invert_values(uint8_t p0cmd, uint8_t p1cmd, size_t plane_count) {
  143. constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
  144. Trace::set_dc_pin(DC);
  145. Peek<Driver> d(CS, DC, RST, BUSY);
  146. Trace::last_busy_release_value = d.busy_level() == HIGH ? LOW : HIGH;
  147. d.selectSPI(SPI, SPISettings());
  148. d.init(0);
  149. PlaneInvert r;
  150. auto cap0 = [&](uint8_t value) -> int {
  151. Trace::start_event_record();
  152. d.writeScreenBuffer(value); // 1-arg form all drivers have; colour defaults blank
  153. Trace::stop_event_record();
  154. return burst_byte_after(group(0, Trace::events.size()), p0cmd);
  155. };
  156. r.w0_white = cap0(0xFF);
  157. r.is_1bpp = (r.w0_white == 0x00 || r.w0_white == 0xFF);
  158. r.inv0 = (r.w0_white == 0x00); // engine plane0 bit=white; white wire 0x00 => invert
  159. if (plane_count > 1) {
  160. if constexpr (has_wsb2<Driver>::value) {
  161. Trace::start_event_record();
  162. d.writeScreenBuffer((uint8_t) 0xFF, (uint8_t) 0x00); // all-red fill
  163. Trace::stop_event_record();
  164. r.w1_red = burst_byte_after(group(0, Trace::events.size()), p1cmd);
  165. r.plane1_valid = (r.w1_red == 0x00 || r.w1_red == 0xFF);
  166. r.inv1 = (r.w1_red == 0x00); // engine plane1 bit=red; red wire 0x00 => invert
  167. }
  168. }
  169. return r;
  170. }
  171. template<typename Driver> void emit_descriptor(const char *class_name, const char *macro) {
  172. constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
  173. Trace::set_dc_pin(DC);
  174. Peek<Driver> driver(CS, DC, RST, BUSY);
  175. const int bl = driver.busy_level();
  176. Trace::last_busy_release_value = bl == HIGH ? LOW : HIGH;
  177. driver.selectSPI(SPI, SPISettings());
  178. driver.init(0);
  179. const uint32_t plane_bytes = (static_cast<uint32_t>(Driver::WIDTH) * Driver::HEIGHT) / 8;
  180. auto *black = new uint8_t[plane_bytes];
  181. auto *color = new uint8_t[plane_bytes];
  182. for (uint32_t i = 0; i < plane_bytes; i++) {
  183. black[i] = 0xA5;
  184. color[i] = 0xA5;
  185. }
  186. Trace::start_event_record();
  187. const size_t s0 = 0;
  188. driver.writeScreenBuffer(); // init + clear burst
  189. const size_t s1 = Trace::events.size();
  190. driver.writeImage(black, color, 0, 0, Driver::WIDTH, Driver::HEIGHT); // window + plane
  191. const size_t s2 = Trace::events.size();
  192. driver.refresh(false); // window-again + trigger
  193. const size_t s3 = Trace::events.size();
  194. Trace::stop_event_record();
  195. delete[] black;
  196. delete[] color;
  197. // --- segment ---
  198. auto init_stage = group(s0, s1);
  199. auto image_stage = group(s1, s2);
  200. auto refresh_stage = group(s2, s3);
  201. auto cmds_equal = [](const std::vector<Cmd> &a, const std::vector<Cmd> &b) {
  202. if (a.size() != b.size())
  203. return false;
  204. for (size_t i = 0; i < a.size(); i++)
  205. if (a[i].cmd != b[i].cmd || a[i].data != b[i].data)
  206. return false;
  207. return true;
  208. };
  209. // Every pixel-plane burst in the image call. One => single-plane panel;
  210. // N => N planes (two colour planes sharing a region, or two physical
  211. // regions - told apart below by whether their window-sets match).
  212. std::vector<size_t> bursts;
  213. for (size_t i = 0; i < image_stage.size(); i++)
  214. if (image_stage[i].data.size() >= PLANE_BURST_MIN)
  215. bursts.push_back(i);
  216. const size_t nplanes = bursts.empty() ? 1 : bursts.size();
  217. if (getenv("EMIT_DEBUG")) {
  218. fprintf(stderr, "image_stage %zu cmds; bursts:", image_stage.size());
  219. for (auto b : bursts)
  220. fprintf(stderr, " [%zu]=0x%02X", b, image_stage[b].cmd);
  221. fprintf(stderr, "\n");
  222. for (size_t i = 0; i < image_stage.size(); i++)
  223. fprintf(stderr, " [%zu] 0x%02X data=%zu\n", i, image_stage[i].cmd, image_stage[i].data.size());
  224. }
  225. // pre_block(k) = commands after burst k-1 (or the start) up to, but not
  226. // including, burst k's own plane-write command - i.e. the window set for
  227. // plane k, possibly with the lazily-run _InitDisplay in front for k==0.
  228. auto pre_block = [&](size_t k) {
  229. size_t lo = (k == 0) ? 0 : bursts[k - 1] + 1;
  230. return std::vector<Cmd>(image_stage.begin() + lo, image_stage.begin() + bursts[k]);
  231. };
  232. std::vector<Cmd> init_seq, window0, window1;
  233. std::vector<uint8_t> plane_cmds;
  234. bool per_plane = false;
  235. if (bursts.size() >= 2) {
  236. // Multi-plane. Two observed layouts:
  237. // interleaved: [init][W0][burst0][W1][burst1] - each plane's window
  238. // sits between its burst and the previous one (dual region);
  239. // batched: [init][W][W][burst0][burst1] - all windows precede all
  240. // bursts (SSD1680 3-colour: writeImage sets the black and
  241. // red RAM windows, then bursts both planes).
  242. for (size_t k = 0; k < bursts.size(); k++)
  243. plane_cmds.push_back(image_stage[bursts[k]].cmd);
  244. const size_t n = bursts.size();
  245. std::vector<Cmd> pre = pre_block(0);
  246. std::vector<std::vector<Cmd>> windows;
  247. bool interleaved = false;
  248. for (size_t k = 1; k < n; k++)
  249. if (bursts[k] - bursts[k - 1] > 1) {
  250. interleaved = true;
  251. break;
  252. }
  253. if (interleaved) {
  254. std::vector<Cmd> gap0(image_stage.begin() + bursts[0] + 1, image_stage.begin() + bursts[1]);
  255. const size_t wl = gap0.size();
  256. if (wl <= pre.size()) {
  257. windows.push_back(std::vector<Cmd>(pre.end() - wl, pre.end()));
  258. init_seq.assign(pre.begin(), pre.end() - wl);
  259. } else {
  260. windows.push_back({});
  261. init_seq = pre;
  262. }
  263. for (size_t k = 1; k < n; k++)
  264. windows.push_back(std::vector<Cmd>(image_stage.begin() + bursts[k - 1] + 1, image_stage.begin() + bursts[k]));
  265. } else {
  266. // Batched: pre = init + n copies of the window. Peel the smallest block
  267. // that repeats n times at the tail; the remainder is init.
  268. size_t L = 0;
  269. for (size_t cand = 1; cand * n <= pre.size(); cand++) {
  270. bool ok = true;
  271. for (size_t b = 0; b < n && ok; b++)
  272. for (size_t j = 0; j < cand && ok; j++) {
  273. const Cmd &a = pre[pre.size() - cand * n + b * cand + j];
  274. const Cmd &c = pre[pre.size() - cand + j];
  275. if (a.cmd != c.cmd || a.data != c.data)
  276. ok = false;
  277. }
  278. if (ok) {
  279. L = cand;
  280. break;
  281. }
  282. }
  283. if (L > 0) {
  284. for (size_t b = 0; b < n; b++)
  285. windows.push_back(std::vector<Cmd>(pre.end() - L * (n - b), pre.end() - L * (n - b - 1)));
  286. init_seq.assign(pre.begin(), pre.end() - L * n);
  287. } else {
  288. windows.push_back({});
  289. init_seq = pre;
  290. }
  291. }
  292. window0 = windows.empty() ? std::vector<Cmd>{} : windows[0];
  293. window1 = windows.size() > 1 ? windows[1] : std::vector<Cmd>{};
  294. for (size_t k = 1; k < windows.size(); k++)
  295. if (!cmds_equal(windows[0], windows[k]))
  296. per_plane = true; // per-plane windows differ => separate regions
  297. } else {
  298. // Single plane: window = the image call's pre-burst block; init comes
  299. // from the writeScreenBuffer stage, cut at the first window-set command
  300. // (SSD16xx sets the window there too - that belongs in window_sequence).
  301. const size_t wp = plane_index(image_stage);
  302. window0.assign(image_stage.begin(), image_stage.begin() + wp);
  303. std::set<uint8_t> wops;
  304. for (const auto &c : window0)
  305. wops.insert(c.cmd);
  306. const size_t ip = plane_index(init_stage);
  307. size_t cut = ip;
  308. for (size_t i = 0; i < ip; i++)
  309. if (wops.count(init_stage[i].cmd)) {
  310. cut = i;
  311. break;
  312. }
  313. init_seq.assign(init_stage.begin(), init_stage.begin() + cut);
  314. plane_cmds.push_back(wp < image_stage.size() ? image_stage[wp].cmd : 0x00);
  315. }
  316. // blank/clear fill byte, observed from the writeScreenBuffer clear burst.
  317. const size_t cip = plane_index(init_stage);
  318. const uint8_t clear_fill = (cip < init_stage.size() && !init_stage[cip].data.empty()) ? init_stage[cip].data[0] : 0x00;
  319. // plane_invert + 1bpp/packed detection, derived by the fill-capture probe.
  320. const uint8_t p0cmd = plane_cmds.empty() ? 0x00 : plane_cmds[0];
  321. const uint8_t p1cmd = plane_cmds.size() > 1 ? plane_cmds[1] : 0x00;
  322. const PlaneInvert pv = probe_plane_invert_values<Driver>(p0cmd, p1cmd, nplanes);
  323. // Refresh = post-write commands after the LAST burst (e.g. UC8179's 0x92),
  324. // then the refresh call minus any window-set it repeats.
  325. std::set<uint8_t> all_wops;
  326. for (const auto &c : window0)
  327. all_wops.insert(c.cmd);
  328. for (const auto &c : window1)
  329. all_wops.insert(c.cmd);
  330. std::vector<Cmd> refresh_seq;
  331. if (!bursts.empty())
  332. for (size_t i = bursts.back() + 1; i < image_stage.size() && image_stage[i].data.size() < PLANE_BURST_MIN; i++)
  333. refresh_seq.push_back(image_stage[i]);
  334. for (const auto &c : refresh_stage)
  335. if (!all_wops.count(c.cmd))
  336. refresh_seq.push_back(c);
  337. // --- emit ---
  338. printf("// GENERATED by emit_descriptor from %s - candidate, segmentation only.\n", class_name);
  339. printf("// bits_per_pixel/palette/plane_invert/plane_width/row_interleave still\n");
  340. printf("// come from the diag passes.\n");
  341. printf("#pragma once\n#include \"epd_command.h\"\n\nnamespace esphome::gxepd2 {\n\n");
  342. auto emit_seq = [&](const char *seqsuffix, std::vector<Cmd> &cmds) {
  343. for (size_t i = 0; i < cmds.size(); i++)
  344. if (!cmds[i].data.empty()) {
  345. char suf[64];
  346. snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
  347. print_data_array(macro, suf, cmds[i].data);
  348. }
  349. printf("\ninline const EpdCommand %s_%s[] = {\n", macro, seqsuffix);
  350. for (size_t i = 0; i < cmds.size(); i++) {
  351. char suf[64];
  352. snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
  353. print_cmd(macro, suf, cmds[i]);
  354. }
  355. printf("};\n\n");
  356. };
  357. emit_seq("INIT", init_seq);
  358. emit_seq("WINDOW_SEQ0", window0);
  359. if (per_plane)
  360. emit_seq("WINDOW_SEQ1", window1);
  361. emit_seq("REFRESH", refresh_seq);
  362. printf("inline const EpdPanelDescriptor %s = {\n", macro);
  363. printf(" .width = %u,\n", (unsigned) Driver::WIDTH);
  364. printf(" .height = %u,\n", (unsigned) Driver::HEIGHT);
  365. printf(" .busy_active_level = %s,\n", bl == HIGH ? "true" : "false");
  366. printf(" .busy_timeout_ms = %u,\n", (unsigned) Driver::full_refresh_time + 5000u);
  367. printf(" .init_sequence = %s_INIT,\n", macro);
  368. printf(" .init_sequence_len = sizeof(%s_INIT) / sizeof(%s_INIT[0]),\n", macro, macro);
  369. if (per_plane) {
  370. printf(" .window_sequence = {%s_WINDOW_SEQ0, %s_WINDOW_SEQ1},\n", macro, macro);
  371. printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), "
  372. "sizeof(%s_WINDOW_SEQ1) / sizeof(%s_WINDOW_SEQ1[0])},\n",
  373. macro, macro, macro, macro);
  374. printf(" .window_per_plane = true, // per-plane windows differ => separate regions\n");
  375. } else {
  376. printf(" .window_sequence = {%s_WINDOW_SEQ0, nullptr},\n", macro);
  377. printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), 0},\n", macro, macro);
  378. }
  379. printf(" .plane_count = %zu,\n", nplanes);
  380. printf(" .plane_write_cmd = {0x%02X, 0x%02X},\n", p0cmd, p1cmd);
  381. // Fields below are emitted in struct-declaration order (plane_invert,
  382. // plane_width, row_interleave, bits_per_pixel, palette, palette_len,
  383. // blank_code) so the designated initializer stays well-formed.
  384. if (pv.is_1bpp) {
  385. const bool i1 = (nplanes > 1 && pv.plane1_valid) ? pv.inv1 : false;
  386. printf(" .plane_invert = {%s, %s}, // probe-derived\n", pv.inv0 ? "true" : "false", i1 ? "true" : "false");
  387. } else {
  388. printf(" .plane_invert = {false, false}, // unused: packed panel\n");
  389. }
  390. if (per_plane)
  391. printf(" .plane_width = 0, // TODO: diag pass (separate-region width)\n");
  392. if (pv.is_1bpp) {
  393. // 1bpp plane model: depth confirmed by the probe; palette/blank_code unused.
  394. printf(" .bits_per_pixel = 1, // probe: white fill => all-bits wire byte 0x%02X\n", pv.w0_white & 0xFF);
  395. printf(" .palette = nullptr,\n");
  396. printf(" .palette_len = 0,\n");
  397. } else {
  398. // Packed panel: depth/palette/blank_code are the diag pass's job.
  399. printf(" .bits_per_pixel = 2, // TODO: diag pass - PACKED (white fill wire 0x%02X, not 1bpp)\n",
  400. pv.w0_white & 0xFF);
  401. printf(" .palette = nullptr, // TODO: diag pass\n");
  402. printf(" .palette_len = 0,\n");
  403. printf(" .blank_code = 0x00, // TODO: diag pass (clear fill observed 0x%02X)\n", clear_fill);
  404. }
  405. printf(" .refresh_sequence = %s_REFRESH,\n", macro);
  406. printf(" .refresh_sequence_len = sizeof(%s_REFRESH) / sizeof(%s_REFRESH[0]),\n", macro, macro);
  407. printf("};\n\n} // namespace esphome::gxepd2\n");
  408. }
  409. } // namespace emit