emit_descriptor.h 15 KB

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