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

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 (191) hide show
  1. package/README.md +22 -35
  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/controllers.d.ts +28 -8
  10. package/dist/chips/controllers.js +49 -12
  11. package/dist/chips/esp32s3.js +49 -0
  12. package/dist/chips/index.d.ts +6 -12
  13. package/dist/chips/index.js +18 -34
  14. package/dist/chips/resolve.d.ts +16 -2
  15. package/dist/chips/resolve.js +298 -15
  16. package/dist/chips/soc/.d.ts +2 -0
  17. package/dist/chips/soc/.js +129 -0
  18. package/dist/chips/soc/esp32.d.ts +2 -0
  19. package/dist/chips/soc/esp32.js +120 -0
  20. package/dist/chips/soc/esp32c3.d.ts +2 -0
  21. package/dist/chips/soc/esp32c3.js +90 -0
  22. package/dist/chips/soc/esp32c6.d.ts +2 -0
  23. package/dist/chips/soc/esp32c6.js +109 -0
  24. package/dist/chips/soc/esp32s3.d.ts +2 -0
  25. package/dist/chips/soc/esp32s3.js +189 -0
  26. package/dist/chips/soc/index.d.ts +2 -0
  27. package/dist/chips/soc/index.js +23 -0
  28. package/dist/chips/soc/nrf52840.d.ts +2 -0
  29. package/dist/chips/soc/nrf52840.js +130 -0
  30. package/dist/chips/soc/rp2040.d.ts +2 -0
  31. package/dist/chips/soc/rp2040.js +141 -0
  32. package/dist/chips/soc/rp2350a.d.ts +2 -0
  33. package/dist/chips/soc/rp2350a.js +145 -0
  34. package/dist/chips/soc/samd21g18a.d.ts +2 -0
  35. package/dist/chips/soc/samd21g18a.js +143 -0
  36. package/dist/chips/soc/stm32f411xe.d.ts +2 -0
  37. package/dist/chips/soc/stm32f411xe.js +251 -0
  38. package/dist/chips/types.d.ts +382 -12
  39. package/dist/chips/xiao-ble.js +33 -0
  40. package/dist/display/profiles.js +1 -1
  41. package/dist/doctor.js +38 -4
  42. package/dist/dt-config/custom-board.d.ts +23 -0
  43. package/dist/dt-config/custom-board.js +227 -0
  44. package/dist/dt-config/kconfig.d.ts +83 -1
  45. package/dist/dt-config/kconfig.js +116 -27
  46. package/dist/dt-config/overlay.js +623 -18
  47. package/dist/framework.manifest.d.ts +20 -30
  48. package/dist/framework.manifest.js +124 -178
  49. package/dist/index.d.ts +4 -1
  50. package/dist/index.js +8 -2
  51. package/dist/lowering/adc.d.ts +26 -5
  52. package/dist/lowering/adc.js +137 -31
  53. package/dist/lowering/ble.js +31 -28
  54. package/dist/lowering/dac.js +9 -9
  55. package/dist/lowering/fs.js +18 -10
  56. package/dist/lowering/gpio.d.ts +2 -0
  57. package/dist/lowering/gpio.js +90 -10
  58. package/dist/lowering/http.js +39 -14
  59. package/dist/lowering/hwtimer.d.ts +4 -0
  60. package/dist/lowering/hwtimer.js +35 -10
  61. package/dist/lowering/i2c.js +46 -54
  62. package/dist/lowering/index.d.ts +5 -5
  63. package/dist/lowering/index.js +15 -16
  64. package/dist/lowering/interrupts.d.ts +22 -5
  65. package/dist/lowering/interrupts.js +104 -22
  66. package/dist/lowering/mqtt.js +12 -6
  67. package/dist/lowering/power.js +0 -4
  68. package/dist/lowering/preferences.js +49 -77
  69. package/dist/lowering/pulse.js +5 -36
  70. package/dist/lowering/pwm.d.ts +32 -3
  71. package/dist/lowering/pwm.js +105 -17
  72. package/dist/lowering/random.js +3 -3
  73. package/dist/lowering/sensor.d.ts +37 -0
  74. package/dist/lowering/sensor.js +119 -0
  75. package/dist/lowering/spi.d.ts +12 -0
  76. package/dist/lowering/spi.js +65 -40
  77. package/dist/lowering/thread.d.ts +14 -0
  78. package/dist/lowering/thread.js +55 -0
  79. package/dist/lowering/timing.js +20 -46
  80. package/dist/lowering/tone.js +18 -5
  81. package/dist/lowering/uart.d.ts +13 -0
  82. package/dist/lowering/uart.js +72 -51
  83. package/dist/lowering/usb.d.ts +34 -0
  84. package/dist/lowering/usb.js +206 -0
  85. package/dist/lowering/wdt.d.ts +1 -1
  86. package/dist/lowering/wdt.js +17 -7
  87. package/dist/lowering/wifi.d.ts +3 -2
  88. package/dist/lowering/wifi.js +120 -111
  89. package/dist/sdk/board-catalog-sync.d.ts +16 -0
  90. package/dist/sdk/board-catalog-sync.js +41 -0
  91. package/dist/sdk/board-data.generated.d.ts +2 -0
  92. package/dist/sdk/board-data.generated.js +4 -0
  93. package/dist/sdk/catalog-walker.d.ts +90 -0
  94. package/dist/sdk/catalog-walker.js +682 -0
  95. package/dist/sdk/dts-reader.d.ts +83 -0
  96. package/dist/sdk/dts-reader.js +596 -0
  97. package/dist/strategy.d.ts +136 -17
  98. package/dist/strategy.js +881 -212
  99. package/dist/toolchain/bossac-touch.d.ts +18 -0
  100. package/dist/toolchain/bossac-touch.js +88 -0
  101. package/dist/toolchain/compat.d.ts +2 -2
  102. package/dist/toolchain/compat.js +8 -3
  103. package/dist/toolchain/debug-config.d.ts +21 -26
  104. package/dist/toolchain/debug-config.js +212 -72
  105. package/dist/toolchain/env-check.d.ts +4 -4
  106. package/dist/toolchain/env-check.js +5 -5
  107. package/dist/toolchain/index.d.ts +66 -1
  108. package/dist/toolchain/index.js +713 -58
  109. package/dist/toolchain/scaffold.d.ts +9 -0
  110. package/dist/toolchain/scaffold.js +84 -7
  111. package/dist/toolchain/west-discover.d.ts +8 -1
  112. package/dist/toolchain/west-discover.js +19 -6
  113. package/dist/toolchain/west-spawn.js +17 -5
  114. package/installer/CHANGELOG.md +473 -0
  115. package/installer/README.md +328 -0
  116. package/installer/environment.yml +46 -0
  117. package/installer/etc/conda/activate.d/zephyr.bat +7 -0
  118. package/installer/etc/conda/activate.d/zephyr.ps1 +12 -0
  119. package/installer/etc/conda/activate.d/zephyr.sh +20 -0
  120. package/installer/etc/conda/deactivate.d/zephyr.bat +6 -0
  121. package/installer/etc/conda/deactivate.d/zephyr.ps1 +6 -0
  122. package/installer/etc/conda/deactivate.d/zephyr.sh +4 -0
  123. package/installer/install.mjs +580 -0
  124. package/installer/install.ps1 +619 -0
  125. package/installer/install.sh +310 -0
  126. package/installer/lib/detect-platform.sh +62 -0
  127. package/installer/lib/fetch-sdk.sh +304 -0
  128. package/installer/lib/init-workspace.sh +153 -0
  129. package/installer/lib/write-activation.sh +76 -0
  130. package/installer/patches/tfm-c-include-separators.patch +19 -0
  131. package/installer/patches/zephyr-tfm-nordic-zephyr-include.patch +24 -0
  132. package/installer/templates/project/.typecad/activate-zephyr.ps1 +31 -0
  133. package/installer/templates/project/.typecad/activate-zephyr.sh +31 -0
  134. package/installer/templates/project/.vscode/settings.json +30 -0
  135. package/installer/templates/project/README.md +58 -0
  136. package/installer/versions.env +110 -0
  137. package/package.json +16 -16
  138. package/src/as-built.ts +206 -0
  139. package/src/boardgen.ts +1428 -0
  140. package/src/chips/controllers.ts +61 -12
  141. package/src/chips/index.ts +35 -54
  142. package/src/chips/resolve.ts +316 -14
  143. package/src/chips/types.ts +388 -13
  144. package/src/display/profiles.ts +1 -1
  145. package/src/doctor.ts +110 -77
  146. package/src/dt-config/custom-board.ts +325 -0
  147. package/src/dt-config/kconfig.ts +177 -19
  148. package/src/dt-config/overlay.ts +1058 -450
  149. package/src/framework.manifest.ts +125 -178
  150. package/src/index.ts +57 -41
  151. package/src/lowering/adc.ts +222 -102
  152. package/src/lowering/ble.ts +32 -28
  153. package/src/lowering/dac.ts +82 -82
  154. package/src/lowering/fs.ts +18 -10
  155. package/src/lowering/gpio.ts +242 -152
  156. package/src/lowering/http.ts +512 -488
  157. package/src/lowering/hwtimer.ts +139 -101
  158. package/src/lowering/i2c.ts +116 -126
  159. package/src/lowering/index.ts +91 -93
  160. package/src/lowering/interrupts.ts +113 -21
  161. package/src/lowering/mqtt.ts +12 -6
  162. package/src/lowering/preferences.ts +327 -354
  163. package/src/lowering/pwm.ts +167 -74
  164. package/src/lowering/random.ts +3 -3
  165. package/src/lowering/sensor.ts +155 -0
  166. package/src/lowering/spi.ts +164 -124
  167. package/src/lowering/thread.ts +63 -0
  168. package/src/lowering/timing.ts +46 -72
  169. package/src/lowering/uart.ts +73 -51
  170. package/src/lowering/usb.ts +221 -0
  171. package/src/lowering/wdt.ts +95 -84
  172. package/src/lowering/wifi.ts +120 -111
  173. package/src/sdk/board-catalog-sync.ts +62 -0
  174. package/src/strategy.ts +888 -229
  175. package/src/toolchain/bossac-touch.ts +112 -0
  176. package/src/toolchain/compat.ts +8 -3
  177. package/src/toolchain/debug-config.ts +666 -522
  178. package/src/toolchain/env-check.ts +9 -9
  179. package/src/toolchain/index.ts +765 -44
  180. package/src/toolchain/scaffold.ts +81 -7
  181. package/src/toolchain/west-discover.ts +334 -316
  182. package/src/toolchain/west-spawn.ts +17 -5
  183. package/src/async/timer-polyfill.ts +0 -107
  184. package/src/chips/esp32.ts +0 -74
  185. package/src/chips/esp32s3.ts +0 -57
  186. package/src/chips/xiao-ble.ts +0 -70
  187. package/src/lowering/power.ts +0 -70
  188. package/src/lowering/pulse.ts +0 -93
  189. package/src/lowering/tone.ts +0 -60
  190. package/src/lowering/worker-backing.ts +0 -94
  191. package/src/lowering/worker.ts +0 -17
