@typecad/framework-zephyr 1.0.0-alpha.10

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 (150) 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/doctor.d.ts +6 -0
  32. package/dist/doctor.js +48 -0
  33. package/dist/dt-config/kconfig.d.ts +27 -0
  34. package/dist/dt-config/kconfig.js +283 -0
  35. package/dist/dt-config/overlay.d.ts +35 -0
  36. package/dist/dt-config/overlay.js +246 -0
  37. package/dist/framework.manifest.d.ts +101 -0
  38. package/dist/framework.manifest.js +536 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.js +17 -0
  41. package/dist/lowering/adc.d.ts +19 -0
  42. package/dist/lowering/adc.js +76 -0
  43. package/dist/lowering/ble.d.ts +20 -0
  44. package/dist/lowering/ble.js +419 -0
  45. package/dist/lowering/board.d.ts +9 -0
  46. package/dist/lowering/board.js +33 -0
  47. package/dist/lowering/gpio.d.ts +12 -0
  48. package/dist/lowering/gpio.js +123 -0
  49. package/dist/lowering/http.d.ts +23 -0
  50. package/dist/lowering/http.js +482 -0
  51. package/dist/lowering/i2c.d.ts +15 -0
  52. package/dist/lowering/i2c.js +114 -0
  53. package/dist/lowering/index.d.ts +29 -0
  54. package/dist/lowering/index.js +93 -0
  55. package/dist/lowering/interrupts.d.ts +21 -0
  56. package/dist/lowering/interrupts.js +91 -0
  57. package/dist/lowering/mqtt.d.ts +19 -0
  58. package/dist/lowering/mqtt.js +366 -0
  59. package/dist/lowering/power.d.ts +9 -0
  60. package/dist/lowering/power.js +64 -0
  61. package/dist/lowering/preferences.d.ts +23 -0
  62. package/dist/lowering/preferences.js +345 -0
  63. package/dist/lowering/pulse.d.ts +7 -0
  64. package/dist/lowering/pulse.js +82 -0
  65. package/dist/lowering/pwm.d.ts +15 -0
  66. package/dist/lowering/pwm.js +59 -0
  67. package/dist/lowering/random.d.ts +18 -0
  68. package/dist/lowering/random.js +129 -0
  69. package/dist/lowering/spi.d.ts +17 -0
  70. package/dist/lowering/spi.js +113 -0
  71. package/dist/lowering/timing.d.ts +9 -0
  72. package/dist/lowering/timing.js +63 -0
  73. package/dist/lowering/tone.d.ts +10 -0
  74. package/dist/lowering/tone.js +50 -0
  75. package/dist/lowering/uart.d.ts +15 -0
  76. package/dist/lowering/uart.js +102 -0
  77. package/dist/lowering/util.d.ts +4 -0
  78. package/dist/lowering/util.js +12 -0
  79. package/dist/lowering/wdt.d.ts +15 -0
  80. package/dist/lowering/wdt.js +80 -0
  81. package/dist/lowering/wifi.d.ts +21 -0
  82. package/dist/lowering/wifi.js +447 -0
  83. package/dist/lowering/worker-backing.d.ts +14 -0
  84. package/dist/lowering/worker-backing.js +79 -0
  85. package/dist/lowering/worker.d.ts +6 -0
  86. package/dist/lowering/worker.js +14 -0
  87. package/dist/strategy.d.ts +168 -0
  88. package/dist/strategy.js +1094 -0
  89. package/dist/toolchain/compat.d.ts +38 -0
  90. package/dist/toolchain/compat.js +133 -0
  91. package/dist/toolchain/debug-config.d.ts +82 -0
  92. package/dist/toolchain/debug-config.js +359 -0
  93. package/dist/toolchain/index.d.ts +73 -0
  94. package/dist/toolchain/index.js +444 -0
  95. package/dist/toolchain/scaffold.d.ts +15 -0
  96. package/dist/toolchain/scaffold.js +196 -0
  97. package/dist/toolchain/west-discover.d.ts +40 -0
  98. package/dist/toolchain/west-discover.js +203 -0
  99. package/dist/toolchain/west-spawn.d.ts +39 -0
  100. package/dist/toolchain/west-spawn.js +117 -0
  101. package/package.json +82 -0
  102. package/src/async/timer-polyfill.ts +107 -0
  103. package/src/chips/controllers.ts +74 -0
  104. package/src/chips/esp32.ts +62 -0
  105. package/src/chips/esp32s3.ts +57 -0
  106. package/src/chips/index.ts +54 -0
  107. package/src/chips/resolve.ts +146 -0
  108. package/src/chips/types.ts +163 -0
  109. package/src/chips/xiao-ble.ts +64 -0
  110. package/src/debug-codegen.ts +207 -0
  111. package/src/display/gfx.ts +190 -0
  112. package/src/display/index.ts +70 -0
  113. package/src/display/profiles.ts +63 -0
  114. package/src/display/touch-adapter.ts +100 -0
  115. package/src/display/ui-adapter.ts +558 -0
  116. package/src/doctor.ts +56 -0
  117. package/src/dt-config/kconfig.ts +308 -0
  118. package/src/dt-config/overlay.ts +293 -0
  119. package/src/framework.manifest.ts +558 -0
  120. package/src/index.ts +29 -0
  121. package/src/lowering/adc.ts +102 -0
  122. package/src/lowering/ble.ts +426 -0
  123. package/src/lowering/board.ts +38 -0
  124. package/src/lowering/gpio.ts +148 -0
  125. package/src/lowering/http.ts +488 -0
  126. package/src/lowering/i2c.ts +126 -0
  127. package/src/lowering/index.ts +86 -0
  128. package/src/lowering/interrupts.ts +114 -0
  129. package/src/lowering/mqtt.ts +371 -0
  130. package/src/lowering/power.ts +70 -0
  131. package/src/lowering/preferences.ts +354 -0
  132. package/src/lowering/pulse.ts +93 -0
  133. package/src/lowering/pwm.ts +74 -0
  134. package/src/lowering/random.ts +135 -0
  135. package/src/lowering/spi.ts +124 -0
  136. package/src/lowering/timing.ts +72 -0
  137. package/src/lowering/tone.ts +60 -0
  138. package/src/lowering/uart.ts +111 -0
  139. package/src/lowering/util.ts +12 -0
  140. package/src/lowering/wdt.ts +84 -0
  141. package/src/lowering/wifi.ts +452 -0
  142. package/src/lowering/worker-backing.ts +94 -0
  143. package/src/lowering/worker.ts +17 -0
  144. package/src/strategy.ts +1265 -0
  145. package/src/toolchain/compat.ts +145 -0
  146. package/src/toolchain/debug-config.ts +399 -0
  147. package/src/toolchain/index.ts +482 -0
  148. package/src/toolchain/scaffold.ts +196 -0
  149. package/src/toolchain/west-discover.ts +233 -0
  150. package/src/toolchain/west-spawn.ts +141 -0
