@typecad/framework-zephyr 1.0.0-alpha.14 → 1.0.0-alpha.16

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 (185) hide show
  1. package/README.md +22 -47
  2. package/dist/as-built.d.ts +33 -0
  3. package/dist/as-built.js +188 -0
  4. package/dist/async/timer-polyfill.js +1 -1
  5. package/dist/boardgen.d.ts +128 -0
  6. package/dist/boardgen.js +1366 -0
  7. package/dist/chips/board-overrides.d.ts +7 -0
  8. package/dist/chips/board-overrides.js +11 -0
  9. package/dist/chips/esp32s3.js +49 -0
  10. package/dist/chips/index.d.ts +6 -12
  11. package/dist/chips/index.js +18 -34
  12. package/dist/chips/resolve.d.ts +16 -2
  13. package/dist/chips/resolve.js +267 -10
  14. package/dist/chips/soc/.d.ts +2 -0
  15. package/dist/chips/soc/.js +129 -0
  16. package/dist/chips/soc/esp32.d.ts +2 -0
  17. package/dist/chips/soc/esp32.js +120 -0
  18. package/dist/chips/soc/esp32c3.d.ts +2 -0
  19. package/dist/chips/soc/esp32c3.js +90 -0
  20. package/dist/chips/soc/esp32c6.d.ts +2 -0
  21. package/dist/chips/soc/esp32c6.js +109 -0
  22. package/dist/chips/soc/esp32s3.d.ts +2 -0
  23. package/dist/chips/soc/esp32s3.js +189 -0
  24. package/dist/chips/soc/index.d.ts +2 -0
  25. package/dist/chips/soc/index.js +23 -0
  26. package/dist/chips/soc/nrf52840.d.ts +2 -0
  27. package/dist/chips/soc/nrf52840.js +130 -0
  28. package/dist/chips/soc/rp2040.d.ts +2 -0
  29. package/dist/chips/soc/rp2040.js +141 -0
  30. package/dist/chips/soc/rp2350a.d.ts +2 -0
  31. package/dist/chips/soc/rp2350a.js +145 -0
  32. package/dist/chips/soc/samd21g18a.d.ts +2 -0
  33. package/dist/chips/soc/samd21g18a.js +143 -0
  34. package/dist/chips/soc/stm32f411xe.d.ts +2 -0
  35. package/dist/chips/soc/stm32f411xe.js +251 -0
  36. package/dist/chips/types.d.ts +319 -0
  37. package/dist/chips/xiao-ble.js +21 -0
  38. package/dist/display/profiles.js +1 -1
  39. package/dist/doctor.js +38 -4
  40. package/dist/dt-config/custom-board.d.ts +23 -0
  41. package/dist/dt-config/custom-board.js +227 -0
  42. package/dist/dt-config/kconfig.d.ts +72 -1
  43. package/dist/dt-config/kconfig.js +115 -26
  44. package/dist/dt-config/overlay.js +548 -28
  45. package/dist/framework.manifest.d.ts +3 -3
  46. package/dist/framework.manifest.js +122 -185
  47. package/dist/index.d.ts +4 -1
  48. package/dist/index.js +8 -2
  49. package/dist/lowering/adc.d.ts +20 -2
  50. package/dist/lowering/adc.js +121 -29
  51. package/dist/lowering/ble.js +31 -28
  52. package/dist/lowering/dac.js +9 -9
  53. package/dist/lowering/fs.js +18 -10
  54. package/dist/lowering/gpio.d.ts +2 -0
  55. package/dist/lowering/gpio.js +82 -5
  56. package/dist/lowering/http.js +39 -14
  57. package/dist/lowering/hwtimer.d.ts +4 -0
  58. package/dist/lowering/hwtimer.js +35 -10
  59. package/dist/lowering/i2c.js +46 -54
  60. package/dist/lowering/index.d.ts +5 -5
  61. package/dist/lowering/index.js +15 -16
  62. package/dist/lowering/interrupts.d.ts +22 -5
  63. package/dist/lowering/interrupts.js +104 -22
  64. package/dist/lowering/mqtt.js +3 -5
  65. package/dist/lowering/power.js +0 -4
  66. package/dist/lowering/preferences.js +49 -77
  67. package/dist/lowering/pulse.js +0 -31
  68. package/dist/lowering/pwm.d.ts +12 -1
  69. package/dist/lowering/pwm.js +78 -14
  70. package/dist/lowering/random.js +3 -3
  71. package/dist/lowering/sensor.d.ts +37 -0
  72. package/dist/lowering/sensor.js +119 -0
  73. package/dist/lowering/spi.d.ts +12 -0
  74. package/dist/lowering/spi.js +65 -40
  75. package/dist/lowering/thread.d.ts +14 -0
  76. package/dist/lowering/thread.js +55 -0
  77. package/dist/lowering/timing.js +20 -46
  78. package/dist/lowering/tone.js +16 -4
  79. package/dist/lowering/uart.d.ts +13 -0
  80. package/dist/lowering/uart.js +72 -51
  81. package/dist/lowering/usb.d.ts +34 -0
  82. package/dist/lowering/usb.js +206 -0
  83. package/dist/lowering/wdt.d.ts +1 -1
  84. package/dist/lowering/wdt.js +17 -7
  85. package/dist/lowering/wifi.d.ts +3 -2
  86. package/dist/lowering/wifi.js +97 -111
  87. package/dist/sdk/board-catalog-sync.d.ts +16 -0
  88. package/dist/sdk/board-catalog-sync.js +41 -0
  89. package/dist/sdk/board-data.generated.d.ts +2 -0
  90. package/dist/sdk/board-data.generated.js +4 -0
  91. package/dist/sdk/catalog-walker.d.ts +90 -0
  92. package/dist/sdk/catalog-walker.js +682 -0
  93. package/dist/sdk/dts-reader.d.ts +83 -0
  94. package/dist/sdk/dts-reader.js +596 -0
  95. package/dist/strategy.d.ts +136 -17
  96. package/dist/strategy.js +839 -222
  97. package/dist/toolchain/bossac-touch.d.ts +18 -0
  98. package/dist/toolchain/bossac-touch.js +88 -0
  99. package/dist/toolchain/compat.d.ts +2 -2
  100. package/dist/toolchain/compat.js +8 -3
  101. package/dist/toolchain/debug-config.d.ts +21 -26
  102. package/dist/toolchain/debug-config.js +226 -76
  103. package/dist/toolchain/env-check.d.ts +4 -4
  104. package/dist/toolchain/env-check.js +5 -5
  105. package/dist/toolchain/index.d.ts +115 -1
  106. package/dist/toolchain/index.js +680 -71
  107. package/dist/toolchain/scaffold.js +39 -7
  108. package/dist/toolchain/west-discover.d.ts +4 -0
  109. package/dist/toolchain/west-discover.js +17 -6
  110. package/installer/CHANGELOG.md +473 -0
  111. package/installer/README.md +328 -0
  112. package/installer/environment.yml +46 -0
  113. package/installer/etc/conda/activate.d/zephyr.bat +7 -0
  114. package/installer/etc/conda/activate.d/zephyr.ps1 +12 -0
  115. package/installer/etc/conda/activate.d/zephyr.sh +20 -0
  116. package/installer/etc/conda/deactivate.d/zephyr.bat +6 -0
  117. package/installer/etc/conda/deactivate.d/zephyr.ps1 +6 -0
  118. package/installer/etc/conda/deactivate.d/zephyr.sh +4 -0
  119. package/installer/install.mjs +580 -0
  120. package/installer/install.ps1 +619 -0
  121. package/installer/install.sh +310 -0
  122. package/installer/lib/detect-platform.sh +62 -0
  123. package/installer/lib/fetch-sdk.sh +304 -0
  124. package/installer/lib/init-workspace.sh +153 -0
  125. package/installer/lib/write-activation.sh +76 -0
  126. package/installer/patches/tfm-c-include-separators.patch +19 -0
  127. package/installer/patches/zephyr-tfm-nordic-zephyr-include.patch +24 -0
  128. package/installer/templates/project/.typecad/activate-zephyr.ps1 +31 -0
  129. package/installer/templates/project/.typecad/activate-zephyr.sh +31 -0
  130. package/installer/templates/project/.vscode/settings.json +30 -0
  131. package/installer/templates/project/README.md +58 -0
  132. package/installer/versions.env +110 -0
  133. package/package.json +15 -15
  134. package/src/as-built.ts +206 -0
  135. package/src/boardgen.ts +1428 -0
  136. package/src/chips/index.ts +35 -54
  137. package/src/chips/resolve.ts +285 -10
  138. package/src/chips/types.ts +325 -1
  139. package/src/display/profiles.ts +1 -1
  140. package/src/doctor.ts +110 -77
  141. package/src/dt-config/custom-board.ts +325 -0
  142. package/src/dt-config/kconfig.ts +165 -18
  143. package/src/dt-config/overlay.ts +537 -25
  144. package/src/framework.manifest.ts +123 -185
  145. package/src/index.ts +57 -41
  146. package/src/lowering/adc.ts +222 -118
  147. package/src/lowering/ble.ts +32 -28
  148. package/src/lowering/dac.ts +82 -82
  149. package/src/lowering/fs.ts +18 -10
  150. package/src/lowering/gpio.ts +242 -155
  151. package/src/lowering/http.ts +512 -488
  152. package/src/lowering/hwtimer.ts +139 -101
  153. package/src/lowering/i2c.ts +116 -126
  154. package/src/lowering/index.ts +91 -93
  155. package/src/lowering/interrupts.ts +113 -21
  156. package/src/lowering/mqtt.ts +3 -5
  157. package/src/lowering/preferences.ts +327 -354
  158. package/src/lowering/pwm.ts +167 -99
  159. package/src/lowering/random.ts +3 -3
  160. package/src/lowering/sensor.ts +155 -0
  161. package/src/lowering/spi.ts +164 -124
  162. package/src/lowering/thread.ts +63 -0
  163. package/src/lowering/timing.ts +46 -72
  164. package/src/lowering/uart.ts +73 -51
  165. package/src/lowering/usb.ts +221 -0
  166. package/src/lowering/wdt.ts +95 -84
  167. package/src/lowering/wifi.ts +97 -112
  168. package/src/sdk/board-catalog-sync.ts +62 -0
  169. package/src/strategy.ts +848 -237
  170. package/src/toolchain/bossac-touch.ts +112 -0
  171. package/src/toolchain/compat.ts +8 -3
  172. package/src/toolchain/debug-config.ts +676 -522
  173. package/src/toolchain/env-check.ts +9 -9
  174. package/src/toolchain/index.ts +1359 -645
  175. package/src/toolchain/scaffold.ts +38 -7
  176. package/src/toolchain/west-discover.ts +19 -6
  177. package/src/async/timer-polyfill.ts +0 -107
  178. package/src/chips/esp32.ts +0 -74
  179. package/src/chips/esp32s3.ts +0 -57
  180. package/src/chips/xiao-ble.ts +0 -82
  181. package/src/lowering/power.ts +0 -70
  182. package/src/lowering/pulse.ts +0 -93
  183. package/src/lowering/tone.ts +0 -60
  184. package/src/lowering/worker-backing.ts +0 -94
  185. package/src/lowering/worker.ts +0 -17
