| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448 |
- #pragma once
- // Prototype: emit a candidate panel_*.h EpdPanelDescriptor by *observing* a
- // real vendor GxEPD2 driver run, instead of hand-transcribing its C++. This
- // closes the hand-derivation gap for the straight-line parts of a descriptor
- // (init / window / refresh command sequences + the plane-write command) by
- // phase-segmenting the captured event stream at the public-API boundary - no
- // edits to the vendor source.
- //
- // Staging (the trick that separates the phases without instrumenting the
- // vendor's private methods):
- // writeScreenBuffer() -> lazy _InitDisplay() + a plane-write burst (clear).
- // Everything before that burst is the INIT sequence;
- // the command right before it is the PLANE-WRITE cmd.
- // writeImage(pattern) -> init already done, so this is just the WINDOW set
- // (commands before the pattern burst) + plane write.
- // refresh() -> re-sets the window then triggers; dropping the
- // duplicate window command leaves the REFRESH seq.
- //
- // Out of scope here (comes from the diag Pattern A/B passes, not one capture):
- // bits_per_pixel / palette / plane_invert / row_interleave. Those are emitted
- // as TODO placeholders so the diff against the hand file is about segmentation.
- #include <cstdint>
- #include <cstdio>
- #include <cstdlib>
- #include <set>
- #include <type_traits>
- #include <utility>
- #include <vector>
- #include "spy/Arduino.h"
- #include "spy/SPI.h"
- #include "trace.h"
- namespace emit {
- // A data burst at least this long is a pixel-plane write, not config data.
- constexpr size_t PLANE_BURST_MIN = 256;
- struct Cmd {
- uint8_t cmd;
- std::vector<uint8_t> data;
- bool wait_busy = false;
- unsigned long delay_after = 0;
- };
- // Expose GxEPD2_EPD's protected busy level without parsing (same trick as
- // run_harness.h's Peek).
- template<typename Driver> struct Peek : Driver {
- using Driver::Driver;
- int busy_level() const { return this->_busy_level; }
- };
- // Group a slice of the event stream into EpdCommand-shaped records. Events
- // before the first SPI *command* (the reset pulse + its delays) are skipped -
- // the engine owns the hardware reset, so it never belongs in a descriptor.
- inline std::vector<Cmd> group(size_t lo, size_t hi) {
- std::vector<Cmd> cmds;
- bool started = false;
- for (size_t i = lo; i < hi; i++) {
- const auto &e = Trace::events[i];
- switch (e.kind) {
- case EventKind::SPI_TRANSFER:
- if (e.is_command) {
- cmds.push_back(Cmd{e.byte});
- started = true;
- } else if (started) {
- cmds.back().data.push_back(e.byte);
- }
- break;
- case EventKind::DELAY:
- if (started)
- cmds.back().delay_after += e.ms;
- break;
- case EventKind::DIGITAL_READ: // the only reads are busy-pin polls
- if (started) {
- cmds.back().wait_busy = true;
- // The delay(1) GxEPD2_EPD::_waitWhileBusy() runs inside its poll
- // loop lands right before this read and is part of the busy-wait,
- // not an inter-command delay - our engine owns busy-waiting, so
- // fold it in rather than emit it. (This also absorbs a vendor's own
- // tiny settle delay right before a refresh trigger, e.g. 290c's
- // _refresh delay(1); immaterial, the panel asserts busy regardless.)
- cmds.back().delay_after = 0;
- }
- break;
- default:
- break; // DIGITAL_WRITE = reset/CS/DC toggles: engine's job, not data
- }
- }
- return cmds;
- }
- // Index of the first command whose data burst marks a plane write, or np
- // (cmds.size()) if there's none in this slice.
- inline size_t plane_index(const std::vector<Cmd> &cmds) {
- for (size_t i = 0; i < cmds.size(); i++)
- if (cmds[i].data.size() >= PLANE_BURST_MIN)
- return i;
- return cmds.size();
- }
- inline void print_data_array(const char *macro, const char *suffix, const std::vector<uint8_t> &d) {
- printf("inline const uint8_t %s_%s[] = {", macro, suffix);
- for (size_t i = 0; i < d.size(); i++)
- printf("%s0x%02X", i ? ", " : "", d[i]);
- printf("};\n");
- }
- // Print one EpdCommand{} initializer line, with the optional fields only when
- // they're non-default (matches the hand files' style).
- inline void print_cmd(const char *macro, const char *suffix, const Cmd &c) {
- if (c.data.empty() && !c.wait_busy && c.delay_after == 0) {
- printf(" {0x%02X, nullptr, 0},\n", c.cmd);
- return;
- }
- const char *dataref = c.data.empty() ? "nullptr" : nullptr;
- if (dataref)
- printf(" {0x%02X, nullptr, 0", c.cmd);
- else
- printf(" {0x%02X, %s_%s, %u", c.cmd, macro, suffix, (unsigned) c.data.size());
- if (c.wait_busy || c.delay_after)
- printf(", /*delay_before_ms=*/0, /*delay_after_ms=*/%lu, /*wait_busy_after=*/%s", c.delay_after,
- c.wait_busy ? "true" : "false");
- printf("},\n");
- }
- // First data byte of the burst written right after command `op`, or -1.
- inline int burst_byte_after(const std::vector<Cmd> &cmds, uint8_t op) {
- for (const auto &c : cmds)
- if (c.cmd == op && c.data.size() >= PLANE_BURST_MIN)
- return c.data[0];
- return -1;
- }
- // Detects the two-arg writeScreenBuffer(black_value, color_value) that colour
- // (plane_count > 1) drivers have and mono drivers don't.
- template<typename T, typename = void> struct has_wsb2 : std::false_type {};
- template<typename T>
- struct has_wsb2<T, std::void_t<decltype(std::declval<T &>().writeScreenBuffer(uint8_t{}, uint8_t{}))>>
- : std::true_type {};
- struct PlaneInvert {
- bool inv0 = false, inv1 = false;
- bool plane1_valid = false;
- bool is_1bpp = false; // white fill => an all-bits-same wire byte (not packed)
- int w0_white = -1, w1_red = -1;
- };
- // plane_invert by capture (see probe_plane_invert.h for the rationale): drive
- // known full-screen fills and read each plane's wire byte, reconciling against
- // the engine's fixed buffer convention (plane0 bit=white, plane1 bit=red). A
- // white-fill plane0 wire that isn't 0x00/0xFF means a packed (>1bpp) panel,
- // where plane_invert is unused and bits_per_pixel/palette come from the diag
- // pass instead.
- template<typename Driver> PlaneInvert probe_plane_invert_values(uint8_t p0cmd, uint8_t p1cmd, size_t plane_count) {
- constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
- Trace::set_dc_pin(DC);
- Peek<Driver> d(CS, DC, RST, BUSY);
- Trace::last_busy_release_value = d.busy_level() == HIGH ? LOW : HIGH;
- d.selectSPI(SPI, SPISettings());
- d.init(0);
- PlaneInvert r;
- auto cap0 = [&](uint8_t value) -> int {
- Trace::start_event_record();
- d.writeScreenBuffer(value); // 1-arg form all drivers have; colour defaults blank
- Trace::stop_event_record();
- return burst_byte_after(group(0, Trace::events.size()), p0cmd);
- };
- r.w0_white = cap0(0xFF);
- r.is_1bpp = (r.w0_white == 0x00 || r.w0_white == 0xFF);
- r.inv0 = (r.w0_white == 0x00); // engine plane0 bit=white; white wire 0x00 => invert
- if (plane_count > 1) {
- if constexpr (has_wsb2<Driver>::value) {
- Trace::start_event_record();
- d.writeScreenBuffer((uint8_t) 0xFF, (uint8_t) 0x00); // all-red fill
- Trace::stop_event_record();
- r.w1_red = burst_byte_after(group(0, Trace::events.size()), p1cmd);
- r.plane1_valid = (r.w1_red == 0x00 || r.w1_red == 0xFF);
- r.inv1 = (r.w1_red == 0x00); // engine plane1 bit=red; red wire 0x00 => invert
- }
- }
- return r;
- }
- template<typename Driver> void emit_descriptor(const char *class_name, const char *macro) {
- constexpr int16_t CS = 10, DC = 11, RST = 12, BUSY = 13;
- Trace::set_dc_pin(DC);
- Peek<Driver> driver(CS, DC, RST, BUSY);
- const int bl = driver.busy_level();
- Trace::last_busy_release_value = bl == HIGH ? LOW : HIGH;
- driver.selectSPI(SPI, SPISettings());
- driver.init(0);
- const uint32_t plane_bytes = (static_cast<uint32_t>(Driver::WIDTH) * Driver::HEIGHT) / 8;
- auto *black = new uint8_t[plane_bytes];
- auto *color = new uint8_t[plane_bytes];
- for (uint32_t i = 0; i < plane_bytes; i++) {
- black[i] = 0xA5;
- color[i] = 0xA5;
- }
- Trace::start_event_record();
- const size_t s0 = 0;
- driver.writeScreenBuffer(); // init + clear burst
- const size_t s1 = Trace::events.size();
- driver.writeImage(black, color, 0, 0, Driver::WIDTH, Driver::HEIGHT); // window + plane
- const size_t s2 = Trace::events.size();
- driver.refresh(false); // window-again + trigger
- const size_t s3 = Trace::events.size();
- Trace::stop_event_record();
- delete[] black;
- delete[] color;
- // --- segment ---
- auto init_stage = group(s0, s1);
- auto image_stage = group(s1, s2);
- auto refresh_stage = group(s2, s3);
- auto cmds_equal = [](const std::vector<Cmd> &a, const std::vector<Cmd> &b) {
- if (a.size() != b.size())
- return false;
- for (size_t i = 0; i < a.size(); i++)
- if (a[i].cmd != b[i].cmd || a[i].data != b[i].data)
- return false;
- return true;
- };
- // Every pixel-plane burst in the image call. One => single-plane panel;
- // N => N planes (two colour planes sharing a region, or two physical
- // regions - told apart below by whether their window-sets match).
- std::vector<size_t> bursts;
- for (size_t i = 0; i < image_stage.size(); i++)
- if (image_stage[i].data.size() >= PLANE_BURST_MIN)
- bursts.push_back(i);
- const size_t nplanes = bursts.empty() ? 1 : bursts.size();
- if (getenv("EMIT_DEBUG")) {
- fprintf(stderr, "image_stage %zu cmds; bursts:", image_stage.size());
- for (auto b : bursts)
- fprintf(stderr, " [%zu]=0x%02X", b, image_stage[b].cmd);
- fprintf(stderr, "\n");
- for (size_t i = 0; i < image_stage.size(); i++)
- fprintf(stderr, " [%zu] 0x%02X data=%zu\n", i, image_stage[i].cmd, image_stage[i].data.size());
- }
- // pre_block(k) = commands after burst k-1 (or the start) up to, but not
- // including, burst k's own plane-write command - i.e. the window set for
- // plane k, possibly with the lazily-run _InitDisplay in front for k==0.
- auto pre_block = [&](size_t k) {
- size_t lo = (k == 0) ? 0 : bursts[k - 1] + 1;
- return std::vector<Cmd>(image_stage.begin() + lo, image_stage.begin() + bursts[k]);
- };
- std::vector<Cmd> init_seq, window0, window1;
- std::vector<uint8_t> plane_cmds;
- bool per_plane = false;
- if (bursts.size() >= 2) {
- // Multi-plane. Two observed layouts:
- // interleaved: [init][W0][burst0][W1][burst1] - each plane's window
- // sits between its burst and the previous one (dual region);
- // batched: [init][W][W][burst0][burst1] - all windows precede all
- // bursts (SSD1680 3-colour: writeImage sets the black and
- // red RAM windows, then bursts both planes).
- for (size_t k = 0; k < bursts.size(); k++)
- plane_cmds.push_back(image_stage[bursts[k]].cmd);
- const size_t n = bursts.size();
- std::vector<Cmd> pre = pre_block(0);
- std::vector<std::vector<Cmd>> windows;
- bool interleaved = false;
- for (size_t k = 1; k < n; k++)
- if (bursts[k] - bursts[k - 1] > 1) {
- interleaved = true;
- break;
- }
- if (interleaved) {
- std::vector<Cmd> gap0(image_stage.begin() + bursts[0] + 1, image_stage.begin() + bursts[1]);
- const size_t wl = gap0.size();
- if (wl <= pre.size()) {
- windows.push_back(std::vector<Cmd>(pre.end() - wl, pre.end()));
- init_seq.assign(pre.begin(), pre.end() - wl);
- } else {
- windows.push_back({});
- init_seq = pre;
- }
- for (size_t k = 1; k < n; k++)
- windows.push_back(std::vector<Cmd>(image_stage.begin() + bursts[k - 1] + 1, image_stage.begin() + bursts[k]));
- } else {
- // Batched: pre = init + n copies of the window. Peel the smallest block
- // that repeats n times at the tail; the remainder is init.
- size_t L = 0;
- for (size_t cand = 1; cand * n <= pre.size(); cand++) {
- bool ok = true;
- for (size_t b = 0; b < n && ok; b++)
- for (size_t j = 0; j < cand && ok; j++) {
- const Cmd &a = pre[pre.size() - cand * n + b * cand + j];
- const Cmd &c = pre[pre.size() - cand + j];
- if (a.cmd != c.cmd || a.data != c.data)
- ok = false;
- }
- if (ok) {
- L = cand;
- break;
- }
- }
- if (L > 0) {
- for (size_t b = 0; b < n; b++)
- windows.push_back(std::vector<Cmd>(pre.end() - L * (n - b), pre.end() - L * (n - b - 1)));
- init_seq.assign(pre.begin(), pre.end() - L * n);
- } else {
- windows.push_back({});
- init_seq = pre;
- }
- }
- window0 = windows.empty() ? std::vector<Cmd>{} : windows[0];
- window1 = windows.size() > 1 ? windows[1] : std::vector<Cmd>{};
- for (size_t k = 1; k < windows.size(); k++)
- if (!cmds_equal(windows[0], windows[k]))
- per_plane = true; // per-plane windows differ => separate regions
- } else {
- // Single plane: window = the image call's pre-burst block; init comes
- // from the writeScreenBuffer stage, cut at the first window-set command
- // (SSD16xx sets the window there too - that belongs in window_sequence).
- const size_t wp = plane_index(image_stage);
- window0.assign(image_stage.begin(), image_stage.begin() + wp);
- std::set<uint8_t> wops;
- for (const auto &c : window0)
- wops.insert(c.cmd);
- const size_t ip = plane_index(init_stage);
- size_t cut = ip;
- for (size_t i = 0; i < ip; i++)
- if (wops.count(init_stage[i].cmd)) {
- cut = i;
- break;
- }
- init_seq.assign(init_stage.begin(), init_stage.begin() + cut);
- plane_cmds.push_back(wp < image_stage.size() ? image_stage[wp].cmd : 0x00);
- }
- // blank/clear fill byte, observed from the writeScreenBuffer clear burst.
- const size_t cip = plane_index(init_stage);
- const uint8_t clear_fill = (cip < init_stage.size() && !init_stage[cip].data.empty()) ? init_stage[cip].data[0] : 0x00;
- // plane_invert + 1bpp/packed detection, derived by the fill-capture probe.
- const uint8_t p0cmd = plane_cmds.empty() ? 0x00 : plane_cmds[0];
- const uint8_t p1cmd = plane_cmds.size() > 1 ? plane_cmds[1] : 0x00;
- const PlaneInvert pv = probe_plane_invert_values<Driver>(p0cmd, p1cmd, nplanes);
- // Refresh = post-write commands after the LAST burst (e.g. UC8179's 0x92),
- // then the refresh call minus any window-set it repeats.
- std::set<uint8_t> all_wops;
- for (const auto &c : window0)
- all_wops.insert(c.cmd);
- for (const auto &c : window1)
- all_wops.insert(c.cmd);
- std::vector<Cmd> refresh_seq;
- if (!bursts.empty())
- for (size_t i = bursts.back() + 1; i < image_stage.size() && image_stage[i].data.size() < PLANE_BURST_MIN; i++)
- refresh_seq.push_back(image_stage[i]);
- for (const auto &c : refresh_stage)
- if (!all_wops.count(c.cmd))
- refresh_seq.push_back(c);
- // --- emit ---
- printf("// GENERATED by emit_descriptor from %s - candidate, segmentation only.\n", class_name);
- printf("// bits_per_pixel/palette/plane_invert/plane_width/row_interleave still\n");
- printf("// come from the diag passes.\n");
- printf("#pragma once\n#include \"epd_command.h\"\n\nnamespace esphome::gxepd2 {\n\n");
- auto emit_seq = [&](const char *seqsuffix, std::vector<Cmd> &cmds) {
- for (size_t i = 0; i < cmds.size(); i++)
- if (!cmds[i].data.empty()) {
- char suf[64];
- snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
- print_data_array(macro, suf, cmds[i].data);
- }
- printf("\ninline const EpdCommand %s_%s[] = {\n", macro, seqsuffix);
- for (size_t i = 0; i < cmds.size(); i++) {
- char suf[64];
- snprintf(suf, sizeof(suf), "%s_%zu_%02X", seqsuffix, i, cmds[i].cmd);
- print_cmd(macro, suf, cmds[i]);
- }
- printf("};\n\n");
- };
- emit_seq("INIT", init_seq);
- emit_seq("WINDOW_SEQ0", window0);
- if (per_plane)
- emit_seq("WINDOW_SEQ1", window1);
- emit_seq("REFRESH", refresh_seq);
- printf("inline const EpdPanelDescriptor %s = {\n", macro);
- printf(" .width = %u,\n", (unsigned) Driver::WIDTH);
- printf(" .height = %u,\n", (unsigned) Driver::HEIGHT);
- printf(" .busy_active_level = %s,\n", bl == HIGH ? "true" : "false");
- printf(" .busy_timeout_ms = %u,\n", (unsigned) Driver::full_refresh_time + 5000u);
- printf(" .init_sequence = %s_INIT,\n", macro);
- printf(" .init_sequence_len = sizeof(%s_INIT) / sizeof(%s_INIT[0]),\n", macro, macro);
- if (per_plane) {
- printf(" .window_sequence = {%s_WINDOW_SEQ0, %s_WINDOW_SEQ1},\n", macro, macro);
- printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), "
- "sizeof(%s_WINDOW_SEQ1) / sizeof(%s_WINDOW_SEQ1[0])},\n",
- macro, macro, macro, macro);
- printf(" .window_per_plane = true, // per-plane windows differ => separate regions\n");
- } else {
- printf(" .window_sequence = {%s_WINDOW_SEQ0, nullptr},\n", macro);
- printf(" .window_sequence_len = {sizeof(%s_WINDOW_SEQ0) / sizeof(%s_WINDOW_SEQ0[0]), 0},\n", macro, macro);
- }
- printf(" .plane_count = %zu,\n", nplanes);
- printf(" .plane_write_cmd = {0x%02X, 0x%02X},\n", p0cmd, p1cmd);
- // Fields below are emitted in struct-declaration order (plane_invert,
- // plane_width, row_interleave, bits_per_pixel, palette, palette_len,
- // blank_code) so the designated initializer stays well-formed.
- if (pv.is_1bpp) {
- const bool i1 = (nplanes > 1 && pv.plane1_valid) ? pv.inv1 : false;
- printf(" .plane_invert = {%s, %s}, // probe-derived\n", pv.inv0 ? "true" : "false", i1 ? "true" : "false");
- } else {
- printf(" .plane_invert = {false, false}, // unused: packed panel\n");
- }
- if (per_plane)
- printf(" .plane_width = 0, // TODO: diag pass (separate-region width)\n");
- if (pv.is_1bpp) {
- // 1bpp plane model: depth confirmed by the probe; palette/blank_code unused.
- printf(" .bits_per_pixel = 1, // probe: white fill => all-bits wire byte 0x%02X\n", pv.w0_white & 0xFF);
- printf(" .palette = nullptr,\n");
- printf(" .palette_len = 0,\n");
- } else {
- // Packed panel: depth/palette/blank_code are the diag pass's job.
- printf(" .bits_per_pixel = 2, // TODO: diag pass - PACKED (white fill wire 0x%02X, not 1bpp)\n",
- pv.w0_white & 0xFF);
- printf(" .palette = nullptr, // TODO: diag pass\n");
- printf(" .palette_len = 0,\n");
- printf(" .blank_code = 0x00, // TODO: diag pass (clear fill observed 0x%02X)\n", clear_fill);
- }
- printf(" .refresh_sequence = %s_REFRESH,\n", macro);
- printf(" .refresh_sequence_len = sizeof(%s_REFRESH) / sizeof(%s_REFRESH[0]),\n", macro, macro);
- printf("};\n\n} // namespace esphome::gxepd2\n");
- }
- } // namespace emit
|