@@ -2,9 +2,8 @@
2
2
  // UART lowering — uart_poll_out / uart_poll_in per-byte
3
3
  //
4
4
  // Zephyr's UART API is byte-oriented (uart_poll_out / uart_poll_in). The HAL's
5
- // uart.print/println/write lower to per-byte poll_out loops. For console output
6
- // the strategy's transformConsoleCall routes to printk; these uart.* ops are
7
- // for a specific UART port (the XIAO exposes uart0 on D6/D7).
5
+ // uart.print/println/write lower to per-byte poll_out loops; these uart.* ops
6
+ // are for a specific UART port (the XIAO exposes uart0 on D6/D7).
8
7
  //
9
8
  // The device resolves at compile time via DEVICE_DT_GET(DT_NODELABEL(uart0)).
10
9
  // uart.begin configures the baud via uart_configure.
@@ -38,16 +37,14 @@ export function uartInitLines(chip: ZephyrChipDescriptor, controllerIndex: numbe
38
37
  ];
39
38
  }
40
39
 
41
- /** Render a string-literal or expression to a per-byte poll_out loop. */
42
- function renderWrite(dev: string, value: string, newline: boolean): string {
43
- // String literal → emit a char-array loop (known length). Otherwise fall back
44
- // to a const char* cast with a strlen-guarded loop.
45
- if (/^".*"$/.test(value)) {
46
- const body = `for (size_t __i = 0; __i < sizeof(${value}) - 1; __i++) { uart_poll_out(${dev}, (${value})[__i]); }`;
47
- return newline ? `${body} uart_poll_out(${dev}, '\\n');` : body;
48
- }
49
- const body = `for (const char* __s = (const char*)(${value}); *__s; __s++) { uart_poll_out(${dev}, *__s); }`;
50
- return newline ? `${body} uart_poll_out(${dev}, '\\n');` : body;
40
+ /** Render a string/number/boolean value to a per-byte poll_out loop via the
41
+ * __tc_dev_put overloads (the const char* overload streams a string; the
42
+ * double overload formats a number with __tc_fmt_num_buf). The value passes
43
+ * through verbatim C++ overload resolution picks the right overload for a
44
+ * string literal, a number literal, or a runtime variable of either type. */
45
+ export function renderWrite(dev: string, value: string, newline: boolean): string {
46
+ const put = `__tc_dev_put(${dev}, ${value});`;
47
+ return newline ? `${put} uart_poll_out(${dev}, '\\n');` : put;
51
48
  }
52
49
 
53
50
  /**
@@ -61,47 +58,33 @@ export function lowerUart(op: HALOpIR): { code?: string; expression?: string } {
61
58
  const dev = `${p}_dev`;
62
59
 
63
60
  switch (op.operation) {
64
- case 'uart.begin':
65
- return { code: `${p}_init(static_cast<uint32_t>(${o.baud}));` };
66
- case 'uart.end':
67
- return { code: `(void)${dev};` };
68
- case 'uart.print':
69
- return { code: renderWrite(dev, o.value, false) };
70
- case 'uart.println':
71
- return { code: renderWrite(dev, o.value, true) };
72
- case 'uart.write':
73
- return { code: renderWrite(dev, o.data, false) };
74
- case 'uart.printf': {
75
- // snprintf into a buffer, then poll_out each byte.
76
- const fmt = o.format;
77
- const args = (o.args ?? []).join(', ');
78
- const argList = args ? `, ${args}` : '';
61
+ case 'uart.poll_write': {
62
+ const pre = uartBaudGuard(p, o.baud);
63
+ return { code: `${pre} ${renderWrite(dev, o.data, false)}` };
64
+ }
65
+
66
+ // ── Thin UART RX (hal/uart-port.ts) — interrupt-drained ring ──────────
67
+ // The first receive call arms the driver IRQ (guarded); the ISR drains
68
+ // the FIFO into the construction-sized static ring (uartRingStateLines).
69
+ // available/peek/read are then pure ring arithmetic — the calls the poll
70
+ // API honestly could not support.
71
+ case 'uart.rx_arm':
72
+ case 'uart.rx_available':
73
+ case 'uart.rx_peek':
74
+ case 'uart.rx_read': {
75
+ const r = `__tc_uartrx${idx}`;
76
+ const arm = `{ static bool ${r}_armed = false; if (!${r}_armed) { uart_irq_callback_user_data_set(${dev}, ${r}_isr, NULL); uart_irq_rx_enable(${dev}); ${r}_armed = true; } }`;
77
+ if (op.operation === 'uart.rx_arm') return { code: arm };
78
+ if (op.operation === 'uart.rx_available') {
79
+ return { expression: `({ ${arm} (${r}_head - ${r}_tail); })` };
80
+ }
81
+ if (op.operation === 'uart.rx_peek') {
82
+ return { expression: `({ ${arm} (${r}_tail < ${r}_head ? ${r}_buf[${r}_tail % ${o.ring}] : -1); })` };
83
+ }
79
84
  return {
80
- code: `char __buf[128]; int __n = snprintk(__buf, sizeof(__buf), ${fmt}${argList}); for (int __i = 0; __i < __n; __i++) { uart_poll_out(${dev}, __buf[__i]); }`,
85
+ expression: `({ ${arm} (${r}_tail < ${r}_head ? ${r}_buf[(${r}_tail)++ % ${o.ring}] : -1); })`,
81
86
  };
82
87
  }
83
- case 'uart.read':
84
- // Non-blocking poll; returns the byte or -1 if none available.
85
- return { expression: `({ unsigned char __b = 0; (uart_poll_in(${dev}, &__b) == 0) ? (int)__b : -1; })` };
86
- case 'uart.peek':
87
- // The poll API has no buffered-byte store, so there is no true peek.
88
- // Return -1 (the Arduino "no data" sentinel) rather than blocking. This
89
- // is an honest limitation of the byte-level poll driver; an interrupt- or
90
- // DMA-backed UART driver would be needed for real peek semantics.
91
- return { expression: '(-1)' };
92
- case 'uart.available':
93
- // The poll API reports only "at least one byte ready" via uart_poll_in's
94
- // return code — it has no buffered-byte count, and probing with poll_in
95
- // would DRAIN the very byte the caller next wants to read. So we cannot
96
- // honestly report availability. Return 0 (Arduino's "no data" value)
97
- // rather than the old truthy -1, so `if (uart.available())` loops don't
98
- // spin forever on a false-positive. Callers should instead just call
99
- // uart.read() directly (it returns -1 when no byte is ready). For true
100
- // buffered availability, use an interrupt/DMA-backed UART driver.
101
- return { expression: '(0)' };
102
- case 'uart.flush':
103
- // poll_out is synchronous (blocking until sent); flush is a no-op.
104
- return { code: `(void)${dev};` };
105
88
  default:
106
89
  throw new Error(
107
90
  `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
@@ -109,3 +92,42 @@ export function lowerUart(op: HALOpIR): { code?: string; expression?: string } {
109
92
  );
110
93
  }
111
94
  }
95
+
96
+ /** The thin-port baud preamble: apply the construction baud once via the
97
+ * shim's `_init` helper (uart_configure). Guarded per controller. */
98
+ function uartBaudGuard(p: string, baud: unknown): string {
99
+ const n = typeof baud === 'number' ? baud : parseInt(String(baud ?? 0), 10);
100
+ if (!n || isNaN(n)) return '';
101
+ const done = `${p}_baud_done`;
102
+ return `{ static bool ${done} = false; if (!${done}) { ${p}_init(static_cast<uint32_t>(${n})); ${done} = true; } } `;
103
+ }
104
+
105
+ /** The per-port RX ring state: a construction-sized static buffer, free-running
106
+ * head/tail counters (available = head - tail, no wrap ambiguity), and the
107
+ * ISR that drains the FIFO. A byte arriving with a full ring is dropped —
108
+ * the embedded-honest answer (no unbounded buffering). Emitted only for
109
+ * ports whose uart.rx_* ops were emitted (collectUartRings), so an unused
110
+ * ISR never trips -Wunused-function. */
111
+ export function uartRingStateLines(index: number, ring: number): string[] {
112
+ const r = `__tc_uartrx${index}`;
113
+ const dev = `__tc_uart${index}_dev`;
114
+ return [
115
+ '// CUTTLEFISH_UARTRX_BEGIN',
116
+ `static uint8_t ${r}_buf[${ring}];`,
117
+ `static volatile uint32_t ${r}_head = 0;`,
118
+ `static volatile uint32_t ${r}_tail = 0;`,
119
+ `static void ${r}_isr(const struct device* dev, void* user_data) {`,
120
+ ` (void)user_data;`,
121
+ ` uart_irq_update(dev);`,
122
+ ` while (uart_irq_rx_ready(dev)) {`,
123
+ ` uint8_t __c = 0;`,
124
+ ` (void)uart_fifo_read(dev, &__c, 1);`,
125
+ ` if ((${r}_head - ${r}_tail) < ${ring}) {`,
126
+ ` ${r}_buf[${r}_head % ${ring}] = __c;`,
127
+ ` ${r}_head++;`,
128
+ ` }`,
129
+ ` }`,
130
+ `}`,
131
+ '// CUTTLEFISH_UARTRX_END',
132
+ ];
133
+ }
@@ -0,0 +1,221 @@
1
+ // ---------------------------------------------------------------------------
2
+ // USB CDC-ACM serial lowering — Zephyr "next" USB device stack
3
+ //
4
+ // A CDC-ACM instance (cdc_acm_uart<N>, composed in the generated overlay as a
5
+ // child of the UDC controller node) registers as a UART-class device, so the
6
+ // lowering drives it with the plain uart_* API — the same per-byte poll_out
7
+ // loops as lowering/uart.ts. The differences from a hardware UART:
8
+ // - usb.begin must start the device stack (usbdDeviceLines' one-shot
9
+ // __tc_usbd_start) before the port carries traffic;
10
+ // - "connected" is a real query (DTR line ctrl), not a constant;
11
+ // - baud is a line-coding hint — recorded, but CDC has no wire baud.
12
+ //
13
+ // If the chip descriptor declares no `usb`, every op throws with a clear
14
+ // "board does not expose USB" message (the diagnostic contract the framework
15
+ // manifest's board-gated support entry promises).
16
+ // ---------------------------------------------------------------------------
17
+
18
+ import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
19
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
20
+ import { parseControllerIndex } from './util.js';
21
+ import { renderWrite } from './uart.js';
22
+
23
+ /** Render a HAL field: pass through (already rendered by the resolver). */
24
+ function s(v: unknown): string {
25
+ return String(v);
26
+ }
27
+
28
+ /** The C variable prefix for a CDC instance's state. */
29
+ function prefix(idx: number): string {
30
+ return `__tc_usb${idx}`;
31
+ }
32
+
33
+ /** Instance N resolves to the DT nodelabel the overlay generator emits. */
34
+ function nodeLabel(idx: number): string {
35
+ return `cdc_acm_uart${idx}`;
36
+ }
37
+
38
+ /**
39
+ * Emit the shared USB device context (USBD_DEVICE_DEFINE + string/config
40
+ * descriptors + configuration + class registration + usbd_enable). Emitted
41
+ * ONCE per program when the chip declares `usb` — the next stack has one
42
+ * device context on the UDC controller, regardless of how many CDC instances
43
+ * hang off it.
44
+ *
45
+ * VID/PID default to the Zephyr-project testing IDs (0x2fe3/0x0001); a board
46
+ * overrides via `zephyr.usb.vid`/`zephyr.usb.pid`. Full-speed only — the
47
+ * boards this framework targets (STM32 OTG_FS, nRF USBD) are FS controllers,
48
+ * and the HS path would need a second USBD_CONFIGURATION_DEFINE.
49
+ *
50
+ * Symbol/API shapes verified against Zephyr 4.3:
51
+ * subsys/usb/device_next/Kconfig, include/zephyr/usb/usbd.h, and
52
+ * samples/subsys/usb/common/sample_usbd_init.c.
53
+ */
54
+ export function usbdDeviceLines(chip: ZephyrChipDescriptor): string[] {
55
+ if (!chip.usb) return [];
56
+ const vid = chip.usb.vid ?? '0x2fe3';
57
+ const pid = chip.usb.pid ?? '0x0001';
58
+ // 1200-baud touch-to-reset (BOSSA-bootloader boards): a usbd message
59
+ // callback that reboots into the bootloader when the host sets the CDC
60
+ // baud rate to 1200. Zephyr's CDC-ACM class publishes
61
+ // USBD_MSG_CDC_ACM_LINE_CODING on every host SET_LINE_CODING (the message
62
+ // carries the CDC uart device; its line coding is readable via
63
+ // uart_cfg_get). The reboot writes the bootloader's stay-resident magic
64
+ // (Arduino SAMD scheme: the bootloader checks the last word of SRAM after
65
+ // reset) so the board waits in the bootloader instead of booting the app.
66
+ const touch = chip.usb.touchReset;
67
+ const touchLines: string[] = touch
68
+ ? [
69
+ `// 1200-baud touch-to-reset: reboot into the bootloader (flag 0x${touch.magic.toString(16)} @ 0x${touch.flagAddress.toString(16)}).`,
70
+ 'static void __tc_usbd_msg_cb(struct usbd_context* ctx, const struct usbd_msg* msg) {',
71
+ ' (void)ctx;',
72
+ ' if (msg->type != USBD_MSG_CDC_ACM_LINE_CODING) { return; }',
73
+ ' struct uart_config __tc_cfg;',
74
+ ' if (uart_config_get(msg->dev, &__tc_cfg) == 0 && __tc_cfg.baudrate == 1200) {',
75
+ ' // Delay the reboot so the host touch (which applies 1200 as part',
76
+ ' // of opening the port) can close its handle first — resetting under',
77
+ ' // an open host handle can wedge the Windows usbser driver and block',
78
+ ' // re-enumeration until a physical replug.',
79
+ ' k_msleep(250);',
80
+ ` *(volatile uint32_t*)0x${touch.flagAddress.toString(16)} = 0x${touch.magic.toString(16)};`,
81
+ ' NVIC_SystemReset();',
82
+ ' }',
83
+ '}',
84
+ ]
85
+ : [];
86
+ const touchRegister: string[] = touch
87
+ ? [' usbd_msg_register_cb(&__tc_usbd, __tc_usbd_msg_cb);']
88
+ : [];
89
+ return [
90
+ '// CUTTLEFISH_USBD_BEGIN',
91
+ 'USBD_DEVICE_DEFINE(__tc_usbd,',
92
+ ` DEVICE_DT_GET(DT_NODELABEL(${chip.usb.controller})),`,
93
+ ` ${vid}, ${pid});`,
94
+ 'USBD_DESC_LANG_DEFINE(__tc_usbd_lang);',
95
+ 'USBD_DESC_MANUFACTURER_DEFINE(__tc_usbd_mfr, "typecad");',
96
+ 'USBD_DESC_PRODUCT_DEFINE(__tc_usbd_product, "cuttlefish app");',
97
+ // Serial number from hwinfo: Windows keys USB devnodes without a serial
98
+ // on the physical port, so flash-cycle re-enumerations reuse stale
99
+ // port-keyed nodes (the "access denied" open wedge). Identity-based
100
+ // instance paths are stable across ports and never hit that pool.
101
+ 'USBD_DESC_SERIAL_NUMBER_DEFINE(__tc_usbd_sn);',
102
+ 'USBD_DESC_CONFIG_DEFINE(__tc_usbd_cfg_desc, "cuttlefish");',
103
+ 'USBD_CONFIGURATION_DEFINE(__tc_usbd_cfg, 0, 250, &__tc_usbd_cfg_desc);',
104
+ 'static bool __tc_usbd_started = false;',
105
+ ...touchLines,
106
+ 'static void __tc_usbd_start(void) {',
107
+ ' if (__tc_usbd_started) { return; }',
108
+ ' __tc_usbd_started = true;',
109
+ ' int err = usbd_add_descriptor(&__tc_usbd, &__tc_usbd_lang);',
110
+ ' if (err != 0) { printk("cuttlefish usb: lang descriptor failed: %d\\n", err); return; }',
111
+ ' err = usbd_add_descriptor(&__tc_usbd, &__tc_usbd_sn);',
112
+ ' if (err != 0) { printk("cuttlefish usb: serial descriptor failed: %d\\n", err); return; }',
113
+ ' err = usbd_add_descriptor(&__tc_usbd, &__tc_usbd_mfr);',
114
+ ' if (err != 0) { printk("cuttlefish usb: manufacturer descriptor failed: %d\\n", err); return; }',
115
+ ' err = usbd_add_descriptor(&__tc_usbd, &__tc_usbd_product);',
116
+ ' if (err != 0) { printk("cuttlefish usb: product descriptor failed: %d\\n", err); return; }',
117
+ ' err = usbd_add_configuration(&__tc_usbd, USBD_SPEED_FS, &__tc_usbd_cfg);',
118
+ ' if (err != 0) { printk("cuttlefish usb: add configuration failed: %d\\n", err); return; }',
119
+ ' err = usbd_register_all_classes(&__tc_usbd, USBD_SPEED_FS, 1, NULL);',
120
+ ' if (err != 0) { printk("cuttlefish usb: register classes failed: %d\\n", err); return; }',
121
+ // Registered before usbd_init so no line-coding event can be missed.
122
+ ...touchRegister,
123
+ // usbd_init builds the descriptor tables from the registered
124
+ // configuration/classes and marks the context initialized — usbd_enable
125
+ // refuses with -EPERM ("not initialized") without it (sample_usbd_init.c
126
+ // calls it between setup and enable).
127
+ ' err = usbd_init(&__tc_usbd);',
128
+ ' if (err != 0) { printk("cuttlefish usb: init failed: %d\\n", err); return; }',
129
+ // Boards with VBUS detection start on the VBUS event in the Zephyr
130
+ // sample, via a message callback we do not register; enabling
131
+ // unconditionally (and reporting the error) is the sample's own path
132
+ // for boards without detection (STM32 OTG_FS).
133
+ ' err = usbd_enable(&__tc_usbd);',
134
+ ' if (err != 0) { printk("cuttlefish usb: enable failed: %d\\n", err); return; }',
135
+ ' printk("cuttlefish usb: device enabled\\n");',
136
+ '}',
137
+ '// CUTTLEFISH_USBD_END',
138
+ ];
139
+ }
140
+
141
+ /**
142
+ * Emit the per-instance CDC device + init helper. Called from shimLines when
143
+ * the program uses USB and the chip declares `usb`; must be paired with one
144
+ * usbdDeviceLines() block. The init starts the device stack (guarded) and
145
+ * applies the line coding.
146
+ */
147
+ export function usbInitLines(chip: ZephyrChipDescriptor, instanceIndex: number): string[] {
148
+ if (!chip.usb) return [];
149
+ const p = prefix(instanceIndex);
150
+ const dev = `${p}_dev`;
151
+ return [
152
+ '// CUTTLEFISH_USB_BEGIN',
153
+ `static const struct device* ${dev} = DEVICE_DT_GET(DT_NODELABEL(${nodeLabel(instanceIndex)}));`,
154
+ `static void ${p}_init(void) {`,
155
+ ` __tc_usbd_start(); // CDC line coding is the host's business`,
156
+ `}`,
157
+ '// CUTTLEFISH_USB_END',
158
+ ];
159
+ }
160
+
161
+ /** Throw the board-capability diagnostic. Centralized so every op reads identically. */
162
+ function requireUsb(chip: ZephyrChipDescriptor, op: string): void {
163
+ if (!chip.usb) {
164
+ throw new Error(
165
+ `framework-zephyr: \`${op}\` needs a USB device stack, but this board's chip data declares no \`zephyr.usb\` ` +
166
+ `(controller + cdcInstances). Boards whose Zephyr DTS has no enabled UDC controller node ` +
167
+ `(zephyr_udc0) cannot provide USB CDC serial.`,
168
+ );
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Resolve a HAL usb.* op to Zephyr C++.
174
+ * Returns `{ code }` for statement ops, `{ expression }` for value-returning ops.
175
+ */
176
+ export function lowerUsb(op: HALOpIR, chip: ZephyrChipDescriptor): { code?: string; expression?: string } {
177
+ requireUsb(chip, op.operation);
178
+ const o = op as any;
179
+ const idx = parseControllerIndex(o.port);
180
+ if (chip.usb && idx >= chip.usb.cdcInstances) {
181
+ throw new Error(
182
+ `framework-zephyr: usb port "${o.port}" (instance ${idx}) is out of range — this board composes ` +
183
+ `${chip.usb.cdcInstances} CDC-ACM instance(s) (USB0..USB${chip.usb.cdcInstances - 1}).`,
184
+ );
185
+ }
186
+ const p = prefix(idx);
187
+ const dev = `${p}_dev`;
188
+
189
+ switch (op.operation) {
190
+ case 'usb.begin':
191
+ return { code: `${p}_init();` };
192
+ case 'usb.wait_ready': {
193
+ // Bounded DTR poll, sliced in the shim-side expression (no user-code
194
+ // busy loop). timeoutMs 0 = wait forever.
195
+ return { expression: `({ bool __ok = false; uint32_t __t = 0U; while (true) { uint32_t __dtr = 0U; if ((uart_line_ctrl_get(${dev}, UART_LINE_CTRL_DTR, &__dtr) == 0) && (__dtr != 0U)) { __ok = true; break; } if ((${s(o.timeoutMs ?? 0)}) != 0 && __t >= (uint32_t)(${s(o.timeoutMs ?? 0)})) { break; } k_msleep(10); __t += 10U; } __ok; })` };
196
+ }
197
+ case 'usb.end':
198
+ // CDC has no per-port disable short of tearing down the device stack
199
+ // (which would drop every other instance); make end observable but safe.
200
+ return { code: `(void)${dev};` };
201
+ case 'usb.print':
202
+ return { code: renderWrite(dev, o.value, false) };
203
+ case 'usb.println':
204
+ return { code: renderWrite(dev, o.value, true) };
205
+ case 'usb.read':
206
+ // Same poll semantics as uart.read: the byte or -1 if none available.
207
+ return { expression: `({ unsigned char __b = 0; (uart_poll_in(${dev}, &__b) == 0) ? (int)__b : -1; })` };
208
+ case 'usb.available':
209
+ // uart_poll_in reports only "one byte ready" and probing would drain it;
210
+ // same honest limitation as uart.available.
211
+ return { expression: '(0)' };
212
+ case 'usb.connected':
213
+ // DTR asserted = the host actually opened the port.
214
+ return { expression: `({ uint32_t __dtr = 0; (uart_line_ctrl_get(${dev}, UART_LINE_CTRL_DTR, &__dtr) == 0) && (__dtr != 0); })` };
215
+ default:
216
+ throw new Error(
217
+ `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
218
+ `Open an issue or use rawCpp() to emit it manually.`,
219
+ );
220
+ }
221
+ }
@@ -1,84 +1,95 @@
1
- // ---------------------------------------------------------------------------
2
- // WDT lowering — nRF watchdog via wdt0
3
- //
4
- // Zephyr's WDT API: install a timeout (before setup), then setup, then feed
5
- // periodically. The lowering caches the channel id returned by
6
- // wdt_install_timeout in a static var so wdt.reset can feed it.
7
- //
8
- // enable(timeout): wdt_install_timeout + wdt_setup. Zephyr expects the timeout
9
- // in milliseconds (wdt_window.max). The HAL passes a "250ms" string or WDTO_*
10
- // constant or a number; we parse to ms in the lowering.
11
- // ---------------------------------------------------------------------------
12
-
13
- import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
14
- import type { ZephyrChipDescriptor } from '../chips/types.js';
15
-
16
- /** Parse a HAL wdt timeout ("250ms", WDTO_2S, or a bare number) to ms.
17
- * Tolerates undefined (the manifest validator's probe sends a minimal op). */
18
- function timeoutToMs(timeout: string | number | undefined): number {
19
- if (typeof timeout === 'number') return timeout;
20
- if (!timeout) return 1000; // default 1s when absent (e.g. the validator probe)
21
- // Arduino WDTO_* constants.
22
- const wdto: Record<string, number> = {
23
- WDTO_15MS: 15, WDTO_30MS: 30, WDTO_60MS: 60, WDTO_120MS: 120,
24
- WDTO_250MS: 250, WDTO_500MS: 500, WDTO_1S: 1000, WDTO_2S: 2000,
25
- WDTO_4S: 4000, WDTO_8S: 8000,
26
- };
27
- if (wdto[timeout]) return wdto[timeout];
28
- const m = timeout.match(/^(\d+)\s*ms$/i);
29
- if (m) return parseInt(m[1], 10);
30
- const s = timeout.match(/^(\d+)\s*s$/i);
31
- if (s) return parseInt(s[1], 10) * 1000;
32
- const n = parseInt(timeout, 10);
33
- return isNaN(n) ? 1000 : n;
34
- }
35
-
36
- /**
37
- * Emit the WDT device + channel state. Called from shimLines when the program
38
- * uses the watchdog.
39
- */
40
- export function wdtInitLines(chip: ZephyrChipDescriptor): string[] {
41
- const nodeLabel = chip.wdt?.nodeLabel ?? 'wdt0';
42
- return [
43
- '// CUTTLEFISH_WDT_BEGIN',
44
- `static const struct device* __tc_wdt_dev = DEVICE_DT_GET(DT_NODELABEL(${nodeLabel}));`,
45
- 'static int __tc_wdt_channel = -1;',
46
- 'static bool __tc_wdt_setup_done = false;',
47
- '// CUTTLEFISH_WDT_END',
48
- ];
49
- }
50
-
51
- /**
52
- * Resolve a HAL wdt.* op to Zephyr C++.
53
- * Returns `{ code }` for statement ops, `{ expression }` for value-returning ops.
54
- */
55
- export function lowerWdt(op: HALOpIR): { code?: string; expression?: string } {
56
- const o = op as any;
57
-
58
- switch (op.operation) {
59
- case 'wdt.enable': {
60
- const ms = timeoutToMs(o.timeout);
61
- // Install a timeout then set up the watchdog. Both are idempotent via
62
- // the static flags. WDT_FLAG_RESET_CPU_CORE = full reset on timeout.
63
- return {
64
- code: [
65
- `if (!__tc_wdt_setup_done) {`,
66
- ` const struct wdt_timeout_cfg __cfg = { .window = { .min = 0, .max = ${ms} }, .callback = NULL, .flags = WDT_FLAG_RESET_CPU_CORE };`,
67
- ` __tc_wdt_channel = wdt_install_timeout(__tc_wdt_dev, &__cfg);`,
68
- ` wdt_setup(__tc_wdt_dev, WDT_OPT_PAUSE_HALTED_BY_DBG);`,
69
- ` __tc_wdt_setup_done = true;`,
70
- `}`,
71
- ].join(' '),
72
- };
73
- }
74
- case 'wdt.reset':
75
- return { code: `if (__tc_wdt_channel >= 0) { wdt_feed(__tc_wdt_dev, __tc_wdt_channel); }` };
76
- case 'wdt.disable':
77
- return { code: `wdt_disable(__tc_wdt_dev); __tc_wdt_setup_done = false;` };
78
- default:
79
- throw new Error(
80
- `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
81
- `Open an issue or use rawCpp() to emit it manually.`,
82
- );
83
- }
84
- }
1
+ // ---------------------------------------------------------------------------
2
+ // WDT lowering — nRF watchdog via wdt0
3
+ //
4
+ // Zephyr's WDT API: install a timeout (before setup), then setup, then feed
5
+ // periodically. The lowering caches the channel id returned by
6
+ // wdt_install_timeout in a static var so wdt.reset can feed it.
7
+ //
8
+ // enable(timeout): wdt_install_timeout + wdt_setup. Zephyr expects the timeout
9
+ // in milliseconds (wdt_window.max). The HAL passes a "250ms" string or WDTO_*
10
+ // constant or a number; we parse to ms in the lowering.
11
+ // ---------------------------------------------------------------------------
12
+
13
+ import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
14
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
15
+
16
+ /** Parse a HAL wdt timeout ("250ms", WDTO_2S, or a bare number) to ms.
17
+ * Tolerates undefined (the manifest validator's probe sends a minimal op)
18
+ * and quote-wrapped strings (resolveSemanticArg can hand the literal's
19
+ * quoted source text through). */
20
+ function timeoutToMs(timeout: string | number | undefined): number {
21
+ if (typeof timeout === 'number') return timeout;
22
+ if (!timeout) return 1000; // default 1s when absent (e.g. the validator probe)
23
+ timeout = timeout.replace(/^['"]|['"]$/g, '');
24
+ // Arduino WDTO_* constants.
25
+ const wdto: Record<string, number> = {
26
+ WDTO_15MS: 15, WDTO_30MS: 30, WDTO_60MS: 60, WDTO_120MS: 120,
27
+ WDTO_250MS: 250, WDTO_500MS: 500, WDTO_1S: 1000, WDTO_2S: 2000,
28
+ WDTO_4S: 4000, WDTO_8S: 8000,
29
+ };
30
+ if (wdto[timeout]) return wdto[timeout];
31
+ const m = timeout.match(/^(\d+)\s*ms$/i);
32
+ if (m) return parseInt(m[1], 10);
33
+ const s = timeout.match(/^(\d+)\s*s$/i);
34
+ if (s) return parseInt(s[1], 10) * 1000;
35
+ const n = parseInt(timeout, 10);
36
+ return isNaN(n) ? 1000 : n;
37
+ }
38
+
39
+ /**
40
+ * Emit the WDT device + channel state. Called from shimLines when the program
41
+ * uses the watchdog.
42
+ */
43
+ export function wdtInitLines(chip: ZephyrChipDescriptor): string[] {
44
+ const nodeLabel = chip.wdt?.nodeLabel ?? 'wdt0';
45
+ return [
46
+ '// CUTTLEFISH_WDT_BEGIN',
47
+ `static const struct device* __tc_wdt_dev = DEVICE_DT_GET(DT_NODELABEL(${nodeLabel}));`,
48
+ 'static int __tc_wdt_channel = -1;',
49
+ 'static bool __tc_wdt_setup_done = false;',
50
+ '// CUTTLEFISH_WDT_END',
51
+ ];
52
+ }
53
+
54
+ /**
55
+ * Resolve a HAL wdt.* op to Zephyr C++.
56
+ * Returns `{ code }` for statement ops, `{ expression }` for value-returning ops.
57
+ */
58
+ export function lowerWdt(op: HALOpIR, chip: ZephyrChipDescriptor): { code?: string; expression?: string } {
59
+ const o = op as any;
60
+
61
+ // No watchdog node on this target (e.g. SAM D21 Zephyr's samd21 dtsi
62
+ // exposes none). Comment + (in profileDiagnostics) a clear error, mirroring
63
+ // the hwtimer unavailable pattern. Without this the wdt_* calls reference
64
+ // the shim vars that wdtInitLines (gated on chip.wdt) never emitted.
65
+ if (!chip.wdt) {
66
+ return { code: `/* ${op.operation}: no watchdog device on ${chip.id} */` };
67
+ }
68
+
69
+ switch (op.operation) {
70
+ case 'wdt.setup': {
71
+ // Same install+setup sequence as wdt.enable, but the timeout is a
72
+ // plain ms number from construction — no WDTO_*/string parsing.
73
+ const ms = Number(o.timeoutMs ?? 1000);
74
+ return {
75
+ code: [
76
+ `if (!__tc_wdt_setup_done) {`,
77
+ ` const struct wdt_timeout_cfg __cfg = { .window = { .min = 0, .max = ${ms} }, .callback = NULL, .flags = WDT_FLAG_RESET_CPU_CORE };`,
78
+ ` __tc_wdt_channel = wdt_install_timeout(__tc_wdt_dev, &__cfg);`,
79
+ ` wdt_setup(__tc_wdt_dev, WDT_OPT_PAUSE_HALTED_BY_DBG);`,
80
+ ` __tc_wdt_setup_done = true;`,
81
+ `}`,
82
+ ].join(' '),
83
+ };
84
+ }
85
+ case 'wdt.feed':
86
+ return { code: `if (__tc_wdt_channel >= 0) { wdt_feed(__tc_wdt_dev, __tc_wdt_channel); }` };
87
+ case 'wdt.disable':
88
+ return { code: `wdt_disable(__tc_wdt_dev); __tc_wdt_setup_done = false;` };
89
+ default:
90
+ throw new Error(
91
+ `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
92
+ `Open an issue or use rawCpp() to emit it manually.`,
93
+ );
94
+ }
95
+ }