@typecad/framework-zephyr 1.0.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -0
  3. package/dist/async/timer-polyfill.d.ts +10 -0
  4. package/dist/async/timer-polyfill.js +95 -0
  5. package/dist/chips/controllers.d.ts +21 -0
  6. package/dist/chips/controllers.js +66 -0
  7. package/dist/chips/esp32.d.ts +2 -0
  8. package/dist/chips/esp32.js +59 -0
  9. package/dist/chips/esp32s3.d.ts +2 -0
  10. package/dist/chips/esp32s3.js +54 -0
  11. package/dist/chips/index.d.ts +15 -0
  12. package/dist/chips/index.js +45 -0
  13. package/dist/chips/resolve.d.ts +9 -0
  14. package/dist/chips/resolve.js +121 -0
  15. package/dist/chips/types.d.ts +154 -0
  16. package/dist/chips/types.js +14 -0
  17. package/dist/chips/xiao-ble.d.ts +2 -0
  18. package/dist/chips/xiao-ble.js +61 -0
  19. package/dist/debug-codegen.d.ts +33 -0
  20. package/dist/debug-codegen.js +162 -0
  21. package/dist/display/gfx.d.ts +17 -0
  22. package/dist/display/gfx.js +171 -0
  23. package/dist/display/index.d.ts +20 -0
  24. package/dist/display/index.js +53 -0
  25. package/dist/display/profiles.d.ts +25 -0
  26. package/dist/display/profiles.js +41 -0
  27. package/dist/display/touch-adapter.d.ts +9 -0
  28. package/dist/display/touch-adapter.js +95 -0
  29. package/dist/display/ui-adapter.d.ts +21 -0
  30. package/dist/display/ui-adapter.js +534 -0
  31. package/dist/dt-config/kconfig.d.ts +27 -0
  32. package/dist/dt-config/kconfig.js +283 -0
  33. package/dist/dt-config/overlay.d.ts +35 -0
  34. package/dist/dt-config/overlay.js +246 -0
  35. package/dist/framework.manifest.d.ts +98 -0
  36. package/dist/framework.manifest.js +525 -0
  37. package/dist/index.d.ts +5 -0
  38. package/dist/index.js +12 -0
  39. package/dist/lowering/adc.d.ts +19 -0
  40. package/dist/lowering/adc.js +76 -0
  41. package/dist/lowering/ble.d.ts +20 -0
  42. package/dist/lowering/ble.js +419 -0
  43. package/dist/lowering/board.d.ts +9 -0
  44. package/dist/lowering/board.js +33 -0
  45. package/dist/lowering/gpio.d.ts +12 -0
  46. package/dist/lowering/gpio.js +123 -0
  47. package/dist/lowering/http.d.ts +23 -0
  48. package/dist/lowering/http.js +482 -0
  49. package/dist/lowering/i2c.d.ts +15 -0
  50. package/dist/lowering/i2c.js +114 -0
  51. package/dist/lowering/index.d.ts +29 -0
  52. package/dist/lowering/index.js +93 -0
  53. package/dist/lowering/interrupts.d.ts +21 -0
  54. package/dist/lowering/interrupts.js +91 -0
  55. package/dist/lowering/mqtt.d.ts +19 -0
  56. package/dist/lowering/mqtt.js +366 -0
  57. package/dist/lowering/power.d.ts +9 -0
  58. package/dist/lowering/power.js +64 -0
  59. package/dist/lowering/preferences.d.ts +23 -0
  60. package/dist/lowering/preferences.js +345 -0
  61. package/dist/lowering/pulse.d.ts +7 -0
  62. package/dist/lowering/pulse.js +82 -0
  63. package/dist/lowering/pwm.d.ts +15 -0
  64. package/dist/lowering/pwm.js +59 -0
  65. package/dist/lowering/random.d.ts +18 -0
  66. package/dist/lowering/random.js +129 -0
  67. package/dist/lowering/spi.d.ts +17 -0
  68. package/dist/lowering/spi.js +113 -0
  69. package/dist/lowering/timing.d.ts +9 -0
  70. package/dist/lowering/timing.js +63 -0
  71. package/dist/lowering/tone.d.ts +10 -0
  72. package/dist/lowering/tone.js +50 -0
  73. package/dist/lowering/uart.d.ts +15 -0
  74. package/dist/lowering/uart.js +102 -0
  75. package/dist/lowering/util.d.ts +4 -0
  76. package/dist/lowering/util.js +12 -0
  77. package/dist/lowering/wdt.d.ts +15 -0
  78. package/dist/lowering/wdt.js +80 -0
  79. package/dist/lowering/wifi.d.ts +21 -0
  80. package/dist/lowering/wifi.js +447 -0
  81. package/dist/lowering/worker-backing.d.ts +14 -0
  82. package/dist/lowering/worker-backing.js +79 -0
  83. package/dist/lowering/worker.d.ts +6 -0
  84. package/dist/lowering/worker.js +14 -0
  85. package/dist/strategy.d.ts +168 -0
  86. package/dist/strategy.js +1094 -0
  87. package/dist/toolchain/debug-config.d.ts +82 -0
  88. package/dist/toolchain/debug-config.js +359 -0
  89. package/dist/toolchain/index.d.ts +73 -0
  90. package/dist/toolchain/index.js +427 -0
  91. package/dist/toolchain/scaffold.d.ts +15 -0
  92. package/dist/toolchain/scaffold.js +196 -0
  93. package/dist/toolchain/west-discover.d.ts +40 -0
  94. package/dist/toolchain/west-discover.js +203 -0
  95. package/dist/toolchain/west-spawn.d.ts +39 -0
  96. package/dist/toolchain/west-spawn.js +117 -0
  97. package/package.json +82 -0
  98. package/src/async/timer-polyfill.ts +107 -0
  99. package/src/chips/controllers.ts +74 -0
  100. package/src/chips/esp32.ts +62 -0
  101. package/src/chips/esp32s3.ts +57 -0
  102. package/src/chips/index.ts +54 -0
  103. package/src/chips/resolve.ts +146 -0
  104. package/src/chips/types.ts +163 -0
  105. package/src/chips/xiao-ble.ts +64 -0
  106. package/src/debug-codegen.ts +207 -0
  107. package/src/display/gfx.ts +190 -0
  108. package/src/display/index.ts +70 -0
  109. package/src/display/profiles.ts +63 -0
  110. package/src/display/touch-adapter.ts +100 -0
  111. package/src/display/ui-adapter.ts +558 -0
  112. package/src/dt-config/kconfig.ts +308 -0
  113. package/src/dt-config/overlay.ts +293 -0
  114. package/src/framework.manifest.ts +545 -0
  115. package/src/index.ts +23 -0
  116. package/src/lowering/adc.ts +102 -0
  117. package/src/lowering/ble.ts +426 -0
  118. package/src/lowering/board.ts +38 -0
  119. package/src/lowering/gpio.ts +148 -0
  120. package/src/lowering/http.ts +488 -0
  121. package/src/lowering/i2c.ts +126 -0
  122. package/src/lowering/index.ts +86 -0
  123. package/src/lowering/interrupts.ts +114 -0
  124. package/src/lowering/mqtt.ts +371 -0
  125. package/src/lowering/power.ts +70 -0
  126. package/src/lowering/preferences.ts +354 -0
  127. package/src/lowering/pulse.ts +93 -0
  128. package/src/lowering/pwm.ts +74 -0
  129. package/src/lowering/random.ts +135 -0
  130. package/src/lowering/spi.ts +124 -0
  131. package/src/lowering/timing.ts +72 -0
  132. package/src/lowering/tone.ts +60 -0
  133. package/src/lowering/uart.ts +111 -0
  134. package/src/lowering/util.ts +12 -0
  135. package/src/lowering/wdt.ts +84 -0
  136. package/src/lowering/wifi.ts +452 -0
  137. package/src/lowering/worker-backing.ts +94 -0
  138. package/src/lowering/worker.ts +17 -0
  139. package/src/strategy.ts +1265 -0
  140. package/src/toolchain/debug-config.ts +399 -0
  141. package/src/toolchain/index.ts +459 -0
  142. package/src/toolchain/scaffold.ts +196 -0
  143. package/src/toolchain/west-discover.ts +233 -0
  144. package/src/toolchain/west-spawn.ts +141 -0