@@ -0,0 +1,325 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Custom board generation — an out-of-tree Zephyr board for an MCU-only target
3
+ //
4
+ // When a project targets an MCU package with no board package (`mcu:` set,
5
+ // `board:` absent) there may be no Zephyr board for the user's hardware. The
6
+ // chip descriptor's `customBoard` block (silicon facts from the MCU package:
7
+ // SoC name, devicetree includes, default console mux, default clock plan) is
8
+ // all a minimal HWMv2 board needs, so we generate one into the project:
9
+ //
10
+ // boards/typecad/<name>/board.yml — board + SoC declaration
11
+ // boards/typecad/<name>/<name>.dts — includes, chosen, console, clocks
12
+ // boards/typecad/<name>/Kconfig.<name> — BOARD_<NAME> symbol selecting the SoC
13
+ // boards/typecad/<name>/<name>_defconfig— baseline (GPIO + console) every
14
+ // in-tree board carries
15
+ //
16
+ // The app's CMakeLists.txt adds the project root to BOARD_ROOT (see
17
+ // toolchain/scaffold.ts), so Zephyr discovers the board without touching the
18
+ // checkout. Everything else (buses, ADC, PWM, USB) stays usage-driven: the
19
+ // overlay generator keeps layering `boards/<name>.overlay` on top exactly as
20
+ // it does for upstream boards.
21
+ //
22
+ // Verified against Zephyr 4.3/4.4 (HWMv2): a minimal board is exactly these
23
+ // four files — Kconfig.<name> + CONFIG_GPIO=y are load-bearing (a board
24
+ // without them fails with "ARCH not defined" / gpio link errors).
25
+ // ---------------------------------------------------------------------------
26
+
27
+ import { mkdirSync } from 'node:fs';
28
+ import { join } from 'node:path';
29
+
30
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
31
+ import { writeIfChanged } from '../toolchain/scaffold.js';
32
+
33
+ /** The vendor segment of the generated board path + board.yml. */
34
+ const CUSTOM_BOARD_VENDOR = 'typecad';
35
+
36
+ /**
37
+ * Sanitize a raw name into a legal Zephyr board name: lowercase, `[a-z0-9_]`
38
+ * (dashes/dots/spaces collapse to underscores, leading/trailing underscores
39
+ * trimmed). Board names become C identifiers in Kconfig symbols, so anything
40
+ * stricter would break `config BOARD_<NAME>`.
41
+ */
42
+ export function sanitizeBoardName(raw: string): string {
43
+ const cleaned = raw
44
+ .toLowerCase()
45
+ .replace(/[^a-z0-9_]+/g, '_')
46
+ .replace(/^_+|_+$/g, '');
47
+ return cleaned.length > 0 ? cleaned : 'custom_board';
48
+ }
49
+
50
+ /** Kconfig symbol fragment: `cb_f411` → `CB_F411`. */
51
+ function kconfigFragment(name: string): string {
52
+ return name.toUpperCase();
53
+ }
54
+
55
+ /** Generated-board file set, all under `<projectRoot>/boards/typecad/<name>/`. */
56
+ export interface GeneratedCustomBoard {
57
+ /** Absolute directory of the generated board. */
58
+ dir: string;
59
+ /** The sanitized board name (the `west build -b` argument). */
60
+ name: string;
61
+ /** Whether any file changed (idempotent regeneration signal). */
62
+ changed: boolean;
63
+ }
64
+
65
+ /**
66
+ * Emit the custom board for a chip whose descriptor carries `customBoard`
67
+ * silicon data. No-op (returns null) when the chip has no generator inputs —
68
+ * board-resolved chips don't need one.
69
+ */
70
+ export function generateCustomBoard(
71
+ projectRoot: string,
72
+ chip: ZephyrChipDescriptor,
73
+ rawName: string,
74
+ ): GeneratedCustomBoard | null {
75
+ const cb = chip.customBoard;
76
+ if (!cb) return null;
77
+
78
+ const name = sanitizeBoardName(rawName);
79
+ const soc = cb.socs[0];
80
+ if (!soc) return null;
81
+
82
+ const dir = join(projectRoot, 'boards', CUSTOM_BOARD_VENDOR, name);
83
+ mkdirSync(dir, { recursive: true });
84
+
85
+ let changed = false;
86
+
87
+ // ── board.yml ────────────────────────────────────────────────────────────
88
+ changed =
89
+ writeIfChanged(
90
+ join(dir, 'board.yml'),
91
+ [
92
+ '# Auto-generated by @typecad/framework-zephyr from the MCU package',
93
+ '# silicon definition. Regenerated on every compile — edit the MCU',
94
+ '# package (or add a board package) instead of this file.',
95
+ 'board:',
96
+ ` name: ${name}`,
97
+ ` full_name: Cuttlefish custom board (${chip.soc})`,
98
+ ` vendor: ${CUSTOM_BOARD_VENDOR}`,
99
+ ' socs:',
100
+ ` - name: ${soc}`,
101
+ '',
102
+ ].join('\n'),
103
+ ) || changed;
104
+
105
+ // ── Kconfig.<name> — the board symbol selecting the SoC ─────────────────
106
+ // Load-bearing: without the BOARD_<NAME> symbol selecting SOC_<SOC>, Kconfig
107
+ // completes with no SoC and the build dies with "ARCH not defined".
108
+ changed =
109
+ writeIfChanged(
110
+ join(dir, `Kconfig.${name}`),
111
+ [
112
+ '# Auto-generated by @typecad/framework-zephyr. Do not edit.',
113
+ '',
114
+ `config BOARD_${kconfigFragment(name)}`,
115
+ `\tselect SOC_${kconfigFragment(soc)}`,
116
+ '',
117
+ ].join('\n'),
118
+ ) || changed;
119
+
120
+ // ── <name>.dts — includes, chosen, console, clock plan ───────────────────
121
+ const lines: string[] = [
122
+ '// Auto-generated by @typecad/framework-zephyr from the MCU package',
123
+ '// silicon definition. Regenerated on every compile — edit the MCU',
124
+ '// package (or add a board package) instead of this file.',
125
+ '/dts-v1/;',
126
+ ...cb.dtsIncludes.map((inc) => `#include <${inc}>`),
127
+ '',
128
+ '/ {',
129
+ ` model = "Cuttlefish custom board (${chip.soc})";`,
130
+ ` compatible = "${CUSTOM_BOARD_VENDOR},${name.replace(/_/g, '-')}";`,
131
+ '',
132
+ ' chosen {',
133
+ ` zephyr,console = &${cb.console.nodeLabel};`,
134
+ ' zephyr,sram = &sram0;',
135
+ ' zephyr,flash = &flash0;',
136
+ ' };',
137
+ '};',
138
+ '',
139
+ ];
140
+
141
+ // The chip descriptor's DT-aliased GPIOs (sw0/led0 from the reference
142
+ // board data): the generated firmware addresses them via DT_ALIAS, so the
143
+ // custom board must define the nodes. Pins map through gpioControllers
144
+ // (port-block numbering: pin = minPin + port bit).
145
+ const controllerFor = (pin: number): { label: string; bit: number } | undefined => {
146
+ const c = chip.gpioControllers?.find((c) => pin >= c.minPin && pin <= c.maxPin);
147
+ if (c) return { label: c.nodelabel, bit: pin - c.minPin };
148
+ return undefined;
149
+ };
150
+ const keys = chip.gpio.dtSpecs.filter((s) => s.dtSpec.startsWith('sw') || s.dtSpec.startsWith('button'));
151
+ const leds = chip.gpio.dtSpecs.filter((s) => s.dtSpec.startsWith('led'));
152
+ if (keys.length > 0 || leds.length > 0) {
153
+ lines.push('/ {');
154
+ if (leds.length > 0) {
155
+ lines.push(' leds {', ' compatible = "gpio-leds";');
156
+ for (const l of leds) {
157
+ const c = controllerFor(l.pin);
158
+ if (!c) continue;
159
+ lines.push(
160
+ ` ${l.dtSpec}_node: ${l.dtSpec.replace(/_/g, '-')} {`,
161
+ ` gpios = <&${c.label} ${c.bit} GPIO_ACTIVE_LOW>;`,
162
+ ' };',
163
+ );
164
+ }
165
+ lines.push(' };');
166
+ }
167
+ if (keys.length > 0) {
168
+ lines.push(' gpio_keys {', ' compatible = "gpio-keys";');
169
+ for (const k of keys) {
170
+ const c = controllerFor(k.pin);
171
+ if (!c) continue;
172
+ lines.push(
173
+ ` ${k.dtSpec}_node: ${k.dtSpec.replace(/_/g, '-')} {`,
174
+ ` gpios = <&${c.label} ${c.bit} (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>;`,
175
+ ' };',
176
+ );
177
+ }
178
+ lines.push(' };');
179
+ lines.push(' aliases {');
180
+ for (const k of keys) lines.push(` ${k.dtSpec} = &${k.dtSpec}_node;`);
181
+ for (const l of leds) lines.push(` ${l.dtSpec} = &${l.dtSpec}_node;`);
182
+ lines.push(' };');
183
+ }
184
+ lines.push('};', '');
185
+ }
186
+
187
+ lines.push(
188
+ // Console UART — the one controller the board enables unconditionally;
189
+ // every other bus is enabled by the usage-driven overlay.
190
+ `&${cb.console.nodeLabel} {`,
191
+ ` pinctrl-0 = <&${cb.console.tx} &${cb.console.rx}>;`,
192
+ ' pinctrl-names = "default";',
193
+ ' status = "okay";',
194
+ ` current-speed = <${cb.console.speed}>;`,
195
+ '};',
196
+ '',
197
+ );
198
+
199
+ // USB: alias the silicon node under the Zephyr convention the descriptor's
200
+ // usb.controller names (e.g. zephyr_udc0: &usbotg_fs), pre-enabled with its
201
+ // pinctrl — the st,stm32-otgfs binding requires pinctrl-0 on an enabled
202
+ // node, and the overlay's CDC composition only flips status/enables the
203
+ // stack (Kconfig-gated), never pins. Mirrors the blackpill board shape.
204
+ if (cb.usbNode && chip.usb) {
205
+ lines.push(
206
+ `${chip.usb.controller}: &${cb.usbNode} {`,
207
+ ...(cb.usbPinctrl && cb.usbPinctrl.length > 0
208
+ ? [
209
+ ` pinctrl-0 = <${cb.usbPinctrl.map((p) => `&${p}`).join(' ')}>;`,
210
+ ' pinctrl-names = "default";',
211
+ ]
212
+ : []),
213
+ ' status = "okay";',
214
+ '};',
215
+ '',
216
+ );
217
+ }
218
+
219
+ // PWM: the overlay enables `&pwm<N>` and synthesizes pwm-leds consumers
220
+ // against it — but the pwm<N> LABEL only exists when a board DTS declares
221
+ // it (the SoC dtsi ships the timers' pwm child unlabeled), and the
222
+ // st,stm32-pwm binding requires pinctrl-0 on an enabled node. Emit the
223
+ // blackpill-shape block per controller whose specs all carry pinctrl
224
+ // tokens; controllers without full token coverage stay to board packages.
225
+ if (chip.pwm) {
226
+ const byController = new Map<string, { n: string; tokens: string[]; complete: boolean }>();
227
+ for (const s of chip.pwm.specs) {
228
+ if (!s.controller) continue;
229
+ const timersMatch = s.controller.match(/^pwm(\d+)$/);
230
+ if (!timersMatch) continue;
231
+ const entry = byController.get(s.controller) ?? { n: timersMatch[1], tokens: [], complete: true };
232
+ if (s.pinctrl) {
233
+ entry.tokens.push(s.pinctrl);
234
+ } else {
235
+ entry.complete = false;
236
+ }
237
+ byController.set(s.controller, entry);
238
+ }
239
+ for (const [controller, entry] of byController) {
240
+ if (!entry.complete || entry.tokens.length === 0) continue;
241
+ lines.push(
242
+ `&timers${entry.n} {`,
243
+ ' status = "okay";',
244
+ '',
245
+ ` ${controller}: pwm {`,
246
+ ` pinctrl-0 = <${entry.tokens.map((t) => `&${t}`).join(' ')}>;`,
247
+ ' pinctrl-names = "default";',
248
+ ' status = "okay";',
249
+ ' };',
250
+ '};',
251
+ '',
252
+ );
253
+ }
254
+ }
255
+
256
+ // ADC: some SoC drivers require board-DTS properties on an enabled adc node
257
+ // (STM32 F4: st,adc-clock-source + st,adc-prescaler, or the binding rejects
258
+ // the node when the usage-driven overlay enables it). Pre-enable with the
259
+ // silicon-required props + a baseline pinctrl; the overlay rewrites
260
+ // pinctrl-0 to the channels the program actually reads.
261
+ if (cb.adcNode) {
262
+ const a = cb.adcNode;
263
+ lines.push(
264
+ `&${a.nodeLabel} {`,
265
+ ` pinctrl-0 = <&${a.pinctrl}>;`,
266
+ ' pinctrl-names = "default";',
267
+ ` st,adc-clock-source = "${a.clockSource}";`,
268
+ ` st,adc-prescaler = <${a.prescaler}>;`,
269
+ ' status = "okay";',
270
+ '};',
271
+ '',
272
+ );
273
+ }
274
+
275
+ // Clock plan — STM32 F4 shape today (the only family carrying a clocks
276
+ // block so far): HSE crystal, PLL, RCC prescalers. SoCs whose dtsi clocks
277
+ // work out of the box ship no clocks block and emit nothing here.
278
+ const clk = cb.clocks;
279
+ lines.push(
280
+ `&clk_hse {`,
281
+ ` clock-frequency = <DT_FREQ_M(${clk.hseMHz})>;`,
282
+ ' status = "okay";',
283
+ '};',
284
+ '',
285
+ '&pll {',
286
+ ` div-m = <${clk.pll.divM}>;`,
287
+ ` mul-n = <${clk.pll.mulN}>;`,
288
+ ` div-p = <${clk.pll.divP}>;`,
289
+ ` div-q = <${clk.pll.divQ}>;`,
290
+ ' clocks = <&clk_hse>;',
291
+ ' status = "okay";',
292
+ '};',
293
+ '',
294
+ '&rcc {',
295
+ ' clocks = <&pll>;',
296
+ ` clock-frequency = <DT_FREQ_M(${clk.sysMHz})>;`,
297
+ ` ahb-prescaler = <${clk.ahbPrescaler}>;`,
298
+ ` apb1-prescaler = <${clk.apb1Prescaler}>;`,
299
+ ` apb2-prescaler = <${clk.apb2Prescaler}>;`,
300
+ '};',
301
+ '',
302
+ );
303
+
304
+ changed = writeIfChanged(join(dir, `${name}.dts`), lines.join('\n')) || changed;
305
+
306
+ // ── <name>_defconfig — the baseline every in-tree board carries ──────────
307
+ // Load-bearing: without CONFIG_GPIO the STM32 pinctrl driver's gpio_ports
308
+ // table references devices that are never built (undefined __device_dts_ord
309
+ // at link). Console/serial match what the DTS enables.
310
+ changed =
311
+ writeIfChanged(
312
+ join(dir, `${name}_defconfig`),
313
+ [
314
+ '# Auto-generated by @typecad/framework-zephyr. Do not edit.',
315
+ '',
316
+ 'CONFIG_GPIO=y',
317
+ 'CONFIG_SERIAL=y',
318
+ 'CONFIG_CONSOLE=y',
319
+ 'CONFIG_UART_CONSOLE=y',
320
+ '',
321
+ ].join('\n'),
322
+ ) || changed;
323
+
324
+ return { dir, name, changed };
325
+ }
@@ -1,3 +1,33 @@
1
+ import { SENSOR_PART_INFO } from '@typecad/hal';
2
+
3
+ /** A sensor part's catalog facts, as the exceptions helper consumes them. */
4
+ interface SensorKconfigSource {
5
+ kconfig: readonly string[];
6
+ }
7
+
8
+ /**
9
+ * Apply the per-part Kconfig exceptions the generated catalog records, for
10
+ * exactly the parts the program constructs. Lines are CONFIG_<SYM>=<value>
11
+ * strings parsed into the map; a symbol the user set explicitly in
12
+ * zephyr.kconfig is left alone (scaffold.ts already skips user overrides for
13
+ * auto symbols, and Map.set idempotence covers the rest). The lookup is a
14
+ * parameter so tests can drive it with a synthetic catalog.
15
+ */
16
+ export function applySensorKconfigExceptions(
17
+ m: Map<string, string>,
18
+ parts: readonly { part: string }[] | undefined,
19
+ lookup: Readonly<Record<string, SensorKconfigSource>> = SENSOR_PART_INFO,
20
+ ): void {
21
+ if (!parts) return;
22
+ for (const sp of parts) {
23
+ for (const line of lookup[sp.part]?.kconfig ?? []) {
24
+ const eq = line.indexOf('=');
25
+ if (eq <= 0) continue;
26
+ m.set(line.slice(0, eq), line.slice(eq + 1));
27
+ }
28
+ }
29
+ }
30
+
1
31
  // ---------------------------------------------------------------------------
