@typecad/framework-zephyr 1.0.0-alpha.15 → 1.0.0-alpha.18

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 (132) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +49 -87
  3. package/dist/as-built.d.ts +2 -2
  4. package/dist/as-built.js +2 -2
  5. package/dist/boardgen.d.ts +1 -9
  6. package/dist/boardgen.js +228 -45
  7. package/dist/chips/types.d.ts +1 -1
  8. package/dist/debug-codegen.js +1 -1
  9. package/dist/display/touch-adapter.js +1 -1
  10. package/dist/display/ui-adapter.js +549 -549
  11. package/dist/doctor.js +4 -4
  12. package/dist/dt-config/custom-board.js +2 -2
  13. package/dist/dt-config/kconfig.js +18 -12
  14. package/dist/dt-config/overlay.d.ts +2 -2
  15. package/dist/dt-config/overlay.js +2 -2
  16. package/dist/framework.manifest.d.ts +3 -3
  17. package/dist/framework.manifest.js +10 -7
  18. package/dist/index.js +5 -5
  19. package/dist/licenses.d.ts +2 -2
  20. package/dist/licenses.js +8 -8
  21. package/dist/lowering/fs.js +1 -1
  22. package/dist/lowering/gpio.js +0 -32
  23. package/dist/lowering/http.js +264 -32
  24. package/dist/lowering/i2c.js +0 -8
  25. package/dist/lowering/interrupts.js +6 -0
  26. package/dist/lowering/mqtt.js +110 -8
  27. package/dist/lowering/usb.js +11 -11
  28. package/dist/lowering/wdt.js +2 -29
  29. package/dist/sdk/board-catalog-sync.d.ts +1 -3
  30. package/dist/sdk/board-catalog-sync.js +4 -10
  31. package/dist/strategy.d.ts +22 -44
  32. package/dist/strategy.js +152 -155
  33. package/dist/tmp-probe.d.ts +2 -0
  34. package/dist/tmp-probe.js +9 -0
  35. package/dist/toolchain/debug-config.d.ts +50 -90
  36. package/dist/toolchain/debug-config.js +241 -502
  37. package/dist/toolchain/env-check.d.ts +1 -3
  38. package/dist/toolchain/env-check.js +2 -7
  39. package/dist/toolchain/index.d.ts +65 -2
  40. package/dist/toolchain/index.js +432 -55
  41. package/dist/toolchain/runners.d.ts +16 -0
  42. package/dist/toolchain/runners.js +75 -0
  43. package/dist/toolchain/scaffold.d.ts +1 -1
  44. package/dist/toolchain/scaffold.js +12 -12
  45. package/dist/toolchain/west-discover.d.ts +6 -0
  46. package/dist/toolchain/west-discover.js +36 -13
  47. package/dist/toolchain/west-spawn.js +8 -2
  48. package/installer/README.md +328 -328
  49. package/installer/install.sh +2 -2
  50. package/installer/templates/project/.typecad/activate-zephyr.ps1 +1 -1
  51. package/installer/templates/project/.typecad/activate-zephyr.sh +1 -1
  52. package/installer/templates/project/.vscode/settings.json +1 -1
  53. package/installer/templates/project/README.md +2 -2
  54. package/package.json +5 -5
  55. package/src/as-built.ts +206 -206
  56. package/src/boardgen.ts +214 -48
  57. package/src/chips/types.ts +567 -567
  58. package/src/display/touch-adapter.ts +204 -204
  59. package/src/display/ui-adapter.ts +781 -781
  60. package/src/doctor.ts +4 -4
  61. package/src/dt-config/custom-board.ts +2 -2
  62. package/src/dt-config/kconfig.ts +18 -12
  63. package/src/dt-config/overlay.ts +1058 -1058
  64. package/src/framework.manifest.ts +538 -535
  65. package/src/index.ts +5 -5
  66. package/src/licenses.ts +425 -425
  67. package/src/lowering/fs.ts +135 -135
  68. package/src/lowering/gpio.ts +0 -33
  69. package/src/lowering/http.ts +264 -32
  70. package/src/lowering/i2c.ts +0 -9
  71. package/src/lowering/interrupts.ts +6 -0
  72. package/src/lowering/mqtt.ts +109 -8
  73. package/src/lowering/usb.ts +221 -221
  74. package/src/lowering/wdt.ts +2 -25
  75. package/src/sdk/board-catalog-sync.ts +4 -25
  76. package/src/strategy.ts +2265 -2309
  77. package/src/toolchain/debug-config.ts +264 -514
  78. package/src/toolchain/env-check.ts +279 -285
  79. package/src/toolchain/index.ts +1703 -1286
  80. package/src/toolchain/runners.ts +80 -0
  81. package/src/toolchain/scaffold.ts +296 -296
  82. package/src/toolchain/west-discover.ts +35 -13
  83. package/src/toolchain/west-spawn.ts +174 -168
  84. package/dist/async/timer-polyfill.d.ts +0 -10
  85. package/dist/async/timer-polyfill.js +0 -95
  86. package/dist/chips/board-overrides.d.ts +0 -7
  87. package/dist/chips/board-overrides.js +0 -11
  88. package/dist/chips/esp32.d.ts +0 -2
  89. package/dist/chips/esp32.js +0 -71
  90. package/dist/chips/esp32s3.d.ts +0 -2
  91. package/dist/chips/esp32s3.js +0 -103
  92. package/dist/chips/soc/.d.ts +0 -2
  93. package/dist/chips/soc/.js +0 -129
  94. package/dist/chips/soc/esp32.d.ts +0 -2
  95. package/dist/chips/soc/esp32.js +0 -120
  96. package/dist/chips/soc/esp32c3.d.ts +0 -2
  97. package/dist/chips/soc/esp32c3.js +0 -90
  98. package/dist/chips/soc/esp32c6.d.ts +0 -2
  99. package/dist/chips/soc/esp32c6.js +0 -109
  100. package/dist/chips/soc/esp32s3.d.ts +0 -2
  101. package/dist/chips/soc/esp32s3.js +0 -189
  102. package/dist/chips/soc/index.d.ts +0 -2
  103. package/dist/chips/soc/index.js +0 -23
  104. package/dist/chips/soc/nrf52840.d.ts +0 -2
  105. package/dist/chips/soc/nrf52840.js +0 -130
  106. package/dist/chips/soc/rp2040.d.ts +0 -2
  107. package/dist/chips/soc/rp2040.js +0 -141
  108. package/dist/chips/soc/rp2350a.d.ts +0 -2
  109. package/dist/chips/soc/rp2350a.js +0 -145
  110. package/dist/chips/soc/samd21g18a.d.ts +0 -2
  111. package/dist/chips/soc/samd21g18a.js +0 -143
  112. package/dist/chips/soc/stm32f411xe.d.ts +0 -2
  113. package/dist/chips/soc/stm32f411xe.js +0 -251
  114. package/dist/chips/xiao-ble.d.ts +0 -2
  115. package/dist/chips/xiao-ble.js +0 -100
  116. package/dist/lowering/power.d.ts +0 -9
  117. package/dist/lowering/power.js +0 -60
  118. package/dist/lowering/pulse.d.ts +0 -7
  119. package/dist/lowering/pulse.js +0 -51
  120. package/dist/lowering/tone.d.ts +0 -10
  121. package/dist/lowering/tone.js +0 -63
  122. package/dist/lowering/worker-backing.d.ts +0 -14
  123. package/dist/lowering/worker-backing.js +0 -79
  124. package/dist/lowering/worker.d.ts +0 -6
  125. package/dist/lowering/worker.js +0 -14
  126. package/dist/sdk/board-data.generated.d.ts +0 -2
  127. package/dist/sdk/board-data.generated.js +0 -4
  128. package/dist/sdk/catalog-walker.d.ts +0 -90
  129. package/dist/sdk/catalog-walker.js +0 -682
  130. package/dist/sdk/dts-reader.d.ts +0 -83
  131. package/dist/sdk/dts-reader.js +0 -596
  132. package/src/debug-codegen.ts +0 -207