@@ -0,0 +1,558 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Zephyr UI display adapter for the Cuttlefish UI rendering pipeline.
3
+ //
4
+ // Bridges the in-tree CuttlefishGFX/CuttlefishCanvas16 class (emitted by the
5
+ // runtime header's cuttlefish-gfx slice) to the ST7796S panel. The panel is
6
+ // driven DIRECTLY over the SPI controller with GPIO chip-select, DC and reset
7
+ // pins — NOT through Zephyr's mipi-dbi-spi bridge: that bridge issues separate
8
+ // SPI transactions for the command byte and its parameters (CS deasserts
9
+ // between them), which scrambles this panel's command decoder and leaves it
10
+ // white. Verified on hardware: the direct protocol (CS held low across the
11
+ // command+data burst, DC toggled mid-burst — the Adafruit ST77xx protocol)
12
+ // initializes the panel and renders pixels correctly.
13
+ //
14
+ // This is the Zephyr analog of the Adafruit adapters in framework-arduino,
15
+ // using the in-tree native GFX class (no #define CuttlefishCanvas16) driven
16
+ // through a CuttlefishPanelOps function-pointer vtable.
17
+ //
18
+ // EMIT BOUNDARY: emitted bytes land in user firmware. Covered by the TypeCAD
19
+ // Runtime Exception (RUNTIME_EXCEPTION.md at the repo root).
20
+ //
21
+ // AGENTS.md rendering guardrails: the line buffer is one row (reused, not
22
+ // per-frame allocated); fillRect writes row-by-row. Pixel bursts use 16-bit
23
+ // SPI words (MSB-first on the wire = RGB565 big-endian, no byte swap).
24
+ // ---------------------------------------------------------------------------
25
+
26
+ import type { DisplayAdapterCode, DisplayAdapterGenerator } from "@typecad/cuttlefish/api/shared";
27
+ import { ZEPHYR_DISPLAY_PROFILES } from "./profiles.js";
28
+ import type { ZephyrDisplayProfile } from "./profiles.js";
29
+
30
+ /**
31
+ * Build the Zephyr UI display adapter for a profile. Emits the full
32
+ * display_ / display_target_ / display_canvas_ surface the UI runtime expects,
33
+ * driving the panel directly via SPI (CS held across command+data).
34
+ */
35
+ export interface ZephyrDisplayReadbackOptions {
36
+ /** Enable the controller GET_SCANLINE dirty-rectangle experiment. */
37
+ scanlineSync?: boolean;
38
+ /** MISO/SDO GPIO; readback is disabled when it is not explicitly wired. */
39
+ miso?: number;
40
+ }
41
+
42
+ export function zephyrUiDisplayAdapter(
43
+ profile: ZephyrDisplayProfile,
44
+ readback: ZephyrDisplayReadbackOptions = {},
45
+ ): DisplayAdapterCode {
46
+ const w = profile.width;
47
+ const h = profile.height;
48
+ const maxDim = Math.max(w, h);
49
+ const dtLabel = profile.dtLabel;
50
+ const backlightAlias = profile.backlight;
51
+ // Never infer readback from a board's default pinmux. SDO/MISO may be left
52
+ // floating or shared with another device, and ST7796S modules are known to
53
+ // react badly to GSCAN reads. Both an explicit opt-in and an explicit MISO
54
+ // pin are required before emitting an active synchronization path.
55
+ const scanlineSync = readback.scanlineSync === true && readback.miso !== undefined;
56
+
57
+ const includes = [
58
+ `// --- Zephyr UI display adapter (${profile.driver}) ---`,
59
+ `// Native CuttlefishGFX path: do NOT #define CuttlefishCanvas16 so the`,
60
+ `// runtime header emits the in-tree CuttlefishGFX/CuttlefishCanvas16 class.`,
61
+ `#define CuttlefishDisplayTarget CuttlefishGFX`,
62
+ `#include <zephyr/kernel.h>`,
63
+ `#include <zephyr/drivers/display.h>`,
64
+ `#include <zephyr/drivers/spi.h>`,
65
+ `#include <zephyr/drivers/gpio.h>`,
66
+ ].join("\n");
67
+
68
+ const declaration = [
69
+ `// CUTTLEFISH_DISPLAY_BEGIN`,
70
+ // The display0 DT node carries frequency/dimensions for DT_PROP reads, but
71
+ // the panel is driven directly via spi_write — no Zephyr display device is
72
+ // needed. Using a constant 1 avoids the ST7796S driver binding (which
73
+ // allocates a tearing-effect GPIO interrupt that conflicts with the SPI/I2C
74
+ // interrupts — the VECDESC_FL_SHARED assertion crash on the 3rd frame).
75
+ `#define __tc_display_dev 1`,
76
+ `// One-row scratch buffer in 18-bit (666) wire format: maxDim px x 3 bytes.`,
77
+ `// Reused across fillRect/draw calls — never per-frame (AGENTS.md: no`,
78
+ `// per-frame heap allocation). The panel is driven in 18-bit mode (COLMOD`,
79
+ `// 0x66): its 16-bit (565) channel routing is crossed (G/B swap, verified`,
80
+ `// with calibration bands), while 18-bit mode routes every channel`,
81
+ `// correctly with plain (R,G,B) byte order.`,
82
+ `static uint8_t __tc_display_row3[${maxDim} * 3];`,
83
+ `// Multi-row block buffer for solid fills (8 rows of maxDim px in 18-bit).`,
84
+ `// fillRect fills this once with the color, then sends the whole rect in a`,
85
+ `// few large spi_write chunks instead of one spi_write per row — a full`,
86
+ `// 480x320 clear went from ~320 syscalls (~110ms) to ~40 (~15ms). Reused,`,
87
+ `// not per-frame (AGENTS.md).`,
88
+ `#define __TC_FILL_ROWS 8`,
89
+ `static uint8_t __tc_display_block3[${maxDim} * 3 * __TC_FILL_ROWS];`,
90
+ `// startWrite/endWrite batching depth. When > 0 the panel CS is held asserted`,
91
+ `// (low) across multiple primitives — DC still toggles mid-burst, but CS does`,
92
+ `// not, matching the Adafruit ST77xx protocol and avoiding one full CS-toggle`,
93
+ `// SPI transaction per primitive. The runtime brackets whole canvas pushes`,
94
+ `// and per-node repaints in display_startWrite/endWrite pairs.`,
95
+ `static uint8_t __tc_pnl_write_depth = 0;`,
96
+ `// Scanline readback is deliberately opt-in. A verified SDO/MISO wire and`,
97
+ `// controller-specific validation are required; otherwise the display stays`,
98
+ `// on the existing retained/composited path with no extra SPI reads.`,
99
+ `static const bool __tc_pnl_scanline_sync = ${scanlineSync ? 'true' : 'false'};`,
100
+ `// Stashed address window from the last setAddrWindow call. The runtime`,
101
+ `// calls setAddrWindow + writePixels as a matched pair, so we stash the rect`,
102
+ `// here and consume it in writePixels.`,
103
+ `static int16_t __tc_aw_x = 0;`,
104
+ `static int16_t __tc_aw_y = 0;`,
105
+ `static int16_t __tc_aw_w = ${w};`,
106
+ `static int16_t __tc_aw_h = ${h};`,
107
+ `// CUTTLEFISH_DISPLAY_END`,
108
+ ].join("\n");
109
+
110
+ // Backlight: drive it as a raw GPIO output. The DT alias points at a
111
+ // gpio-leds node whose 'gpios' property is a phandle to the GPIO controller
112
+ // + pin. GPIO_DT_SPEC_GET resolves that phandle into a gpio_dt_spec. The
113
+ // overlay only emits this alias when a backlight GPIO is configured, so guard
114
+ // with DT_HAS_ALIAS (the safe primitive for an alias that may be absent —
115
+ // DT_NODE_HAS_STATUS(DT_ALIAS(...)) is version-dependent when the alias is
116
+ // missing and can fail the build).
117
+ const blInit = backlightAlias
118
+ ? `#if DT_HAS_ALIAS(${backlightAlias})\n const struct gpio_dt_spec __bl = GPIO_DT_SPEC_GET(DT_ALIAS(${backlightAlias}), gpios);\n if (device_is_ready(__bl.port)) { gpio_pin_configure_dt(&__bl, GPIO_OUTPUT_ACTIVE); }\n#endif`
119
+ : '';
120
+
121
+ const functions = `
122
+ // ── Direct panel transport ──────────────────────────────────────────────
123
+ // GPIOs: CS/DC/RST driven manually; CS stays LOW for the whole command+data
124
+ // burst (DC toggles between command byte and parameters/pixels), matching the
125
+ // Adafruit ST77xx protocol this panel requires. The SPI config carries no CS
126
+ // (cs_is_gpio = false -> the ESP32 driver's hardware CSEL pin is left idle;
127
+ // it is not connected to the panel).
128
+ static const struct gpio_dt_spec __tc_pnl_cs = GPIO_DT_SPEC_GET(DT_NODELABEL(spi2), cs_gpios);
129
+ static const struct gpio_dt_spec __tc_pnl_dc = GPIO_DT_SPEC_GET(DT_NODELABEL(mipi_dbi), dc_gpios);
130
+ static const struct gpio_dt_spec __tc_pnl_rst = GPIO_DT_SPEC_GET(DT_NODELABEL(mipi_dbi), reset_gpios);
131
+
132
+ // 8-bit frames for commands/parameters and 18-bit (3 bytes/pixel) pixel data.
133
+ static struct spi_config __tc_pnl_cfg8 = {
134
+ .frequency = DT_PROP(DT_NODELABEL(${dtLabel}), mipi_max_frequency),
135
+ .operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8),
136
+ .slave = 0,
137
+ };
138
+
139
+ // Assert CS (active=low) unless a startWrite/endWrite batch already holds it.
140
+ static inline void __tc_pnl_cs_assert(void) {
141
+ if (__tc_pnl_write_depth == 0U) { gpio_pin_set_dt(&__tc_pnl_cs, 1); }
142
+ }
143
+ // Deassert CS unless a startWrite/endWrite batch is still holding it.
144
+ static inline void __tc_pnl_cs_release(void) {
145
+ if (__tc_pnl_write_depth == 0U) { gpio_pin_set_dt(&__tc_pnl_cs, 0); }
146
+ }
147
+
148
+ // Write one command byte (DC low) + its parameters (DC high). CS is asserted
149
+ // for the burst unless an outer startWrite is already holding it.
150
+ static void __tc_pnl_cmd(uint8_t cmd, const uint8_t* data, uint16_t len) {
151
+ struct spi_buf __bc = { &cmd, 1 };
152
+ struct spi_buf_set __sc = { &__bc, 1 };
153
+ __tc_pnl_cs_assert();
154
+ gpio_pin_set_dt(&__tc_pnl_dc, 0);
155
+ (void)spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sc);
156
+ if (len > 0) {
157
+ struct spi_buf __bd = { const_cast<uint8_t*>(data), len };
158
+ struct spi_buf_set __sd = { &__bd, 1 };
159
+ gpio_pin_set_dt(&__tc_pnl_dc, 1);
160
+ (void)spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sd);
161
+ }
162
+ __tc_pnl_cs_release();
163
+ }
164
+
165
+ // Open a RAMWR burst: CS low, RAMWR command, DC high for the pixel data.
166
+ static void __tc_pnl_ramwr_begin(void) {
167
+ uint8_t __ramwr = 0x2C;
168
+ struct spi_buf __bc = { &__ramwr, 1 };
169
+ struct spi_buf_set __sc = { &__bc, 1 };
170
+ __tc_pnl_cs_assert();
171
+ gpio_pin_set_dt(&__tc_pnl_dc, 0);
172
+ (void)spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sc);
173
+ gpio_pin_set_dt(&__tc_pnl_dc, 1);
174
+ }
175
+
176
+ static void __tc_pnl_ramwr_end(void) { __tc_pnl_cs_release(); }
177
+
178
+ // Read ST7796S/ILI9341 GET_SCANLINE (0x45). These controllers return one
179
+ // dummy byte followed by the 16-bit scanline. Some modules do not implement
180
+ // readback correctly; 0xFFFF means "unknown" and disables waiting for that
181
+ // update rather than stalling or corrupting the frame.
182
+ static uint16_t __tc_pnl_read_scanline(void) {
183
+ if (!__tc_pnl_scanline_sync) return 0xFFFFu;
184
+ uint8_t __cmd = 0x45;
185
+ uint8_t __tx[3] = {0, 0, 0};
186
+ uint8_t __rx[3] = {0, 0, 0};
187
+ struct spi_buf __bc = { &__cmd, 1 };
188
+ struct spi_buf_set __sc = { &__bc, 1 };
189
+ struct spi_buf __bt = { __tx, sizeof(__tx) };
190
+ struct spi_buf __br = { __rx, sizeof(__rx) };
191
+ struct spi_buf_set __st = { &__bt, 1 };
192
+ struct spi_buf_set __sr = { &__br, 1 };
193
+ __tc_pnl_cs_assert();
194
+ gpio_pin_set_dt(&__tc_pnl_dc, 0);
195
+ int __cmd_err = spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sc);
196
+ int __read_err = 0;
197
+ if (__cmd_err == 0) {
198
+ gpio_pin_set_dt(&__tc_pnl_dc, 1);
199
+ __read_err = spi_transceive(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__st, &__sr);
200
+ }
201
+ __tc_pnl_cs_release();
202
+ if (__cmd_err != 0 || __read_err != 0) return 0xFFFFu;
203
+ uint16_t __line = static_cast<uint16_t>((static_cast<uint16_t>(__rx[1]) << 8) | __rx[2]);
204
+ return (__line < ${h}) ? __line : 0xFFFFu;
205
+ }
206
+
207
+ // Wait until the panel has scanned past a dirty rectangle. This is intentionally
208
+ // bounded: a broken/floating SDO must never hang the UI loop. Full-height writes
209
+ // have no safe post-rectangle interval, so they retain the normal single-burst
210
+ // behavior; the caller's framebuffer still prevents intermediate software frames.
211
+ static void __tc_pnl_wait_for_safe_rect(int16_t y, int16_t rh) {
212
+ if (!__tc_pnl_scanline_sync || rh < 8 || y < 0) return;
213
+ int16_t __last = static_cast<int16_t>(y + rh - 1);
214
+ if (__last >= static_cast<int16_t>(${h} - 2)) return;
215
+ uint32_t __deadline = k_uptime_get_32() + 20U;
216
+ for (;;) {
217
+ uint16_t __line = __tc_pnl_read_scanline();
218
+ if (__line == 0xFFFFu || (__line > static_cast<uint16_t>(__last + 2) && __line < static_cast<uint16_t>(${h} - 2))) return;
219
+ if (static_cast<int32_t>(k_uptime_get_32() - __deadline) >= 0) return;
220
+ k_msleep(0);
221
+ }
222
+ }
223
+
224
+ // Pack count rgb565 pixels into the row3 scratch buffer as 18-bit (666) wire
225
+ // format: (r<<3, g<<2, b<<3) — R,G,B byte order, verified correct on this
226
+ // panel in 18-bit mode. The caller then streams the buffer with the 8-bit
227
+ // config (one row at a time; the buffer holds maxDim pixels).
228
+ static void __tc_pnl_pack666(const uint16_t* px, uint32_t count) {
229
+ for (uint32_t i = 0; i < count; i++) {
230
+ uint16_t c = px[i];
231
+ __tc_display_row3[i * 3] = static_cast<uint8_t>((c >> 8) & 0xF8u);
232
+ __tc_display_row3[i * 3 + 1] = static_cast<uint8_t>((c >> 3) & 0xFCu);
233
+ __tc_display_row3[i * 3 + 2] = static_cast<uint8_t>((c << 3) & 0xF8u);
234
+ }
235
+ }
236
+
237
+ // Stream count rgb565 pixels to the panel (converted to 18-bit, chunked
238
+ // through the row3 scratch). Caller holds the RAMWR burst.
239
+ static void __tc_pnl_pixels666(const uint16_t* px, uint32_t count) {
240
+ while (count > 0) {
241
+ uint32_t __chunk = (count > ${maxDim}) ? ${maxDim} : count;
242
+ __tc_pnl_pack666(px, __chunk);
243
+ struct spi_buf __bd = { __tc_display_row3, static_cast<size_t>(__chunk) * 3U };
244
+ struct spi_buf_set __sd = { &__bd, 1 };
245
+ (void)spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sd);
246
+ px += __chunk;
247
+ count -= __chunk;
248
+ }
249
+ }
250
+
251
+ // Set the address window. Coordinates are in the effective (rotated) UI
252
+ // space; the panel's MADCTL (rotation 1: MV) maps them onto the native
253
+ // 320x480 raster, so CASET/RASET take the UI x/y ranges directly.
254
+ static void __tc_pnl_set_window(int16_t x, int16_t y, int16_t winW, int16_t winH) {
255
+ __tc_pnl_wait_for_safe_rect(y, winH);
256
+ uint16_t __x0 = static_cast<uint16_t>(x);
257
+ uint16_t __x1 = static_cast<uint16_t>(x + winW - 1);
258
+ uint16_t __y0 = static_cast<uint16_t>(y);
259
+ uint16_t __y1 = static_cast<uint16_t>(y + winH - 1);
260
+ uint8_t __ca[4] = { static_cast<uint8_t>(__x0 >> 8), static_cast<uint8_t>(__x0),
261
+ static_cast<uint8_t>(__x1 >> 8), static_cast<uint8_t>(__x1) };
262
+ uint8_t __ra[4] = { static_cast<uint8_t>(__y0 >> 8), static_cast<uint8_t>(__y0),
263
+ static_cast<uint8_t>(__y1 >> 8), static_cast<uint8_t>(__y1) };
264
+ __tc_pnl_cmd(0x2A, __ca, 4);
265
+ __tc_pnl_cmd(0x2B, __ra, 4);
266
+ }
267
+
268
+ // ── Panel-ops consumed by CuttlefishGFX ─────────────────────────────────
269
+ // startWrite/endWrite batch multiple primitives under one CS-asserted burst
270
+ // (Adafruit ST77xx protocol: CS held low across the burst, DC toggles
271
+ // mid-burst). A depth counter supports nested startWrite calls — the runtime
272
+ // sometimes wraps a canvas push inside an outer transaction. Only the
273
+ // outermost startWrite asserts CS and the outermost endWrite releases it;
274
+ // inner ones just bump the depth. This collapses per-primitive CS-toggle
275
+ // overhead (one transaction per burst instead of one per rect/glyph row).
276
+ static void __tc_op_startWrite(void* /*ctx*/) {
277
+ if (__tc_pnl_write_depth == 0U) { gpio_pin_set_dt(&__tc_pnl_cs, 1); }
278
+ __tc_pnl_write_depth++;
279
+ }
280
+ static void __tc_op_endWrite(void* /*ctx*/) {
281
+ if (__tc_pnl_write_depth > 0U) {
282
+ __tc_pnl_write_depth--;
283
+ if (__tc_pnl_write_depth == 0U) { gpio_pin_set_dt(&__tc_pnl_cs, 0); }
284
+ }
285
+ }
286
+
287
+ // Stash the target rect. The runtime always follows this with writePixels
288
+ // delivering exactly (w*h) pixels for this rect, OR fillRect/writePixel which
289
+ // ignore the stash.
290
+ static void __tc_op_setAddrWindow(void* /*ctx*/, int16_t x, int16_t y, int16_t winW, int16_t winH) {
291
+ __tc_aw_x = x; __tc_aw_y = y; __tc_aw_w = winW; __tc_aw_h = winH;
292
+ }
293
+
294
+ // Push the stashed rect's worth of rgb565 pixels. Called right after
295
+ // setAddrWindow with exactly (aw_w * aw_h) pixels. The caller's buffer is
296
+ // never mutated (scroll canvases persist across frames), so pixels are
297
+ // converted in chunks through the row3 scratch buffer.
298
+ static void __tc_op_writePixels(void* /*ctx*/, const uint16_t* px, uint32_t n) {
299
+ if (n == 0U) return;
300
+ __tc_pnl_set_window(__tc_aw_x, __tc_aw_y, __tc_aw_w, __tc_aw_h);
301
+ __tc_pnl_ramwr_begin();
302
+ __tc_pnl_pixels666(px, n);
303
+ __tc_pnl_ramwr_end();
304
+ }
305
+
306
+ // Single pixel: write a 1x1 rect.
307
+ static void __tc_op_writePixel(void* /*ctx*/, int16_t x, int16_t y, uint16_t c) {
308
+ uint16_t __c = c;
309
+ __tc_pnl_set_window(x, y, 1, 1);
310
+ __tc_pnl_ramwr_begin();
311
+ __tc_pnl_pixels666(&__c, 1);
312
+ __tc_pnl_ramwr_end();
313
+ }
314
+
315
+ // Fill a rect row-by-row using the one-row 18-bit scratch buffer. This is the
316
+ // hot path for background clears and large fills; building the color into the
317
+ // reused buffer and writing each row keeps memory bounded.
318
+ // Fill a rect with a solid color. The 18-bit row is tiled into the block buffer
319
+ // (__TC_FILL_ROWS rows), then the whole rect is sent in multi-row spi_write
320
+ // chunks. A full 480x320 clear is ~40 writes instead of ~320, dropping it from
321
+ // ~110ms to ~15ms — the ESP32 SPI driver's per-transaction overhead (not SPI
322
+ // bandwidth) is the binding cost, so fewer/larger writes win. Scatter-gather
323
+ // descriptor lists tested slower (the driver walks each descriptor), so this
324
+ // uses one contiguous buffer per write.
325
+ static void __tc_op_fillRect(void* /*ctx*/, int16_t x, int16_t y, int16_t rw, int16_t rh, uint16_t c) {
326
+ if (rw <= 0 || rh <= 0) return;
327
+ uint8_t __b0 = static_cast<uint8_t>((c >> 8) & 0xF8u);
328
+ uint8_t __b1 = static_cast<uint8_t>((c >> 3) & 0xFCu);
329
+ uint8_t __b2 = static_cast<uint8_t>((c << 3) & 0xF8u);
330
+ // Build one 18-bit row, then tile it into the block buffer.
331
+ for (int16_t i = 0; i < rw; i++) {
332
+ __tc_display_row3[i * 3] = __b0;
333
+ __tc_display_row3[i * 3 + 1] = __b1;
334
+ __tc_display_row3[i * 3 + 2] = __b2;
335
+ }
336
+ size_t rowBytes = static_cast<size_t>(rw) * 3U;
337
+ for (int16_t r = 0; r < __TC_FILL_ROWS; r++) {
338
+ memcpy(&__tc_display_block3[static_cast<size_t>(r) * rowBytes], __tc_display_row3, rowBytes);
339
+ }
340
+ __tc_pnl_set_window(x, y, rw, rh);
341
+ __tc_pnl_ramwr_begin();
342
+ int16_t remaining = rh;
343
+ while (remaining > 0) {
344
+ int16_t chunk = (remaining > __TC_FILL_ROWS) ? __TC_FILL_ROWS : remaining;
345
+ struct spi_buf __bd = { __tc_display_block3, static_cast<size_t>(chunk) * rowBytes };
346
+ struct spi_buf_set __sd = { &__bd, 1 };
347
+ (void)spi_write(DEVICE_DT_GET(DT_NODELABEL(spi2)), &__tc_pnl_cfg8, &__sd);
348
+ remaining -= chunk;
349
+ }
350
+ __tc_pnl_ramwr_end();
351
+ }
352
+
353
+ static int16_t __tc_op_width(void* /*ctx*/) { return ${w}; }
354
+ static int16_t __tc_op_height(void* /*ctx*/) { return ${h}; }
355
+
356
+ // flush is nullptr — direct-mode panel (TFT), no backing store to push.
357
+ struct CuttlefishPanelOps;
358
+ extern const CuttlefishPanelOps __tc_display_ops;
359
+
360
+ const CuttlefishPanelOps __tc_display_ops = {
361
+ __tc_op_startWrite,
362
+ __tc_op_endWrite,
363
+ __tc_op_setAddrWindow,
364
+ __tc_op_writePixels,
365
+ __tc_op_writePixel,
366
+ __tc_op_fillRect,
367
+ __tc_op_width,
368
+ __tc_op_height,
369
+ nullptr, // flush — direct-mode panel
370
+ };
371
+
372
+ // The live display target: a CuttlefishGFX driven by the panel-ops vtable.
373
+ CuttlefishGFX __tc_display(&__tc_display_ops, nullptr);
374
+
375
+ // ── Panel init ──────────────────────────────────────────────────────────
376
+ // Adafruit ST7796S init sequence (demo-st lib fork), byte for byte: hw reset
377
+ // pulse, SWRESET, manufacturer unlock, VCOM/MADCTL/COLMOD/porch registers,
378
+ // lock, SLPOUT (150ms), DISPON (150ms), INVOFF. MADCTL 0x28 = MV (rotation 1
379
+ // landscape) + BGR=1. BGR=1 makes the controller route data R/B to the
380
+ // B/R subpixels (verified: red data shows blue with BGR=1), which combined
381
+ // with a lossless R/B data swap renders the UI correctly; BGR=0 leaves a
382
+ // half-lossy G/B quirk on this clone controller.
383
+ struct __tc_pnl_init_cmd { uint8_t cmd; uint8_t len; const uint8_t* data; uint16_t delay_ms; };
384
+ static const uint8_t __tc_pnl_i1[] = {0xC3};
385
+ static const uint8_t __tc_pnl_i2[] = {0x96};
386
+ static const uint8_t __tc_pnl_i3[] = {0x1C};
387
+ static const uint8_t __tc_pnl_i4[] = {0x28};
388
+ static const uint8_t __tc_pnl_i5[] = {0x66};
389
+ static const uint8_t __tc_pnl_i6[] = {0x80};
390
+ static const uint8_t __tc_pnl_i7[] = {0x00};
391
+ static const uint8_t __tc_pnl_i8[] = {0x80, 0x02, 0x3B};
392
+ static const uint8_t __tc_pnl_i9[] = {0xC6};
393
+ static const uint8_t __tc_pnl_i10[] = {0x69};
394
+ static const uint8_t __tc_pnl_i11[] = {0x3C};
395
+ static const struct __tc_pnl_init_cmd __tc_pnl_init_seq[] = {
396
+ {0x01, 0, NULL, 150}, // SWRESET
397
+ {0xF0, 1, __tc_pnl_i1, 0}, // unlock manufacturer
398
+ {0xF0, 1, __tc_pnl_i2, 0},
399
+ {0xC5, 1, __tc_pnl_i3, 0}, // VCOM control
400
+ {0x36, 1, __tc_pnl_i4, 0}, // MADCTL 0x28: MV (rotation 1) + BGR=1
401
+ {0x3A, 1, __tc_pnl_i5, 0}, // COLMOD 0x66 (18-bit, 262K) — clean channel routing
402
+ {0xB0, 1, __tc_pnl_i6, 0}, // interface control
403
+ {0xB4, 1, __tc_pnl_i7, 0}, // inversion control
404
+ {0xB6, 3, __tc_pnl_i8, 0}, // display function control
405
+ {0xB7, 1, __tc_pnl_i9, 0}, // entry mode
406
+ {0xF0, 1, __tc_pnl_i10, 0}, // lock manufacturer
407
+ {0xF0, 1, __tc_pnl_i11, 0},
408
+ {0x11, 0, NULL, 150}, // SLPOUT (sleep out — 120ms typical)
409
+ {0x29, 0, NULL, 150}, // DISPON
410
+ {0x20, 0, NULL, 0}, // INVOFF (non-inverted at power-on)
411
+ };
412
+
413
+ // ── display_init (called from setup) ────────────────────────────────────
414
+ static inline void display_init() {
415
+ printk("TC_DISPLAY: device ready\\n");
416
+ ${blInit}
417
+ gpio_pin_configure_dt(&__tc_pnl_cs, GPIO_OUTPUT);
418
+ gpio_pin_configure_dt(&__tc_pnl_dc, GPIO_OUTPUT);
419
+ gpio_pin_configure_dt(&__tc_pnl_rst, GPIO_OUTPUT);
420
+ // Hardware reset pulse (Adafruit init behavior).
421
+ gpio_pin_set_dt(&__tc_pnl_rst, 1);
422
+ k_msleep(20);
423
+ gpio_pin_set_dt(&__tc_pnl_rst, 0);
424
+ k_msleep(20);
425
+ // Adafruit init sequence, direct protocol.
426
+ for (uint32_t i = 0; i < (sizeof(__tc_pnl_init_seq) / sizeof(__tc_pnl_init_seq[0])); i++) {
427
+ __tc_pnl_cmd(__tc_pnl_init_seq[i].cmd, __tc_pnl_init_seq[i].data,
428
+ __tc_pnl_init_seq[i].len);
429
+ if (__tc_pnl_init_seq[i].delay_ms > 0) k_msleep(__tc_pnl_init_seq[i].delay_ms);
430
+ }
431
+ __tc_op_fillRect(nullptr, 0, 0, ${w}, ${h}, 0x0000);
432
+ printk("TC_DISPLAY: direct init done (18-bit, black fill)\\n");
433
+ }
434
+
435
+ static inline void display_fillScreen(UI_COLOR_T color) {
436
+ __tc_op_fillRect(nullptr, 0, 0, ${w}, ${h}, static_cast<uint16_t>(color));
437
+ }
438
+ static inline CuttlefishDisplayTarget* display_defaultTarget() { return &__tc_display; }
439
+ static inline int16_t display_width() { return ${w}; }
440
+ static inline int16_t display_height() { return ${h}; }
441
+
442
+ static inline void display_startWrite() { __tc_op_startWrite(nullptr); }
443
+ static inline void display_endWrite() { __tc_op_endWrite(nullptr); }
444
+ static inline void display_setAddrWindow(int16_t x, int16_t y, int16_t winW, int16_t winH) {
445
+ __tc_op_setAddrWindow(nullptr, x, y, winW, winH);
446
+ }
447
+ static inline void display_writePixels(uint16_t* pixels, uint32_t count) {
448
+ __tc_op_writePixels(nullptr, pixels, count);
449
+ }
450
+
451
+ // ── Canvas lifecycle + accessors (offscreen rgb565 compositing) ──────────
452
+ // Allocate the canvas object via malloc + placement-new (not operator new).
453
+ // Under CONFIG_REQUIRES_FULL_LIBCPP without CONFIG_CPP_EXCEPTIONS, operator new
454
+ // throws std::bad_alloc on OOM and the nothrow wrapper's internal catch cannot
455
+ // unwind (no EH runtime) → std::terminate → abort. malloc returns NULL on
456
+ // failure with no exception path; placement-new then constructs the object in
457
+ // place (vtable included). display_deleteCanvas mirrors with an explicit dtor
458
+ // + free. The runtime's callers already null-check the return, so an OOM
459
+ // degrades gracefully instead of aborting.
460
+ static inline CuttlefishCanvas16* display_createCanvas(int16_t cw, int16_t ch) {
461
+ void* mem = malloc(sizeof(CuttlefishCanvas16));
462
+ if (!mem) return nullptr;
463
+ return new (mem) CuttlefishCanvas16(cw, ch);
464
+ }
465
+ // psramFound() shim: the Arduino ESP32 core provides this, but Zephyr does not.
466
+ // Under BOARD_HAS_PSRAM the ESP heap serves PSRAM, so report it as present. The
467
+ // runtime's ui_create_canvas_best calls this under #if defined(BOARD_HAS_PSRAM).
468
+ #if defined(BOARD_HAS_PSRAM) && !defined(psramFound)
469
+ #include <zephyr/multi_heap/shared_multi_heap.h>
470
+ static inline bool psramFound() {
471
+ // Compile-time truth: if BOARD_HAS_PSRAM is defined, the build targets a
472
+ // PSRAM board with CONFIG_ESP_SPIRAM enabled (the framework emits both).
473
+ return true;
474
+ }
475
+ // Allocate from PSRAM via Zephyr's shared multi-heap (the ESP32 SoC code
476
+ // registers PSRAM as an SMH_REG_ATTR_EXTERNAL region at boot).
477
+ static inline void* ui_psram_malloc(size_t bytes) {
478
+ return shared_multi_heap_alloc(SMH_REG_ATTR_EXTERNAL, bytes);
479
+ }
480
+ #endif
481
+ static inline CuttlefishCanvas16* display_createCanvasPsram(int16_t cw, int16_t ch) {
482
+ // Allocate the pixel buffer in PSRAM (large: w*h*2 bytes) and the small
483
+ // canvas object in SRAM. The canvas takes ownership of the PSRAM buffer and
484
+ // frees it via free() in its dtor (the SMH allocator's free is compatible
485
+ // with the standard k_free/free path). Returns nullptr if PSRAM isn't
486
+ // available or the allocation fails — ui_create_canvas_best falls back.
487
+ #if defined(BOARD_HAS_PSRAM)
488
+ if ((cw > 0) && (ch > 0)) {
489
+ size_t bytes = static_cast<size_t>(cw) * static_cast<size_t>(ch) * sizeof(uint16_t);
490
+ uint16_t* psramBuf = static_cast<uint16_t*>(ui_psram_malloc(bytes));
491
+ if (psramBuf) {
492
+ void* mem = malloc(sizeof(CuttlefishCanvas16));
493
+ if (mem) {
494
+ return new (mem) CuttlefishCanvas16(cw, ch, psramBuf, 1);
495
+ }
496
+ free(psramBuf);
497
+ }
498
+ }
499
+ #else
500
+ (void)cw; (void)ch;
501
+ #endif
502
+ return nullptr;
503
+ }
504
+ static inline void display_deleteCanvas(CuttlefishCanvas16* canvas) {
505
+ if (!canvas) return;
506
+ canvas->~CuttlefishCanvas16();
507
+ free(canvas);
508
+ }
509
+ static inline int16_t display_canvasWidth(CuttlefishCanvas16* c) { return c->width(); }
510
+ static inline int16_t display_canvasHeight(CuttlefishCanvas16* c) { return c->height(); }
511
+ static inline uint16_t* display_canvasBuffer(CuttlefishCanvas16* c) { return c->getBuffer(); }
512
+ static inline uint16_t display_canvasGetPixel(CuttlefishCanvas16* c, int16_t x, int16_t y) { return c->getPixel(x, y); }
513
+ static inline void display_canvasFillScreen(CuttlefishCanvas16* c, UI_COLOR_T color) { c->fillScreen(static_cast<uint16_t>(color)); }
514
+ static inline void display_canvasFillRect(CuttlefishCanvas16* c, int16_t x, int16_t y, int16_t cw, int16_t ch, UI_COLOR_T color) {
515
+ c->fillRect(x, y, cw, ch, static_cast<uint16_t>(color));
516
+ }
517
+
518
+ // ── Target-polymorphic draw (panel or canvas via CuttlefishDisplayTarget*) ─
519
+ static inline void display_targetDrawPixel(CuttlefishDisplayTarget* t, int16_t x, int16_t y, UI_COLOR_T color) { t->drawPixel(x, y, static_cast<uint16_t>(color)); }
520
+ static inline int16_t display_targetWidth(CuttlefishDisplayTarget* t) { return t->width(); }
521
+ static inline int16_t display_targetHeight(CuttlefishDisplayTarget* t) { return t->height(); }
522
+ static inline void display_targetDrawRGBBitmap(CuttlefishDisplayTarget* t, int16_t x, int16_t y, const uint16_t* bitmap, int16_t bw, int16_t bh) {
523
+ t->drawRGBBitmap(x, y, bitmap, bw, bh);
524
+ }
525
+ static inline void display_targetFillRect(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bw, int16_t bh, UI_COLOR_T color) { t->fillRect(x, y, bw, bh, static_cast<uint16_t>(color)); }
526
+ static inline void display_targetDrawFastHLine(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bw, UI_COLOR_T color) { t->drawFastHLine(x, y, bw, static_cast<uint16_t>(color)); }
527
+ static inline void display_targetDrawFastVLine(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bh, UI_COLOR_T color) { t->drawFastVLine(x, y, bh, static_cast<uint16_t>(color)); }
528
+ static inline void display_targetFillRoundRect(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bw, int16_t bh, int16_t r, UI_COLOR_T color) { t->fillRoundRect(x, y, bw, bh, r, static_cast<uint16_t>(color)); }
529
+ static inline void display_targetDrawRect(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bw, int16_t bh, UI_COLOR_T color) { t->drawRect(x, y, bw, bh, static_cast<uint16_t>(color)); }
530
+ static inline void display_targetDrawRoundRect(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t bw, int16_t bh, int16_t r, UI_COLOR_T color) { t->drawRoundRect(x, y, bw, bh, r, static_cast<uint16_t>(color)); }
531
+ static inline void display_targetDrawLine(CuttlefishDisplayTarget* t, int16_t x0, int16_t y0, int16_t x1, int16_t y1, UI_COLOR_T color) { t->drawLine(x0, y0, x1, y1, static_cast<uint16_t>(color)); }
532
+ static inline void display_targetFillCircle(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t r, UI_COLOR_T color) { t->fillCircle(x, y, r, static_cast<uint16_t>(color)); }
533
+ static inline void display_targetDrawCircle(CuttlefishDisplayTarget* t, int16_t x, int16_t y, int16_t r, UI_COLOR_T color) { t->drawCircle(x, y, r, static_cast<uint16_t>(color)); }
534
+ static inline void display_targetSetCursor(CuttlefishDisplayTarget* t, int16_t x, int16_t y) { t->setCursor(x, y); }
535
+ static inline void display_targetSetTextColor(CuttlefishDisplayTarget* t, UI_COLOR_T fg) { t->setTextColor(static_cast<uint16_t>(fg)); }
536
+ static inline void display_targetSetTextColorBg(CuttlefishDisplayTarget* t, UI_COLOR_T fg, UI_COLOR_T bg) { t->setTextColor(static_cast<uint16_t>(fg), static_cast<uint16_t>(bg)); }
537
+ static inline void display_targetSetTextSize(CuttlefishDisplayTarget* t, uint8_t s) { t->setTextSize(s); }
538
+ static inline void display_targetSetTextWrap(CuttlefishDisplayTarget* t, bool wp) { t->setTextWrap(wp); }
539
+ static inline void display_targetPrint(CuttlefishDisplayTarget* t, const char* s) { t->print(s); }
540
+ `;
541
+
542
+ return { includes, declaration, functions };
543
+ }
544
+
545
+ /**
546
+ * Strategy-owned display adapter generator. Receives the resolved display and
547
+ * looks up the Zephyr DT-binding profile by driver id. Returns undefined for
548
+ * unknown drivers so resolveDisplayAdapter can decline and
549
+ * generateDisplayAdapter surfaces a clear error.
550
+ */
551
+ export const zephyrDisplayAdapterGenerator: DisplayAdapterGenerator = (display) => {
552
+ const profile = ZEPHYR_DISPLAY_PROFILES[display.driver];
553
+ if (!profile) return undefined as unknown as DisplayAdapterCode;
554
+ return zephyrUiDisplayAdapter(profile, {
555
+ scanlineSync: display.scanlineSync,
556
+ miso: display.spiPins?.miso,
557
+ });
558
+ };