@@ -0,0 +1,163 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Zephyr chip descriptor — pure-data model
3
+ //
4
+ // Mirrors the per-framework chip-descriptor pattern established by
5
+ // framework-esp32 (Esp32ChipDescriptor) and framework-avr (AVRChipDescriptor):
6
+ // the framework owns its own device-tree-derived descriptor, keyed off the
7
+ // Zephyr board target string in frameworkData.buildTarget. The board/MCU
8
+ // packages are deliberately NOT read at emit time (see the framework-package
9
+ // data-flow split); this descriptor is the source the lowering reads.
10
+ //
11
+ // No behavior — the lowering code in src/lowering/*.ts reads getActiveChip()
12
+ // to resolve pins to devicetree specs and raw-controller fallbacks.
13
+ // ---------------------------------------------------------------------------
14
+
15
+ /**
16
+ * A GPIO pin described as a devicetree spec.
17
+ *
18
+ * Zephyr addresses GPIO via `struct gpio_dt_spec` resolved from devicetree
19
+ * aliases/labels (e.g. DT_ALIAS(led0)). The dtSpec form is preferred because
20
+ * `gpio_pin_set_dt()` honors the node's polarity flags — so an active-low LED
21
+ * (logical 1 = LED on) is handled by the DT `GPIO_ACTIVE_LOW` flag, not by the
22
+ * generated C++.
23
+ */
24
+ export interface ZephyrGpioDtSpec {
25
+ /** GPIO number — matches the HAL op `pin` field (P0.X → X, P1.X → 32+X). */
26
+ readonly pin: number;
27
+ /**
28
+ * Devicetree alias/nodelabel macro, e.g. `led0`, `sw0`, `led1`.
29
+ * Emitted as `GPIO_DT_SPEC_GET(DT_ALIAS(<dtSpec>), gpios)`.
30
+ */
31
+ readonly dtSpec: string;
32
+ }
33
+
34
+ /**
35
+ * A GPIO controller devicetree node, and the HAL pin-number range it owns.
36
+ *
37
+ * Most SoCs expose a single GPIO controller (nRF52840: `gpio0` owns every
38
+ * pin). SoCs that split GPIO across multiple devicetree nodes — e.g. the
39
+ * ESP32-S3 (`gpio0`: pins 0–31, `gpio1`: pins 32–48) — list one entry per
40
+ * controller so the lowering can route a HAL pin to the owning controller at
41
+ * runtime. Pin numbers match the HAL op `pin` field.
42
+ */
43
+ export interface ZephyrGpioController {
44
+ /** Devicetree nodelabel, e.g. 'gpio0', 'gpio1'. */
45
+ readonly nodelabel: string;
46
+ /** First HAL pin number owned by this controller (inclusive). */
47
+ readonly minPin: number;
48
+ /** Last HAL pin number owned by this controller (inclusive). */
49
+ readonly maxPin: number;
50
+ }
51
+
52
+ /**
53
+ * A bus controller (I2C / SPI / UART) described by its devicetree nodelabel.
54
+ *
55
+ * Zephyr resolves the `const struct device*` at compile time via
56
+ * `DEVICE_DT_GET(DT_NODELABEL(<nodeLabel>))`, so unlike ESP-IDF there is no
57
+ * lazy handle resolution — the lowering emits the macro directly.
58
+ */
59
+ export interface ZephyrBusController {
60
+ /** Devicetree nodelabel, e.g. 'i2c1', 'spi2', 'uart0'. */
61
+ readonly nodeLabel: string;
62
+ }
63
+
64
+ /**
65
+ * A PWM channel described as a devicetree spec.
66
+ *
67
+ * Emitted as `struct pwm_dt_spec __tc_pwm<N> = PWM_DT_SPEC_GET(DT_ALIAS(<dtSpec>))`.
68
+ * `pwm_set_pulse_dt(&__tc_pwm<N>, pulse_ns)` honors the spec's period/polarity.
69
+ */
70
+ export interface ZephyrPwmSpec {
71
+ /** GPIO number (matches the HAL op `pin` field). */
72
+ readonly pin: number;
73
+ /** Devicetree alias, e.g. 'pwm-led0'. */
74
+ readonly dtSpec: string;
75
+ }
76
+
77
+ /**
78
+ * A GPIO pin usable as an interrupt source.
79
+ *
80
+ * Emitted as `struct gpio_dt_spec __tc_int<N> = GPIO_DT_SPEC_GET(DT_ALIAS(<dtSpec>), gpios)`
81
+ * + a `struct gpio_callback` registered via `gpio_add_callback`.
82
+ */
83
+ export interface ZephyrInterruptPin {
84
+ /** GPIO number (matches the HAL op `pin` field). */
85
+ readonly pin: number;
86
+ /** Devicetree alias, e.g. 'sw0', or a nodelabel. */
87
+ readonly dtSpec: string;
88
+ }
89
+
90
+ /**
91
+ * An ADC channel: which SAADC input a given HAL pin maps to.
92
+ *
93
+ * The XIAO nRF52840 has no pre-declared ADC channel nodes in devicetree, so the
94
+ * lowering emits `adc_channel_setup` against `DEVICE_DT_GET(DT_NODELABEL(adc))`
95
+ * using the `channel` index here (SAADC AIN0–AIN7).
96
+ */
97
+ export interface ZephyrAdcChannel {
98
+ /** GPIO number (matches the HAL op `pin` field). */
99
+ readonly pin: number;
100
+ /** SAADC channel index (AIN0–AIN7). */
101
+ readonly channel: number;
102
+ }
103
+
104
+ /**
105
+ * Pure-data descriptor for a Zephyr board + its SoC's peripheral layout.
106
+ */
107
+ export interface ZephyrChipDescriptor {
108
+ /** Zephyr board target (the `west build -b <id>` argument), e.g. 'xiao_ble'. */
109
+ readonly id: string;
110
+ /** SoC family, e.g. 'nrf52840'. */
111
+ readonly soc: string;
112
+ /**
113
+ * Default GPIO controller nodelabel for the raw-pin fallback. Pins not in
114
+ * `gpio.dtSpecs` are addressed via
115
+ * `DEVICE_DT_GET(DT_NODELABEL(<gpioController>))` + gpio_pin_*_raw().
116
+ *
117
+ * For SoCs that split GPIO across multiple devicetree nodes, `gpioControllers`
118
+ * overrides this per pin range; this field is then only the out-of-range
119
+ * fallback (so a single-controller board is unaffected by it).
120
+ */
121
+ readonly gpioController: string;
122
+ /**
123
+ * Per-range GPIO controllers for SoCs that split GPIO across multiple
124
+ * devicetree nodes (ESP32-S3: `gpio0` 0–31, `gpio1` 32–48). When present, the
125
+ * lowering routes a HAL pin to its owning controller at runtime via the
126
+ * emitted `__tc_gpio_dev(pin)` dispatcher; `gpioController` is the fallback.
127
+ * Omit on single-controller SoCs (nRF52840, RP2040, …) — every pin is on the
128
+ * one controller described by `gpioController`.
129
+ */
130
+ readonly gpioControllers?: readonly ZephyrGpioController[];
131
+ /** GPIO pins with devicetree specs (LEDs, buttons, board-defined pins). */
132
+ readonly gpio: {
133
+ readonly dtSpecs: readonly ZephyrGpioDtSpec[];
134
+ /** Interrupt-capable pins with DT specs (buttons etc.). */
135
+ readonly interruptPins?: readonly ZephyrInterruptPin[];
136
+ };
137
+ /** I2C controllers (board-wired). Index 0 = the primary bus. */
138
+ readonly i2c?: { readonly controllers: readonly ZephyrBusController[] };
139
+ /** SPI controllers (board-wired). Index 0 = the primary bus. */
140
+ readonly spi?: { readonly controllers: readonly ZephyrBusController[] };
141
+ /** UART controllers (board-wired). Index 0 = the primary port. */
142
+ readonly uart?: { readonly controllers: readonly ZephyrBusController[] };
143
+ /** PWM channels with DT specs. */
144
+ readonly pwm?: { readonly specs: readonly ZephyrPwmSpec[] };
145
+ /** ADC: the SAADC node label + the pin→channel map. */
146
+ readonly adc?: {
147
+ readonly nodeLabel: string;
148
+ readonly channels: readonly ZephyrAdcChannel[];
149
+ /** Reference voltage in millivolts (nRF internal = 3000 for VDD/4 + gain 1/4… use 3000). */
150
+ readonly vrefMv: number;
151
+ /** ADC resolution in bits. */
152
+ readonly resolution: number;
153
+ };
154
+ /** Watchdog node label, e.g. 'wdt0'. */
155
+ readonly wdt?: { readonly nodeLabel: string };
156
+ /**
157
+ * WiFi capability marker. Present only on chips with a WiFi radio (ESP32-S3).
158
+ * Read by profileDiagnostics to flag wifi.* usage on chips without a radio.
159
+ * Omit on radioless chips (nRF52840) — its absence is the "no WiFi" signal.
160
+ */
161
+ readonly wifi?: { readonly supported: true };
162
+ }
163
+
@@ -0,0 +1,64 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Seeed Studio XIAO nRF52840 — Zephyr board descriptor
3
+ //
4
+ // Board target: `xiao_ble` (mainline Zephyr, boards/seeed/xiao_ble).
5
+ // The onboard user LED is active-low and exposed as the DT alias `led0`.
6
+ // ---------------------------------------------------------------------------
7
+
8
+ import type { ZephyrChipDescriptor } from './types.js';
9
+
10
+ export const XIAO_BLE: ZephyrChipDescriptor = {
11
+ id: 'xiao_ble',
12
+ soc: 'nrf52840',
13
+ gpioController: 'gpio0',
14
+ gpio: {
15
+ dtSpecs: [
16
+ // Onboard RGB LEDs — active-low (GPIO_ACTIVE_LOW in xiao_ble_common.dtsi).
17
+ // Verified against the board's `aliases { led0 = &led0; led1 = &led1; led2 = &led2; }`.
18
+ { pin: 26, dtSpec: 'led0' }, // Red (P0.26)
19
+ { pin: 30, dtSpec: 'led1' }, // Green (P0.30)
20
+ { pin: 6, dtSpec: 'led2' }, // Blue (P0.06)
21
+ ],
22
+ // The XIAO nRF52840 has a user button on P0.04, but mainline Zephyr's
23
+ // xiao_ble board (verified against Zephyr 4.3.99) does NOT expose it as a
24
+ // DT `sw0` alias — there is no gpio-keys node in xiao_ble.dts. Emitting
25
+ // GPIO_DT_SPEC_GET(DT_ALIAS(sw0), gpios) therefore fails to compile
26
+ // ('DT_N_ALIAS_sw0_... was not declared'). Until a button node + alias is
27
+ // added (via an overlay or an upstream board update), interruptPins stays
28
+ // empty: attachInterrupt on this board lowers to the no-DT-spec comment
29
+ // fallback rather than a hard compile error.
30
+ interruptPins: [],
31
+ },
32
+ // The XIAO connector wiring (from seeed_xiao_connector.dtsi + xiao_ble-pinctrl.dtsi):
33
+ // xiao_i2c → i2c1 (SDA P0.04/D4, SCL P0.05/D5)
34
+ // xiao_spi → spi2 (SCK P1.13/D8, MOSI P1.15/D10, MISO P1.14/D9)
35
+ // xiao_serial → uart0 (TX P1.11/D6, RX P1.12/D7)
36
+ // The board DTS leaves i2c0/spi0/spi1 disabled (shared instances).
37
+ i2c: {
38
+ controllers: [{ nodeLabel: 'i2c1' }],
39
+ },
40
+ spi: {
41
+ controllers: [{ nodeLabel: 'spi2' }],
42
+ },
43
+ uart: {
44
+ controllers: [{ nodeLabel: 'uart0' }],
45
+ },
46
+ pwm: {
47
+ // pwm-led0 drives the board PWM LED (PWM_OUT0 on P0.17, inverted).
48
+ specs: [{ pin: 17, dtSpec: 'pwm-led0' }],
49
+ },
50
+ adc: {
51
+ // SAADC node is `adc`; no pre-declared channels. XIAO D0–D3 = AIN0–AIN3
52
+ // (P0.02/P0.03/P0.28/P0.29). Internal VREF ~0.6V with VDD/4 gain ⇒ 3000mV.
53
+ nodeLabel: 'adc',
54
+ resolution: 12,
55
+ vrefMv: 3000,
56
+ channels: [
57
+ { pin: 2, channel: 0 }, // P0.02 / D0 / AIN0
58
+ { pin: 3, channel: 1 }, // P0.03 / D1 / AIN1
59
+ { pin: 28, channel: 2 }, // P0.28 / D2 / AIN2
60
+ { pin: 29, channel: 3 }, // P0.29 / D3 / AIN3
61
+ ],
62
+ },
63
+ wdt: { nodeLabel: 'wdt0' },
64
+ };
@@ -0,0 +1,207 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Zephyr debug code generator — printk-based debug output
3
+ //
4
+ // The Zephyr counterpart to framework-esp32/src/debug-codegen.ts. Zephyr's
5
+ // minimal C++ config has no <iostream> (manifest: needsIostream=false,
6
+ // stdlibSupport.hasIostream=false), so the GenericStrategy's std::cout fallback
7
+ // used by the debug preprocessor would NOT compile. This module routes every
8
+ // debug line through printk("...\n") — the always-available Zephyr console,
9
+ // with no CONFIG_CONSOLE dependency — so `cuttlefish build --debug` produces
10
+ // compiling output.
11
+ //
12
+ // The halt primitive is __tc_debug_wait_for_continue() (emitted in
13
+ // ZephyrStrategy.shimLines when --debug is active): a k_console-input / busy
14
+ // poll that yields to the scheduler so an unattended breakpoint does not trip
15
+ // any watchdog. ENTER continues; 's' disables this breakpoint for the run.
16
+ //
17
+ // Used by ZephyrStrategy's generateDebug* overrides, dispatched by the
18
+ // cuttlefish debug preprocessor (cuttlefish/src/debug/preprocessor.ts).
19
+ // ---------------------------------------------------------------------------
20
+
21
+ export interface CapturedVariable {
22
+ name: string;
23
+ isFunction?: boolean;
24
+ /** Coarse C++ type category (inferred by the preprocessor without a checker). */
25
+ cppType?: 'bool' | 'int' | 'long' | 'float' | 'string' | 'unknown';
26
+ }
27
+
28
+ export interface LogMessagePart {
29
+ type: 'text' | 'variable';
30
+ value: string;
31
+ }
32
+
33
+ /**
34
+ * Generate the debug-mode banner. printk is always wired (Zephyr console), so
35
+ * there is no init to perform — just confirm debug instrumentation is live.
36
+ */
37
+ export function generateZephyrInitCode(): string[] {
38
+ return [
39
+ `// === DEBUG: Zephyr console (printk) ===`,
40
+ `printk("[TypeCAD] Debug Mode Active\\n");`,
41
+ `// === END DEBUG INIT ===`,
42
+ ``,
43
+ ];
44
+ }
45
+
46
+ /**
47
+ * Generate Zephyr code for a breakpoint.
48
+ *
49
+ * The halt is __tc_debug_wait_for_continue() (emitted in ZephyrStrategy.shimLines
50
+ * under --debug): blocks until a byte arrives on the console, yielding to the
51
+ * scheduler between polls. The user must have a console attached (`west serial`
52
+ * or a terminal on the USB-CDC port); ENTER continues, 's' skips this breakpoint
53
+ * for the rest of the run.
54
+ *
55
+ * When `breakpointId` is set, the whole halt block is wrapped in
56
+ * `if (!__tc_bp_disabled_<id>)`, so a skipped breakpoint becomes a no-op until
57
+ * reboot. The flag is `static` so it persists across loop() iterations.
58
+ */
59
+ export function generateZephyrBreakpointCode(
60
+ fileName: string,
61
+ lineNum: number,
62
+ originalLine: string,
63
+ variables: CapturedVariable[],
64
+ normalizedCondition: string | undefined,
65
+ breakpointId?: number,
66
+ ): string[] {
67
+ const lines: string[] = [];
68
+ const hasDisableGuard = breakpointId !== undefined;
69
+ // Each wrap level adds two spaces of indent: the disable guard (outermost)
70
+ // then the condition (if any).
71
+ const indent = ' ' + (hasDisableGuard ? ' ' : '') + (normalizedCondition ? ' ' : '');
72
+
73
+ lines.push(` // === BREAKPOINT: ${fileName}:${lineNum} ===`);
74
+
75
+ // Disable guard: a skipped breakpoint becomes a no-op until reboot. The
76
+ // disable state lives in the framework's debug shim (a static registry keyed
77
+ // by breakpointId) — NOT as a per-breakpoint declaration here, because the
78
+ // transpiler mangles `static bool` declarations injected into the source.
79
+ if (hasDisableGuard) {
80
+ lines.push(` if (!__tc_bp_is_disabled(${breakpointId})) {`);
81
+ }
82
+
83
+ if (normalizedCondition) {
84
+ lines.push(` ${hasDisableGuard ? ' ' : ''}if (${normalizedCondition}) {`);
85
+ }
86
+
87
+ lines.push(`${indent}printk("----------------------------------------\\n");`);
88
+
89
+ const headerText = normalizedCondition
90
+ ? `[BREAK] ${fileName}:${lineNum} (condition: ${escapeString(normalizedCondition)})`
91
+ : `[BREAK] ${fileName}:${lineNum}`;
92
+ lines.push(`${indent}printk("%s\\n", "${headerText}");`);
93
+
94
+ lines.push(`${indent}printk(" %s\\n", "${escapeString(originalLine)}");`);
95
+
96
+ if (variables.length > 0) {
97
+ lines.push(`${indent}printk(" Variables:\\n");`);
98
+ for (const v of variables) {
99
+ if (v.isFunction) {
100
+ lines.push(`${indent}printk(" - %s = [function]\\n", "${v.name}");`);
101
+ } else {
102
+ const { spec, arg } = formatSpecFor(v.name, v.cppType);
103
+ lines.push(`${indent}printk(" - %s = ${spec}\\n", "${v.name}", ${arg});`);
104
+ }
105
+ }
106
+ } else {
107
+ lines.push(`${indent}printk(" (no variables in scope)\\n");`);
108
+ }
109
+
110
+ lines.push(`${indent}printk(" [ENTER: continue | s: skip this breakpoint]\\n");`);
111
+ lines.push(`${indent}printk("----------------------------------------\\n");`);
112
+
113
+ // Halt — block on console input, scheduler-yielding. 's' records this id as
114
+ // disabled in the shim's registry. Pass -1 when no id (never disable).
115
+ lines.push(`${indent}__tc_debug_wait_for_continue(${hasDisableGuard ? breakpointId : -1});`);
116
+
117
+ if (normalizedCondition) {
118
+ lines.push(` ${hasDisableGuard ? ' ' : ''}}`);
119
+ }
120
+
121
+ if (hasDisableGuard) {
122
+ lines.push(` }`);
123
+ }
124
+
125
+ lines.push(` // === END BREAKPOINT ===`);
126
+
127
+ return lines;
128
+ }
129
+
130
+ /**
131
+ * Generate Zephyr code for a logpoint (logs a message without halting).
132
+ */
133
+ export function generateZephyrLogpointCode(
134
+ fileName: string,
135
+ lineNum: number,
136
+ parts: LogMessagePart[],
137
+ variables: CapturedVariable[],
138
+ ): string[] {
139
+ const lines: string[] = [];
140
+
141
+ lines.push(` // === LOGPOINT: ${fileName}:${lineNum} ===`);
142
+ lines.push(` printk("[LOG ${fileName}:${lineNum}] ");`);
143
+
144
+ for (const part of parts) {
145
+ if (part.type === 'text') {
146
+ lines.push(` printk("${escapeString(part.value)}");`);
147
+ } else {
148
+ // variable part: only printable if it is a non-function value in scope.
149
+ const match = variables.find((v) => v.name === part.value && !v.isFunction);
150
+ if (match) {
151
+ const { spec, arg } = formatSpecFor(match.name, match.cppType);
152
+ lines.push(` printk("${spec}", ${arg});`);
153
+ } else {
154
+ lines.push(` printk("{${escapeString(part.value)}}"); // variable not in scope`);
155
+ }
156
+ }
157
+ }
158
+
159
+ lines.push(` printk("\\n");`);
160
+ lines.push(` // === END LOGPOINT ===`);
161
+
162
+ return lines;
163
+ }
164
+
165
+ /**
166
+ * Escape a string for use inside printk("..."). Same rules as the ESP-IDF
167
+ * generator: backslash, double-quote, newline, carriage return.
168
+ */
169
+ function escapeString(s: string): string {
170
+ return s
171
+ .replace(/\\/g, '\\\\')
172
+ .replace(/"/g, '\\"')
173
+ .replace(/\n/g, '\\n')
174
+ .replace(/\r/g, '\\r');
175
+ }
176
+
177
+ /**
178
+ * Pick a printk format specifier + argument expression for a debug variable.
179
+ *
180
+ * The debug preprocessor has no TypeChecker, so `cppType` is a coarse category
181
+ * inferred from AST shape. For `unknown` we cast to `double` and use `%g` so
182
+ * the generated printk always compiles for any numeric/bool variable. printk
183
+ * supports the standard printf format specifiers.
184
+ *
185
+ * Returns `{ spec, arg }` where `spec` is the `%`-specifier substring to embed
186
+ * in the format string and `arg` is the C++ argument expression.
187
+ */
188
+ function formatSpecFor(
189
+ varName: string,
190
+ cppType: CapturedVariable['cppType'],
191
+ ): { spec: string; arg: string } {
192
+ switch (cppType) {
193
+ case 'bool':
194
+ case 'int':
195
+ return { spec: '%d', arg: varName };
196
+ case 'long':
197
+ return { spec: '%ld', arg: varName };
198
+ case 'float':
199
+ return { spec: '%g', arg: varName };
200
+ case 'string':
201
+ return { spec: '%s', arg: varName };
202
+ case 'unknown':
203
+ default:
204
+ // Cast to double so printk compiles regardless of the real C++ type.
205
+ return { spec: '%g', arg: `static_cast<double>(${varName})` };
206
+ }
207
+ }
@@ -0,0 +1,190 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Zephyr display GFX runtime — generic display_write + ported GFX primitives
3
+ //
4
+ // Emits C++ that resolves a DT-bound display device, keeps a one-row line
5
+ // buffer (no full framebuffer — see AGENTS.md rendering guardrails), and
6
+ // implements fill_rect / draw_rect / draw_text / flush on top of display_write.
7
+ // Text uses a minimal 5x7 bitmap font covering digits 0-9 and uppercase A-Z
8
+ // only; unknown characters render as a space.
9
+ //
10
+ // EMIT BOUNDARY: emitted bytes land in user firmware. Covered by the TypeCAD
11
+ // Runtime Exception (RUNTIME_EXCEPTION.md at the repo root).
12
+ // ---------------------------------------------------------------------------
13
+
14
+ import type { ZephyrDisplayProfile } from './profiles.js';
15
+
16
+ export interface DisplayRuntimeResult {
17
+ /** #include lines to force when the display is used. */
18
+ readonly includes: string[];
19
+ /** File-scope C++ declarations (device handle + line buffer). */
20
+ readonly stateLines: string[];
21
+ /** The C++ helper functions (display_init/fill_rect/draw_rect/draw_text/flush). */
22
+ readonly helpers: string;
23
+ /** The C++ font-table source (exposed for testing). */
24
+ readonly fontTable: string;
25
+ }
26
+
27
+ // 5x7 bitmap glyphs for 0-9 and A-Z. Each glyph is 5 bytes (columns), MSB=top.
28
+ // Unknown characters fall back to the space (all-zero columns).
29
+ // (Compact hand-authored bitmaps; the test asserts presence of '0'..'9','A'..'Z'.)
30
+ function fontTableCpp(): string {
31
+ // A flat map: char -> 5 bytes. Built so the test sees '0'..'9' and 'A'..'Z'.
32
+ const glyphs: Record<string, number[]> = {
33
+ '0': [0x3e, 0x51, 0x49, 0x45, 0x3e],
34
+ '1': [0x00, 0x42, 0x7f, 0x40, 0x00],
35
+ '2': [0x42, 0x61, 0x51, 0x49, 0x46],
36
+ '3': [0x21, 0x41, 0x45, 0x4b, 0x31],
37
+ '4': [0x18, 0x14, 0x12, 0x7f, 0x10],
38
+ '5': [0x27, 0x45, 0x45, 0x45, 0x39],
39
+ '6': [0x3c, 0x4a, 0x49, 0x49, 0x30],
40
+ '7': [0x01, 0x71, 0x09, 0x05, 0x03],
41
+ '8': [0x36, 0x49, 0x49, 0x49, 0x36],
42
+ '9': [0x06, 0x49, 0x49, 0x29, 0x1e],
43
+ 'A': [0x7e, 0x11, 0x11, 0x11, 0x7e],
44
+ 'B': [0x7f, 0x49, 0x49, 0x49, 0x36],
45
+ 'C': [0x3e, 0x41, 0x41, 0x41, 0x22],
46
+ 'D': [0x7f, 0x41, 0x41, 0x22, 0x1c],
47
+ 'E': [0x7f, 0x49, 0x49, 0x49, 0x41],
48
+ 'F': [0x7f, 0x09, 0x09, 0x09, 0x01],
49
+ 'G': [0x3e, 0x41, 0x49, 0x49, 0x7a],
50
+ 'H': [0x7f, 0x08, 0x08, 0x08, 0x7f],
51
+ 'I': [0x00, 0x41, 0x7f, 0x41, 0x00],
52
+ 'J': [0x20, 0x40, 0x41, 0x3f, 0x01],
53
+ 'K': [0x7f, 0x08, 0x14, 0x22, 0x41],
54
+ 'L': [0x7f, 0x40, 0x40, 0x40, 0x40],
55
+ 'M': [0x7f, 0x02, 0x0c, 0x02, 0x7f],
56
+ 'N': [0x7f, 0x04, 0x08, 0x10, 0x7f],
57
+ 'O': [0x3e, 0x41, 0x41, 0x41, 0x3e],
58
+ 'P': [0x7f, 0x09, 0x09, 0x09, 0x06],
59
+ 'Q': [0x3e, 0x41, 0x51, 0x21, 0x5e],
60
+ 'R': [0x7f, 0x09, 0x19, 0x29, 0x46],
61
+ 'S': [0x46, 0x49, 0x49, 0x49, 0x31],
62
+ 'T': [0x01, 0x01, 0x7f, 0x01, 0x01],
63
+ 'U': [0x3f, 0x40, 0x40, 0x40, 0x3f],
64
+ 'V': [0x1f, 0x20, 0x40, 0x20, 0x1f],
65
+ 'W': [0x3f, 0x40, 0x38, 0x40, 0x3f],
66
+ 'X': [0x63, 0x14, 0x08, 0x14, 0x63],
67
+ 'Y': [0x07, 0x08, 0x70, 0x08, 0x07],
68
+ 'Z': [0x61, 0x51, 0x49, 0x45, 0x43],
69
+ };
70
+ const lines: string[] = [
71
+ '// Minimal 5x7 font: digits 0-9 and uppercase A-Z. Unknown chars → space.',
72
+ '// (Rows for other codes are all-zero — the table is indexed by char code.)',
73
+ 'static const uint8_t __tc_font5x7[128][5] = {',
74
+ ];
75
+ for (let c = 0; c < 128; c++) {
76
+ const ch = String.fromCharCode(c);
77
+ const known = Object.prototype.hasOwnProperty.call(glyphs, ch);
78
+ const g = glyphs[ch] ?? [0x00, 0x00, 0x00, 0x00, 0x00];
79
+ // Annotate known glyphs (0-9, A-Z) with their char literal; other rows use
80
+ // only the code point so the table carries no stray char literals.
81
+ const label = known ? ` '${ch}'` : ` ${c}`;
82
+ lines.push(` {0x${g[0].toString(16).padStart(2, '0')}, 0x${g[1].toString(16).padStart(2, '0')}, 0x${g[2].toString(16).padStart(2, '0')}, 0x${g[3].toString(16).padStart(2, '0')}, 0x${g[4].toString(16).padStart(2, '0')}}, //${label}`);
83
+ }
84
+ lines.push('};');
85
+ return lines.join('\n');
86
+ }
87
+
88
+ /**
89
+ * Build the display runtime C++ for a profile. The line buffer is one row
90
+ * (width pixels × 2 bytes rgb565); fill_rect/draw_rect/draw_text compute into
91
+ * it row-by-row and display_write each row. No full framebuffer.
92
+ */
93
+ export function buildDisplayRuntime(profile: ZephyrDisplayProfile): DisplayRuntimeResult {
94
+ const w = profile.width;
95
+ const stateLines: string[] = [
96
+ '// CUTTLEFISH_DISPLAY_BEGIN',
97
+ `static const struct device* __tc_display = DEVICE_DT_GET(DT_NODELABEL(${profile.dtLabel}));`,
98
+ `static uint16_t __tc_display_line[${w}]; // one-row line buffer (rgb565)`,
99
+ '// CUTTLEFISH_DISPLAY_END',
100
+ ];
101
+
102
+ // Backlight is optional: the overlay emits the DT alias only when a backlight
103
+ // GPIO is configured. Guard with DT_HAS_ALIAS so this compiles whether or not
104
+ // the alias exists (DT_NODE_HAS_STATUS(DT_ALIAS(...)) is version-dependent
105
+ // when the alias is missing).
106
+ const blInit = profile.backlight
107
+ ? `#if DT_HAS_ALIAS(${profile.backlight})\n const struct device* __bl = DEVICE_DT_GET(DT_ALIAS(${profile.backlight}));\n gpio_pin_configure(__bl, 0, GPIO_OUTPUT); gpio_pin_set(__bl, 0, 1);\n#endif`
108
+ : '';
109
+
110
+ const helpers = `
111
+ // Write a single row of \`rw\` rgb565 pixels at (x,y). Builds the
112
+ // display_buffer_descriptor the Zephyr display_write API requires (rgb565 =
113
+ // 2 bytes/pixel) and pushes the one-row line buffer.
114
+ static inline void __tc_display_write_row(uint16_t x, uint16_t y, uint16_t rw) {
115
+ struct display_buffer_descriptor __desc;
116
+ __desc.buf_size = static_cast<uint32_t>(rw) * 2U; // 2 bytes per rgb565 pixel
117
+ __desc.width = rw;
118
+ __desc.height = 1U;
119
+ __desc.pitch = rw;
120
+ __desc.frame_incomplete = false;
121
+ (void)display_write(__tc_display, x, y, &__desc, __tc_display_line);
122
+ }
123
+
124
+ static inline void display_init(void) {
125
+ if (!device_is_ready(__tc_display)) { for (;;) { k_msleep(1000); } }
126
+ ${blInit}
127
+ display_blanking_off(__tc_display);
128
+ }
129
+
130
+ static inline void display_fill_rect(uint16_t x, uint16_t y, uint16_t rw, uint16_t h, uint16_t color) {
131
+ for (uint16_t row = 0; row < h; row++) {
132
+ for (uint16_t i = 0; i < rw; i++) { __tc_display_line[i] = color; }
133
+ __tc_display_write_row(x, static_cast<uint16_t>(y + row), rw);
134
+ }
135
+ }
136
+
137
+ static inline void display_draw_rect(uint16_t x, uint16_t y, uint16_t rw, uint16_t h, uint16_t color) {
138
+ // Top + bottom edges.
139
+ for (uint16_t i = 0; i < rw; i++) { __tc_display_line[i] = color; }
140
+ __tc_display_write_row(x, y, rw);
141
+ __tc_display_write_row(x, static_cast<uint16_t>(y + h - 1U), rw);
142
+ // Left + right edges.
143
+ for (uint16_t row = 1U; row < h - 1U; row++) {
144
+ __tc_display_line[0] = color;
145
+ if (rw > 1U) { __tc_display_line[rw - 1U] = color; }
146
+ __tc_display_write_row(x, static_cast<uint16_t>(y + row), rw);
147
+ }
148
+ }
149
+
150
+ static inline void display_draw_text(uint16_t x, uint16_t y, const char* text, uint16_t color) {
151
+ uint16_t cx = x;
152
+ for (const char* p = text; *p != 0; p++) {
153
+ // Read the byte UNSIGNED so bytes >= 0x80 don't index the 128-entry
154
+ // font table negatively (signed char would make 0x80 == -128).
155
+ uint8_t uc = static_cast<uint8_t>(*p);
156
+ if (uc >= 128U) { uc = static_cast<uint8_t>(' '); } // unknown → space
157
+ const uint8_t* glyph = &__tc_font5x7[uc][0];
158
+ // Lowercase → uppercase; anything outside 0-9/A-Z → space glyph.
159
+ if (uc >= static_cast<uint8_t>('a') && uc <= static_cast<uint8_t>('z')) {
160
+ glyph = &__tc_font5x7[uc - 32U][0];
161
+ } else if (uc < static_cast<uint8_t>('0')
162
+ || (uc > static_cast<uint8_t>('9') && uc < static_cast<uint8_t>('A'))
163
+ || uc > static_cast<uint8_t>('Z')) {
164
+ glyph = &__tc_font5x7[static_cast<uint8_t>(' ')][0];
165
+ }
166
+ for (uint16_t col = 0; col < 5U; col++) {
167
+ uint8_t bits = glyph[col];
168
+ for (uint16_t row = 0; row < 7U; row++) {
169
+ __tc_display_line[0] = ((bits & static_cast<uint8_t>(1U << row)) != 0U) ? color : 0U;
170
+ __tc_display_write_row(static_cast<uint16_t>(cx + col), static_cast<uint16_t>(y + row), 1U);
171
+ }
172
+ }
173
+ cx = static_cast<uint16_t>(cx + 6U); // 5 cols + 1 space
174
+ }
175
+ }
176
+
177
+ static inline void display_flush(void) {
178
+ // No-op: writes are immediate via display_write; there is no framebuffer to push.
179
+ }
180
+ `;
181
+
182
+ const fontTable = fontTableCpp();
183
+
184
+ return {
185
+ includes: ['<zephyr/drivers/display.h>'],
186
+ stateLines,
187
+ helpers,
188
+ fontTable,
189
+ };
190
+ }