@@ -1,1286 +1,1703 @@
1
- // ---------------------------------------------------------------------------
2
- // FrameworkToolchain impl for Zephyr (west / CMake)
3
- //
4
- // compile() scaffolds the project (idempotent) then runs `west build -b <board>`.
5
- // upload() runs `west flash`. monitor() runs a best-effort serial monitor.
6
- //
7
- // west resolution goes through westSpawn(), which finds a usable west without
8
- // requiring the user to have activated the Zephyr Python venv — it prefers
9
- // `<python> -m west` (robust cross-platform form) and injects ZEPHYR_BASE when
10
- // a SDK root is discovered. See west-discover.ts / west-spawn.ts.
11
- //
12
- // The board target is carried via frameworkData.buildTarget (populated as
13
- // ToolchainOptions.buildTarget by the cuttlefish CLI), defaulting to the
14
- // framework's canonical MVP target (xiao_ble).
15
- //
16
- // Mirrors framework-esp32/src/toolchain/index.ts structure: projectRoot derived
17
- // from outputDir, prepare is a no-op (scaffold happens in compile when the
18
- // target is known), GCC errors parsed via the shared parseCompileErrors helper.
19
- // ---------------------------------------------------------------------------
20
-
21
- import { spawnSync } from 'node:child_process';
22
- import { basename, dirname, join } from 'node:path';
23
- import { readdirSync, readFileSync, mkdirSync, rmSync, existsSync, writeFileSync } from 'node:fs';
24
- import type { ToolchainOptions, CompileResult, UploadResult } from '@typecad/cuttlefish/api/shared';
25
- import { parseCompileErrors } from '@typecad/cuttlefish/api/shared';
26
- import { scaffoldZephyrProject, writeIfChanged, appendLibraryOverlayFragments } from './scaffold.js';
27
- import { parseZephyrDts, asBuiltJson } from '../as-built.js';
28
- import { westSpawn, buildEnv } from './west-spawn.js';
29
- import { discoverWest } from './west-discover.js';
30
- import { writeDebugConfig, resolveDebugLocations } from './debug-config.js';
31
- import { bossacTouchReset } from './bossac-touch.js';
32
- import { ZephyrStrategy } from '../strategy.js';
33
- import { generateOverlay, type DisplayWiring, type TouchWiring, type OverlayDiagnostic } from '../dt-config/overlay.js';
34
- import { generateCustomBoard } from '../dt-config/custom-board.js';
35
- import { NO_BOARD_CHIP } from '../chips/index.js';
36
- import { resolveChipFromBoard } from '../chips/resolve.js';
37
- import type { ZephyrChipDescriptor } from '../chips/types.js';
38
- import { pwmDtAliasToken } from '../lowering/pwm.js';
39
- import { detectZephyrVersion, checkZephyrCompat, resolveBoardTarget } from './compat.js';
40
- import { DEFAULT_ZEPHYR_DISPLAY_PROFILE } from '../display/profiles.js';
41
-
42
- /**
43
- * Resolve the chip for a build the same way the strategy does at emit time —
44
- * from the board constants the transpile persisted next to the emitted
45
- * source (`board-constants.json`). There is no registry fallback: a build
46
- * whose constants did not persist stays NO_BOARD_CHIP, exactly like the
47
- * emit-time path.
48
- */
49
- function chipForBuild(projectRoot: string, board: string): ZephyrChipDescriptor {
50
- try {
51
- // The transpile writes the constants into the emit outDir, which is
52
- // <projectRoot>/src for the standard layout (basename 'src' collapsed by
53
- // projectRootFromOptions); check both locations.
54
- const bcPath = [join(projectRoot, 'src', 'board-constants.json'), join(projectRoot, 'board-constants.json')]
55
- .find(p => existsSync(p));
56
- if (bcPath) {
57
- const raw = JSON.parse(readFileSync(bcPath, 'utf8')) as Record<string, string | number | boolean>;
58
- const bc = new Map(Object.entries(raw));
59
- const fromBoard = resolveChipFromBoard(bc);
60
- if (fromBoard) return fromBoard;
61
- }
62
- } catch { /* constants unreadable — no board resolved */ }
63
- return NO_BOARD_CHIP;
64
- }
65
-
66
- /**
67
- * HAL pins the emitted sources read via adc.* — scanned from the emitted
68
- * `__tc_adc<N>_setup()` call sites (N = channel index, mapped back to the HAL
69
- * pin via the chip descriptor). Feeds the overlay's ADC pinctrl rewrite: on
70
- * SoCs that mux ADC pads via pinctrl (STM32), only the read channels are
71
- * switched to analog mode.
72
- */
73
- function scanAdcReadPins(src: string, chip: ZephyrChipDescriptor): number[] {
74
- const pins: number[] = [];
75
- // Two used-signal forms:
76
- // - `__tc_adc<N>_setup()` / `__tc_adc_<ctrl>_<N>_setup()` CALL SITES
77
- // (empty parens — the adcInitLines definitions have `(void)` and would
78
- // otherwise mark every descriptor channel as used).
79
- // - `__tc_adct<pin>_done` lazy-guard vars — the thin-ADC read lowering's
80
- // inline setup (families without pinctrl groups, e.g. ESP32 SARADC,
81
- // never emit the setup-function form at all).
82
- // Channel indices are unique per CONTROLLER, so the labeled form resolves
83
- // (controller, channel) before mapping back to the HAL pin.
84
- for (const m of src.matchAll(/__tc_adc(?:(\w+?)_)?(\d+)_setup\(\)/g)) {
85
- const ch = Number(m[2]);
86
- const label = m[1];
87
- const c = chip.adc?.channels.find(
88
- (x) => x.channel === ch && (x.controller ?? chip.adc?.nodeLabel) === (label ?? chip.adc?.nodeLabel),
89
- );
90
- if (c && !pins.includes(c.pin)) pins.push(c.pin);
91
- }
92
- for (const m of src.matchAll(/__tc_adct(\d+)_done/g)) {
93
- const pin = Number(m[1]);
94
- if (chip.adc?.channels.some((x) => x.pin === pin) && !pins.includes(pin)) pins.push(pin);
95
- }
96
- return pins;
97
- }
98
-
99
- /**
100
- * HAL pins the emitted sources drive with dac.* — the DAC lowering's lazy
101
- * per-pin setup guard is `__tc_dact<pin>_done` (lowering/dac.ts), so
102
- * var-presence is the authoritative used-signal. Feeds the overlay's DAC
103
- * pinctrl gating (same pattern as scanAdcReadPins).
104
- */
105
- function scanDacWritePins(src: string): number[] {
106
- const pins: number[] = [];
107
- for (const m of src.matchAll(/__tc_dact(\d+)_done/g)) {
108
- const pin = Number(m[1]);
109
- if (!pins.includes(pin)) pins.push(pin);
110
- }
111
- return pins;
112
- }
113
-
114
- /**
115
- * HAL pins the emitted sources drive with pwm.* — the emitted source
116
- * references each used spec as `__tc_pwm_<alias token>` (pwmVarName in
117
- * lowering/pwm.ts), and the lowering only emits specs for driven pins, so
118
- * var-presence is the authoritative signal. Feeds the overlay's per-pin
119
- * pwm-leds gating (no dead DT channels).
120
- */
121
- /**
122
- * Inline-override markers (the escape hatch): the adc/pwm lowerings emit
123
- * `/* cuttlefish-user-facts: <kind> pin=N [device=X] [pinctrl=P] channel=C *​/`
124
- * comments when a construction carries routing overrides. Merged into the
125
- * chip so the overlay synthesis + used-pin scans treat them as facts —
126
- * the transpiler cannot create DT nodes, but this regen can.
127
- */
128
- function applyUserFactMarkers(chip: ZephyrChipDescriptor, src: string): ZephyrChipDescriptor {
129
- const adcAdds: { pin: number; channel: number; controller?: string; pinctrl?: string }[] = [];
130
- const pwmAdds: { pin: number; controller: string; channel: number }[] = [];
131
- for (const m of src.matchAll(/\/\* cuttlefish-user-facts: (adc|pwm) ([^*]*?) \*\//g)) {
132
- const kind = m[1];
133
- const fields = new Map<string, string>();
134
- for (const kv of m[2]!.split(/\s+/).filter(Boolean)) {
135
- const eq = kv.indexOf('=');
136
- if (eq > 0) fields.set(kv.slice(0, eq), kv.slice(eq + 1));
137
- }
138
- const pin = Number(fields.get('pin'));
139
- const channel = Number(fields.get('channel'));
140
- if (!Number.isFinite(pin) || !Number.isFinite(channel)) continue;
141
- if (kind === 'adc') {
142
- adcAdds.push({
143
- pin,
144
- channel,
145
- ...(fields.get('device') ? { controller: fields.get('device') } : {}),
146
- ...(fields.get('pinctrl') ? { pinctrl: fields.get('pinctrl') } : {}),
147
- });
148
- } else if (fields.get('controller')) {
149
- pwmAdds.push({ pin, channel, controller: fields.get('controller')! });
150
- }
151
- }
152
- if (adcAdds.length === 0 && pwmAdds.length === 0) return chip;
153
- const adc = chip.adc
154
- ? chip.adc
155
- : { nodeLabel: adcAdds.find((a) => !a.controller)?.controller ?? 'adc', resolution: 12, vrefMv: 3000, channels: [] };
156
- const adcChannels = [...adc.channels];
157
- for (const a of adcAdds) {
158
- const existing = adcChannels.findIndex((c) => c.pin === a.pin);
159
- if (existing >= 0) adcChannels.splice(existing, 1);
160
- adcChannels.push({ pin: a.pin, channel: a.channel, ...(a.controller ? { controller: a.controller } : {}), ...(a.pinctrl ? { pinctrl: a.pinctrl } : {}) });
161
- }
162
- const pwmSpecs = [...(chip.pwm?.specs ?? [])];
163
- for (const p of pwmAdds) {
164
- const existing = pwmSpecs.findIndex((s) => s.pin === p.pin);
165
- if (existing >= 0) pwmSpecs.splice(existing, 1);
166
- pwmSpecs.push({ pin: p.pin, controller: p.controller, channel: p.channel });
167
- }
168
- return {
169
- ...chip,
170
- adc: { ...adc, channels: adcChannels },
171
- pwm: { ...(chip.pwm ?? { specs: [] }), specs: pwmSpecs },
172
- };
173
- }
174
-
175
- function scanPwmUsedPins(src: string, chip: ZephyrChipDescriptor): number[] { const pins = (chip.pwm?.specs ?? [])
176
- .filter((s) => src.includes(`__tc_pwm_${pwmDtAliasToken(s)}`))
177
- .map((s) => s.pin);
178
- // Matrix pins (ESP32 LEDC) have no static specs — recover the driven pins
179
- // from the same alias-var presence signal (`__tc_pwm_tc_pwm<N>`), keeping
180
- // only pins the descriptor's matrix allows (the regex grabs the full
181
- // number, so pin 4 never matches a reference to pin 45).
182
- const matrix = chip.pwm?.matrix;
183
- if (matrix) {
184
- const present = new Set<number>();
185
- for (const match of src.matchAll(/__tc_pwm_tc_pwm(\d+)/g)) {
186
- present.add(Number(match[1]));
187
- }
188
- for (const pin of matrix.pins) {
189
- if (present.has(pin)) pins.push(pin);
190
- }
191
- }
192
- return pins;
193
- }
194
-
195
- /**
196
- * Bus controller indexes the emitted sources actually reference — the shim
197
- * declares one `__tc_<bus><N>_dev` state block per used instance (gated by
198
- * collectUsedBusIndices at transpile time), so var-presence is the
199
- * authoritative signal. The overlay enables only these controllers: an
200
- * enabled-but-unused one claims its default pins (i2c0's GP4/GP5 on the
201
- * Pico) which a program driving the OTHER controller may want as GPIO.
202
- * Empty list (no state blocks — e.g. display/touch composites that use the
203
- * driver API directly) means "no signal"; the caller then passes undefined
204
- * so the overlay enables every declared controller, preserving old behavior.
205
- */
206
- function scanUsedBusInstances(
207
- src: string,
208
- controllers: readonly { nodeLabel: string }[] | undefined,
209
- bus: 'i2c' | 'spi' | 'uart',
210
- ): number[] | undefined {
211
- if (!controllers) return undefined;
212
- const used: number[] = [];
213
- for (let i = 0; i < controllers.length; i++) {
214
- if (src.includes(`__tc_${bus}${i}_dev`)) used.push(i);
215
- }
216
- return used.length > 0 ? used : undefined;
217
- }
218
-
219
- /**
220
- * Distinct DT-bound sensors the emitted sources reference — the lowering's
221
- * state blocks name each one `__tc_sensor_<part>_i2c<N>_0x<addr>_dev`
222
- * (lowering/sensor.ts sensorNames), so var-presence is the authoritative
223
- * signal. Feeds the overlay's DT child nodes; the part group is greedy so a
224
- * compatible containing '_i2c<N>_' still resolves to the longest part match.
225
- */
226
- export interface ScannedSensorPart {
227
- part: string; busIndex: number; port: number; busKind: 'i2c' | 'spi';
228
- spiHz: number; spiMode: number; alertPin: number;
229
- }
230
-
231
- export interface ScannedSpiTarget {
232
- busIndex: number; cs: number; hz: number; mode: number;
233
- }
234
-
235
- /** Scan the emitted source for thin SPI targets (hal/spi-target.ts): the
236
- * spi_dt_spec state block's tc-spit-cfg comment carries the construction
237
- * facts, the same channel tc-sensor-cfg uses. */
238
- export function scanSpiTargets(src: string): ScannedSpiTarget[] {
239
- const out = new Map<string, ScannedSpiTarget>();
240
- for (const m of src.matchAll(/tc-spit-cfg: tc_spit_spi(\d+)_cs(\d+) hz=(\d+) mode=(\d+)/g)) {
241
- const ref: ScannedSpiTarget = { busIndex: parseInt(m[1], 10), cs: parseInt(m[2], 10), hz: parseInt(m[3], 10), mode: parseInt(m[4], 10) };
242
- out.set(`${ref.busIndex}|${ref.cs}`, ref);
243
- }
244
- return [...out.values()];
245
- }
246
-
247
- export function scanSensorParts(src: string): ScannedSensorPart[] {
248
- const out = new Map<string, ScannedSensorPart>();
249
- for (const m of src.matchAll(/__tc_sensor_([a-z0-9_]+)_(i2c|spi)(\d+)_(0x[0-9a-f]+|cs[0-9]+)_dev\b/g)) {
250
- const port = m[4].startsWith('0x') ? parseInt(m[4], 16) : parseInt(m[4].slice(2), 10);
251
- const ref: ScannedSensorPart = { part: m[1], busIndex: parseInt(m[3], 10), port, busKind: m[2] as 'i2c' | 'spi', spiHz: 0, spiMode: 0, alertPin: -1 };
252
- out.set(`${ref.part}|${ref.busKind}${ref.busIndex}|${ref.port}`, ref);
253
- }
254
- // Construction facts ride the state block's config comment — merge by
255
- // nodelabel so the scanner stays the single source for the overlay.
256
- for (const m of src.matchAll(/tc-sensor-cfg: tc_([a-z0-9_]+)_(i2c|spi)(\d+)_(0x[0-9a-f]+|cs[0-9]+) hz=(\d+) mode=(\d+) alert=(-?\d+)/g)) {
257
- const port = m[4].startsWith('0x') ? parseInt(m[4], 16) : parseInt(m[4].slice(2), 10);
258
- const key = `${m[1]}|${m[2]}${m[3]}|${port}`;
259
- const existing = out.get(key);
260
- if (existing) {
261
- existing.spiHz = parseInt(m[5], 10);
262
- existing.spiMode = parseInt(m[6], 10);
263
- existing.alertPin = parseInt(m[7], 10);
264
- }
265
- }
266
- return [...out.values()];
267
- }
268
-
269
- function targetFromOptions(o: ToolchainOptions): string {
270
- // The cuttlefish CLI populates ToolchainOptions.buildTarget from the
271
- // config's board: (frameworkData.buildTarget for board-less projects).
272
- // Accept frameworkData.target as an alias. No silent default: building for
273
- // a wrong hard-coded board is the split-brain trap.
274
- const fcTarget = (o.frameworkConfig?.target as string | undefined);
275
- const board = (o.buildTarget as string | undefined) ?? fcTarget;
276
- if (!board) {
277
- throw new Error(
278
- 'No build target: set board: in cuttlefish.config.ts (or frameworkData.buildTarget for custom-board projects).',
279
- );
280
- }
281
- return board;
282
- }
283
-
284
- /**
285
- * Derive the Zephyr project root from the cuttlefish-emitted source path.
286
- *
287
- * Cuttlefish emits `src/main.cpp` under the output dir. The CLI passes
288
- * `sourcePath` = full path to `main.cpp` and `outputDir` = its parent (`src/`).
289
- * For Zephyr, the project root is the parent of `src/` — one level above
290
- * `outputDir`. Detect that shape and adjust; otherwise fall back to `outputDir`.
291
- */
292
- export function projectRootFromOptions(o: ToolchainOptions): string {
293
- const outDir = o.outputDir;
294
- if (basename(outDir) === 'src') {
295
- return dirname(outDir);
296
- }
297
- return outDir;
298
- }
299
-
300
- /**
301
- * west build timeout. Zephyr's first build fetches the toolchain modules and
302
- * configures CMake/Ninja, which can take several minutes; allow generous headroom.
303
- */
304
- const BUILD_TIMEOUT_MS = 600_000;
305
- const FLASH_TIMEOUT_MS = 120_000;
306
-
307
- /**
308
- * Build the `west flash` argument list for a board.
309
- *
310
- * Runner selection: each board's board.cmake declares a sensible default flash
311
- * runner for its hardware (xiao_ble → nrfutil, esp32* → esptool), and `west
312
- * flash` resolves it automatically. The framework only intervenes where the
313
- * board default needs an argument it can't infer:
314
- * - An explicit `zephyr.runner` (from cuttlefish.config.ts) always wins.
315
- * - ESP32 boards forward the port via `--esp-device` (esptool reads the
316
- * device from it); board.cmake still picks the runner.
317
- * - Every other board trusts the board.cmake default. Previously this forced
318
- * `--runner nrfjprog` for every non-ESP32 target, which broke boards whose
319
- * default is not nrfjprog (xiao_ble defaults to nrfutil) and required
320
- * Nordic J-Link tools that a USB-bootloader board does not have.
321
- *
322
- * Exported (pure) so the runner-selection contract is unit-testable without
323
- * spawning west.
324
- */
325
- /**
326
- * Resolve HOW this build attaches to the board for flashing OR debugging:
327
- * the friendly `zephyr.probe` id from the board's probeMethods table (quirks
328
- * included), or the raw `zephyr.runner` escape hatch. Exported (pure) so the
329
- * selection contract is unit-testable without spawning west.
330
- *
331
- * Rules:
332
- * - `probe` + `runner` together is an error (two ways of saying it — pick one).
333
- * - An unknown `probe` id is an error listing what the board supports; a board
334
- * with no probeMethods table gets a hint to use `runner` directly.
335
- * - purpose 'debug': the chosen method must be debug-capable (`debug` is not
336
- * false — a bootloader is not a debugger). Non-capable or unknown ids list
337
- * the debug-capable methods.
338
- * - User `runnerArgs` are appended AFTER the method's args, so they can
339
- * override the method's baked-in flags (argparse takes the last value).
340
- */
341
- export type ProbeResolution =
342
- | { ok: true; runner?: string; args: string[] }
343
- | { ok: false; error: string };
344
-
345
- export function resolveProbeMethod(
346
- zc: Record<string, unknown> | undefined,
347
- chip: ZephyrChipDescriptor,
348
- purpose: 'flash' | 'debug' = 'flash',
349
- ): ProbeResolution {
350
- const probe = zc?.probe as string | undefined;
351
- const runner = zc?.runner as string | undefined;
352
- const userArgs = (zc?.runnerArgs as string[] | undefined) ?? [];
353
-
354
- if (probe && runner) {
355
- return {
356
- ok: false,
357
- error:
358
- `cuttlefish.config.ts sets both zephyr.probe ('${probe}') and zephyr.runner ('${runner}'). ` +
359
- `They are two ways to choose the probe method — remove one.`,
360
- };
361
- }
362
-
363
- if (probe) {
364
- const methods = chip.probeMethods ?? [];
365
- const method = methods.find((m) => m.id === probe);
366
- if (!method) {
367
- const listAll = methods
368
- .map((m) => `${m.id} (${m.runner}${m.description ? ` — ${m.description}` : ''})`)
369
- .join('; ');
370
- return {
371
- ok: false,
372
- error: methods.length > 0
373
- ? `Unknown probe method '${probe}' for ${chip.id}. Supported: ${listAll}.`
374
- : `This board (${chip.id}) ships no probe-method table, so 'zephyr.probe' cannot resolve '${probe}'. ` +
375
- `Use the raw 'zephyr.runner' field instead (run 'west flash --context' in the build dir for options).`,
376
- };
377
- }
378
- if (purpose === 'debug' && method.debug === false) {
379
- const debuggable = methods.filter((m) => m.debug !== false).map((m) => m.id).join(', ');
380
- return {
381
- ok: false,
382
- error:
383
- `The '${probe}' method cannot debug ${chip.id} — a bootloader is not a debugger. ` +
384
- `Debug-capable methods: ${debuggable || '(none — this board needs an external probe)'}.`,
385
- };
386
- }
387
- return {
388
- ok: true,
389
- runner: method.runner,
390
- args: [...(method.args ?? []), ...userArgs],
391
- };
392
- }
393
-
394
- return { ok: true, runner, args: userArgs };
395
- }
396
-
397
- /**
398
- * Run an openocd session against the board's probe config — the shared
399
- * engine for the pre-flash quiesce and the post-flash SYSRESETREQ (see the
400
- * call sites in upload()). The config is the probe method's verbatim
401
- * debugCfg from the board catalog (the same lines `west debug` uses);
402
- * `commands` are appended after `-f <cfg> -c init`. Returns a flash note on
403
- * success, undefined when skipped or failed (best-effort by design).
404
- */
405
- function openocdProbeSession(
406
- buildDir: string,
407
- zc: Record<string, unknown> | undefined,
408
- chip: ZephyrChipDescriptor,
409
- commands: readonly string[],
410
- ): string | undefined {
411
- // Config resolution — two sources, in order:
412
- // 1. The named probe method's verbatim debugCfg from the board catalog
413
- // (written to a temp cfg), when zephyr.probe names a method that has
414
- // one.
415
- // 2. The board's own support/openocd.cfg in the Zephyr tree — the exact
416
- // config `west flash` resolves for the openocd runner. This covers
417
- // raw `zephyr.runner: 'openocd'` (no named probe) and probe methods
418
- // that ship no debugCfg of their own.
419
- const probeId = zc?.probe as string | undefined;
420
- const method = chip.probeMethods?.find((m) => m.id === probeId);
421
- const cfgLines = method?.debugCfg;
422
- // Session reset policy: `reset_config none`. The session's resets are
423
- // core-domain by design — vector-catch halt before the flash write,
424
- // SYSRESETREQ to boot — so they must not depend on the SRST pin. Boards
425
- // like the WeAct Black Pill don't break NRST out at all: under the board
426
- // cfg's `srst_only`, every `reset` asserts a pin that reaches nothing
427
- // (the target never resets, `reset halt` catches the core mid-app in
428
- // dirty state and the flash algorithm times out) while the probe's
429
- // floating SRST sense reports phantom "external reset detected" events
430
- // that leave the session's halt state inconsistent. Method-declared west
431
- // quirks (`--cmd-pre-init=…`) are appended after and override the
432
- // default for boards whose facts carry one.
433
- const preInit = [
434
- 'reset_config none',
435
- ...(method?.args ?? [])
436
- .filter((a) => a.startsWith('--cmd-pre-init='))
437
- .map((a) => a.slice('--cmd-pre-init='.length)),
438
- ];
439
-
440
- const install = discoverWest();
441
- const sdkRoot = process.env.ZEPHYR_SDK_INSTALL_DIR || install?.sdkInstallDir;
442
- if (!sdkRoot) return undefined;
443
- const openocdExe = join(sdkRoot, 'hosttools', 'openocd', 'bin',
444
- process.platform === 'win32' ? 'openocd.exe' : 'openocd');
445
- if (!existsSync(openocdExe)) return undefined;
446
- // Script search path: the SDK layouts differ across versions — prefer the
447
- // share/ form west's own runner uses, fall back to the scripts/ form.
448
- const shareScripts = join(sdkRoot, 'hosttools', 'openocd', 'share', 'openocd', 'scripts');
449
- const binScripts = join(sdkRoot, 'hosttools', 'openocd', 'scripts');
450
- const searchDir = existsSync(shareScripts) ? shareScripts : binScripts;
451
-
452
- let cfgArgs: string[] | undefined;
453
- let sessionCfg: string | undefined;
454
- if (cfgLines && cfgLines.length > 0) {
455
- sessionCfg = join(buildDir, 'cuttlefish-probe.cfg');
456
- } else {
457
- // The board target's qualifier ('blackpill_f411ce/stm32f411xe' →
458
- // 'blackpill_f411ce') identifies the board dir; the vendor segment is
459
- // not part of the target, so probe the boards/ tree for it.
460
- const zephyrBase = process.env.ZEPHYR_BASE || install?.zephyrBase;
461
- const boardDir = (chip.id ?? '').split('/')[0];
462
- if (!zephyrBase || !boardDir) return undefined;
463
- const boardsRoot = join(zephyrBase, 'boards');
464
- let supportCfg: string | undefined;
465
- try {
466
- for (const vendor of readdirSync(boardsRoot)) {
467
- const candidate = join(boardsRoot, vendor, boardDir, 'support', 'openocd.cfg');
468
- if (existsSync(candidate)) { supportCfg = candidate; break; }
469
- }
470
- } catch {
471
- return undefined;
472
- }
473
- if (!supportCfg) return undefined;
474
- cfgArgs = ['-s', dirname(supportCfg), '-f', supportCfg];
475
- }
476
-
477
- try {
478
- mkdirSync(buildDir, { recursive: true });
479
- if (sessionCfg) {
480
- writeFileSync(sessionCfg, cfgLines!.join('\n') + '\n', 'utf-8');
481
- cfgArgs = ['-f', sessionCfg];
482
- }
483
- const res = spawnSync(openocdExe, [
484
- '-s', searchDir, ...cfgArgs!,
485
- // Pre-init TCL AFTER the cfg (overrides its reset_config) and BEFORE
486
- // init — the same position west gives --cmd-pre-init.
487
- ...preInit.map((c) => ['-c', c] as [string, string]).flat(),
488
- '-c', 'init',
489
- ...commands.map((c) => ['-c', c]).flat(),
490
- '-c', 'shutdown',
491
- ], {
492
- cwd: buildDir,
493
- encoding: 'utf-8' as const,
494
- timeout: 20_000,
495
- });
496
- return res.status === 0 ? `-- probe session ok: ${commands.join('; ')}` : undefined;
497
- } catch {
498
- return undefined;
499
- }
500
- }
501
-
502
- /**
503
- * Whether a flash runner carries the upload over a serial port. Runner-gated,
504
- * never board-name-gated: esptool and bossac are the only runners
505
- * `buildFlashArgs` forwards `--port` to, so they are the only ones that
506
- * cannot flash without one. Probe runners (openocd, jlink) and USB flows
507
- * (dfu-util, uf2 mass storage) need no port — a missing `--port` must not
508
- * block them.
509
- *
510
- * Exported (pure) so the port-requirement contract is unit-testable without
511
- * spawning west.
512
- */
513
- export function uploadRequiresPort(runner: string | undefined): boolean {
514
- return runner === 'esptool' || runner === 'bossac';
515
- }
516
-
517
- export function buildFlashArgs(
518
- buildDir: string,
519
- userRunner: string | undefined,
520
- port: string | undefined,
521
- flashRunner?: string,
522
- runnerArgs?: readonly string[],
523
- ): string[] {
524
- // flashRunner is the runner the flash will actually use — the explicit
525
- // zephyr.runner when set, else the board's declared default from its probe
526
- // table. It gates the esptool port forwarding below; only an EXPLICIT
527
- // userRunner forces west's --runner (board defaults stay board.cmake's
528
- // choice). Runner-gated, never board-name-gated: any board whose flash
529
- // runs esptool gets the same forwarding.
530
- const args = ['flash', '-d', buildDir];
531
- if (userRunner) {
532
- args.push('--runner', userRunner);
533
- }
534
- if (port && flashRunner === 'esptool') {
535
- args.push('--esp-device', port);
536
- }
537
- // The bossac runner defaults its port to /dev/ttyACM0 — on Windows that
538
- // never matches, so the port MUST be forwarded or bossac fails with
539
- // "No device found on /dev/ttyACM0" (same class of port-forwarding
540
- // problem as the esptool --esp-device above).
541
- if (port && flashRunner === 'bossac') {
542
- args.push('--bossac-port', port);
543
- }
544
- // Extra runner-specific flags, appended verbatim (west's runner parsers
545
- // accept them after the runner is selected).
546
- if (runnerArgs && runnerArgs.length > 0) {
547
- args.push(...runnerArgs);
548
- }
549
- return args;
550
- }
551
-
552
- /**
553
- * Classify a `west flash` result as success/failure.
554
- *
555
- * west's exit status is authoritative except for one known race in the uf2
556
- * runner on Windows: the UF2 bootloader reboots to run new firmware the instant
557
- * the file copy completes, unmounting the USB-MSC drive before `shutil.copy`'s
558
- * trailing `copymode`/chmod runs. That raises `OSError: [WinError 433] A
559
- * device which does not exist was specified` and makes west exit non-zero —
560
- * even though the firmware copied and flashed correctly (the LED blinks).
561
- *
562
- * The copy starting is logged ("Copying UF2 file to '<drive>'"); WinError 433
563
- * during `copymode` after that point proves the data write finished and the
564
- * drive only vanished on the metadata step. Treat that exact signature as
565
- * success so the upload isn't reported as a failure. Genuine uf2 failures
566
- * (no partition found, write errors before the copy) still surface as failures.
567
- *
568
- * Exported (pure) so the classification is unit-testable without spawning west.
569
- */
570
- export function classifyUploadResult(
571
- runner: string | undefined,
572
- status: number | null,
573
- output: string,
574
- ): boolean {
575
- if (status === 0) return true;
576
- if (isUf2DriveVanishRace(output)) return runner === 'uf2';
577
- return false;
578
- }
579
-
580
- /**
581
- * Whether `output` carries the benign UF2 copymode/WinError-433 race signature
582
- * (see classifyUploadResult). Centralized so classify + cleanse share one match.
583
- */
584
- function isUf2DriveVanishRace(output: string): boolean {
585
- return /Copying UF2 file to/.test(output)
586
- && /WinError 433/.test(output)
587
- && /copymode/.test(output);
588
- }
589
-
590
- /**
591
- * Cleanse the `west flash` output shown to the user.
592
- *
593
- * When classifyUploadResult has decided a non-zero west exit was the benign UF2
594
- * race (firmware copied, drive unmounted on the trailing chmod), the raw output
595
- * is a wall of Python traceback that reads like a hard failure. Drop everything
596
- * after the "Copying UF2 file to" line — i.e. the entire traceback — so a
597
- * successful flash reads as a success (the framework's ✓ Done follows). Non-race
598
- * output is returned untouched; genuine errors stay fully visible for diagnosis.
599
- *
600
- * Exported (pure) so the cleansing is unit-testable without spawning west.
601
- */
602
- export function cleanseUploadOutput(
603
- runner: string | undefined,
604
- status: number | null,
605
- output: string,
606
- ): string {
607
- if (status === 0) return output;
608
- if (runner === 'uf2' && isUf2DriveVanishRace(output)) {
609
- // Keep everything west printed up to and including "Copying UF2 file to",
610
- // then stop — everything after that is the drive-vanish traceback.
611
- const upto = output.match(/[\s\S]*Copying UF2 file to[^\n]*/);
612
- const head = upto ? upto[0] : '-- west flash: using runner uf2';
613
- return head;
614
- }
615
- return output;
616
- }
617
-
618
-
619
- /**
620
- * Whether a failed `west build` output carries ninja's `dependency cycle`
621
- * signature. Zephyr 4.3.99-dev snapshots have a regression
622
- * (zephyrproject-rtos/zephyr#104757, fixed upstream by the #104784 revert,
623
- * in v4.4+): after CMake re-runs from a .config change, the build dir's
624
- * .ninja_deps records an `offsets.h -> offsets.c.obj -> offsets.h` cycle and
625
- * ninja aborts with `ninja: error: dependency cycle: ...` before compiling
626
- * anything. The cycle lives in the build dir, not the sources, so compile()
627
- * recovers by deleting the dir and retrying once.
628
- *
629
- * Exported (pure) so the detection is unit-testable without spawning west.
630
- */
631
- export function isDependencyCycleFailure(output: string): boolean {
632
- return output.includes('dependency cycle');
633
- }
634
-
635
- /** stdout+stderr of a spawnSync result coerced to one string. Defensive about
636
- * the buffer form (spawnSync only returns strings when `encoding` is set,
637
- * which every call site here does — but the coercion costs nothing). */
638
- function combinedSpawnOutput(
639
- result: { stdout?: string | Buffer | null; stderr?: string | Buffer | null },
640
- ): string {
641
- const so = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
642
- const se = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
643
- return so + se;
644
- }
645
-
646
- /**
647
- * FrameworkToolchain for Zephyr. Spec §3.5 (mirror of the ESP-IDF toolchain).
648
- * The target board is carried via frameworkData.buildTarget; scaffolding
649
- * happens at compile time when the target is known.
650
- */
651
- export const Toolchain = {
652
- prepare(outputDir: string, entryPoint: string): void {
653
- // Write the DT overlay for the default board (the real target is known at
654
- // compile time; prepare runs before compile, so use the default board id).
655
- // The overlay is additive and idempotent; compile re-runs prepare-equivalent
656
- // logic in scaffold via the usage scan. Mirrors how Arduino's library
657
- // resolution is a pre-build artifact step.
658
- const projectRoot = basename(outputDir) === 'src' ? dirname(outputDir) : outputDir;
659
- // Scan the emitted source for usage tokens (same authoritative signal the
660
- // scaffold uses). entryPoint is the path to main.cpp; its dir is src/.
661
- const srcDir = dirname(entryPoint);
662
- let src = '';
663
- try {
664
- for (const name of readdirSync(srcDir)) {
665
- if (name.endsWith('.cpp') || name.endsWith('.c')) {
666
- src += readFileSync(join(srcDir, name), 'utf8');
667
- }
668
- }
669
- } catch { /* src may not exist yet on first prepare */ }
670
- const uses = (t: string): boolean => src.includes(t);
671
- // Inline-override markers (the escape hatch): the lowerings emit
672
- // `cuttlefish-user-facts` comments carrying routing the transpiler
673
- // cannot synthesize (adc device/pinctrl, pwm controller/channel).
674
- // Merged into the chip BEFORE the scans + overlay generation, so the DT
675
- // nodes, pinctrl groups, and used-pin recovery treat them as facts.
676
- const chip = applyUserFactMarkers(chipForBuild(projectRoot, ''), src);
677
- // Display usage tokens: the minimal GFX runtime (display_write/_fill_rect)
678
- // and the UI display adapter (display_init / __tc_display_dev /
679
- // DEVICE_DT_GET on the display nodelabel). Both paths need the DT overlay
680
- // to enable the display node.
681
- const usesDisplay = uses('display_write') || uses('display_init')
682
- || uses('display_fill_rect') || uses('__tc_display_dev')
683
- || uses('CuttlefishDisplayTarget');
684
- // Both registered Zephyr display profiles use dtLabel 'display0', so the
685
- // default profile's overlay block (&display0 { status="okay" }) is correct
686
- // for either driver. Thread a non-default profile here only if a future
687
- // board carries a display node under a different nodelabel.
688
- const displayProfile = usesDisplay ? DEFAULT_ZEPHYR_DISPLAY_PROFILE : undefined;
689
- // Touch controller kind comes from which DT nodelabel the emitted adapter
690
- // references (FT6336U on I2C, XPT2046 on the display's SPI bus).
691
- const usesTouch = uses('ft6336u') || uses('touch_');
692
- const usesXpt = uses('xpt2046');
693
- const sensorParts = scanSensorParts(src);
694
- const spiTargetParts = scanSpiTargets(src);
695
- const overlay = generateOverlay(chip, {
696
- // __tc_<bus> matches the shim state block — a begin()-only program
697
- // emits no driver API call but still declares the DT device. A
698
- // constructed sensor is also a bus user (its device handle is the
699
- // only i2c reference a sensor-only program carries).
700
- usesI2c: uses('i2c_') || uses('__tc_i2c') || sensorParts.length > 0,
701
- usesSensor: uses('sensor_') || sensorParts.length > 0,
702
- usesFloatFormat: /%[-0-9.]*[eEfFgG]/.test(src),
703
- sensorParts,
704
- spiTargets: spiTargetParts,
705
- usesSpi: uses('spi_') || uses('__tc_spi') || spiTargetParts.length > 0,
706
- usesUart: uses('__tc_uart'),
707
- usesUsb: uses('__tc_usb'),
708
- usesPwm: uses('pwm_'),
709
- usesAdc: uses('adc_'),
710
- adcReadPins: scanAdcReadPins(src, chip),
711
- dacWritePins: scanDacWritePins(src),
712
- pwmUsedPins: scanPwmUsedPins(src, chip),
713
- i2cUsedInstances: scanUsedBusInstances(src, chip.i2c?.controllers, 'i2c'),
714
- spiUsedInstances: scanUsedBusInstances(src, chip.spi?.controllers, 'spi'),
715
- uartUsedInstances: scanUsedBusInstances(src, chip.uart?.controllers, 'uart'),
716
- // Preferences/FS — same tokens scaffoldZephyrProject scans (the ZMS
717
- // settings_* API + __tc_prefs shim, the __tc_fs mount shim); drive the
718
- // storage-partition synthesis + /chosen settings pointer.
719
- usesPreferences: uses('settings_') || uses('__tc_prefs'),
720
- usesFS: uses('__tc_fs'),
721
- usesWdt: uses('wdt_'),
722
- usesHwtimer: uses('counter_') || uses('__tc_hw'),
723
- usesDisplay,
724
- usesTouch: usesTouch || usesXpt,
725
- touchController: usesXpt ? 'xpt2046' : 'ft6336u',
726
- }, displayProfile);
727
- const overlayDir = join(projectRoot, 'boards');
728
- mkdirSync(overlayDir, { recursive: true });
729
- // prepare() runs before the real target is known — the placeholder name
730
- // never matches `west build -b <board>` (compile rewrites the overlay
731
- // under the actual board's name below).
732
- writeIfChanged(join(overlayDir, 'board.overlay'), overlay);
733
- // Thin SPI targets need an app-local binding: a compatible-less DT node
734
- // generates NO property macros, so SPI_DT_SPEC_GET's spi-max-frequency
735
- // lookup would not exist. The binding has no driver — it exists so
736
- // gen_defines emits the spi properties for the target nodes.
737
- if (spiTargetParts.length > 0) {
738
- const bindingsDir = join(projectRoot, 'dts', 'bindings');
739
- mkdirSync(bindingsDir, { recursive: true });
740
- writeIfChanged(join(bindingsDir, 'cuttlefish,spi-target.yaml'), [
741
- 'description: |',
742
- ' Cuttlefish thin SPITarget (hal/spi-target.ts) — a raw spi_dt_spec',
743
- ' peer. No driver binds this compatible; it exists so devicetree',
744
- ' generation emits the spi properties (spi-max-frequency,',
745
- ' spi-cpol/spi-cpha, reg = the cs-gpios index) that SPI_DT_SPEC_GET',
746
- ' consumes from the generated C++.',
747
- 'compatible: "cuttlefish,spi-target"',
748
- 'include: spi-device.yaml',
749
- '',
750
- ].join('\n'));
751
- }
752
- },
753
-
754
- compile(o: ToolchainOptions): CompileResult {
755
- const projectRoot = projectRootFromOptions(o);
756
- const rawBoard = targetFromOptions(o);
757
-
758
- // Fail fast on an incompatible Zephyr (clear message vs. a cryptic west/
759
- // CMake board error), then normalize the board target for the installed
760
- // version — Zephyr 4.3+ rejects bare multi-core board names, so a stale
761
- // config (esp32s3_devkitc) is rewritten to the qualified form
762
- // (esp32s3_devkitc/esp32s3/procpu). See toolchain/compat.ts.
763
- const zephyrVersion = detectZephyrVersion();
764
- const compat = checkZephyrCompat(zephyrVersion);
765
- if (compat.status === 'out-of-range') {
766
- throw new Error(
767
- `Zephyr ${zephyrVersion} is outside the supported range (${compat.range}) for @typecad/framework-zephyr. ` +
768
- `Set ZEPHYR_BASE to a compatible Zephyr checkout, or install one via '@typecad/zephyr-installer'.`,
769
- );
770
- }
771
- if (compat.status === 'undetectable') {
772
- console.warn(
773
- `! Could not detect the installed Zephyr version (is ZEPHYR_BASE set?). ` +
774
- `Skipping compat check; declared range is ${compat.range}.`,
775
- );
776
- }
777
- const board = resolveBoardTarget(rawBoard, zephyrVersion);
778
-
779
- const debugMode = new ZephyrStrategy().debugMode(board);
780
- const isGdbDebug = o.debug === true && debugMode === 'gdb';
781
- const zc = o.zephyrConfig as Record<string, unknown> | undefined;
782
- const userKconfig = zc?.kconfig as Record<string, string> | undefined;
783
- const configChanged = scaffoldZephyrProject(projectRoot, isGdbDebug, userKconfig, o.psram);
784
-
785
- // Regenerate the DT overlay for the ACTUAL target board. prepare() writes
786
- // it for the default board (the real target is unknown until compile), so
787
- // the <default>.overlay it wrote does not match `west build -b <board>`.
788
- // Zephyr auto-detects boards/<board>.overlay under APPLICATION_CONFIG_DIR.
789
- try {
790
- const chip = chipForBuild(projectRoot, board);
791
- // Custom-board generation: an MCU-only target (no board package) has no
792
- // upstream Zephyr board — generate one under boards/typecad/<name>/ from
793
- // the chip's silicon data. Opt-in via `zephyr.customBoard: true` in
794
- // cuttlefish.config.ts; the board takes its name from the build target.
795
- // Idempotent — regenerated on every compile, before the overlay pass.
796
- if (zc?.customBoard === true) {
797
- const generated = generateCustomBoard(projectRoot, chip, board.split('/')[0]);
798
- if (!generated) {
799
- throw new Error(
800
- `zephyr.customBoard is set, but the resolved chip ('${chip.id}') carries no ` +
801
- `silicon board data. Custom-board generation requires an MCU-only config ` +
802
- `(mcu set, board absent) whose MCU package ships a zephyr block.`,
803
- );
804
- }
805
- }
806
- const srcDir = join(projectRoot, 'src');
807
- let src = '';
808
- try {
809
- for (const name of readdirSync(srcDir)) {
810
- if (name.endsWith('.cpp') || name.endsWith('.c')) {
811
- src += readFileSync(join(srcDir, name), 'utf-8');
812
- }
813
- }
814
- } catch { /* src may not exist */ }
815
- const uses = (t: string): boolean => src.includes(t);
816
- const usesDisplay = uses('display_write') || uses('display_init')
817
- || uses('display_fill_rect') || uses('__tc_display_dev')
818
- || uses('CuttlefishDisplayTarget');
819
- // Derive the display dimensions from the emitted adapter code
820
- // (display_width/height return the profile's w/h). This ensures the DT
821
- // overlay's width/height match the panel the adapter targets, not the
822
- // default profile — critical for drivers like ST7796S that initialize
823
- // the panel geometry from the DT node.
824
- let displayProfile = usesDisplay ? DEFAULT_ZEPHYR_DISPLAY_PROFILE : undefined;
825
- if (usesDisplay) {
826
- const wMatch = src.match(/display_width\(\)\s*\{\s*return\s+(\d+)\s*;\s*\}/);
827
- const hMatch = src.match(/display_height\(\)\s*\{\s*return\s+(\d+)\s*;\s*\}/);
828
- if (wMatch && hMatch) {
829
- displayProfile = {
830
- ...DEFAULT_ZEPHYR_DISPLAY_PROFILE,
831
- width: parseInt(wMatch[1], 10),
832
- height: parseInt(hMatch[1], 10),
833
- };
834
- }
835
- }
836
- // Extract display pin wiring (cs/dc/rst/spiFrequency/spiPins) from the
837
- // config display section so the DT overlay wires the MIPI DBI bridge to
838
- // the correct GPIOs + SPI bus pins.
839
- const dispCfg = o.display as Record<string, unknown> | undefined;
840
- const spiPins = (dispCfg?.spiPins ?? undefined) as
841
- { sck?: unknown; mosi?: unknown; miso?: unknown } | undefined;
842
- const wiring: DisplayWiring | undefined = dispCfg
843
- ? {
844
- cs: typeof dispCfg.cs === 'number' ? dispCfg.cs : undefined,
845
- dc: typeof dispCfg.dc === 'number' ? dispCfg.dc : undefined,
846
- rst: typeof dispCfg.rst === 'number' ? dispCfg.rst : undefined,
847
- spiFrequency: typeof dispCfg.spiFrequency === 'number' ? dispCfg.spiFrequency : undefined,
848
- sck: typeof spiPins?.sck === 'number' ? spiPins.sck : undefined,
849
- mosi: typeof spiPins?.mosi === 'number' ? spiPins.mosi : undefined,
850
- miso: typeof spiPins?.miso === 'number' ? spiPins.miso : undefined,
851
- backlightPin: typeof dispCfg.backlightPin === 'number' ? dispCfg.backlightPin : undefined,
852
- tearingEffectPin: typeof dispCfg.tearingEffectPin === 'number' ? dispCfg.tearingEffectPin : undefined,
853
- }
854
- : undefined;
855
- // Extract touch pin wiring from the config display.touch section so the
856
- // DT overlay wires the bus + touch node. I2C (FT6336U) carries
857
- // irq/resetPin/sda/scl; SPI (XPT2046) carries irq/cs + the calibration
858
- // range the xptek,xpt2046 binding requires.
859
- const touchCfg = dispCfg?.touch as Record<string, unknown> | undefined;
860
- const isXpt = touchCfg?.library === 'XPT2046_Touchscreen';
861
- const touchCal = touchCfg?.calibration as
862
- { xMin?: unknown; xMax?: unknown; yMin?: unknown; yMax?: unknown } | undefined;
863
- const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);
864
- let touchWiring: TouchWiring | undefined = touchCfg
865
- ? {
866
- controller: isXpt ? 'xpt2046' : 'ft6336u',
867
- irq: num(touchCfg.irq),
868
- resetPin: num(touchCfg.resetPin),
869
- sda: num(touchCfg.sda),
870
- scl: num(touchCfg.scl),
871
- cs: num(touchCfg.cs),
872
- calibration: touchCal
873
- ? {
874
- xMin: num(touchCal.xMin) ?? 0,
875
- xMax: num(touchCal.xMax) ?? 4095,
876
- yMin: num(touchCal.yMin) ?? 0,
877
- yMax: num(touchCal.yMax) ?? 4095,
878
- }
879
- : undefined,
880
- minPressure: num(touchCfg.minPressure),
881
- }
882
- : undefined;
883
- // Touch controller kind for Kconfig (bus driver selection) and the DT
884
- // node shape: from the config when available, else from the DT nodelabel
885
- // the emitted adapter references. Forced onto touchWiring so a source
886
- // scan match without a config section still emits the right node.
887
- const usesXpt = isXpt || uses('xpt2046');
888
- if (usesXpt) {
889
- touchWiring = { controller: 'xpt2046', ...(touchWiring ?? {}) };
890
- }
891
- const overlayDiagnostics: OverlayDiagnostic[] = [];
892
- const sensorParts = scanSensorParts(src);
893
- const spiTargetParts = scanSpiTargets(src);
894
- const overlay = generateOverlay(chip, {
895
- // __tc_<bus> matches the shim state block — a begin()-only program
896
- // emits no driver API call but still declares the DT device. A
897
- // constructed sensor is also a bus user (see scanSensorParts).
898
- usesI2c: uses('i2c_') || uses('__tc_i2c') || sensorParts.length > 0,
899
- usesSensor: uses('sensor_') || sensorParts.length > 0,
900
- usesFloatFormat: /%[-0-9.]*[eEfFgG]/.test(src),
901
- sensorParts,
902
- spiTargets: spiTargetParts,
903
- usesSpi: uses('spi_') || uses('__tc_spi') || spiTargetParts.length > 0,
904
- usesUart: uses('__tc_uart'),
905
- usesUsb: uses('__tc_usb'),
906
- usesPwm: uses('pwm_'),
907
- usesAdc: uses('adc_'),
908
- adcReadPins: scanAdcReadPins(src, chip),
909
- usesDac: uses('dac_') || uses('__tc_dac'),
910
- dacWritePins: scanDacWritePins(src),
911
- pwmUsedPins: scanPwmUsedPins(src, chip),
912
- i2cUsedInstances: scanUsedBusInstances(src, chip.i2c?.controllers, 'i2c'),
913
- spiUsedInstances: scanUsedBusInstances(src, chip.spi?.controllers, 'spi'),
914
- uartUsedInstances: scanUsedBusInstances(src, chip.uart?.controllers, 'uart'),
915
- // Preferences/FS — same tokens scaffoldZephyrProject scans; drive the
916
- // storage-partition synthesis + /chosen settings pointer.
917
- usesPreferences: uses('settings_') || uses('__tc_prefs'),
918
- usesWdt: uses('wdt_'),
919
- usesHwtimer: uses('counter_') || uses('__tc_hw'),
920
- usesFS: uses('__tc_fs'),
921
- usesDisplay,
922
- usesTouch: uses('ft6336u') || uses('touch_') || usesXpt,
923
- touchController: usesXpt ? 'xpt2046' : 'ft6336u',
924
- psram: o.psram,
925
- }, displayProfile, wiring, touchWiring, overlayDiagnostics);
926
- for (const d of overlayDiagnostics) {
927
- console.warn(`overlay: ${d.message}`);
928
- }
929
- const overlayDir = join(projectRoot, 'boards');
930
- mkdirSync(overlayDir, { recursive: true });
931
- // Write the board-specific overlay (the one west loads). Zephyr looks for
932
- // boards/<board_id>.overlay under APPLICATION_CONFIG_DIR — use the bare
933
- // board id (before any hardware-qualifier suffix, e.g. 'esp32_devkitc'
934
- // not the full 'esp32_devkitc/esp32/procpu' target string). Library
935
- // packages' overlay fragments are appended by the scaffold helper.
936
- const boardId = board.split('/')[0];
937
- writeIfChanged(
938
- join(overlayDir, `${boardId}.overlay`),
939
- appendLibraryOverlayFragments(overlay, projectRoot),
940
- );
941
- // Thin SPI targets need the app-local binding (see the transpile-side
942
- // write for the rationale): no compatible → no generated spi props →
943
- // SPI_DT_SPEC_GET's spi-max-frequency lookup does not exist.
944
- if (spiTargetParts.length > 0) {
945
- const bindingsDir = join(projectRoot, 'dts', 'bindings');
946
- mkdirSync(bindingsDir, { recursive: true });
947
- writeIfChanged(join(bindingsDir, 'cuttlefish,spi-target.yaml'), [
948
- 'description: |',
949
- ' Cuttlefish thin SPITarget (hal/spi-target.ts) — a raw spi_dt_spec',
950
- ' peer. No driver binds this compatible; it exists so devicetree',
951
- ' generation emits the spi properties (spi-max-frequency,',
952
- ' spi-cpol/spi-cpha, reg = the cs-gpios index) that SPI_DT_SPEC_GET',
953
- ' consumes from the generated C++.',
954
- 'compatible: "cuttlefish,spi-target"',
955
- 'include: spi-device.yaml',
956
- '',
957
- ].join('\n'));
958
- }
959
- } catch { /* best-effort overlay regen; the build surfaces DT errors */ }
960
-
961
- // Use a stable build dir so incremental builds reuse the Ninja graph.
962
- // west defaults to <projectRoot>/build.
963
- const buildDir = join(projectRoot, 'build');
964
-
965
- // Reuse the build dir across builds so ninja recompiles only the changed
966
- // app translation units and re-links — a pristine configure + the
967
- // ~280-target Zephyr library rebuild costs minutes on Windows
968
- // (demo-shadcn measures 69s of ninja wall time, 448s of summed compile
969
- // work, and every build redid all of it). Nuke it only when the generated
970
- // config changed (prj.conf / CMakeLists content), the one path that must
971
- // not reuse a cached graph: Zephyr 4.3.99-dev snapshots carry a
972
- // regression (zephyrproject-rtos/zephyr#104757, fixed by the #104784
973
- // revert on 2026-03-03, in v4.4+) where re-running CMake after a .config
974
- // change records an `offsets.h -> offsets.c.obj -> offsets.h` cycle in
975
- // .ninja_deps, after which every ninja run fails with `dependency cycle`.
976
- // Plain source edits never reconfigure CMake, so they cannot trigger it —
977
- // and the retry after the spawn below self-heals any path that still does.
978
- // Board switches need no nuke here: `west build` is --pristine=auto by
979
- // default and recreates the dir itself when -b <board> mismatches the
980
- // cached board.
981
- if (configChanged) {
982
- try { rmSync(buildDir, { recursive: true, force: true }); } catch { /* may not exist */ }
983
- }
984
-
985
- const buildArgs = ['build', '-b', board, '-d', buildDir, projectRoot];
986
- // Explicitly pass the generated DT overlay. Zephyr's auto-detection of
987
- // boards/<board>.overlay fails for hardware-qualified targets (e.g.
988
- // esp32_devkitc/esp32/procpu) because the FILE_SUFFIX matching doesn't
989
- // resolve — passing -DDTC_OVERLAY_FILE forces it unconditionally.
990
- const boardId = board.split('/')[0];
991
- const overlayPath = join(projectRoot, 'boards', `${boardId}.overlay`);
992
- try {
993
- if (readFileSync(overlayPath, 'utf-8').length > 0) {
994
- // CMake parses backslashes as escapes — use forward slashes so the
995
- // Windows path survives the -D argument intact.
996
- buildArgs.push('--', `-DDTC_OVERLAY_FILE=${overlayPath.replace(/\\/g, '/')}`);
997
- }
998
- } catch { /* no overlay — let Zephyr auto-detect or build without one */ }
999
- // Append user cmake args from cuttlefish.config.ts zephyr.cmakeArgs.
1000
- const userCmakeArgs = zc?.cmakeArgs as string[] | undefined;
1001
- if (userCmakeArgs && userCmakeArgs.length > 0) {
1002
- if (!buildArgs.includes('--')) buildArgs.push('--');
1003
- buildArgs.push(...userCmakeArgs);
1004
- }
1005
- const inv = westSpawn(
1006
- buildArgs,
1007
- { cwd: projectRoot, encoding: 'utf-8', timeout: BUILD_TIMEOUT_MS },
1008
- );
1009
- let result = spawnSync(inv.command, inv.args, inv.options);
1010
- // Self-heal the Zephyr 4.3.99 dep-cycle regression (see the nuke comment
1011
- // above): when the cached .ninja_deps carries the cycle, ninja aborts with
1012
- // `dependency cycle` before compiling anything. The cycle lives in the
1013
- // build dir, not the sources — one pristine retry clears it and the build
1014
- // proceeds. On fixed Zephyr (>=4.4) this never fires.
1015
- let pristineRetry = false;
1016
- if (result.status !== 0 && isDependencyCycleFailure(combinedSpawnOutput(result))) {
1017
- try { rmSync(buildDir, { recursive: true, force: true }); } catch { /* may not exist */ }
1018
- result = spawnSync(inv.command, inv.args, inv.options);
1019
- pristineRetry = true;
1020
- }
1021
-
1022
- const stdout = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
1023
- const stderr = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
1024
- const output = stdout + stderr + (pristineRetry
1025
- ? '\n[cuttlefish] dependency cycle detected in the cached build dir — retried with a pristine build'
1026
- : '');
1027
- // Prefix the build log with how west was resolved, for transparency.
1028
- const header = `Using west via ${inv.install.source}` +
1029
- (inv.install.zephyrBase ? ` (ZEPHYR_BASE=${inv.install.zephyrBase})` : '') + '\n';
1030
-
1031
- // After a successful build in gdb mode (--debug on a probe-capable target),
1032
- // write the VS Code launch.json + tasks.json + gdb-script artifacts so F5
1033
- // attaches GDB to the chip's debug probe. Non-fatal on failure — a missing
1034
- // artifact doesn't block the build. Mirrors the deleted framework-esp32
1035
- // toolchain compile() debug-config wiring.
1036
- if (result.status === 0 && isGdbDebug) {
1037
- try {
1038
- const { workspaceRoot, appRel } = resolveDebugLocations(projectRoot);
1039
- writeDebugConfig({
1040
- projectRoot,
1041
- workspaceRoot,
1042
- appRel,
1043
- target: board,
1044
- buildDir,
1045
- sourceMapPath: join(dirname(o.sourcePath), `${basename(o.sourcePath)}.thcppmap.json`),
1046
- });
1047
- } catch (e) {
1048
- console.warn(`[cuttlefish] gdb debug config generation failed: ${(e as Error).message}`);
1049
- }
1050
- }
1051
-
1052
- // As-built snapshot: after a successful build, the resolved devicetree
1053
- // at <buildDir>/zephyr/zephyr.dts carries the board's pinctrl labels —
1054
- // the STABLE name grammar, immune to vendor macro churn. Harvest its
1055
- // routes into .cuttlefish/as-built.json; the next build's board-module
1056
- // generation merges them per-pin over the catalog harvest (build wins,
1057
- // silently when they agree). One-build freshness lag on first setup,
1058
- // self-maintaining after. Best-effort — a missing/unparseable artifact
1059
- // never fails the build.
1060
- if (result.status === 0) {
1061
- try {
1062
- const dtsPath = join(buildDir, 'zephyr', 'zephyr.dts');
1063
- const dtsText = readFileSync(dtsPath, 'utf8');
1064
- const facts = parseZephyrDts(dtsText);
1065
- const total = facts.adc.length + facts.pwm.length + facts.dac.length;
1066
- if (total > 0) {
1067
- // Write beside the project's board module — the .cuttlefish dir the
1068
- // config loader reads from, discovered by walking up to the
1069
- // generated board.json (the scaffold root and the config root are
1070
- // different dirs in the standard layout: src/out vs project root).
1071
- let cfDir = join(projectRoot, '.cuttlefish');
1072
- for (let dir = projectRoot; ; dir = dirname(dir)) {
1073
- if (existsSync(join(dir, '.cuttlefish', 'board.json'))) {
1074
- cfDir = join(dir, '.cuttlefish');
1075
- break;
1076
- }
1077
- const parent = dirname(dir);
1078
- if (parent === dir) break;
1079
- }
1080
- mkdirSync(cfDir, { recursive: true });
1081
- writeIfChanged(join(cfDir, 'as-built.json'), asBuiltJson(board, facts));
1082
- }
1083
- } catch { /* best-effort snapshot — nothing to harvest or unreadable */ }
1084
- }
1085
-
1086
- return {
1087
- success: result.status === 0,
1088
- output: header + output,
1089
- errors: parseCompileErrors(output, o.sourcePath),
1090
- };
1091
- },
1092
-
1093
- upload(o: ToolchainOptions): UploadResult {
1094
- const projectRoot = projectRootFromOptions(o);
1095
- const buildDir = join(projectRoot, 'build');
1096
- const board = targetFromOptions(o);
1097
- const zc = o.zephyrConfig as Record<string, unknown> | undefined;
1098
- const chip = chipForBuild(projectRoot, board);
1099
- const probe = resolveProbeMethod(zc, chip, 'flash');
1100
- if (!probe.ok) {
1101
- return { success: false, output: `-- west flash: ${probe.error}` };
1102
- }
1103
- // BOSSA bootloader boards with touch-reset data: open the app's console
1104
- // port at 1200 baud (the firmware's USB shim reboots into the
1105
- // bootloader), wait for the bootloader identity, and flash THAT port.
1106
- // Falls back to the configured port (manual double-tap) on any failure.
1107
- let flashPort = o.port;
1108
- const flashNotes: string[] = [];
1109
- // The runner this flash will actually use: the explicit choice, else the
1110
- // board's declared default (first probe-method entry). Gates port
1111
- // forwarding and the bossac touch below — board.cmake still resolves
1112
- // the default runner itself.
1113
- const flashRunner = probe.runner ?? chip.probeMethods?.[0]?.runner;
1114
- // Serial-port runners cannot flash without a port; every other runner
1115
- // (probe or USB) proceeds — whether a port is required is the runner's
1116
- // call, not the CLI's blanket gate.
1117
- if (uploadRequiresPort(flashRunner) && !flashPort) {
1118
- return {
1119
- success: false,
1120
- output: `-- upload requires a port for ${flashRunner} flashing. Set --port <port> on the command line (or the CUTTLEFISH_PORT env var).`,
1121
- };
1122
- }
1123
- if (flashRunner === 'bossac' && flashPort && chip.usb?.touchReset) {
1124
- const touch = bossacTouchReset(flashPort, chip.usb.touchReset);
1125
- flashNotes.push(`-- ${touch.note}`);
1126
- if (touch.port) flashPort = touch.port;
1127
- }
1128
- const args = buildFlashArgs(buildDir, probe.runner, flashPort, flashRunner, probe.args);
1129
-
1130
- // openocd flashes go through a dedicated session instead of `west flash`.
1131
- // west's flow has three sequential races that each strand the board: the
1132
- // connect happens against a running (often USB-active) application, the
1133
- // erase precedes the write so the vector table is 0xFFFFFFFF while the
1134
- // RAM algorithm runs (any exception → core LOCKUP at 0xFFFFFFFE, "timeout
1135
- // waiting for algorithm"), and the trailing `reset run` frequently does
1136
- // not reach the core. This session is deterministic end to end: halt at
1137
- // the reset vector (static target for the DAP), mask interrupts for the
1138
- // algorithm (exceptions cannot vector through erased flash), unmask
1139
- // after, and boot the flashed app with a direct SYSRESETREQ. Falls back
1140
- // to `west flash` when the image or session is unavailable.
1141
- let westFallback = true;
1142
- if (probe.runner === 'openocd') {
1143
- const hex = join(buildDir, 'zephyr', 'zephyr.hex');
1144
- if (existsSync(hex)) {
1145
- // Forward slashes + TCL quoting so project paths with spaces work.
1146
- const hexArg = `"${hex.replace(/\\/g, '/')}"`;
1147
- // Target addressing: `cortex_m` is a PER-TARGET subcommand — a bare
1148
- // `cortex_m maskisr on` is an unknown command (a silent no-op inside
1149
- // catch). Resolve the session's target object once and address it.
1150
- // Cortex-M-only, self-gating: on other cores the cortex_m method
1151
- // errors and catch contains it (the plain flash path is safe there
1152
- // without masking — the lockup class is Cortex-M vectoring).
1153
- const flashed = openocdProbeSession(buildDir, zc, chip, [
1154
- 'set _tgt [lindex [target names] 0]',
1155
- 'reset halt',
1156
- 'catch { $_tgt cortex_m maskisr on }',
1157
- `flash write_image erase ${hexArg}`,
1158
- 'catch { $_tgt cortex_m maskisr off }',
1159
- // Boot the flashed app. Cortex-M: a direct SYSRESETREQ via AIRCR —
1160
- // pin-independent, always reaches the core, and clears PRIMASK
1161
- // (so the masked algorithm leaves nothing behind). Other cores:
1162
- // openocd's generic reset run. A halted core STAYS halted across
1163
- // a core-initiated reset (debug halt state survives — that is how
1164
- // reset halt works), so resume it; on a running core resume errors
1165
- // and the catch swallows it.
1166
- 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1167
- 'sleep 100',
1168
- 'catch { resume }',
1169
- 'sleep 200',
1170
- ]);
1171
- if (flashed) {
1172
- westFallback = false;
1173
- flashNotes.push('-- probe flash ok: halt → masked write → SYSRESETREQ');
1174
- }
1175
- }
1176
- }
1177
-
1178
- let result: ReturnType<typeof spawnSync> | undefined;
1179
- let raw = '';
1180
- let ok = false;
1181
- if (westFallback) {
1182
- const inv = westSpawn(args, {
1183
- cwd: projectRoot,
1184
- encoding: 'utf-8',
1185
- timeout: FLASH_TIMEOUT_MS,
1186
- });
1187
- result = spawnSync(inv.command, inv.args, inv.options);
1188
- const fstdout = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
1189
- const fstderr = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
1190
- raw = fstdout + fstderr;
1191
- ok = classifyUploadResult(probe.runner, result.status, raw);
1192
- // A SUCCESSFUL west openocd flash can still leave the core HALTED:
1193
- // west's trailing `reset run` does not reach a core behind an unwired
1194
- // SRST, and the user's only recourse is the NRST button. Boot it from
1195
- // a probe session instead — one core reset (a halted core re-halts at
1196
- // the reset vector; a running core restarts the just-flashed app)
1197
- // plus a resume.
1198
- if (ok && probe.runner === 'openocd') {
1199
- const booted = openocdProbeSession(buildDir, zc, chip, [
1200
- 'set _tgt [lindex [target names] 0]',
1201
- 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1202
- 'sleep 100',
1203
- 'catch { resume }',
1204
- 'sleep 200',
1205
- ]);
1206
- if (booted) flashNotes.push('-- probe boot ok: SYSRESETREQ → resume');
1207
- }
1208
- // Fallback-path recovery: a failed west flash leaves the core in
1209
- // lockup; a direct SYSRESETREQ clears it so the caller's retry (or a
1210
- // later flash) starts from a clean chip.
1211
- if (!ok && probe.runner === 'openocd') {
1212
- const revived = openocdProbeSession(buildDir, zc, chip, [
1213
- 'init',
1214
- 'set _tgt [lindex [target names] 0]',
1215
- 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1216
- 'sleep 300',
1217
- ]);
1218
- if (revived) flashNotes.push(revived);
1219
- }
1220
- } else {
1221
- ok = true;
1222
- }
1223
- return {
1224
- success: ok,
1225
- output: [...flashNotes, cleanseUploadOutput(probe.runner, westFallback ? result!.status : 0, raw)]
1226
- .filter(Boolean).join('\n'),
1227
- };
1228
- },
1229
-
1230
- monitor(o: ToolchainOptions): void {
1231
- // Serial monitor over USB-CDC. Zephyr does NOT ship a `west serial`
1232
- // subcommand (it's not a real west command — invoking it errors with
1233
- // "unknown command"). The discovered west install's venv carries pyserial,
1234
- // so run its bundled miniterm directly: `python -m serial.tools.miniterm`.
1235
- // That is the same cross-platform terminal pyserial provides in ESP-IDF's
1236
- // idf.py monitor, and it inherits stdio so Ctrl+C exits cleanly.
1237
- if (!o.port) {
1238
- throw new Error(
1239
- 'A serial port is required to monitor. Pass --port <COMx/ttyX>.',
1240
- );
1241
- }
1242
- // ESP32 USB-CDC console runs at 115200 (the Zephyr ESP32 board default).
1243
- // The CLI's generic default of 9600 is wrong for this target; honor an
1244
- // explicit --baud when given, else 115200.
1245
- const baud = o.baud ?? 115200;
1246
- const install = discoverWest();
1247
- const py = install?.pythonExecutable ?? process.env.PYTHON ?? 'python';
1248
- // Reuse west-spawn's env builder (prepends the venv bin dir to PATH so the
1249
- // python we spawn resolves pyserial from the same venv). Falls back to the
1250
- // process env when no install is discovered.
1251
- const env = install ? buildEnv(install) : process.env;
1252
- spawnSync(py, ['-m', 'serial.tools.miniterm', o.port, String(baud)], {
1253
- cwd: projectRootFromOptions(o),
1254
- env,
1255
- stdio: 'inherit',
1256
- });
1257
- },
1258
-
1259
- debug(o: ToolchainOptions): void {
1260
- // Launch an interactive GDB session for the last build. The probe method
1261
- // resolves exactly like flashing (zephyr.probe / zephyr.runner — the same
1262
- // attach session, so the same quirks apply); debug-incapable methods
1263
- // (bootloaders) are rejected with the debug-capable list. west debug
1264
- // resolves the GDB binary from the build dir's CMakeCache — no
1265
- // hand-authored gdbinit needed. Inherits stdio so GDB runs interactively.
1266
- const projectRoot = projectRootFromOptions(o);
1267
- const buildDir = join(projectRoot, 'build');
1268
- const board = targetFromOptions(o);
1269
- const zc = o.zephyrConfig as Record<string, unknown> | undefined;
1270
- const probe = resolveProbeMethod(zc, chipForBuild(projectRoot, board), 'debug');
1271
- if (!probe.ok) {
1272
- console.error(`-- west debug: ${probe.error}`);
1273
- process.exitCode = 1;
1274
- return;
1275
- }
1276
- const debugArgs = ['debug', '-d', buildDir];
1277
- if (probe.runner) debugArgs.push('--runner', probe.runner);
1278
- debugArgs.push(...probe.args);
1279
- const inv = westSpawn(debugArgs, {
1280
- cwd: projectRoot,
1281
- encoding: 'utf-8',
1282
- stdio: 'inherit',
1283
- });
1284
- spawnSync(inv.command, inv.args, inv.options);
1285
- },
1286
- };
1
+ // ---------------------------------------------------------------------------
2
+ // FrameworkToolchain impl for Zephyr (west / CMake)
3
+ //
4
+ // compile() scaffolds the project (idempotent) then runs `west build -b <board>`.
5
+ // upload() runs `west flash`. monitor() runs a best-effort serial monitor.
6
+ //
7
+ // west resolution goes through westSpawn(), which finds a usable west without
8
+ // requiring the user to have activated the Zephyr Python venv — it prefers
9
+ // `<python> -m west` (robust cross-platform form) and injects ZEPHYR_BASE when
10
+ // a SDK root is discovered. See west-discover.ts / west-spawn.ts.
11
+ //
12
+ // The board target is carried via frameworkData.buildTarget (populated as
13
+ // ToolchainOptions.buildTarget by the typecad-hal CLI), defaulting to the
14
+ // framework's canonical MVP target (xiao_ble).
15
+ //
16
+ // Mirrors framework-esp32/src/toolchain/index.ts structure: projectRoot derived
17
+ // from outputDir, prepare is a no-op (scaffold happens in compile when the
18
+ // target is known), GCC errors parsed via the shared parseCompileErrors helper.
19
+ // ---------------------------------------------------------------------------
20
+
21
+ import { spawn, spawnSync } from 'node:child_process';
22
+ import { connect as netConnect } from 'node:net';
23
+ import { basename, delimiter, dirname, join } from 'node:path';
24
+ import { readdirSync, readFileSync, mkdirSync, rmSync, existsSync, writeFileSync } from 'node:fs';
25
+ import type { ToolchainOptions, CompileResult, UploadResult } from '@typecad/cuttlefish/api/shared';
26
+ import { parseCompileErrors } from '@typecad/cuttlefish/api/shared';
27
+ import { scaffoldZephyrProject, writeIfChanged, appendLibraryOverlayFragments } from './scaffold.js';
28
+ import { parseZephyrDts, asBuiltJson } from '../as-built.js';
29
+ import { westSpawn, buildEnv } from './west-spawn.js';
30
+ import { discoverWest } from './west-discover.js';
31
+ import { writeDebugConfig, resolveDebugLocations, debugArtifactsNeedRewrite, DEBUG_SERVER_PORT, DEBUG_SERVER_TCL_PORT } from './debug-config.js';
32
+ import { readRunnersFacts } from './runners.js';
33
+ import { bossacTouchReset } from './bossac-touch.js';
34
+ import { ZephyrStrategy } from '../strategy.js';
35
+ import { generateOverlay, type DisplayWiring, type TouchWiring, type OverlayDiagnostic } from '../dt-config/overlay.js';
36
+ import { generateCustomBoard } from '../dt-config/custom-board.js';
37
+ import { NO_BOARD_CHIP } from '../chips/index.js';
38
+ import { resolveChipFromBoard } from '../chips/resolve.js';
39
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
40
+ import { pwmDtAliasToken } from '../lowering/pwm.js';
41
+ import { detectZephyrVersion, checkZephyrCompat, resolveBoardTarget } from './compat.js';
42
+ import { DEFAULT_ZEPHYR_DISPLAY_PROFILE } from '../display/profiles.js';
43
+
44
+ /**
45
+ * Resolve the chip for a build the same way the strategy does at emit time —
46
+ * from the board constants the transpile persisted next to the emitted
47
+ * source (`board-constants.json`). There is no registry fallback: a build
48
+ * whose constants did not persist stays NO_BOARD_CHIP, exactly like the
49
+ * emit-time path.
50
+ */
51
+ function chipForBuild(projectRoot: string, board: string): ZephyrChipDescriptor {
52
+ try {
53
+ // The transpile writes the constants into the emit outDir, which is
54
+ // <projectRoot>/src for the standard layout (basename 'src' collapsed by
55
+ // projectRootFromOptions); check both locations.
56
+ const bcPath = [join(projectRoot, 'src', 'board-constants.json'), join(projectRoot, 'board-constants.json')]
57
+ .find(p => existsSync(p));
58
+ if (bcPath) {
59
+ const raw = JSON.parse(readFileSync(bcPath, 'utf8')) as Record<string, string | number | boolean>;
60
+ const bc = new Map(Object.entries(raw));
61
+ const fromBoard = resolveChipFromBoard(bc);
62
+ if (fromBoard) return fromBoard;
63
+ }
64
+ } catch { /* constants unreadable — no board resolved */ }
65
+ return NO_BOARD_CHIP;
66
+ }
67
+
68
+ /**
69
+ * HAL pins the emitted sources read via adc.* — scanned from the emitted
70
+ * `__tc_adc<N>_setup()` call sites (N = channel index, mapped back to the HAL
71
+ * pin via the chip descriptor). Feeds the overlay's ADC pinctrl rewrite: on
72
+ * SoCs that mux ADC pads via pinctrl (STM32), only the read channels are
73
+ * switched to analog mode.
74
+ */
75
+ function scanAdcReadPins(src: string, chip: ZephyrChipDescriptor): number[] {
76
+ const pins: number[] = [];
77
+ // Two used-signal forms:
78
+ // - `__tc_adc<N>_setup()` / `__tc_adc_<ctrl>_<N>_setup()` CALL SITES
79
+ // (empty parens — the adcInitLines definitions have `(void)` and would
80
+ // otherwise mark every descriptor channel as used).
81
+ // - `__tc_adct<pin>_done` lazy-guard vars — the thin-ADC read lowering's
82
+ // inline setup (families without pinctrl groups, e.g. ESP32 SARADC,
83
+ // never emit the setup-function form at all).
84
+ // Channel indices are unique per CONTROLLER, so the labeled form resolves
85
+ // (controller, channel) before mapping back to the HAL pin.
86
+ for (const m of src.matchAll(/__tc_adc(?:(\w+?)_)?(\d+)_setup\(\)/g)) {
87
+ const ch = Number(m[2]);
88
+ const label = m[1];
89
+ const c = chip.adc?.channels.find(
90
+ (x) => x.channel === ch && (x.controller ?? chip.adc?.nodeLabel) === (label ?? chip.adc?.nodeLabel),
91
+ );
92
+ if (c && !pins.includes(c.pin)) pins.push(c.pin);
93
+ }
94
+ for (const m of src.matchAll(/__tc_adct(\d+)_done/g)) {
95
+ const pin = Number(m[1]);
96
+ if (chip.adc?.channels.some((x) => x.pin === pin) && !pins.includes(pin)) pins.push(pin);
97
+ }
98
+ return pins;
99
+ }
100
+
101
+ /**
102
+ * HAL pins the emitted sources drive with dac.* — the DAC lowering's lazy
103
+ * per-pin setup guard is `__tc_dact<pin>_done` (lowering/dac.ts), so
104
+ * var-presence is the authoritative used-signal. Feeds the overlay's DAC
105
+ * pinctrl gating (same pattern as scanAdcReadPins).
106
+ */
107
+ function scanDacWritePins(src: string): number[] {
108
+ const pins: number[] = [];
109
+ for (const m of src.matchAll(/__tc_dact(\d+)_done/g)) {
110
+ const pin = Number(m[1]);
111
+ if (!pins.includes(pin)) pins.push(pin);
112
+ }
113
+ return pins;
114
+ }
115
+
116
+ /**
117
+ * HAL pins the emitted sources drive with pwm.* — the emitted source
118
+ * references each used spec as `__tc_pwm_<alias token>` (pwmVarName in
119
+ * lowering/pwm.ts), and the lowering only emits specs for driven pins, so
120
+ * var-presence is the authoritative signal. Feeds the overlay's per-pin
121
+ * pwm-leds gating (no dead DT channels).
122
+ */
123
+ /**
124
+ * Inline-override markers (the escape hatch): the adc/pwm lowerings emit
125
+ * `/* cuttlefish-user-facts: <kind> pin=N [device=X] [pinctrl=P] channel=C *​/`
126
+ * comments when a construction carries routing overrides. Merged into the
127
+ * chip so the overlay synthesis + used-pin scans treat them as facts —
128
+ * the transpiler cannot create DT nodes, but this regen can.
129
+ */
130
+ function applyUserFactMarkers(chip: ZephyrChipDescriptor, src: string): ZephyrChipDescriptor {
131
+ const adcAdds: { pin: number; channel: number; controller?: string; pinctrl?: string }[] = [];
132
+ const pwmAdds: { pin: number; controller: string; channel: number }[] = [];
133
+ for (const m of src.matchAll(/\/\* cuttlefish-user-facts: (adc|pwm) ([^*]*?) \*\//g)) {
134
+ const kind = m[1];
135
+ const fields = new Map<string, string>();
136
+ for (const kv of m[2]!.split(/\s+/).filter(Boolean)) {
137
+ const eq = kv.indexOf('=');
138
+ if (eq > 0) fields.set(kv.slice(0, eq), kv.slice(eq + 1));
139
+ }
140
+ const pin = Number(fields.get('pin'));
141
+ const channel = Number(fields.get('channel'));
142
+ if (!Number.isFinite(pin) || !Number.isFinite(channel)) continue;
143
+ if (kind === 'adc') {
144
+ adcAdds.push({
145
+ pin,
146
+ channel,
147
+ ...(fields.get('device') ? { controller: fields.get('device') } : {}),
148
+ ...(fields.get('pinctrl') ? { pinctrl: fields.get('pinctrl') } : {}),
149
+ });
150
+ } else if (fields.get('controller')) {
151
+ pwmAdds.push({ pin, channel, controller: fields.get('controller')! });
152
+ }
153
+ }
154
+ if (adcAdds.length === 0 && pwmAdds.length === 0) return chip;
155
+ const adc = chip.adc
156
+ ? chip.adc
157
+ : { nodeLabel: adcAdds.find((a) => !a.controller)?.controller ?? 'adc', resolution: 12, vrefMv: 3000, channels: [] };
158
+ const adcChannels = [...adc.channels];
159
+ for (const a of adcAdds) {
160
+ const existing = adcChannels.findIndex((c) => c.pin === a.pin);
161
+ if (existing >= 0) adcChannels.splice(existing, 1);
162
+ adcChannels.push({ pin: a.pin, channel: a.channel, ...(a.controller ? { controller: a.controller } : {}), ...(a.pinctrl ? { pinctrl: a.pinctrl } : {}) });
163
+ }
164
+ const pwmSpecs = [...(chip.pwm?.specs ?? [])];
165
+ for (const p of pwmAdds) {
166
+ const existing = pwmSpecs.findIndex((s) => s.pin === p.pin);
167
+ if (existing >= 0) pwmSpecs.splice(existing, 1);
168
+ pwmSpecs.push({ pin: p.pin, controller: p.controller, channel: p.channel });
169
+ }
170
+ return {
171
+ ...chip,
172
+ adc: { ...adc, channels: adcChannels },
173
+ pwm: { ...(chip.pwm ?? { specs: [] }), specs: pwmSpecs },
174
+ };
175
+ }
176
+
177
+ function scanPwmUsedPins(src: string, chip: ZephyrChipDescriptor): number[] { const pins = (chip.pwm?.specs ?? [])
178
+ .filter((s) => src.includes(`__tc_pwm_${pwmDtAliasToken(s)}`))
179
+ .map((s) => s.pin);
180
+ // Matrix pins (ESP32 LEDC) have no static specs — recover the driven pins
181
+ // from the same alias-var presence signal (`__tc_pwm_tc_pwm<N>`), keeping
182
+ // only pins the descriptor's matrix allows (the regex grabs the full
183
+ // number, so pin 4 never matches a reference to pin 45).
184
+ const matrix = chip.pwm?.matrix;
185
+ if (matrix) {
186
+ const present = new Set<number>();
187
+ for (const match of src.matchAll(/__tc_pwm_tc_pwm(\d+)/g)) {
188
+ present.add(Number(match[1]));
189
+ }
190
+ for (const pin of matrix.pins) {
191
+ if (present.has(pin)) pins.push(pin);
192
+ }
193
+ }
194
+ return pins;
195
+ }
196
+
197
+ /**
198
+ * Bus controller indexes the emitted sources actually reference — the shim
199
+ * declares one `__tc_<bus><N>_dev` state block per used instance (gated by
200
+ * collectUsedBusIndices at transpile time), so var-presence is the
201
+ * authoritative signal. The overlay enables only these controllers: an
202
+ * enabled-but-unused one claims its default pins (i2c0's GP4/GP5 on the
203
+ * Pico) which a program driving the OTHER controller may want as GPIO.
204
+ * Empty list (no state blocks — e.g. display/touch composites that use the
205
+ * driver API directly) means "no signal"; the caller then passes undefined
206
+ * so the overlay enables every declared controller, preserving old behavior.
207
+ */
208
+ function scanUsedBusInstances(
209
+ src: string,
210
+ controllers: readonly { nodeLabel: string }[] | undefined,
211
+ bus: 'i2c' | 'spi' | 'uart',
212
+ ): number[] | undefined {
213
+ if (!controllers) return undefined;
214
+ const used: number[] = [];
215
+ for (let i = 0; i < controllers.length; i++) {
216
+ if (src.includes(`__tc_${bus}${i}_dev`)) used.push(i);
217
+ }
218
+ return used.length > 0 ? used : undefined;
219
+ }
220
+
221
+ /**
222
+ * Distinct DT-bound sensors the emitted sources reference — the lowering's
223
+ * state blocks name each one `__tc_sensor_<part>_i2c<N>_0x<addr>_dev`
224
+ * (lowering/sensor.ts sensorNames), so var-presence is the authoritative
225
+ * signal. Feeds the overlay's DT child nodes; the part group is greedy so a
226
+ * compatible containing '_i2c<N>_' still resolves to the longest part match.
227
+ */
228
+ export interface ScannedSensorPart {
229
+ part: string; busIndex: number; port: number; busKind: 'i2c' | 'spi';
230
+ spiHz: number; spiMode: number; alertPin: number;
231
+ }
232
+
233
+ export interface ScannedSpiTarget {
234
+ busIndex: number; cs: number; hz: number; mode: number;
235
+ }
236
+
237
+ /** Scan the emitted source for thin SPI targets (hal/spi-target.ts): the
238
+ * spi_dt_spec state block's tc-spit-cfg comment carries the construction
239
+ * facts, the same channel tc-sensor-cfg uses. */
240
+ export function scanSpiTargets(src: string): ScannedSpiTarget[] {
241
+ const out = new Map<string, ScannedSpiTarget>();
242
+ for (const m of src.matchAll(/tc-spit-cfg: tc_spit_spi(\d+)_cs(\d+) hz=(\d+) mode=(\d+)/g)) {
243
+ const ref: ScannedSpiTarget = { busIndex: parseInt(m[1], 10), cs: parseInt(m[2], 10), hz: parseInt(m[3], 10), mode: parseInt(m[4], 10) };
244
+ out.set(`${ref.busIndex}|${ref.cs}`, ref);
245
+ }
246
+ return [...out.values()];
247
+ }
248
+
249
+ export function scanSensorParts(src: string): ScannedSensorPart[] {
250
+ const out = new Map<string, ScannedSensorPart>();
251
+ for (const m of src.matchAll(/__tc_sensor_([a-z0-9_]+)_(i2c|spi)(\d+)_(0x[0-9a-f]+|cs[0-9]+)_dev\b/g)) {
252
+ const port = m[4].startsWith('0x') ? parseInt(m[4], 16) : parseInt(m[4].slice(2), 10);
253
+ const ref: ScannedSensorPart = { part: m[1], busIndex: parseInt(m[3], 10), port, busKind: m[2] as 'i2c' | 'spi', spiHz: 0, spiMode: 0, alertPin: -1 };
254
+ out.set(`${ref.part}|${ref.busKind}${ref.busIndex}|${ref.port}`, ref);
255
+ }
256
+ // Construction facts ride the state block's config comment — merge by
257
+ // nodelabel so the scanner stays the single source for the overlay.
258
+ for (const m of src.matchAll(/tc-sensor-cfg: tc_([a-z0-9_]+)_(i2c|spi)(\d+)_(0x[0-9a-f]+|cs[0-9]+) hz=(\d+) mode=(\d+) alert=(-?\d+)/g)) {
259
+ const port = m[4].startsWith('0x') ? parseInt(m[4], 16) : parseInt(m[4].slice(2), 10);
260
+ const key = `${m[1]}|${m[2]}${m[3]}|${port}`;
261
+ const existing = out.get(key);
262
+ if (existing) {
263
+ existing.spiHz = parseInt(m[5], 10);
264
+ existing.spiMode = parseInt(m[6], 10);
265
+ existing.alertPin = parseInt(m[7], 10);
266
+ }
267
+ }
268
+ return [...out.values()];
269
+ }
270
+
271
+ function targetFromOptions(o: ToolchainOptions): string {
272
+ // The cuttlefish CLI populates ToolchainOptions.buildTarget from the
273
+ // config's board: (frameworkData.buildTarget for board-less projects).
274
+ // Accept frameworkData.target as an alias. No silent default: building for
275
+ // a wrong hard-coded board is the split-brain trap.
276
+ const fcTarget = (o.frameworkConfig?.target as string | undefined);
277
+ const board = (o.buildTarget as string | undefined) ?? fcTarget;
278
+ if (!board) {
279
+ throw new Error(
280
+ 'No build target: set board: in typecad-hal.config.ts (or frameworkData.buildTarget for custom-board projects).',
281
+ );
282
+ }
283
+ return board;
284
+ }
285
+
286
+ /**
287
+ * Derive the Zephyr project root from the typecad-hal-emitted source path.
288
+ *
289
+ * Cuttlefish emits `src/main.cpp` under the output dir. The CLI passes
290
+ * `sourcePath` = full path to `main.cpp` and `outputDir` = its parent (`src/`).
291
+ * For Zephyr, the project root is the parent of `src/` — one level above
292
+ * `outputDir`. Detect that shape and adjust; otherwise fall back to `outputDir`.
293
+ */
294
+ export function projectRootFromOptions(o: ToolchainOptions): string {
295
+ const outDir = o.outputDir;
296
+ if (basename(outDir) === 'src') {
297
+ return dirname(outDir);
298
+ }
299
+ return outDir;
300
+ }
301
+
302
+ /**
303
+ * west build timeout. Zephyr's first build fetches the toolchain modules and
304
+ * configures CMake/Ninja, which can take several minutes; allow generous headroom.
305
+ */
306
+ const BUILD_TIMEOUT_MS = 600_000;
307
+ const FLASH_TIMEOUT_MS = 120_000;
308
+
309
+ /**
310
+ * Build the `west flash` argument list for a board.
311
+ *
312
+ * Runner selection: each board's board.cmake declares a sensible default flash
313
+ * runner for its hardware (xiao_ble → nrfutil, esp32* → esptool), and `west
314
+ * flash` resolves it automatically. The framework only intervenes where the
315
+ * board default needs an argument it can't infer:
316
+ * - An explicit `zephyr.runner` (from typecad-hal.config.ts) always wins.
317
+ * - ESP32 boards forward the port via `--esp-device` (esptool reads the
318
+ * device from it); board.cmake still picks the runner.
319
+ * - Every other board trusts the board.cmake default. Previously this forced
320
+ * `--runner nrfjprog` for every non-ESP32 target, which broke boards whose
321
+ * default is not nrfjprog (xiao_ble defaults to nrfutil) and required
322
+ * Nordic J-Link tools that a USB-bootloader board does not have.
323
+ *
324
+ * Exported (pure) so the runner-selection contract is unit-testable without
325
+ * spawning west.
326
+ */
327
+ /**
328
+ * Resolve HOW this build attaches to the board for flashing OR debugging:
329
+ * the friendly `zephyr.probe` id from the board's probeMethods table (quirks
330
+ * included), or the raw `zephyr.runner` escape hatch. Exported (pure) so the
331
+ * selection contract is unit-testable without spawning west.
332
+ *
333
+ * Rules:
334
+ * - `probe` + `runner` together is an error (two ways of saying it — pick one).
335
+ * - An unknown `probe` id is an error listing what the board supports; a board
336
+ * with no probeMethods table gets a hint to use `runner` directly.
337
+ * - purpose 'debug': the chosen method must be debug-capable (`debug` is not
338
+ * false — a bootloader is not a debugger). Non-capable or unknown ids list
339
+ * the debug-capable methods.
340
+ * - User `runnerArgs` are appended AFTER the method's args, so they can
341
+ * override the method's baked-in flags (argparse takes the last value).
342
+ */
343
+ export type ProbeResolution =
344
+ | { ok: true; runner?: string; args: string[] }
345
+ | { ok: false; error: string };
346
+
347
+ /**
348
+ * The board a cached build dir was configured for (CMakeCache.txt's
349
+ * BOARD:STRING — the exact value passed to `west build -b`), or undefined
350
+ * when no cache exists. compile() compares it against the requested board
351
+ * and nukes the dir on mismatch: `west build`'s --pristine=auto covers
352
+ * cmake/config churn, NOT a board switch — west aborts with "refusing to
353
+ * proceed without --force", and cuttlefish doesn't forward that flag.
354
+ */
355
+ export function cachedBuildBoard(buildDir: string): string | undefined {
356
+ try {
357
+ return readFileSync(join(buildDir, 'CMakeCache.txt'), 'utf-8')
358
+ .match(/^BOARD:STRING=(.+)$/m)?.[1]?.trim() || undefined;
359
+ } catch {
360
+ return undefined; // no build dir / unreadable cache — treat as fresh
361
+ }
362
+ }
363
+
364
+ export function resolveProbeMethod(
365
+ zc: Record<string, unknown> | undefined,
366
+ chip: ZephyrChipDescriptor,
367
+ purpose: 'flash' | 'debug' = 'flash',
368
+ ): ProbeResolution {
369
+ const probe = zc?.probe as string | undefined;
370
+ const runner = zc?.runner as string | undefined;
371
+ const userArgs = (zc?.runnerArgs as string[] | undefined) ?? [];
372
+
373
+ if (probe && runner) {
374
+ return {
375
+ ok: false,
376
+ error:
377
+ `typecad-hal.config.ts sets both zephyr.probe ('${probe}') and zephyr.runner ('${runner}'). ` +
378
+ `They are two ways to choose the probe method — remove one.`,
379
+ };
380
+ }
381
+
382
+ if (probe) {
383
+ const methods = chip.probeMethods ?? [];
384
+ const method = methods.find((m) => m.id === probe);
385
+ if (!method) {
386
+ const listAll = methods
387
+ .map((m) => `${m.id} (${m.runner}${m.description ? ` — ${m.description}` : ''})`)
388
+ .join('; ');
389
+ return {
390
+ ok: false,
391
+ error: methods.length > 0
392
+ ? `Unknown probe method '${probe}' for ${chip.id}. Supported: ${listAll}.`
393
+ : `This board (${chip.id}) ships no probe-method table, so 'zephyr.probe' cannot resolve '${probe}'. ` +
394
+ `Use the raw 'zephyr.runner' field instead (run 'west flash --context' in the build dir for options).`,
395
+ };
396
+ }
397
+ if (purpose === 'debug' && method.debug === false) {
398
+ const debuggable = methods.filter((m) => m.debug !== false).map((m) => m.id).join(', ');
399
+ return {
400
+ ok: false,
401
+ error:
402
+ `The '${probe}' method cannot debug ${chip.id} — a bootloader is not a debugger. ` +
403
+ `Debug-capable methods: ${debuggable || '(none — this board needs an external probe)'}.`,
404
+ };
405
+ }
406
+ return {
407
+ ok: true,
408
+ runner: method.runner,
409
+ args: [...(method.args ?? []), ...userArgs],
410
+ };
411
+ }
412
+
413
+ return { ok: true, runner, args: userArgs };
414
+ }
415
+
416
+ /**
417
+ * Run an openocd session against the board's probe config — the shared
418
+ * engine for the pre-flash quiesce and the post-flash SYSRESETREQ (see the
419
+ * call sites in upload()). The config is the probe method's verbatim
420
+ * debugCfg from the board catalog (the same lines `west debug` uses);
421
+ * `commands` are appended after `-f <cfg> -c init`. Returns a flash note on
422
+ * success, undefined when skipped or failed (best-effort by design).
423
+ */
424
+ /**
425
+ * Resolve the openocd binary (plus script search dirs) for the probe session.
426
+ *
427
+ * Resolution order mirrors how west's own openocd runner finds the binary, so
428
+ * the session and `west flash` drive the SAME openocd:
429
+ * 1. $OPENOCD — the variable Zephyr's CMake reads into the build cache.
430
+ * 2. A Zephyr-SDK-hosted install ($ZEPHYR_SDK_INSTALL_DIR, else the
431
+ * discovered west install's SDK). Layout differs by SDK generation —
432
+ * hosttools/openocd/share/openocd/scripts vs hosttools/openocd/scripts —
433
+ * so both script dirs are collected.
434
+ * 3. PATH — Linux distro / conda / micromamba installs (a micromamba-env
435
+ * openocd is the common Linux setup; the SDK layout check alone made the
436
+ * deterministic probe session unreachable there, silently dropping every
437
+ * Linux flash to the racy `west flash` fallback).
438
+ *
439
+ * A non-SDK binary resolves with no explicit -s dirs: it finds its own
440
+ * interface/target scripts via its compiled-in search path. Returns undefined
441
+ * when no openocd can be found (the caller then uses the west fallback).
442
+ *
443
+ * Exported (pure) so the resolution contract is unit-testable without
444
+ * spawning openocd.
445
+ */
446
+ export interface SessionOpenOcd {
447
+ readonly exe: string;
448
+ readonly searchDirs: readonly string[];
449
+ }
450
+
451
+ export function resolveSessionOpenOcd(
452
+ env: {
453
+ OPENOCD?: string | undefined;
454
+ ZEPHYR_SDK_INSTALL_DIR?: string | undefined;
455
+ PATH?: string | undefined;
456
+ } = process.env,
457
+ sdkInstallDir?: string,
458
+ ): SessionOpenOcd | undefined {
459
+ const exeName = process.platform === 'win32' ? 'openocd.exe' : 'openocd';
460
+ if (env.OPENOCD && existsSync(env.OPENOCD)) {
461
+ return { exe: env.OPENOCD, searchDirs: [] };
462
+ }
463
+ const sdkRoot = env.ZEPHYR_SDK_INSTALL_DIR || sdkInstallDir;
464
+ if (sdkRoot) {
465
+ const exe = join(sdkRoot, 'hosttools', 'openocd', 'bin', exeName);
466
+ if (existsSync(exe)) {
467
+ const searchDirs = [
468
+ join(sdkRoot, 'hosttools', 'openocd', 'share', 'openocd', 'scripts'),
469
+ join(sdkRoot, 'hosttools', 'openocd', 'scripts'),
470
+ ].filter((d) => existsSync(d));
471
+ return { exe, searchDirs };
472
+ }
473
+ }
474
+ for (const dir of (env.PATH ?? '').split(delimiter)) {
475
+ if (!dir) continue;
476
+ const candidate = join(dir, exeName);
477
+ if (existsSync(candidate)) return { exe: candidate, searchDirs: [] };
478
+ }
479
+ return undefined;
480
+ }
481
+
482
+ function openocdProbeSession(
483
+ buildDir: string,
484
+ zc: Record<string, unknown> | undefined,
485
+ chip: ZephyrChipDescriptor,
486
+ commands: readonly string[],
487
+ ): string | undefined {
488
+ // Config resolution — two sources, in order:
489
+ // 1. The named probe method's verbatim debugCfg from the board catalog
490
+ // (written to a temp cfg), when zephyr.probe names a method that has
491
+ // one.
492
+ // 2. The board's own support/openocd.cfg in the Zephyr tree — the exact
493
+ // config `west flash` resolves for the openocd runner. This covers
494
+ // raw `zephyr.runner: 'openocd'` (no named probe) and probe methods
495
+ // that ship no debugCfg of their own.
496
+ const probeId = zc?.probe as string | undefined;
497
+ const method = chip.probeMethods?.find((m) => m.id === probeId);
498
+ const cfgLines = method?.debugCfg;
499
+ // Session reset policy: `reset_config none`. The session's resets are
500
+ // core-domain by design — vector-catch halt before the flash write,
501
+ // SYSRESETREQ to boot — so they must not depend on the SRST pin. Boards
502
+ // like the WeAct Black Pill don't break NRST out at all: under the board
503
+ // cfg's `srst_only`, every `reset` asserts a pin that reaches nothing
504
+ // (the target never resets, `reset halt` catches the core mid-app in
505
+ // dirty state and the flash algorithm times out) while the probe's
506
+ // floating SRST sense reports phantom "external reset detected" events
507
+ // that leave the session's halt state inconsistent. Method-declared west
508
+ // quirks (`--cmd-pre-init=…`) are appended after and override the
509
+ // default for boards whose facts carry one.
510
+ const preInit = [
511
+ 'reset_config none',
512
+ ...(method?.args ?? [])
513
+ .filter((a) => a.startsWith('--cmd-pre-init='))
514
+ .map((a) => a.slice('--cmd-pre-init='.length)),
515
+ ];
516
+
517
+ const install = discoverWest();
518
+ const sessionOpenOcd = resolveSessionOpenOcd(process.env, install?.sdkInstallDir);
519
+ if (!sessionOpenOcd) return undefined;
520
+ const openocdExe = sessionOpenOcd.exe;
521
+ const searchArgs = sessionOpenOcd.searchDirs.flatMap((d) => ['-s', d] as [string, string]);
522
+
523
+ let cfgArgs: string[] | undefined;
524
+ let sessionCfg: string | undefined;
525
+ if (cfgLines && cfgLines.length > 0) {
526
+ sessionCfg = join(buildDir, 'typecad-hal-probe.cfg');
527
+ } else {
528
+ // The board target's qualifier ('blackpill_f411ce/stm32f411xe' →
529
+ // 'blackpill_f411ce') identifies the board dir; the vendor segment is
530
+ // not part of the target, so probe the boards/ tree for it.
531
+ const zephyrBase = process.env.ZEPHYR_BASE || install?.zephyrBase;
532
+ const boardDir = (chip.id ?? '').split('/')[0];
533
+ if (!zephyrBase || !boardDir) return undefined;
534
+ const boardsRoot = join(zephyrBase, 'boards');
535
+ let supportCfg: string | undefined;
536
+ try {
537
+ for (const vendor of readdirSync(boardsRoot)) {
538
+ const candidate = join(boardsRoot, vendor, boardDir, 'support', 'openocd.cfg');
539
+ if (existsSync(candidate)) { supportCfg = candidate; break; }
540
+ }
541
+ } catch {
542
+ return undefined;
543
+ }
544
+ if (!supportCfg) return undefined;
545
+ cfgArgs = ['-s', dirname(supportCfg), '-f', supportCfg];
546
+ }
547
+
548
+ try {
549
+ mkdirSync(buildDir, { recursive: true });
550
+ if (sessionCfg) {
551
+ writeFileSync(sessionCfg, cfgLines!.join('\n') + '\n', 'utf-8');
552
+ cfgArgs = ['-f', sessionCfg];
553
+ }
554
+ const res = spawnSync(openocdExe, [
555
+ ...searchArgs, ...cfgArgs!,
556
+ // Pre-init TCL AFTER the cfg (overrides its reset_config) and BEFORE
557
+ // init — the same position west gives --cmd-pre-init.
558
+ ...preInit.map((c) => ['-c', c] as [string, string]).flat(),
559
+ '-c', 'init',
560
+ ...commands.map((c) => ['-c', c]).flat(),
561
+ '-c', 'shutdown',
562
+ ], {
563
+ cwd: buildDir,
564
+ encoding: 'utf-8' as const,
565
+ timeout: 20_000,
566
+ });
567
+ return res.status === 0 ? `-- probe session ok: ${commands.join('; ')}` : undefined;
568
+ } catch {
569
+ return undefined;
570
+ }
571
+ }
572
+
573
+ /**
574
+ * Whether a flash runner carries the upload over a serial port. Runner-gated,
575
+ * never board-name-gated: esptool and bossac are the only runners
576
+ * `buildFlashArgs` forwards `--port` to, so they are the only ones that
577
+ * cannot flash without one. Probe runners (openocd, jlink) and USB flows
578
+ * (dfu-util, uf2 mass storage) need no port — a missing `--port` must not
579
+ * block them.
580
+ *
581
+ * Exported (pure) so the port-requirement contract is unit-testable without
582
+ * spawning west.
583
+ */
584
+ export function uploadRequiresPort(runner: string | undefined): boolean {
585
+ return runner === 'esptool' || runner === 'bossac';
586
+ }
587
+
588
+ export function buildFlashArgs(
589
+ buildDir: string,
590
+ userRunner: string | undefined,
591
+ port: string | undefined,
592
+ flashRunner?: string,
593
+ runnerArgs?: readonly string[],
594
+ ): string[] {
595
+ // flashRunner is the runner the flash will actually use — the explicit
596
+ // zephyr.runner when set, else the board's declared default from its probe
597
+ // table. It gates the esptool port forwarding below; only an EXPLICIT
598
+ // userRunner forces west's --runner (board defaults stay board.cmake's
599
+ // choice). Runner-gated, never board-name-gated: any board whose flash
600
+ // runs esptool gets the same forwarding.
601
+ const args = ['flash', '-d', buildDir];
602
+ if (userRunner) {
603
+ args.push('--runner', userRunner);
604
+ }
605
+ if (port && flashRunner === 'esptool') {
606
+ args.push('--esp-device', port);
607
+ }
608
+ // The bossac runner defaults its port to /dev/ttyACM0 — on Windows that
609
+ // never matches, so the port MUST be forwarded or bossac fails with
610
+ // "No device found on /dev/ttyACM0" (same class of port-forwarding
611
+ // problem as the esptool --esp-device above).
612
+ if (port && flashRunner === 'bossac') {
613
+ args.push('--bossac-port', port);
614
+ }
615
+ // Extra runner-specific flags, appended verbatim (west's runner parsers
616
+ // accept them after the runner is selected).
617
+ if (runnerArgs && runnerArgs.length > 0) {
618
+ args.push(...runnerArgs);
619
+ }
620
+ return args;
621
+ }
622
+
623
+ /**
624
+ * Classify a `west flash` result as success/failure.
625
+ *
626
+ * west's exit status is authoritative except for one known race in the uf2
627
+ * runner on Windows: the UF2 bootloader reboots to run new firmware the instant
628
+ * the file copy completes, unmounting the USB-MSC drive before `shutil.copy`'s
629
+ * trailing `copymode`/chmod runs. That raises `OSError: [WinError 433] A
630
+ * device which does not exist was specified` and makes west exit non-zero —
631
+ * even though the firmware copied and flashed correctly (the LED blinks).
632
+ *
633
+ * The copy starting is logged ("Copying UF2 file to '<drive>'"); WinError 433
634
+ * during `copymode` after that point proves the data write finished and the
635
+ * drive only vanished on the metadata step. Treat that exact signature as
636
+ * success so the upload isn't reported as a failure. Genuine uf2 failures
637
+ * (no partition found, write errors before the copy) still surface as failures.
638
+ *
639
+ * Exported (pure) so the classification is unit-testable without spawning west.
640
+ */
641
+ export function classifyUploadResult(
642
+ runner: string | undefined,
643
+ status: number | null,
644
+ output: string,
645
+ ): boolean {
646
+ if (status === 0) return true;
647
+ if (isUf2DriveVanishRace(output)) return runner === 'uf2';
648
+ return false;
649
+ }
650
+
651
+ /**
652
+ * Whether `output` carries the benign UF2 copymode/WinError-433 race signature
653
+ * (see classifyUploadResult). Centralized so classify + cleanse share one match.
654
+ */
655
+ function isUf2DriveVanishRace(output: string): boolean {
656
+ return /Copying UF2 file to/.test(output)
657
+ && /WinError 433/.test(output)
658
+ && /copymode/.test(output);
659
+ }
660
+
661
+ /**
662
+ * Whether a `west flash` (openocd) output carries one of the known
663
+ * target-ignored-SWD signatures — the DAP connect failing ("init mode
664
+ * failed (unable to connect to the target)", i.e. the DPIDR read never
665
+ * succeeded) or a reset/halt never landing ("timed out while waiting for
666
+ * target halted" / "TARGET: <name> - Not halted"). Both mean the board (or
667
+ * probe) needs a power-cycle or the SWD-free DFU path, not a retry of the
668
+ * same command. Centralized so the upload hint stays testable.
669
+ */
670
+ export function isTargetSwdFailure(output: string): boolean {
671
+ return /unable to connect to the target|timed out while waiting for target halted|TARGET: \S+ - Not halted/.test(output);
672
+ }
673
+
674
+ /**
675
+ * Cleanse the `west flash` output shown to the user.
676
+ *
677
+ * When classifyUploadResult has decided a non-zero west exit was the benign UF2
678
+ * race (firmware copied, drive unmounted on the trailing chmod), the raw output
679
+ * is a wall of Python traceback that reads like a hard failure. Drop everything
680
+ * after the "Copying UF2 file to" line — i.e. the entire traceback — so a
681
+ * successful flash reads as a success (the framework's ✓ Done follows). Non-race
682
+ * output is returned untouched; genuine errors stay fully visible for diagnosis.
683
+ *
684
+ * Exported (pure) so the cleansing is unit-testable without spawning west.
685
+ */
686
+ export function cleanseUploadOutput(
687
+ runner: string | undefined,
688
+ status: number | null,
689
+ output: string,
690
+ ): string {
691
+ if (status === 0) return output;
692
+ if (runner === 'uf2' && isUf2DriveVanishRace(output)) {
693
+ // Keep everything west printed up to and including "Copying UF2 file to",
694
+ // then stop — everything after that is the drive-vanish traceback.
695
+ const upto = output.match(/[\s\S]*Copying UF2 file to[^\n]*/);
696
+ const head = upto ? upto[0] : '-- west flash: using runner uf2';
697
+ return head;
698
+ }
699
+ return output;
700
+ }
701
+
702
+
703
+ /**
704
+ * Whether a failed `west build` output carries ninja's `dependency cycle`
705
+ * signature. Zephyr 4.3.99-dev snapshots have a regression
706
+ * (zephyrproject-rtos/zephyr#104757, fixed upstream by the #104784 revert,
707
+ * in v4.4+): after CMake re-runs from a .config change, the build dir's
708
+ * .ninja_deps records an `offsets.h -> offsets.c.obj -> offsets.h` cycle and
709
+ * ninja aborts with `ninja: error: dependency cycle: ...` before compiling
710
+ * anything. The cycle lives in the build dir, not the sources, so compile()
711
+ * recovers by deleting the dir and retrying once.
712
+ *
713
+ * Exported (pure) so the detection is unit-testable without spawning west.
714
+ */
715
+ export function isDependencyCycleFailure(output: string): boolean {
716
+ return output.includes('dependency cycle');
717
+ }
718
+
719
+ /** stdout+stderr of a spawnSync result coerced to one string. Defensive about
720
+ * the buffer form (spawnSync only returns strings when `encoding` is set,
721
+ * which every call site here does — but the coercion costs nothing). */
722
+ function combinedSpawnOutput(
723
+ result: { stdout?: string | Buffer | null; stderr?: string | Buffer | null },
724
+ ): string {
725
+ const so = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
726
+ const se = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
727
+ return so + se;
728
+ }
729
+
730
+ /**
731
+ * FrameworkToolchain for Zephyr. Spec §3.5 (mirror of the ESP-IDF toolchain).
732
+ * The target board is carried via frameworkData.buildTarget; scaffolding
733
+ * happens at compile time when the target is known.
734
+ */
735
+ export const Toolchain = {
736
+ prepare(outputDir: string, entryPoint: string): void {
737
+ // Write the DT overlay for the default board (the real target is known at
738
+ // compile time; prepare runs before compile, so use the default board id).
739
+ // The overlay is additive and idempotent; compile re-runs prepare-equivalent
740
+ // logic in scaffold via the usage scan. Mirrors how Arduino's library
741
+ // resolution is a pre-build artifact step.
742
+ const projectRoot = basename(outputDir) === 'src' ? dirname(outputDir) : outputDir;
743
+ // Scan the emitted source for usage tokens (same authoritative signal the
744
+ // scaffold uses). entryPoint is the path to main.cpp; its dir is src/.
745
+ const srcDir = dirname(entryPoint);
746
+ let src = '';
747
+ try {
748
+ for (const name of readdirSync(srcDir)) {
749
+ if (name.endsWith('.cpp') || name.endsWith('.c')) {
750
+ src += readFileSync(join(srcDir, name), 'utf8');
751
+ }
752
+ }
753
+ } catch { /* src may not exist yet on first prepare */ }
754
+ const uses = (t: string): boolean => src.includes(t);
755
+ // Inline-override markers (the escape hatch): the lowerings emit
756
+ // `cuttlefish-user-facts` comments carrying routing the transpiler
757
+ // cannot synthesize (adc device/pinctrl, pwm controller/channel).
758
+ // Merged into the chip BEFORE the scans + overlay generation, so the DT
759
+ // nodes, pinctrl groups, and used-pin recovery treat them as facts.
760
+ const chip = applyUserFactMarkers(chipForBuild(projectRoot, ''), src);
761
+ // Display usage tokens: the minimal GFX runtime (display_write/_fill_rect)
762
+ // and the UI display adapter (display_init / __tc_display_dev /
763
+ // DEVICE_DT_GET on the display nodelabel). Both paths need the DT overlay
764
+ // to enable the display node.
765
+ const usesDisplay = uses('display_write') || uses('display_init')
766
+ || uses('display_fill_rect') || uses('__tc_display_dev')
767
+ || uses('CuttlefishDisplayTarget');
768
+ // Both registered Zephyr display profiles use dtLabel 'display0', so the
769
+ // default profile's overlay block (&display0 { status="okay" }) is correct
770
+ // for either driver. Thread a non-default profile here only if a future
771
+ // board carries a display node under a different nodelabel.
772
+ const displayProfile = usesDisplay ? DEFAULT_ZEPHYR_DISPLAY_PROFILE : undefined;
773
+ // Touch controller kind comes from which DT nodelabel the emitted adapter
774
+ // references (FT6336U on I2C, XPT2046 on the display's SPI bus).
775
+ const usesTouch = uses('ft6336u') || uses('touch_');
776
+ const usesXpt = uses('xpt2046');
777
+ const sensorParts = scanSensorParts(src);
778
+ const spiTargetParts = scanSpiTargets(src);
779
+ const overlay = generateOverlay(chip, {
780
+ // __tc_<bus> matches the shim state block — a begin()-only program
781
+ // emits no driver API call but still declares the DT device. A
782
+ // constructed sensor is also a bus user (its device handle is the
783
+ // only i2c reference a sensor-only program carries).
784
+ usesI2c: uses('i2c_') || uses('__tc_i2c') || sensorParts.length > 0,
785
+ usesSensor: uses('sensor_') || sensorParts.length > 0,
786
+ usesFloatFormat: /%[-0-9.]*[eEfFgG]/.test(src),
787
+ sensorParts,
788
+ spiTargets: spiTargetParts,
789
+ usesSpi: uses('spi_') || uses('__tc_spi') || spiTargetParts.length > 0,
790
+ usesUart: uses('__tc_uart'),
791
+ usesUsb: uses('__tc_usb'),
792
+ usesPwm: uses('pwm_'),
793
+ usesAdc: uses('adc_'),
794
+ adcReadPins: scanAdcReadPins(src, chip),
795
+ dacWritePins: scanDacWritePins(src),
796
+ pwmUsedPins: scanPwmUsedPins(src, chip),
797
+ i2cUsedInstances: scanUsedBusInstances(src, chip.i2c?.controllers, 'i2c'),
798
+ spiUsedInstances: scanUsedBusInstances(src, chip.spi?.controllers, 'spi'),
799
+ uartUsedInstances: scanUsedBusInstances(src, chip.uart?.controllers, 'uart'),
800
+ // Preferences/FS — same tokens scaffoldZephyrProject scans (the ZMS
801
+ // settings_* API + __tc_prefs shim, the __tc_fs mount shim); drive the
802
+ // storage-partition synthesis + /chosen settings pointer.
803
+ usesPreferences: uses('settings_') || uses('__tc_prefs'),
804
+ usesFS: uses('__tc_fs'),
805
+ usesWdt: uses('wdt_'),
806
+ usesHwtimer: uses('counter_') || uses('__tc_hw'),
807
+ usesDisplay,
808
+ usesTouch: usesTouch || usesXpt,
809
+ touchController: usesXpt ? 'xpt2046' : 'ft6336u',
810
+ }, displayProfile);
811
+ const overlayDir = join(projectRoot, 'boards');
812
+ mkdirSync(overlayDir, { recursive: true });
813
+ // prepare() runs before the real target is known — the placeholder name
814
+ // never matches `west build -b <board>` (compile rewrites the overlay
815
+ // under the actual board's name below).
816
+ writeIfChanged(join(overlayDir, 'board.overlay'), overlay);
817
+ // Thin SPI targets need an app-local binding: a compatible-less DT node
818
+ // generates NO property macros, so SPI_DT_SPEC_GET's spi-max-frequency
819
+ // lookup would not exist. The binding has no driver — it exists so
820
+ // gen_defines emits the spi properties for the target nodes.
821
+ if (spiTargetParts.length > 0) {
822
+ const bindingsDir = join(projectRoot, 'dts', 'bindings');
823
+ mkdirSync(bindingsDir, { recursive: true });
824
+ writeIfChanged(join(bindingsDir, 'cuttlefish,spi-target.yaml'), [
825
+ 'description: |',
826
+ ' Cuttlefish thin SPITarget (hal/spi-target.ts) — a raw spi_dt_spec',
827
+ ' peer. No driver binds this compatible; it exists so devicetree',
828
+ ' generation emits the spi properties (spi-max-frequency,',
829
+ ' spi-cpol/spi-cpha, reg = the cs-gpios index) that SPI_DT_SPEC_GET',
830
+ ' consumes from the generated C++.',
831
+ 'compatible: "cuttlefish,spi-target"',
832
+ 'include: spi-device.yaml',
833
+ '',
834
+ ].join('\n'));
835
+ }
836
+ },
837
+
838
+ compile(o: ToolchainOptions): CompileResult {
839
+ const projectRoot = projectRootFromOptions(o);
840
+ const rawBoard = targetFromOptions(o);
841
+
842
+ // Fail fast on an incompatible Zephyr (clear message vs. a cryptic west/
843
+ // CMake board error), then normalize the board target for the installed
844
+ // version — Zephyr 4.3+ rejects bare multi-core board names, so a stale
845
+ // config (esp32s3_devkitc) is rewritten to the qualified form
846
+ // (esp32s3_devkitc/esp32s3/procpu). See toolchain/compat.ts.
847
+ const zephyrVersion = detectZephyrVersion();
848
+ const compat = checkZephyrCompat(zephyrVersion);
849
+ if (compat.status === 'out-of-range') {
850
+ throw new Error(
851
+ `Zephyr ${zephyrVersion} is outside the supported range (${compat.range}) for @typecad/framework-zephyr. ` +
852
+ `Set ZEPHYR_BASE to a compatible Zephyr checkout, or install one via '@typecad/zephyr-installer'.`,
853
+ );
854
+ }
855
+ if (compat.status === 'undetectable') {
856
+ console.warn(
857
+ `! Could not detect the installed Zephyr version (is ZEPHYR_BASE set?). ` +
858
+ `Skipping compat check; declared range is ${compat.range}.`,
859
+ );
860
+ }
861
+ const board = resolveBoardTarget(rawBoard, zephyrVersion);
862
+
863
+ const debugMode = new ZephyrStrategy().debugMode(board);
864
+ const isGdbDebug = o.debug === true && debugMode === 'gdb';
865
+ const zc = o.zephyrConfig as Record<string, unknown> | undefined;
866
+ const userKconfig = zc?.kconfig as Record<string, string> | undefined;
867
+ const configChanged = scaffoldZephyrProject(projectRoot, isGdbDebug, userKconfig, o.psram);
868
+
869
+ // Regenerate the DT overlay for the ACTUAL target board. prepare() writes
870
+ // it for the default board (the real target is unknown until compile), so
871
+ // the <default>.overlay it wrote does not match `west build -b <board>`.
872
+ // Zephyr auto-detects boards/<board>.overlay under APPLICATION_CONFIG_DIR.
873
+ try {
874
+ const chip = chipForBuild(projectRoot, board);
875
+ // Custom-board generation: an MCU-only target (no board package) has no
876
+ // upstream Zephyr board — generate one under boards/typecad/<name>/ from
877
+ // the chip's silicon data. Opt-in via `zephyr.customBoard: true` in
878
+ // typecad-hal.config.ts; the board takes its name from the build target.
879
+ // Idempotent — regenerated on every compile, before the overlay pass.
880
+ if (zc?.customBoard === true) {
881
+ const generated = generateCustomBoard(projectRoot, chip, board.split('/')[0]);
882
+ if (!generated) {
883
+ throw new Error(
884
+ `zephyr.customBoard is set, but the resolved chip ('${chip.id}') carries no ` +
885
+ `silicon board data. Custom-board generation requires an MCU-only config ` +
886
+ `(mcu set, board absent) whose MCU package ships a zephyr block.`,
887
+ );
888
+ }
889
+ }
890
+ const srcDir = join(projectRoot, 'src');
891
+ let src = '';
892
+ try {
893
+ for (const name of readdirSync(srcDir)) {
894
+ if (name.endsWith('.cpp') || name.endsWith('.c')) {
895
+ src += readFileSync(join(srcDir, name), 'utf-8');
896
+ }
897
+ }
898
+ } catch { /* src may not exist */ }
899
+ const uses = (t: string): boolean => src.includes(t);
900
+ const usesDisplay = uses('display_write') || uses('display_init')
901
+ || uses('display_fill_rect') || uses('__tc_display_dev')
902
+ || uses('CuttlefishDisplayTarget');
903
+ // Derive the display dimensions from the emitted adapter code
904
+ // (display_width/height return the profile's w/h). This ensures the DT
905
+ // overlay's width/height match the panel the adapter targets, not the
906
+ // default profile — critical for drivers like ST7796S that initialize
907
+ // the panel geometry from the DT node.
908
+ let displayProfile = usesDisplay ? DEFAULT_ZEPHYR_DISPLAY_PROFILE : undefined;
909
+ if (usesDisplay) {
910
+ const wMatch = src.match(/display_width\(\)\s*\{\s*return\s+(\d+)\s*;\s*\}/);
911
+ const hMatch = src.match(/display_height\(\)\s*\{\s*return\s+(\d+)\s*;\s*\}/);
912
+ if (wMatch && hMatch) {
913
+ displayProfile = {
914
+ ...DEFAULT_ZEPHYR_DISPLAY_PROFILE,
915
+ width: parseInt(wMatch[1], 10),
916
+ height: parseInt(hMatch[1], 10),
917
+ };
918
+ }
919
+ }
920
+ // Extract display pin wiring (cs/dc/rst/spiFrequency/spiPins) from the
921
+ // config display section so the DT overlay wires the MIPI DBI bridge to
922
+ // the correct GPIOs + SPI bus pins.
923
+ const dispCfg = o.display as Record<string, unknown> | undefined;
924
+ const spiPins = (dispCfg?.spiPins ?? undefined) as
925
+ { sck?: unknown; mosi?: unknown; miso?: unknown } | undefined;
926
+ const wiring: DisplayWiring | undefined = dispCfg
927
+ ? {
928
+ cs: typeof dispCfg.cs === 'number' ? dispCfg.cs : undefined,
929
+ dc: typeof dispCfg.dc === 'number' ? dispCfg.dc : undefined,
930
+ rst: typeof dispCfg.rst === 'number' ? dispCfg.rst : undefined,
931
+ spiFrequency: typeof dispCfg.spiFrequency === 'number' ? dispCfg.spiFrequency : undefined,
932
+ sck: typeof spiPins?.sck === 'number' ? spiPins.sck : undefined,
933
+ mosi: typeof spiPins?.mosi === 'number' ? spiPins.mosi : undefined,
934
+ miso: typeof spiPins?.miso === 'number' ? spiPins.miso : undefined,
935
+ backlightPin: typeof dispCfg.backlightPin === 'number' ? dispCfg.backlightPin : undefined,
936
+ tearingEffectPin: typeof dispCfg.tearingEffectPin === 'number' ? dispCfg.tearingEffectPin : undefined,
937
+ }
938
+ : undefined;
939
+ // Extract touch pin wiring from the config display.touch section so the
940
+ // DT overlay wires the bus + touch node. I2C (FT6336U) carries
941
+ // irq/resetPin/sda/scl; SPI (XPT2046) carries irq/cs + the calibration
942
+ // range the xptek,xpt2046 binding requires.
943
+ const touchCfg = dispCfg?.touch as Record<string, unknown> | undefined;
944
+ const isXpt = touchCfg?.library === 'XPT2046_Touchscreen';
945
+ const touchCal = touchCfg?.calibration as
946
+ { xMin?: unknown; xMax?: unknown; yMin?: unknown; yMax?: unknown } | undefined;
947
+ const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined);
948
+ let touchWiring: TouchWiring | undefined = touchCfg
949
+ ? {
950
+ controller: isXpt ? 'xpt2046' : 'ft6336u',
951
+ irq: num(touchCfg.irq),
952
+ resetPin: num(touchCfg.resetPin),
953
+ sda: num(touchCfg.sda),
954
+ scl: num(touchCfg.scl),
955
+ cs: num(touchCfg.cs),
956
+ calibration: touchCal
957
+ ? {
958
+ xMin: num(touchCal.xMin) ?? 0,
959
+ xMax: num(touchCal.xMax) ?? 4095,
960
+ yMin: num(touchCal.yMin) ?? 0,
961
+ yMax: num(touchCal.yMax) ?? 4095,
962
+ }
963
+ : undefined,
964
+ minPressure: num(touchCfg.minPressure),
965
+ }
966
+ : undefined;
967
+ // Touch controller kind for Kconfig (bus driver selection) and the DT
968
+ // node shape: from the config when available, else from the DT nodelabel
969
+ // the emitted adapter references. Forced onto touchWiring so a source
970
+ // scan match without a config section still emits the right node.
971
+ const usesXpt = isXpt || uses('xpt2046');
972
+ if (usesXpt) {
973
+ touchWiring = { controller: 'xpt2046', ...(touchWiring ?? {}) };
974
+ }
975
+ const overlayDiagnostics: OverlayDiagnostic[] = [];
976
+ const sensorParts = scanSensorParts(src);
977
+ const spiTargetParts = scanSpiTargets(src);
978
+ const overlay = generateOverlay(chip, {
979
+ // __tc_<bus> matches the shim state block — a begin()-only program
980
+ // emits no driver API call but still declares the DT device. A
981
+ // constructed sensor is also a bus user (see scanSensorParts).
982
+ usesI2c: uses('i2c_') || uses('__tc_i2c') || sensorParts.length > 0,
983
+ usesSensor: uses('sensor_') || sensorParts.length > 0,
984
+ usesFloatFormat: /%[-0-9.]*[eEfFgG]/.test(src),
985
+ sensorParts,
986
+ spiTargets: spiTargetParts,
987
+ usesSpi: uses('spi_') || uses('__tc_spi') || spiTargetParts.length > 0,
988
+ usesUart: uses('__tc_uart'),
989
+ usesUsb: uses('__tc_usb'),
990
+ usesPwm: uses('pwm_'),
991
+ usesAdc: uses('adc_'),
992
+ adcReadPins: scanAdcReadPins(src, chip),
993
+ usesDac: uses('dac_') || uses('__tc_dac'),
994
+ dacWritePins: scanDacWritePins(src),
995
+ pwmUsedPins: scanPwmUsedPins(src, chip),
996
+ i2cUsedInstances: scanUsedBusInstances(src, chip.i2c?.controllers, 'i2c'),
997
+ spiUsedInstances: scanUsedBusInstances(src, chip.spi?.controllers, 'spi'),
998
+ uartUsedInstances: scanUsedBusInstances(src, chip.uart?.controllers, 'uart'),
999
+ // Preferences/FS — same tokens scaffoldZephyrProject scans; drive the
1000
+ // storage-partition synthesis + /chosen settings pointer.
1001
+ usesPreferences: uses('settings_') || uses('__tc_prefs'),
1002
+ usesWdt: uses('wdt_'),
1003
+ usesHwtimer: uses('counter_') || uses('__tc_hw'),
1004
+ usesFS: uses('__tc_fs'),
1005
+ usesDisplay,
1006
+ usesTouch: uses('ft6336u') || uses('touch_') || usesXpt,
1007
+ touchController: usesXpt ? 'xpt2046' : 'ft6336u',
1008
+ psram: o.psram,
1009
+ }, displayProfile, wiring, touchWiring, overlayDiagnostics);
1010
+ for (const d of overlayDiagnostics) {
1011
+ console.warn(`overlay: ${d.message}`);
1012
+ }
1013
+ const overlayDir = join(projectRoot, 'boards');
1014
+ mkdirSync(overlayDir, { recursive: true });
1015
+ // Write the board-specific overlay (the one west loads). Zephyr looks for
1016
+ // boards/<board_id>.overlay under APPLICATION_CONFIG_DIR — use the bare
1017
+ // board id (before any hardware-qualifier suffix, e.g. 'esp32_devkitc'
1018
+ // not the full 'esp32_devkitc/esp32/procpu' target string). Library
1019
+ // packages' overlay fragments are appended by the scaffold helper.
1020
+ const boardId = board.split('/')[0];
1021
+ writeIfChanged(
1022
+ join(overlayDir, `${boardId}.overlay`),
1023
+ appendLibraryOverlayFragments(overlay, projectRoot),
1024
+ );
1025
+ // Thin SPI targets need the app-local binding (see the transpile-side
1026
+ // write for the rationale): no compatible → no generated spi props →
1027
+ // SPI_DT_SPEC_GET's spi-max-frequency lookup does not exist.
1028
+ if (spiTargetParts.length > 0) {
1029
+ const bindingsDir = join(projectRoot, 'dts', 'bindings');
1030
+ mkdirSync(bindingsDir, { recursive: true });
1031
+ writeIfChanged(join(bindingsDir, 'cuttlefish,spi-target.yaml'), [
1032
+ 'description: |',
1033
+ ' Cuttlefish thin SPITarget (hal/spi-target.ts) — a raw spi_dt_spec',
1034
+ ' peer. No driver binds this compatible; it exists so devicetree',
1035
+ ' generation emits the spi properties (spi-max-frequency,',
1036
+ ' spi-cpol/spi-cpha, reg = the cs-gpios index) that SPI_DT_SPEC_GET',
1037
+ ' consumes from the generated C++.',
1038
+ 'compatible: "cuttlefish,spi-target"',
1039
+ 'include: spi-device.yaml',
1040
+ '',
1041
+ ].join('\n'));
1042
+ }
1043
+ } catch { /* best-effort overlay regen; the build surfaces DT errors */ }
1044
+
1045
+ // Use a stable build dir so incremental builds reuse the Ninja graph.
1046
+ // west defaults to <projectRoot>/build.
1047
+ const buildDir = join(projectRoot, 'build');
1048
+
1049
+ // Reuse the build dir across builds so ninja recompiles only the changed
1050
+ // app translation units and re-links — a pristine configure + the
1051
+ // ~280-target Zephyr library rebuild costs minutes on Windows
1052
+ // (demo-shadcn measures 69s of ninja wall time, 448s of summed compile
1053
+ // work, and every build redid all of it). Nuke it only when the generated
1054
+ // config changed (prj.conf / CMakeLists content), the one path that must
1055
+ // not reuse a cached graph: Zephyr 4.3.99-dev snapshots carry a
1056
+ // regression (zephyrproject-rtos/zephyr#104757, fixed by the #104784
1057
+ // revert on 2026-03-03, in v4.4+) where re-running CMake after a .config
1058
+ // change records an `offsets.h -> offsets.c.obj -> offsets.h` cycle in
1059
+ // .ninja_deps, after which every ninja run fails with `dependency cycle`.
1060
+ // Plain source edits never reconfigure CMake, so they cannot trigger it —
1061
+ // and the retry after the spawn below self-heals any path that still does.
1062
+ // Board switches DO need a nuke: `west build`'s --pristine=auto covers
1063
+ // cmake/config churn, not a -b <board> mismatch — west aborts with
1064
+ // "refusing to proceed without --force" and cuttlefish doesn't forward
1065
+ // that flag, so the user would be stuck deleting the dir by hand. The
1066
+ // cache names the board it was configured for (BOARD:STRING); detect the
1067
+ // mismatch and apply west's own suggested remedy automatically.
1068
+ const cachedBoard = cachedBuildBoard(buildDir);
1069
+ const boardChanged = Boolean(cachedBoard && cachedBoard !== board);
1070
+ if (configChanged || boardChanged) {
1071
+ try { rmSync(buildDir, { recursive: true, force: true }); } catch { /* may not exist */ }
1072
+ }
1073
+
1074
+ const buildArgs = ['build', '-b', board, '-d', buildDir, projectRoot];
1075
+ // Explicitly pass the generated DT overlay. Zephyr's auto-detection of
1076
+ // boards/<board>.overlay fails for hardware-qualified targets (e.g.
1077
+ // esp32_devkitc/esp32/procpu) because the FILE_SUFFIX matching doesn't
1078
+ // resolve — passing -DDTC_OVERLAY_FILE forces it unconditionally.
1079
+ const boardId = board.split('/')[0];
1080
+ const overlayPath = join(projectRoot, 'boards', `${boardId}.overlay`);
1081
+ try {
1082
+ if (readFileSync(overlayPath, 'utf-8').length > 0) {
1083
+ // CMake parses backslashes as escapes — use forward slashes so the
1084
+ // Windows path survives the -D argument intact.
1085
+ buildArgs.push('--', `-DDTC_OVERLAY_FILE=${overlayPath.replace(/\\/g, '/')}`);
1086
+ }
1087
+ } catch { /* no overlay — let Zephyr auto-detect or build without one */ }
1088
+ // Append user cmake args from typecad-hal.config.ts zephyr.cmakeArgs.
1089
+ const userCmakeArgs = zc?.cmakeArgs as string[] | undefined;
1090
+ if (userCmakeArgs && userCmakeArgs.length > 0) {
1091
+ if (!buildArgs.includes('--')) buildArgs.push('--');
1092
+ buildArgs.push(...userCmakeArgs);
1093
+ }
1094
+ const inv = westSpawn(
1095
+ buildArgs,
1096
+ { cwd: projectRoot, encoding: 'utf-8', timeout: BUILD_TIMEOUT_MS },
1097
+ );
1098
+ let result = spawnSync(inv.command, inv.args, inv.options);
1099
+ // Self-heal the Zephyr 4.3.99 dep-cycle regression (see the nuke comment
1100
+ // above): when the cached .ninja_deps carries the cycle, ninja aborts with
1101
+ // `dependency cycle` before compiling anything. The cycle lives in the
1102
+ // build dir, not the sources — one pristine retry clears it and the build
1103
+ // proceeds. On fixed Zephyr (>=4.4) this never fires.
1104
+ let pristineRetry = false;
1105
+ if (result.status !== 0 && isDependencyCycleFailure(combinedSpawnOutput(result))) {
1106
+ try { rmSync(buildDir, { recursive: true, force: true }); } catch { /* may not exist */ }
1107
+ result = spawnSync(inv.command, inv.args, inv.options);
1108
+ pristineRetry = true;
1109
+ }
1110
+
1111
+ const stdout = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
1112
+ const stderr = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
1113
+ const output = stdout + stderr + (pristineRetry
1114
+ ? '\n[typecad-hal] dependency cycle detected in the cached build dir — retried with a pristine build'
1115
+ : '');
1116
+ // Prefix the build log with how west was resolved, for transparency.
1117
+ const header = `Using west via ${inv.install.source}` +
1118
+ (inv.install.zephyrBase ? ` (ZEPHYR_BASE=${inv.install.zephyrBase})` : '') + '\n';
1119
+
1120
+ // After a successful build on a gdb-capable board, keep the VS Code debug
1121
+ // artifacts current: always under --debug, or on a plain build when they
1122
+ // need it (still in create-time starter shape, an outDir rename moved the
1123
+ // app root, or a pre-west self-managed-server entry). Non-fatal on
1124
+ // failure — a missing artifact doesn't block the build.
1125
+ if (result.status === 0 && debugMode === 'gdb') {
1126
+ try {
1127
+ const { workspaceRoot, appRel } = resolveDebugLocations(projectRoot);
1128
+ if (isGdbDebug
1129
+ || debugArtifactsNeedRewrite(workspaceRoot, appRel, readRunnersFacts(buildDir)?.gdb?.replace(/\\/g, '/'))) {
1130
+ writeDebugConfig({
1131
+ projectRoot,
1132
+ workspaceRoot,
1133
+ appRel,
1134
+ target: board,
1135
+ buildDir,
1136
+ sourceMapPath: join(dirname(o.sourcePath), `${basename(o.sourcePath)}.thcppmap.json`),
1137
+ });
1138
+ }
1139
+ } catch (e) {
1140
+ console.warn(`[typecad-hal] gdb debug config generation failed: ${(e as Error).message}`);
1141
+ }
1142
+ }
1143
+
1144
+ // As-built snapshot: after a successful build, the resolved devicetree
1145
+ // at <buildDir>/zephyr/zephyr.dts carries the board's pinctrl labels —
1146
+ // the STABLE name grammar, immune to vendor macro churn. Harvest its
1147
+ // routes into .typecad-hal/as-built.json; the next build's board-module
1148
+ // generation merges them per-pin over the catalog harvest (build wins,
1149
+ // silently when they agree). One-build freshness lag on first setup,
1150
+ // self-maintaining after. Best-effort — a missing/unparseable artifact
1151
+ // never fails the build.
1152
+ if (result.status === 0) {
1153
+ try {
1154
+ const dtsPath = join(buildDir, 'zephyr', 'zephyr.dts');
1155
+ const dtsText = readFileSync(dtsPath, 'utf8');
1156
+ const facts = parseZephyrDts(dtsText);
1157
+ const total = facts.adc.length + facts.pwm.length + facts.dac.length;
1158
+ if (total > 0) {
1159
+ // Write beside the project's board module — the .typecad-hal dir the
1160
+ // config loader reads from, discovered by walking up to the
1161
+ // generated board.json (the scaffold root and the config root are
1162
+ // different dirs in the standard layout: src/out vs project root).
1163
+ let cfDir = join(projectRoot, '.typecad-hal');
1164
+ for (let dir = projectRoot; ; dir = dirname(dir)) {
1165
+ if (existsSync(join(dir, '.typecad-hal', 'board.json'))) {
1166
+ cfDir = join(dir, '.typecad-hal');
1167
+ break;
1168
+ }
1169
+ const parent = dirname(dir);
1170
+ if (parent === dir) break;
1171
+ }
1172
+ mkdirSync(cfDir, { recursive: true });
1173
+ writeIfChanged(join(cfDir, 'as-built.json'), asBuiltJson(board, facts));
1174
+ }
1175
+ } catch { /* best-effort snapshot — nothing to harvest or unreadable */ }
1176
+ }
1177
+
1178
+ return {
1179
+ success: result.status === 0,
1180
+ output: header + output,
1181
+ errors: parseCompileErrors(output, o.sourcePath),
1182
+ };
1183
+ },
1184
+
1185
+ upload(o: ToolchainOptions): UploadResult {
1186
+ const projectRoot = projectRootFromOptions(o);
1187
+ const buildDir = join(projectRoot, 'build');
1188
+ const board = targetFromOptions(o);
1189
+ const zc = o.zephyrConfig as Record<string, unknown> | undefined;
1190
+ const chip = chipForBuild(projectRoot, board);
1191
+ const probe = resolveProbeMethod(zc, chip, 'flash');
1192
+ if (!probe.ok) {
1193
+ return { success: false, output: `-- west flash: ${probe.error}` };
1194
+ }
1195
+ // Flashing over a probe needs it EXCLUSIVE: a debug server still bound to
1196
+ // the gdb port (live session or an orphan whose wrapper died — a VS Code
1197
+ // window reload kills task terminals without killing their children on
1198
+ // Windows) makes openocd fail with LIBUSB_ERROR_ACCESS before any retry
1199
+ // logic can help. Reclaim it up front — it is ours by convention.
1200
+ {
1201
+ const holder = portOwnerPid(DEBUG_SERVER_PORT);
1202
+ if (holder !== undefined && holder !== process.pid) {
1203
+ console.log(`-- west flash: stopping debug server (pid ${holder}) — flashing needs exclusive probe access`);
1204
+ killPidTree(holder);
1205
+ try {
1206
+ rmSync(join(projectRoot, '.typecad-hal', 'debug-server.pid'), { force: true });
1207
+ } catch { /* already gone */ }
1208
+ }
1209
+ }
1210
+ // BOSSA bootloader boards with touch-reset data: open the app's console
1211
+ // port at 1200 baud (the firmware's USB shim reboots into the
1212
+ // bootloader), wait for the bootloader identity, and flash THAT port.
1213
+ // Falls back to the configured port (manual double-tap) on any failure.
1214
+ let flashPort = o.port;
1215
+ const flashNotes: string[] = [];
1216
+ // The runner this flash will actually use: the explicit choice, else the
1217
+ // board's declared default (first probe-method entry). Gates port
1218
+ // forwarding and the bossac touch below — board.cmake still resolves
1219
+ // the default runner itself.
1220
+ const flashRunner = probe.runner ?? chip.probeMethods?.[0]?.runner;
1221
+ // Serial-port runners cannot flash without a port; every other runner
1222
+ // (probe or USB) proceeds — whether a port is required is the runner's
1223
+ // call, not the CLI's blanket gate.
1224
+ if (uploadRequiresPort(flashRunner) && !flashPort) {
1225
+ return {
1226
+ success: false,
1227
+ output: `-- upload requires a port for ${flashRunner} flashing. Set --port <port> on the command line (or the TYPECAD_HAL_PORT env var).`,
1228
+ };
1229
+ }
1230
+ if (flashRunner === 'bossac' && flashPort && chip.usb?.touchReset) {
1231
+ const touch = bossacTouchReset(flashPort, chip.usb.touchReset);
1232
+ flashNotes.push(`-- ${touch.note}`);
1233
+ if (touch.port) flashPort = touch.port;
1234
+ }
1235
+ const args = buildFlashArgs(buildDir, probe.runner, flashPort, flashRunner, probe.args);
1236
+
1237
+ // openocd flashes go through a dedicated session instead of `west flash`.
1238
+ // west's flow has three sequential races that each strand the board: the
1239
+ // connect happens against a running (often USB-active) application, the
1240
+ // erase precedes the write so the vector table is 0xFFFFFFFF while the
1241
+ // RAM algorithm runs (any exception → core LOCKUP at 0xFFFFFFFE, "timeout
1242
+ // waiting for algorithm"), and the trailing `reset run` frequently does
1243
+ // not reach the core. This session is deterministic end to end: halt at
1244
+ // the reset vector (static target for the DAP), mask interrupts for the
1245
+ // algorithm (exceptions cannot vector through erased flash), unmask
1246
+ // after, and boot the flashed app with a direct SYSRESETREQ. Falls back
1247
+ // to `west flash` when the image or session is unavailable.
1248
+ let westFallback = true;
1249
+ if (probe.runner === 'openocd') {
1250
+ const hex = join(buildDir, 'zephyr', 'zephyr.hex');
1251
+ if (existsSync(hex)) {
1252
+ // Forward slashes + TCL quoting so project paths with spaces work.
1253
+ const hexArg = `"${hex.replace(/\\/g, '/')}"`;
1254
+ // Target addressing: `cortex_m` is a PER-TARGET subcommand — a bare
1255
+ // `cortex_m maskisr on` is an unknown command (a silent no-op inside
1256
+ // catch). Resolve the session's target object once and address it.
1257
+ // Cortex-M-only, self-gating: on other cores the cortex_m method
1258
+ // errors and catch contains it (the plain flash path is safe there
1259
+ // without masking — the lockup class is Cortex-M vectoring).
1260
+ const flashed = openocdProbeSession(buildDir, zc, chip, [
1261
+ 'set _tgt [lindex [target names] 0]',
1262
+ 'reset halt',
1263
+ 'catch { $_tgt cortex_m maskisr on }',
1264
+ `flash write_image erase ${hexArg}`,
1265
+ 'catch { $_tgt cortex_m maskisr off }',
1266
+ // Boot the flashed app. Cortex-M: a direct SYSRESETREQ via AIRCR —
1267
+ // pin-independent, always reaches the core, and clears PRIMASK
1268
+ // (so the masked algorithm leaves nothing behind). Other cores:
1269
+ // openocd's generic reset run. A halted core STAYS halted across
1270
+ // a core-initiated reset (debug halt state survives — that is how
1271
+ // reset halt works), so resume it; on a running core resume errors
1272
+ // and the catch swallows it.
1273
+ 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1274
+ 'sleep 100',
1275
+ 'catch { resume }',
1276
+ 'sleep 200',
1277
+ ]);
1278
+ if (flashed) {
1279
+ westFallback = false;
1280
+ flashNotes.push('-- probe flash ok: halt → masked write → SYSRESETREQ');
1281
+ }
1282
+ }
1283
+ }
1284
+
1285
+ let result: ReturnType<typeof spawnSync> | undefined;
1286
+ let raw = '';
1287
+ let ok = false;
1288
+ if (westFallback) {
1289
+ const inv = westSpawn(args, {
1290
+ cwd: projectRoot,
1291
+ encoding: 'utf-8',
1292
+ timeout: FLASH_TIMEOUT_MS,
1293
+ });
1294
+ result = spawnSync(inv.command, inv.args, inv.options);
1295
+ const fstdout = typeof result.stdout === 'string' ? result.stdout : (result.stdout?.toString() ?? '');
1296
+ const fstderr = typeof result.stderr === 'string' ? result.stderr : (result.stderr?.toString() ?? '');
1297
+ raw = fstdout + fstderr;
1298
+ ok = classifyUploadResult(probe.runner, result.status, raw);
1299
+ // A SUCCESSFUL west openocd flash can still leave the core HALTED:
1300
+ // west's trailing `reset run` does not reach a core behind an unwired
1301
+ // SRST, and the user's only recourse is the NRST button. Boot it from
1302
+ // a probe session instead — one core reset (a halted core re-halts at
1303
+ // the reset vector; a running core restarts the just-flashed app)
1304
+ // plus a resume.
1305
+ if (ok && probe.runner === 'openocd') {
1306
+ const booted = openocdProbeSession(buildDir, zc, chip, [
1307
+ 'set _tgt [lindex [target names] 0]',
1308
+ 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1309
+ 'sleep 100',
1310
+ 'catch { resume }',
1311
+ 'sleep 200',
1312
+ ]);
1313
+ if (booted) flashNotes.push('-- probe boot ok: SYSRESETREQ → resume');
1314
+ }
1315
+ // Fallback-path recovery: a failed west flash leaves the core in
1316
+ // lockup; a direct SYSRESETREQ clears it so the caller's retry (or a
1317
+ // later flash) starts from a clean chip.
1318
+ if (!ok && probe.runner === 'openocd') {
1319
+ const revived = openocdProbeSession(buildDir, zc, chip, [
1320
+ 'init',
1321
+ 'set _tgt [lindex [target names] 0]',
1322
+ 'if {[catch {$_tgt cortex_m maskisr on}] == 0} { $_tgt cortex_m maskisr off; mww 0xE000ED0C 0x05FA0004 } else { reset run }',
1323
+ 'sleep 300',
1324
+ ]);
1325
+ if (revived) flashNotes.push(revived);
1326
+ // Known SWD-failure signatures get a recovery pointer — a board that
1327
+ // ignores SWD until power-cycled (low-power state, lockup, a wedged
1328
+ // probe) otherwise reads as a toolchain bug.
1329
+ if (isTargetSwdFailure(raw)) {
1330
+ flashNotes.push(
1331
+ '-- target ignored SWD — if a retry fails too: power-cycle the board, replug the probe, or skip SWD entirely (hold BOOT0, tap reset, re-run with --probe dfu)',
1332
+ );
1333
+ }
1334
+ }
1335
+ } else {
1336
+ ok = true;
1337
+ }
1338
+ return {
1339
+ success: ok,
1340
+ output: [...flashNotes, cleanseUploadOutput(probe.runner, westFallback ? result!.status : 0, raw)]
1341
+ .filter(Boolean).join('\n'),
1342
+ };
1343
+ },
1344
+
1345
+ monitor(o: ToolchainOptions): void {
1346
+ // Serial monitor over USB-CDC. Zephyr does NOT ship a `west serial`
1347
+ // subcommand (it's not a real west command — invoking it errors with
1348
+ // "unknown command"). The discovered west install's venv carries pyserial,
1349
+ // so run its bundled miniterm directly: `python -m serial.tools.miniterm`.
1350
+ // That is the same cross-platform terminal pyserial provides in ESP-IDF's
1351
+ // idf.py monitor, and it inherits stdio so Ctrl+C exits cleanly.
1352
+ if (!o.port) {
1353
+ throw new Error(
1354
+ 'A serial port is required to monitor. Pass --port <COMx/ttyX>.',
1355
+ );
1356
+ }
1357
+ // ESP32 USB-CDC console runs at 115200 (the Zephyr ESP32 board default).
1358
+ // The CLI's generic default of 9600 is wrong for this target; honor an
1359
+ // explicit --baud when given, else 115200.
1360
+ const baud = o.baud ?? 115200;
1361
+ const install = discoverWest();
1362
+ const py = install?.pythonExecutable ?? process.env.PYTHON ?? 'python';
1363
+ // Reuse west-spawn's env builder (prepends the venv bin dir to PATH so the
1364
+ // python we spawn resolves pyserial from the same venv). Falls back to the
1365
+ // process env when no install is discovered.
1366
+ const env = install ? buildEnv(install) : process.env;
1367
+ // Post-flash re-enumeration: the chip resets when `--upload` finishes, the
1368
+ // OS tears the serial device object down and re-creates it, and miniterm's
1369
+ // single open can land inside that window (a FileNotFoundError even though
1370
+ // the board never unplugged). Wait for the port to (re)appear first.
1371
+ if (!waitForSerialPort(py, env, projectRootFromOptions(o), o.port)) {
1372
+ process.exitCode = 1;
1373
+ return;
1374
+ }
1375
+ spawnSync(py, ['-m', 'serial.tools.miniterm', o.port, String(baud)], {
1376
+ cwd: projectRootFromOptions(o),
1377
+ env,
1378
+ stdio: 'inherit',
1379
+ });
1380
+ },
1381
+
1382
+ debug(o: ToolchainOptions): void {
1383
+ // Launch an interactive GDB session for the last build. The probe method
1384
+ // resolves exactly like flashing (zephyr.probe / zephyr.runner — the same
1385
+ // attach session, so the same quirks apply); debug-incapable methods
1386
+ // (bootloaders) are rejected with the debug-capable list. west debug
1387
+ // resolves the GDB binary from the build dir's CMakeCache — no
1388
+ // hand-authored gdbinit needed. Inherits stdio so GDB runs interactively.
1389
+ const projectRoot = projectRootFromOptions(o);
1390
+ const buildDir = join(projectRoot, 'build');
1391
+ const board = targetFromOptions(o);
1392
+ const zc = o.zephyrConfig as Record<string, unknown> | undefined;
1393
+ const probe = resolveProbeMethod(zc, chipForBuild(projectRoot, board), 'debug');
1394
+ if (!probe.ok) {
1395
+ console.error(`-- west debug: ${probe.error}`);
1396
+ process.exitCode = 1;
1397
+ return;
1398
+ }
1399
+ const debugArgs = ['debug', '-d', buildDir];
1400
+ if (probe.runner) debugArgs.push('--runner', probe.runner);
1401
+ debugArgs.push(...probe.args);
1402
+ const inv = westSpawn(debugArgs, {
1403
+ cwd: projectRoot,
1404
+ encoding: 'utf-8',
1405
+ stdio: 'inherit',
1406
+ });
1407
+ spawnSync(inv.command, inv.args, inv.options);
1408
+ },
1409
+
1410
+ debugServer(o: ToolchainOptions, action: 'start' | 'stop'): void {
1411
+ const projectRoot = projectRootFromOptions(o);
1412
+ const buildDir = join(projectRoot, 'build');
1413
+ const pidFile = join(projectRoot, '.typecad-hal', 'debug-server.pid');
1414
+
1415
+ if (action === 'stop') {
1416
+ stopDebugServer(pidFile);
1417
+ return;
1418
+ }
1419
+
1420
+ // start: wrap `west debugserver` as a long-running foreground process (the
1421
+ // VS Code background task owns this process; postDebugTask runs `stop`).
1422
+ if (!existsSync(join(buildDir, 'zephyr', 'runners.yaml'))) {
1423
+ console.error(
1424
+ `! No build at ${buildDir} — run 'npm run compile' (or F5's preLaunchTask) first.`,
1425
+ );
1426
+ process.exitCode = 1;
1427
+ return;
1428
+ }
1429
+ const stale = readStaleServerPid(pidFile);
1430
+ if (stale !== undefined) {
1431
+ // Already running (pid alive): just re-emit the ready marker so the
1432
+ // task's problem matcher completes immediately.
1433
+ console.log(`[typecad-hal] west debugserver already running (pid ${stale})`);
1434
+ console.log(`TYPECAD_HAL: debug server ready on ${DEBUG_SERVER_PORT}`);
1435
+ return;
1436
+ }
1437
+ try { rmSync(pidFile, { force: true }); } catch { /* already gone */ }
1438
+ // A wrapper/west that died without cleanup can leave openocd bound to
1439
+ // the gdb port with a stale pidfile — reclaim it or the new server
1440
+ // cannot bind (and gdb would attach to the orphan).
1441
+ const orphan = portOwnerPid(DEBUG_SERVER_PORT);
1442
+ if (orphan !== undefined && orphan !== process.pid) {
1443
+ console.log(`[typecad-hal] reclaiming orphaned debug server on :${DEBUG_SERVER_PORT} (pid ${orphan})`);
1444
+ killPidTree(orphan);
1445
+ }
1446
+
1447
+ // Runner + quirk parity with flash (resolveProbeMethod, same as `west
1448
+ // debug`): an explicit zephyr.probe selects the runner; either way, an
1449
+ // srst-based openocd cfg behind an unwired NRST (the probeRunnerQuirks
1450
+ // condition, read from the board's own method data) makes `reset init`
1451
+ // time out — the IDE's post-attach reset would hang the session. Apply
1452
+ // the core-reset override server-side unless the config's runnerArgs
1453
+ // already carry it (the create flow bakes it in).
1454
+ const board = targetFromOptions(o);
1455
+ const chip = chipForBuild(projectRoot, board);
1456
+ const zc = o.zephyrConfig as Record<string, unknown> | undefined;
1457
+ const probe = resolveProbeMethod(zc, chip, 'debug');
1458
+ // The runner west will actually drive: the explicit choice, else the
1459
+ // board's declared debug-runner default from the build's runners.yaml.
1460
+ const runner = ((probe.ok && probe.runner) || undefined)
1461
+ ?? readRunnersFacts(buildDir)?.debugRunner;
1462
+ const isOcd = runner === undefined || runner === 'openocd' || runner.startsWith('openocd');
1463
+ if (!isOcd) {
1464
+ console.warn(`! debug-server: the IDE wiring (ready marker, quirk args) targets the ` +
1465
+ `openocd runner; this build's debug runner is '${runner}'. Starting it plain — ` +
1466
+ `the F5 session may not connect.`);
1467
+ }
1468
+ const serverArgs = ['debugserver', '-d', buildDir];
1469
+ if (probe.ok) {
1470
+ if (probe.runner) serverArgs.push('--runner', probe.runner);
1471
+ serverArgs.push(...probe.args);
1472
+ }
1473
+ if (isOcd) {
1474
+ serverArgs.push(
1475
+ '--gdb-port', String(DEBUG_SERVER_PORT),
1476
+ // Pinned so the readiness poll below has a deterministic port.
1477
+ '--tcl-port', String(DEBUG_SERVER_TCL_PORT),
1478
+ // The board's own openocd.cfg may declare gdb-attach/gdb-detach
1479
+ // events (reset-on-attach for standalone sessions). Under an
1480
+ // IDE-managed session a stop event mid-initialization aborts
1481
+ // debugger setup, so neutralize them: west's --cmd-pre-init lands
1482
+ // AFTER the cfg files in the openocd command line, so these win.
1483
+ '--cmd-pre-init', '$_TARGETNAME configure -event gdb-attach {}',
1484
+ '--cmd-pre-init', '$_TARGETNAME configure -event gdb-detach {}',
1485
+ );
1486
+ const method = (zc?.probe as string | undefined)
1487
+ ? chip.probeMethods?.find((m) => m.id === zc?.probe)
1488
+ : chip.probeMethods?.find((m) => m.debug !== false);
1489
+ const cfg = method?.debugCfg ?? [];
1490
+ const srst = cfg.some((l) => /reset_config\s+srst/.test(l));
1491
+ const connectAssert = cfg.some((l) => /connect_assert_srst/.test(l));
1492
+ if (method?.runner === 'openocd' && srst && !connectAssert
1493
+ && !(probe.ok && probe.args.includes('--cmd-pre-init=reset_config none'))) {
1494
+ serverArgs.push('--cmd-pre-init', 'reset_config none');
1495
+ }
1496
+ }
1497
+ const inv = westSpawn(serverArgs, { cwd: projectRoot });
1498
+ const child = spawn(inv.command, inv.args, {
1499
+ ...inv.options,
1500
+ stdio: ['ignore', 'pipe', 'pipe'],
1501
+ // Own process group on POSIX so `stop` can signal the whole tree.
1502
+ ...(process.platform !== 'win32' ? { detached: true } : {}),
1503
+ });
1504
+ // @types/node 26 types ChildProcess's on/once through the internal
1505
+ // InternalEventEmitter base. When `tsc -b` rechecks this package in the
1506
+ // same solution pass that rebuilds its project references, that
1507
+ // inheritance can fail to surface and the spawned child's type loses
1508
+ // .on/.once (TS2339) — while stream types, which COPY the event
1509
+ // signatures, keep working. Subscribe through a structural copy of the
1510
+ // one signature this file needs: the copy-don't-inherit prescription
1511
+ // @types/node itself applies to multi-level emitter classes. The `unknown`
1512
+ // hop keeps the cast legal in both resolution states.
1513
+ const childExit = child as unknown as {
1514
+ on(event: 'exit', listener: (code: number | null) => void): unknown;
1515
+ once(event: 'exit', listener: (code: number | null) => void): unknown;
1516
+ };
1517
+ mkdirSync(join(projectRoot, '.typecad-hal'), { recursive: true });
1518
+ writeFileSync(pidFile, String(child.pid), 'utf-8');
1519
+ console.log(`[typecad-hal] starting west debugserver (gdb on localhost:${DEBUG_SERVER_PORT})`);
1520
+ // A reader that goes away (closed task terminal, piped head) must not
1521
+ // take the server down with an EPIPE.
1522
+ process.stdout?.on?.('error', () => { /* EPIPE — server keeps running */ });
1523
+ process.stderr?.on?.('error', () => { /* EPIPE — server keeps running */ });
1524
+ child.stdout?.on('data', (d: Buffer) => process.stdout.write(d));
1525
+ child.stderr?.on('data', (d: Buffer) => process.stderr.write(d));
1526
+
1527
+ // Ready = the TCL port accepts connections. NOT the gdb port: openocd's
1528
+ // gdb server takes ONE client, so a TCP probe there both logs
1529
+ // "attempted 'gdb' connection rejected" and can race the real gdb
1530
+ // connection for the slot. The tcl listener opens at the END of openocd
1531
+ // init (after the gdb listener and the startup halt) — a truer signal —
1532
+ // and probes there are inert.
1533
+ const deadline = Date.now() + DEBUG_SERVER_START_TIMEOUT_MS;
1534
+ const poll = (): void => {
1535
+ const sock = netConnect(DEBUG_SERVER_TCL_PORT, '127.0.0.1');
1536
+ sock.once('connect', () => {
1537
+ sock.destroy();
1538
+ console.log(`TYPECAD_HAL: debug server ready on ${DEBUG_SERVER_PORT}`);
1539
+ });
1540
+ sock.once('error', () => {
1541
+ sock.destroy();
1542
+ if (child.exitCode !== null) return; // server died — exit handler reports
1543
+ if (Date.now() > deadline) {
1544
+ console.error(`! west debugserver did not open :${DEBUG_SERVER_TCL_PORT} within `
1545
+ + `${DEBUG_SERVER_START_TIMEOUT_MS / 1000}s — see its output above.`);
1546
+ stopDebugServer(pidFile);
1547
+ process.exitCode = 1;
1548
+ return;
1549
+ }
1550
+ setTimeout(poll, 250);
1551
+ });
1552
+ };
1553
+ poll();
1554
+
1555
+ childExit.on('exit', (code) => {
1556
+ try { rmSync(pidFile, { force: true }); } catch { /* already gone */ }
1557
+ // Exit before ready: surface as a task failure (the debugger never
1558
+ // connects and VS Code reports the background task's non-zero exit).
1559
+ if (code !== null && code !== 0) process.exitCode = code;
1560
+ });
1561
+ const forwardSignal = (): void => {
1562
+ stopDebugServer(pidFile);
1563
+ childExit.once('exit', () => process.exit(0));
1564
+ setTimeout(() => process.exit(0), 1500).unref();
1565
+ };
1566
+ process.on('SIGINT', forwardSignal);
1567
+ process.on('SIGTERM', forwardSignal);
1568
+ },
1569
+ };
1570
+
1571
+ /** How long `debug-server start` waits for the gdb port before failing. */
1572
+ const DEBUG_SERVER_START_TIMEOUT_MS = 45_000;
1573
+
1574
+ /**
1575
+ * Read the pidfile and return the pid when that process is still alive,
1576
+ * undefined otherwise (no file, dead pid, or unparseable). Best-effort.
1577
+ */
1578
+ function readStaleServerPid(pidFile: string): number | undefined {
1579
+ try {
1580
+ const pid = Number.parseInt(readFileSync(pidFile, 'utf-8').trim(), 10);
1581
+ if (!Number.isInteger(pid)) return undefined;
1582
+ process.kill(pid, 0); // throws ESRCH when dead
1583
+ return pid;
1584
+ } catch {
1585
+ return undefined;
1586
+ }
1587
+ }
1588
+
1589
+ /**
1590
+ * The pid of whatever process is LISTENING on the gdb port — the recovery
1591
+ * path for orphaned servers (the wrapper and west can die while openocd
1592
+ * survives, e.g. a killed task terminal; the pidfile is then stale but the
1593
+ * port stays bound and the next session would attach to the orphan).
1594
+ * Best-effort: netstat on Windows, lsof on POSIX; undefined when the port is
1595
+ * free or the platform tool is unavailable.
1596
+ */
1597
+ function portOwnerPid(port: number): number | undefined {
1598
+ try {
1599
+ if (process.platform === 'win32') {
1600
+ const out = spawnSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf-8' });
1601
+ if (out.status !== 0) return undefined;
1602
+ for (const line of (out.stdout ?? '').split(/\r?\n/)) {
1603
+ const cols = line.trim().split(/\s+/);
1604
+ if (cols.length >= 5 && cols[3] === 'LISTENING'
1605
+ && cols[1].endsWith(`:${port}`)) {
1606
+ const pid = Number.parseInt(cols[4], 10);
1607
+ if (Number.isInteger(pid)) return pid;
1608
+ }
1609
+ }
1610
+ return undefined;
1611
+ }
1612
+ const out = spawnSync('lsof', ['-ti', `tcp:${port}`], { encoding: 'utf-8' });
1613
+ if (out.status !== 0 || !out.stdout?.trim()) return undefined;
1614
+ const pid = Number.parseInt(out.stdout.trim().split(/\s+/)[0]!, 10);
1615
+ return Number.isInteger(pid) ? pid : undefined;
1616
+ } catch {
1617
+ return undefined;
1618
+ }
1619
+ }
1620
+
1621
+ /** Kill a pid tree (Windows: taskkill /T; POSIX: the process group). */
1622
+ function killPidTree(pid: number): void {
1623
+ if (process.platform === 'win32') {
1624
+ // /T: the whole tree (the pid may be the micromamba/west wrapper; openocd
1625
+ // is its grandchild). /F: force — the server has no stdin to close.
1626
+ spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { encoding: 'utf-8' });
1627
+ } else {
1628
+ try {
1629
+ process.kill(-pid, 'SIGTERM'); // the detached process group
1630
+ } catch {
1631
+ try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ }
1632
+ }
1633
+ }
1634
+ }
1635
+
1636
+ /** Kill the debug server tree (micromamba/west → openocd) and drop the pidfile.
1637
+ * Falls back to the gdb-port owner when the recorded pid is already dead —
1638
+ * that orphan would otherwise serve stale sessions forever. */
1639
+ function stopDebugServer(pidFile: string): void {
1640
+ const pid = readStaleServerPid(pidFile) ?? portOwnerPid(DEBUG_SERVER_PORT);
1641
+ if (pid === undefined) {
1642
+ try { rmSync(pidFile, { force: true }); } catch { /* already gone */ }
1643
+ console.log('[typecad-hal] debug server not running');
1644
+ return;
1645
+ }
1646
+ killPidTree(pid);
1647
+ try { rmSync(pidFile, { force: true }); } catch { /* already gone */ }
1648
+ console.log(`[typecad-hal] debug server stopped (pid ${pid})`);
1649
+ }
1650
+
1651
+ // -- serial monitor: post-flash re-enumeration wait --------------------------
1652
+
1653
+ /** How long `--monitor` waits for the port to (re)appear after a flash reset. */
1654
+ export const MONITOR_PORT_WAIT_MS = 8000;
1655
+
1656
+ /**
1657
+ * The pyserial port wait run before miniterm (argv built by
1658
+ * serialPortWaitArgs). Polls list_ports — never OPENS the port, because
1659
+ * toggling DTR on an open can itself reset some boards — until the device
1660
+ * name matches case-insensitively or the timeout elapses. Exit codes:
1661
+ * 0 port present, 1 timeout (message printed to stderr), 2 pyserial
1662
+ * unavailable (the caller lets miniterm surface the real error instead of
1663
+ * reporting a bogus timeout).
1664
+ */
1665
+ const SERIAL_PORT_WAIT_PY = [
1666
+ 'import sys, time',
1667
+ 'try:',
1668
+ ' from serial.tools import list_ports',
1669
+ 'except Exception:',
1670
+ ' sys.exit(2)',
1671
+ 'port, timeout = sys.argv[1], float(sys.argv[2])',
1672
+ 'def present():',
1673
+ ' return any(d.device.lower() == port.lower() for d in list_ports.comports())',
1674
+ 'if not present():',
1675
+ " print('waiting for %s to re-enumerate (the board resets after flashing)...' % port, flush=True)",
1676
+ ' end = time.time() + timeout',
1677
+ ' while not present():',
1678
+ ' if time.time() >= end:',
1679
+ " print('%s did not come back within %ds - some boards re-enumerate under a different port name' % (port, int(timeout)), file=sys.stderr, flush=True)",
1680
+ ' sys.exit(1)',
1681
+ ' time.sleep(0.25)',
1682
+ ].join('\n');
1683
+
1684
+ /** argv for the pyserial port wait — exported for the toolchain unit tests. */
1685
+ export function serialPortWaitArgs(port: string, timeoutMs: number): string[] {
1686
+ return ['-c', SERIAL_PORT_WAIT_PY, port, String(timeoutMs / 1000)];
1687
+ }
1688
+
1689
+ /**
1690
+ * Wait for `port` to be listed by the venv's pyserial before miniterm opens
1691
+ * it once. True = proceed to miniterm (port present, or the wait itself was
1692
+ * best-effort-skipped — a missing python/pyserial lets miniterm show the
1693
+ * underlying failure); false = the port never came back (message printed).
1694
+ */
1695
+ function waitForSerialPort(py: string, env: NodeJS.ProcessEnv, cwd: string, port: string): boolean {
1696
+ const res = spawnSync(py, serialPortWaitArgs(port, MONITOR_PORT_WAIT_MS), {
1697
+ cwd,
1698
+ env,
1699
+ stdio: 'inherit',
1700
+ });
1701
+ if (res.error || res.status === null || res.status === 2) return true;
1702
+ return res.status === 0;
1703
+ }