2
32
  // Kconfig fragment resolver — extracts the prj.conf symbol logic
3
33
  //
@@ -17,21 +47,47 @@ export interface KconfigUsage {
17
47
  usesI2c?: boolean;
18
48
  usesSpi?: boolean;
19
49
  usesUart?: boolean;
50
+ /** USB CDC-ACM serial used (usb.* ops). Selects the "next" USB device
51
+ * stack + CDC class; the class instances themselves are composed in the
52
+ * DT overlay and auto-default on once the node exists (assigning the
53
+ * class symbol keeps prj.conf explicit and survives DT-only probes). */
54
+ usesUsb?: boolean;
20
55
  usesWdt?: boolean;
21
56
  usesBle?: boolean;
22
57
  usesDisplay?: boolean;
23
- usesPower?: boolean;
24
58
  usesWifi?: boolean;
25
59
  usesHttp?: boolean;
26
60
  usesMqtt?: boolean;
27
61
  usesPreferences?: boolean;
28
62
  usesRandom?: boolean;
63
+ /** A printf-family format specifier with a float conversion (%f, %.2f, %e,
64
+ * …) appears in the emitted source — Zephyr's cbprintf only links float
65
+ * conversions with FP_SUPPORT (which itself needs the COMPLETE impl). */
66
+ usesFloatFormat?: boolean;
67
+ /** DT-bound sensor parts used (sensor.* ops — the generic catalog). The
68
+ * umbrella under which every driver sensor Kconfig lives (`if SENSOR`);
69
+ * the per-driver symbols default on from their DT node presence. */
70
+ usesSensor?: boolean;
71
+ /** Distinct constructed sensors — only the overlay generator consumes this
72
+ * (one DT child node per entry, on the given I2C controller index); prj.conf
73
+ * ignores it. Same adcReadPins/pwmUsedPins pattern. */
74
+ sensorParts?: readonly { part: string; busIndex: number; port: number; busKind: 'i2c' | 'spi'; spiHz?: number; spiMode?: number; alertPin?: number }[];
75
+ /** Distinct thin SPI targets (hal/spi-target.ts) — one DT child node per
76
+ * entry (no compatible — a raw spi_dt_spec peer), appended after sensor
77
+ * CS entries in the controller's merged cs-gpios. */
78
+ spiTargets?: readonly { busIndex: number; cs: number; hz?: number; mode?: number }[];
29
79
  /** Touch controller referenced (UI touch adapter emits DT_NODELABEL(ft6336u)
30
80
  * or DT_NODELABEL(xpt2046)). Selects the bus driver the node needs. */
31
81
  usesTouch?: boolean;
32
82
  /** Which touch controller the program uses — FT6336U rides I2C, XPT2046
33
83
  * rides the display's SPI bus. Only meaningful with usesTouch. */
34
84
  touchController?: 'ft6336u' | 'xpt2046';
85
+ /** The emitted shim carries the STM32F4 DBGMCU keep-SWD-alive init
86
+ * (__tc_stm32_dbgmcu token). Selects Zephyr's own "debugger attach in
87
+ * stop/sleep" init (sets DBG_STOP via the LL headers); the shim's raw
88
+ * register poke additionally covers DBG_SLEEP, which the Zephyr F4 path
89
+ * does not set. */
90
+ usesStm32DebugSleep?: boolean;
35
91
  /** PSRAM type ('opi' | 'quad') when the target board has PSRAM. Emits the
36
92
  * CONFIG_SPIRAM symbols so the ESP heap serves PSRAM for canvas allocations. */
37
93
  psram?: 'opi' | 'quad';
@@ -40,12 +96,28 @@ export interface KconfigUsage {
40
96
  * consumes this (to rewrite the ADC node's pinctrl-0 to the used channels
41
97
  * on SoCs that need pad muxing, e.g. STM32); prj.conf ignores it. */
42
98
  adcReadPins?: readonly number[];
99
+ /** HAL pin numbers the program drives with dac.* — scanned from the
100
+ * emitted lazy-setup guards (__tc_dact<pin>_done) at compile time. Only
101
+ * the overlay generator consumes this (the DAC node's pinctrl-0 lists
102
+ * the used channels); prj.conf ignores it. */
103
+ dacWritePins?: readonly number[];
43
104
  /** HAL pin numbers the program drives with pwm.* — scanned from the
44
105
  * emitted `__tc_pwm_*` spec references at compile time. Only the overlay
45
106
  * generator consumes this (synthesized pwm-leds consumers + aliases are
46
107
  * emitted per used pin, so the DT carries no dead channels); prj.conf
47
108
  * ignores it. */
48
109
  pwmUsedPins?: readonly number[];
110
+ /** Controller indexes per bus the program actually drives — scanned from
111
+ * the emitted `__tc_<bus><N>_dev` state blocks at compile time. The
112
+ * overlay enables only those controllers (an enabled-but-unused
113
+ * controller claims its default pins — e.g. i2c0's GP4/GP5 on the Pico —
114
+ * which a program using the OTHER controller may want as GPIO). Absent
115
+ * (prepare-time overlays, driver-API-only users like the display
116
+ * adapter) → every declared controller is enabled, preserving the old
117
+ * behavior. prj.conf ignores these. */
118
+ i2cUsedInstances?: readonly number[];
119
+ spiUsedInstances?: readonly number[];
120
+ uartUsedInstances?: readonly number[];
49
121
  }
50
122
 
51
123
  /**
@@ -66,11 +138,54 @@ export function resolveKconfigFragments(
66
138
  m.set('CONFIG_CONSOLE', 'y');
67
139
 
68
140
  if (usage.usesAdc) m.set('CONFIG_ADC', 'y');
141
+ // Sensors: only the umbrella — each in-tree driver is `default y` on its
142
+ // DT_HAS_<COMPAT>_ENABLED, so the overlay's child node enables the driver.
143
+ if (usage.usesSensor) m.set('CONFIG_SENSOR', 'y');
144
+ // The rare driver that is NOT DT-default-on: the catalog records its
145
+ // Kconfig lines (from the driver's own Kconfig) and they are applied for
146
+ // exactly the parts the program constructs. Empty for every in-tree part
147
+ // today — this path is insurance for the next exception.
148
+ applySensorKconfigExceptions(m, usage.sensorParts);
149
+ // Float formatting: cbprintf builds float conversions only under
150
+ // FP_SUPPORT, which depends on the COMPLETE implementation — without these,
151
+ // %f silently prints garbage instead of the value.
152
+ if (usage.usesFloatFormat) {
153
+ m.set('CONFIG_CBPRINTF_COMPLETE', 'y');
154
+ m.set('CONFIG_CBPRINTF_FP_SUPPORT', 'y');
155
+ }
69
156
  if (usage.usesPwm) m.set('CONFIG_PWM', 'y');
70
157
  if (usage.usesDac) m.set('CONFIG_DAC', 'y');
71
158
  if (usage.usesI2c) m.set('CONFIG_I2C', 'y');
72
159
  if (usage.usesSpi) m.set('CONFIG_SPI', 'y');
160
+ // USB CDC-ACM serial: the "next" USB device stack + the CDC-ACM class.
161
+ // Symbol names verified against Zephyr 4.3 (subsys/usb/device_next/Kconfig):
162
+ // - USB_DEVICE_STACK_NEXT is the new stack (selects UDC_DRIVER);
163
+ // USB_DEVICE_STACK is the LEGACY stack — deprecated in 4.3 (selects
164
+ // DEPRECATED) and its assignment is what trips the build.
165
+ // - USBD_CDC_ACM_CLASS is the class (note the USBD_ prefix — a bare
166
+ // CDC_ACM_CLASS is an undefined symbol). It depends on SERIAL +
167
+ // DT_HAS_ZEPHYR_CDC_ACM_UART_ENABLED (the overlay's cdc-acm-uart node)
168
+ // and selects UART_INTERRUPT_DRIVEN/RING_BUFFER itself; assigning it
169
+ // keeps prj.conf explicit.
170
+ // - UART_LINE_CTRL gates the driver's line_ctrl_get — usb.connected()
171
+ // polls DTR through it.
172
+ if (usage.usesUsb) {
173
+ m.set('CONFIG_USB_DEVICE_STACK_NEXT', 'y');
174
+ m.set('CONFIG_USBD_CDC_ACM_CLASS', 'y');
175
+ m.set('CONFIG_UART_LINE_CTRL', 'y');
176
+ m.set('CONFIG_SERIAL', 'y');
177
+ // The device presents a serial-number string descriptor sourced from
178
+ // hwinfo (the SoC's unique ID). Without it Windows keys the CDC devnode
179
+ // on the physical USB port: replugs reuse stale nodes and repeated flash
180
+ // cycles wedge them into permanent "access denied" opens. A serial makes
181
+ // the instance path identity-based — stable across ports, immune to the
182
+ // port-keyed ghost pool.
183
+ m.set('CONFIG_HWINFO', 'y');
184
+ }
73
185
  if (usage.usesWdt) m.set('CONFIG_WATCHDOG', 'y');
186
+ // STM32: keep the debugger attachable in sleep/stop (see the shim's
187
+ // DBGMCU init — this covers the Zephyr-side DBG_STOP bit via LL headers).
188
+ if (usage.usesStm32DebugSleep) m.set('CONFIG_STM32_ENABLE_DEBUG_SLEEP_STOP', 'y');
74
189
  // Hardware timers via the counter driver.
75
190
  if (usage.usesHwtimer) m.set('CONFIG_COUNTER', 'y');
76
191
  if (usage.usesDisplay) {
@@ -124,11 +239,6 @@ export function resolveKconfigFragments(
124
239
  m.set('CONFIG_SPIRAM_MODE_QUAD', 'y');
125
240
  }
126
241
  }
127
- // deep_sleep_pin wake needs PM + PM_DEVICE.
128
- if (usage.usesPower) {
129
- m.set('CONFIG_PM', 'y');
130
- m.set('CONFIG_PM_DEVICE', 'y');
131
- }
132
242
  if (usage.usesWifi) {
133
243
  // Master networking switch — every CONFIG_NET_* symbol depends on NETWORKING
134
244
  // (without it, Kconfig silently forces them all to n).
@@ -141,7 +251,7 @@ export function resolveKconfigFragments(
141
251
  m.set('CONFIG_NET_DHCPV4', 'y');
142
252
  // NOT CONFIG_NET_CONFIG_SETTINGS: that runs net_config_init() at boot which
143
253
  // BLOCKS up to NET_CONFIG_INIT_TIMEOUT (default 30s) waiting for the iface
144
- // to come up — but our shim brings the iface up itself in setup() (connect),
254
+ // to come up — but our shim brings the iface up itself in main() (connect),
145
255
  // so net_config waits the full 30s, then the dual management of the same
146
256
  // iface crashes the driver. Our shim owns connectivity (net_mgmt connect/
147
257
  // disconnect + conn_mgr monitor for L4), exactly like the standalone Zephyr
@@ -226,13 +336,26 @@ export function resolveKconfigFragments(
226
336
  // server's RSA cert (rsa:2048) and is widely offered; add more ciphersuites
227
337
  // here to broaden server compatibility.
228
338
  m.set('CONFIG_MBEDTLS_CIPHERSUITE_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256', 'y');
339
+ // Ciphersuites only *depend on* X509_CRT_PARSE_C (they don't select it) —
340
+ // without it sockets_tls.c compiles out mbedtls_x509_crt_parse and every
341
+ // pinned-CA handshake fails with EPERM at connect (the insecure path
342
+ // skips verification, so it works either way).
343
+ m.set('CONFIG_MBEDTLS_X509_CRT_PARSE_C', 'y');
344
+ // KNOWN LIMITATION on this Zephyr tree: pinned-CA (verified TLS) fails at
345
+ // connect — the tf-psa-crypto mbedTLS needs a wider symbol matrix
346
+ // (RSA public-key parse + PEM/DER glue) than the single-ciphersuite
347
+ // select pulls in, and forcing the extra symbols regresses the insecure
348
+ // path. insecure() HTTPS is fully verified; caCert() chain verification
349
+ // stays open until the upstream matrix is mapped.
229
350
  // Handshake/protocol buffers allocate from the mbedTLS heap; MBEDTLS_HEAP_SIZE
230
351
  // must hold ~2x MBEDTLS_SSL_MAX_CONTENT_LEN plus working state. 65000 fits on
231
352
  // the ESP32; mbedTLS requires the full libc and PEM (not DER) cert format.
232
353
  m.set('CONFIG_MBEDTLS_ENABLE_HEAP', 'y');
233
- m.set('CONFIG_MBEDTLS_HEAP_SIZE', '65000');
354
+ // 2x SSL_MAX_CONTENT_LEN record buffers + CA-chain parse state +
355
+ // handshake working memory. 65000 fit insecure-mode handshakes but the
356
+ // pinned-CA path (verification state) overflowed → EPERM at connect.
357
+ m.set('CONFIG_MBEDTLS_HEAP_SIZE', '100000');
234
358
  m.set('CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN', '16384');
235
- m.set('CONFIG_MBEDTLS_PEM_CERTIFICATE_FORMAT', 'y');
236
359
  m.set('CONFIG_PSA_CRYPTO', 'y');
237
360
  m.set('CONFIG_REQUIRES_FULL_LIBC', 'y');
238
361
  // The http client + TLS handshake are stack-hungry; mirror the wifi bumps
@@ -255,6 +378,12 @@ export function resolveKconfigFragments(
255
378
  m.set('CONFIG_NET_SOCKETS', 'y');
256
379
  m.set('CONFIG_MQTT_LIB', 'y');
257
380
  m.set('CONFIG_MQTT_LIB_TLS', 'y');
381
+ // The shim getaddrinfo-resolves the broker host — without the DNS
382
+ // resolver linked, getaddrinfo fails numeric AND hostname lookups with
383
+ // EAI_FAIL even while plain HTTP (which selects DNS via its own block)
384
+ // works.
385
+ m.set('CONFIG_DNS_RESOLVER', 'y');
386
+ m.set('CONFIG_DNS_SERVER_IP_ADDRESSES', 'y');
258
387
  // NET_MAX_CONTEXTS / NET_MAX_CONN: same exhaustion risk as HTTP — sequential
259
388
  // connections linger after close. Give the broker session + headroom.
260
389
  m.set('CONFIG_NET_MAX_CONTEXTS', '16');
@@ -266,10 +395,23 @@ export function resolveKconfigFragments(
266
395
  m.set('CONFIG_MBEDTLS', 'y');
267
396
  m.set('CONFIG_MBEDTLS_BUILTIN', 'y');
268
397
  m.set('CONFIG_MBEDTLS_CIPHERSUITE_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256', 'y');
398
+ // Ciphersuites only *depend on* X509_CRT_PARSE_C (they don't select it) —
399
+ // without it sockets_tls.c compiles out mbedtls_x509_crt_parse and every
400
+ // pinned-CA handshake fails with EPERM at connect (the insecure path
401
+ // skips verification, so it works either way).
402
+ m.set('CONFIG_MBEDTLS_X509_CRT_PARSE_C', 'y');
403
+ // KNOWN LIMITATION on this Zephyr tree: pinned-CA (verified TLS) fails at
404
+ // connect — the tf-psa-crypto mbedTLS needs a wider symbol matrix
405
+ // (RSA public-key parse + PEM/DER glue) than the single-ciphersuite
406
+ // select pulls in, and forcing the extra symbols regresses the insecure
407
+ // path. insecure() HTTPS is fully verified; caCert() chain verification
408
+ // stays open until the upstream matrix is mapped.
269
409
  m.set('CONFIG_MBEDTLS_ENABLE_HEAP', 'y');
270
- m.set('CONFIG_MBEDTLS_HEAP_SIZE', '65000');
410
+ // 2x SSL_MAX_CONTENT_LEN record buffers + CA-chain parse state +
411
+ // handshake working memory. 65000 fit insecure-mode handshakes but the
412
+ // pinned-CA path (verification state) overflowed → EPERM at connect.
413
+ m.set('CONFIG_MBEDTLS_HEAP_SIZE', '100000');
271
414
  m.set('CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN', '16384');
272
- m.set('CONFIG_MBEDTLS_PEM_CERTIFICATE_FORMAT', 'y');
273
415
  m.set('CONFIG_PSA_CRYPTO', 'y');
274
416
  m.set('CONFIG_REQUIRES_FULL_LIBC', 'y');
275
417
  m.set('CONFIG_NET_TX_STACK_SIZE', '2048');
@@ -306,19 +448,24 @@ export function resolveKconfigFragments(
306
448
  m.set('CONFIG_FLASH_MAP', 'y');
307
449
  m.set('CONFIG_FILE_SYSTEM', 'y');
308
450
  m.set('CONFIG_FILE_SYSTEM_LITTLEFS', 'y');
451
+ // fs_mkfs (the lazy first-use format in the shim) is gated behind this —
452
+ // without it the mount path links fine but the format call is undefined.
453
+ m.set('CONFIG_FILE_SYSTEM_MKFS', 'y');
309
454
  }
310
455
  // usesUart: the board enables the console UART by default; the overlay (not
311
456
  // Kconfig) is where a UART node would be enabled, so no symbol here.
312
457
  // Random: <zephyr/random/random.h> sys_rand_get is backed by the random
313
- // generator subsystem. CONFIG_RANDOM_GENERATOR is the umbrella that selects a
314
- // working backend for the board (nRF52840 hardware RNG via the entropy
315
- // driver; QEMU/host → the test generator). CONFIG_ENTROPY_GENERATOR is its
316
- // hard dependency on hardware targets. Both default on for most boards, but
317
- // setting them explicitly keeps the symbol set honest and survives a board
318
- // whose defconfig leaves them off.
458
+ // generator subsystem's RNG_GENERATOR_CHOICE. There is no umbrella symbol
459
+ // CONFIG_RANDOM_GENERATOR is a phantom in 4.x (assigning an undefined symbol
460
+ // aborts the build). The choice defaults to the entropy-device generator
461
+ // when the board has a driver (ENTROPY_HAS_DRIVER: nRF52840, ESP32, …);
462
+ // RNG-less SoCs (STM32F411 has no hardware RNG) need
463
+ // CONFIG_TEST_RANDOM_GENERATOR to unlock the timer-clock fallback, which
464
+ // the choice then picks by default. Setting both keys gets the best
465
+ // available source per board.
319
466
  if (usage.usesRandom) {
320
467
  m.set('CONFIG_ENTROPY_GENERATOR', 'y');
321
- m.set('CONFIG_RANDOM_GENERATOR', 'y');
468
+ m.set('CONFIG_TEST_RANDOM_GENERATOR', 'y');
322
469
  }
323
470
 
324
471
  // System workqueue — bumped for worker-offload AND timer callbacks. The