@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
@@ -1,101 +1,139 @@
1
- // ---------------------------------------------------------------------------
2
- // Hardware-timer lowering — Zephyr counter API
3
- //
4
- // HAL `hwtimer.*` (instance → frequency/overflow/start/stop) maps onto Zephyr's
5
- // counter driver (<zephyr/drivers/counter.h>). A chip declares the counter
6
- // devices it exposes (e.g. nRF RTC1 — RTC0 is kernel-owned) via
7
- // `hwtimer.controllers[instance].nodeLabel`.
8
- //
9
- // Frequency model: a Zephyr counter has a fixed clock; the HAL
10
- // set_frequency(hz) is realized as a top value of counter_freq/hz with an alarm
11
- // callback (the on_overflow handler). start() arms both the top value and the
12
- // callback so the call order (setFrequency → onOverflow → start, or any
13
- // permutation) is handled uniformly.
14
- //
15
- // Targets without a free counter omit `hwtimer`; usage lowers to a comment and
16
- // profileDiagnostics flags it. The JS setInterval/setTimeout polyfill
17
- // (k_timer) is a separate surface and is unaffected.
18
- // ---------------------------------------------------------------------------
19
-
20
- import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
21
- import type { ZephyrChipDescriptor } from '../chips/types.js';
22
-
23
- /** Per-instance emitted symbol stems. */
24
- function devVar(instance: number): string {
25
- return `__tc_hw_dev_${instance}`;
26
- }
27
- function hzVar(instance: number): string {
28
- return `__tc_hw_hz_${instance}`;
29
- }
30
- function cbVar(instance: number): string {
31
- return `__tc_hw_cb_${instance}`;
32
- }
33
-
34
- /**
35
- * Emit the per-instance counter device handles + frequency/callback state.
36
- * Called from shimLines when the program uses hardware timers.
37
- */
38
- export function hwtimerInitLines(chip: ZephyrChipDescriptor): string[] {
39
- const controllers = chip.hwtimer?.controllers ?? [];
40
- if (controllers.length === 0) return [];
41
- const lines: string[] = ['// CUTTLEFISH_HWTIMER_BEGIN'];
42
- controllers.forEach((c, i) => {
43
- lines.push(
44
- `static const struct device* ${devVar(i)} = DEVICE_DT_GET(DT_NODELABEL(${c.nodeLabel}));`,
45
- `static uint32_t ${hzVar(i)} = 1;`,
46
- `static counter_top_callback_t ${cbVar(i)} = NULL;`,
47
- );
48
- });
49
- lines.push('// CUTTLEFISH_HWTIMER_END');
50
- return lines;
51
- }
52
-
53
- /**
54
- * Resolve a HAL hwtimer.* op to Zephyr C++.
55
- * Returns `{ code }` for statement ops.
56
- */
57
- export function lowerHwtimer(
58
- op: HALOpIR,
59
- chip: ZephyrChipDescriptor,
60
- ): { code?: string; expression?: string } {
61
- const o = op as any;
62
- const controllers = chip.hwtimer?.controllers ?? [];
63
-
64
- // No counter on this target. Comment + (in profileDiagnostics) a clear error.
65
- if (controllers.length === 0) {
66
- return { code: `/* hwtimer instance ${o.instance}: no counter device on ${chip.id} */` };
67
- }
68
-
69
- const instance = typeof o.instance === 'number' ? o.instance : parseInt(String(o.instance), 10);
70
- if (isNaN(instance) || instance < 0 || instance >= controllers.length) {
71
- return { code: `/* hwtimer instance ${o.instance}: out of range on ${chip.id} */` };
72
- }
73
-
74
- switch (op.operation) {
75
- case 'hwtimer.set_frequency':
76
- return { code: `${hzVar(instance)} = ${o.hz};` };
77
- case 'hwtimer.on_overflow':
78
- return { code: `${cbVar(instance)} = (${o.handler});` };
79
- case 'hwtimer.start':
80
- // Arm the top value (counter_freq / desired_hz) + the overflow callback,
81
- // then start the counter. Doing both here handles any call order — the
82
- // HAL typical sequence (setFrequency → onOverflow → start) and permutations.
83
- return {
84
- code: [
85
- `{`,
86
- ` uint32_t __f = counter_get_frequency(${devVar(instance)});`,
87
- ` uint32_t __top = __f ? (__f / ${hzVar(instance)}) : 0U;`,
88
- ` if (__top > 0U) { (void)counter_set_top_value(${devVar(instance)}, __top, ${cbVar(instance)}, NULL); }`,
89
- ` (void)counter_start(${devVar(instance)});`,
90
- `}`,
91
- ].join(' '),
92
- };
93
- case 'hwtimer.stop':
94
- return { code: `(void)counter_stop(${devVar(instance)});` };
95
- default:
96
- throw new Error(
97
- `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
98
- `Open an issue or use rawCpp() to emit it manually.`,
99
- );
100
- }
101
- }
1
+ // ---------------------------------------------------------------------------
2
+ // Hardware-timer lowering — Zephyr counter API
3
+ //
4
+ // HAL `hwtimer.*` (instance → frequency/overflow/start/stop) maps onto Zephyr's
5
+ // counter driver (<zephyr/drivers/counter.h>). A chip declares the counter
6
+ // devices it exposes (e.g. nRF RTC1 — RTC0 is kernel-owned) via
7
+ // `hwtimer.controllers[instance].nodeLabel`.
8
+ //
9
+ // Frequency model: a Zephyr counter has a fixed clock; the HAL
10
+ // set_frequency(hz) is realized as a top value of counter_freq/hz with an alarm
11
+ // callback (the on_overflow handler). start() arms both the top value and the
12
+ // callback so the call order (setFrequency → onOverflow → start, or any
13
+ // permutation) is handled uniformly.
14
+ //
15
+ // Targets without a free counter omit `hwtimer`; usage lowers to a comment and
16
+ // profileDiagnostics flags it. The JS setInterval/setTimeout polyfill
17
+ // (k_timer) is a separate surface and is unaffected.
18
+ // ---------------------------------------------------------------------------
19
+
20
+ import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
21
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
22
+
23
+ /** Per-instance emitted symbol stems. */
24
+ function devVar(instance: number): string {
25
+ return `__tc_hw_dev_${instance}`;
26
+ }
27
+ function hzVar(instance: number): string {
28
+ return `__tc_hw_hz_${instance}`;
29
+ }
30
+ function cbVar(instance: number): string {
31
+ return `__tc_hw_cb_${instance}`;
32
+ }
33
+ /** The trampoline matching counter_top_callback_t: (dev, user_data). */
34
+ function trampVar(instance: number): string {
35
+ return `__tc_hw_tramp_${instance}`;
36
+ }
37
+
38
+ /**
39
+ * Emit the per-instance counter device handles + frequency/callback state.
40
+ * Called from shimLines when the program uses hardware timers.
41
+ */
42
+ export function hwtimerInitLines(chip: ZephyrChipDescriptor): string[] {
43
+ const controllers = chip.hwtimer?.controllers ?? [];
44
+ if (controllers.length === 0) return [];
45
+ const lines: string[] = ['// CUTTLEFISH_HWTIMER_BEGIN'];
46
+ controllers.forEach((c, i) => {
47
+ lines.push(
48
+ `static const struct device* ${devVar(i)} = DEVICE_DT_GET(DT_NODELABEL(${c.nodeLabel}));`,
49
+ `static uint32_t ${hzVar(i)} = 1;`,
50
+ `static void (*${cbVar(i)})(void) = NULL;`,
51
+ `static void ${trampVar(i)}(const struct device* dev, void* user_data) {`,
52
+ ` (void)dev; (void)user_data;`,
53
+ ` if (${cbVar(i)}) { ${cbVar(i)}(); }`,
54
+ `}`,
55
+ );
56
+ });
57
+ lines.push('// CUTTLEFISH_HWTIMER_END');
58
+ return lines;
59
+ }
60
+
61
+ /**
62
+ * Resolve a HAL hwtimer.* op to Zephyr C++.
63
+ * Returns `{ code }` for statement ops.
64
+ */
65
+ export function lowerHwtimer(
66
+ op: HALOpIR,
67
+ chip: ZephyrChipDescriptor,
68
+ ): { code?: string; expression?: string } {
69
+ const o = op as any;
70
+ const controllers = chip.hwtimer?.controllers ?? [];
71
+
72
+ // No counter on this target. Comment + (in profileDiagnostics) a clear error.
73
+ if (controllers.length === 0) {
74
+ return { code: `/* hwtimer instance ${o.instance}: no counter device on ${chip.id} */` };
75
+ }
76
+
77
+ const instance = typeof o.instance === 'number' ? o.instance : parseInt(String(o.instance), 10);
78
+ if (isNaN(instance) || instance < 0 || instance >= controllers.length) {
79
+ return { code: `/* hwtimer instance ${o.instance}: out of range on ${chip.id} */` };
80
+ }
81
+
82
+ switch (op.operation) {
83
+ default:
84
+ throw new Error(
85
+ `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
86
+ `Open an issue or use rawCpp() to emit it manually.`,
87
+ );
88
+ }
89
+ }
90
+
91
+ export function lowerCounter(
92
+ op: HALOpIR,
93
+ chip: ZephyrChipDescriptor,
94
+ ): { code?: string; expression?: string } {
95
+ const o = op as any;
96
+ const controllers = chip.hwtimer?.controllers ?? [];
97
+
98
+ if (controllers.length === 0) {
99
+ return { code: `/* ${op.operation}: no counter device on ${chip.id} */` };
100
+ }
101
+
102
+ const instance = typeof o.instance === 'number' ? o.instance : parseInt(String(o.instance), 10);
103
+ if (isNaN(instance) || instance < 0 || instance >= controllers.length) {
104
+ return { code: `/* counter instance ${o.instance}: out of range on ${chip.id} (${controllers.length} declared) */` };
105
+ }
106
+
107
+ switch (op.operation) {
108
+ case 'counter.on_alarm':
109
+ return { code: `${cbVar(instance)} = (${o.handler});` };
110
+ case 'counter.start': {
111
+ // Apply the construction hz as the top value, arm the alarm callback,
112
+ // start. hz rides the op, so no ordering constraint exists. The API
113
+ // is counter_set_top_value(dev, const counter_top_cfg*) with a
114
+ // (dev, user_data) callback — the trampoline in hwtimerInitLines
115
+ // adapts the user's void() handler.
116
+ return {
117
+ code: [
118
+ `{`,
119
+ ` ${hzVar(instance)} = ${o.hz};`,
120
+ ` uint32_t __f = counter_get_frequency(${devVar(instance)});`,
121
+ ` uint32_t __top = __f ? (__f / ${hzVar(instance)}) : 0U;`,
122
+ ` if (__top > 0U) {`,
123
+ ` struct counter_top_cfg __cfg = { .ticks = __top, .callback = ${trampVar(instance)}, .user_data = NULL, .flags = 0U };`,
124
+ ` (void)counter_set_top_value(${devVar(instance)}, &__cfg);`,
125
+ ` }`,
126
+ ` (void)counter_start(${devVar(instance)});`,
127
+ `}`,
128
+ ].join(' '),
129
+ };
130
+ }
131
+ case 'counter.stop':
132
+ return { code: `(void)counter_stop(${devVar(instance)});` };
133
+ default:
134
+ throw new Error(
135
+ `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
136
+ `Open an issue or use rawCpp() to emit it manually.`,
137
+ );
138
+ }
139
+ }
@@ -1,126 +1,116 @@
1
- // ---------------------------------------------------------------------------
2
- // I2C lowering — transactional txbuf accumulator + per-call i2c_write
3
- //
4
- // Mirrors the ESP32 stateful model but simpler: Zephyr's `i2c_write(bus, buf,
5
- // len, addr)` takes the address per-call, so there's no device-handle cache.
6
- // The begin_transmission → write* → end_transmission sequence accumulates into
7
- // `__tc_i2c<N>_txbuf` and flushes as one `i2c_write` at end_transmission.
8
- // Reads go through request_from → i2c_read into `__tc_i2c<N>_rxbuf`, consumed
9
- // by subsequent i2c.read / i2c.available calls.
10
- //
11
- // The device handle resolves at compile time via DEVICE_DT_GET(DT_NODELABEL(...)).
12
- // ---------------------------------------------------------------------------
13
-
14
- import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
15
- import type { ZephyrChipDescriptor } from '../chips/types.js';
16
- import { parseControllerIndex } from './util.js';
17
-
18
- const TXBUF_SIZE = 32;
19
- const RXBUF_SIZE = 32;
20
-
21
- /** The C variable prefix for a controller's state. */
22
- function prefix(idx: number): string {
23
- return `__tc_i2c${idx}`;
24
- }
25
-
26
- /**
27
- * Emit the per-controller I2C state. Called from shimLines for each
28
- * controller the program uses (gated on ctx.analysis.usesI2C).
29
- */
30
- export function i2cInitLines(chip: ZephyrChipDescriptor, controllerIndex: number): string[] {
31
- const ctrl = chip.i2c?.controllers[controllerIndex];
32
- if (!ctrl) return [];
33
- const p = prefix(controllerIndex);
34
- return [
35
- '// CUTTLEFISH_I2C_BEGIN',
36
- `static const struct device* ${p}_dev = DEVICE_DT_GET(DT_NODELABEL(${ctrl.nodeLabel}));`,
37
- `static uint16_t ${p}_addr = 0xFFFF;`,
38
- `static uint8_t ${p}_txbuf[${TXBUF_SIZE}];`,
39
- `static size_t ${p}_txlen = 0;`,
40
- `static uint8_t ${p}_rxbuf[${RXBUF_SIZE}];`,
41
- `static size_t ${p}_rxlen = 0;`,
42
- `static size_t ${p}_rxpos = 0;`,
43
- '// CUTTLEFISH_I2C_END',
44
- ];
45
- }
46
-
47
- /** Map a clock speed in Hz to an I2C_SPEED_* define. */
48
- function speedForHz(hz: number): string {
49
- if (hz <= 100_000) return 'I2C_SPEED_STANDARD';
50
- if (hz <= 400_000) return 'I2C_SPEED_FAST';
51
- if (hz <= 1_000_000) return 'I2C_SPEED_FAST_PLUS';
52
- return 'I2C_SPEED_HIGH';
53
- }
54
-
55
- /**
56
- * Resolve a HAL i2c.* op to Zephyr C++.
57
- * Returns `{ code }` for statement ops, `{ expression }` for value-returning ops.
58
- */
59
- export function lowerI2c(
60
- op: HALOpIR,
61
- chip: ZephyrChipDescriptor,
62
- ): { code?: string; expression?: string } {
63
- const o = op as any;
64
- const idx = parseControllerIndex(o.bus);
65
- const p = prefix(idx);
66
-
67
- switch (op.operation) {
68
- case 'i2c.begin':
69
- // Zephyr resolves the device at compile time; begin is a no-op (device
70
- // ready check is folded into the driver calls).
71
- return { code: `(void)${p}_dev;` };
72
- case 'i2c.end':
73
- return { code: `(void)${p}_dev;` };
74
- case 'i2c.set_clock': {
75
- const hz = typeof o.hz === 'number' ? o.hz : parseInt(String(o.hz), 10);
76
- const speed = isNaN(hz) ? 'I2C_SPEED_STANDARD' : speedForHz(hz || 100000);
77
- return { code: `i2c_configure(${p}_dev, I2C_SPEED_SET(${speed}));` };
78
- }
79
- case 'i2c.begin_transmission':
80
- // Record the target address + reset the pending write buffer.
81
- return { code: `${p}_addr = static_cast<uint16_t>(${o.address}); ${p}_txlen = 0;` };
82
- case 'i2c.write':
83
- // Append one byte (clamped to capacity).
84
- return { code: `if (${p}_txlen < ${TXBUF_SIZE}) { ${p}_txbuf[${p}_txlen++] = static_cast<uint8_t>(${o.data}); }` };
85
- case 'i2c.write_bytes': {
86
- const bytes: unknown[] = o.bytes ?? [];
87
- const stmts = bytes.map(
88
- (b) => `if (${p}_txlen < ${TXBUF_SIZE}) { ${p}_txbuf[${p}_txlen++] = static_cast<uint8_t>(${b}); }`,
89
- );
90
- return { code: stmts.join(' ') };
91
- }
92
- case 'i2c.write_buffer': {
93
- // Copy from a user buffer (its name is o.data), clamped to capacity.
94
- return {
95
- code: `for (size_t __i = 0; __i < sizeof(${o.data}) && ${p}_txlen < ${TXBUF_SIZE}; __i++) { ${p}_txbuf[${p}_txlen++] = reinterpret_cast<const uint8_t*>(${o.data})[__i]; }`,
96
- };
97
- }
98
- case 'i2c.end_transmission':
99
- // Flush the accumulated txbuf to the cached address.
100
- return { code: `i2c_write(${p}_dev, ${p}_txbuf, ${p}_txlen, ${p}_addr);` };
101
- case 'i2c.request_from': {
102
- const qty = o.quantity;
103
- return {
104
- code: `i2c_read(${p}_dev, ${p}_rxbuf, static_cast<uint32_t>(${qty}), static_cast<uint16_t>(${o.address})); ${p}_rxlen = ${qty}; ${p}_rxpos = 0;`,
105
- };
106
- }
107
- case 'i2c.available':
108
- return { expression: `(${p}_rxlen - ${p}_rxpos)` };
109
- case 'i2c.read':
110
- return { expression: `(${p}_rxpos < ${p}_rxlen ? ${p}_rxbuf[${p}_rxpos++] : -1)` };
111
- case 'i2c.read_buffer': {
112
- // Read straight into the user's buffer (o.buffer), count bytes.
113
- const count = o.count;
114
- return {
115
- code: `i2c_read(${p}_dev, reinterpret_cast<uint8_t*>(${o.buffer}), static_cast<uint32_t>(${count}), ${p}_addr);`,
116
- };
117
- }
118
- case 'i2c.recover':
119
- return { code: `i2c_recover_bus(${p}_dev);` };
120
- default:
121
- throw new Error(
122
- `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
123
- `Open an issue or use rawCpp() to emit it manually.`,
124
- );
125
- }
126
- }
1
+ // ---------------------------------------------------------------------------
2
+ // I2C lowering — transactional txbuf accumulator + per-call i2c_write
3
+ //
4
+ // Mirrors the ESP32 stateful model but simpler: Zephyr's `i2c_write(bus, buf,
5
+ // len, addr)` takes the address per-call, so there's no device-handle cache.
6
+ // The begin_transmission → write* → end_transmission sequence accumulates into
7
+ // `__tc_i2c<N>_txbuf` and flushes as one `i2c_write` at end_transmission.
8
+ // Reads go through request_from → i2c_read into `__tc_i2c<N>_rxbuf`, consumed
9
+ // by subsequent i2c.read / i2c.available calls.
10
+ //
11
+ // The device handle resolves at compile time via DEVICE_DT_GET(DT_NODELABEL(...)).
12
+ // ---------------------------------------------------------------------------
13
+
14
+ import type { HALOpIR } from '@typecad/cuttlefish/api/shared';
15
+ import type { ZephyrChipDescriptor } from '../chips/types.js';
16
+ import { parseControllerIndex } from './util.js';
17
+
18
+ /** The C variable prefix for a controller's state. */
19
+ function prefix(idx: number): string {
20
+ return `__tc_i2c${idx}`;
21
+ }
22
+
23
+ /**
24
+ * Emit the per-controller I2C state. Called from shimLines for each
25
+ * controller the program uses (gated on ctx.analysis.usesI2C).
26
+ */
27
+ export function i2cInitLines(chip: ZephyrChipDescriptor, controllerIndex: number): string[] {
28
+ const ctrl = chip.i2c?.controllers[controllerIndex];
29
+ if (!ctrl) return [];
30
+ const p = prefix(controllerIndex);
31
+ return [
32
+ '// CUTTLEFISH_I2C_BEGIN',
33
+ `static const struct device* ${p}_dev = DEVICE_DT_GET(DT_NODELABEL(${ctrl.nodeLabel}));`,
34
+ '// CUTTLEFISH_I2C_END',
35
+ ];
36
+ }
37
+
38
+ /** Map a clock speed in Hz to an I2C_SPEED_* define. */
39
+ function speedForHz(hz: number): string {
40
+ if (hz <= 100_000) return 'I2C_SPEED_STANDARD';
41
+ if (hz <= 400_000) return 'I2C_SPEED_FAST';
42
+ if (hz <= 1_000_000) return 'I2C_SPEED_FAST_PLUS';
43
+ return 'I2C_SPEED_HIGH';
44
+ }
45
+
46
+ /**
47
+ * The (void) comma expression begin/end lower to a no-op that references
48
+ * the controller's whole state block (device + transaction buffers) so a
49
+ * program calling only begin() stays -Werror clean (-Wunused-variable).
50
+ */
51
+ function i2cKeepAlive(p: string): string {
52
+ return `(void)${p}_dev;`;
53
+ }
54
+
55
+ /** The thin-device bus-speed preamble: apply the construction hz once
56
+ * (i2c_configure with Zephyr's I2C_SPEED_SET tier mapping), or '' when the
57
+ * target constructed without hz. Guarded per controller, so the cost after
58
+ * the first op is one bool test. */
59
+ function i2cSpeedGuard(p: string, hz: unknown): string {
60
+ const n = typeof hz === 'number' ? hz : parseInt(String(hz ?? 0), 10);
61
+ if (!n || isNaN(n)) return '';
62
+ const speed = speedForHz(n);
63
+ const done = `${p}_spd_done`;
64
+ return `{ static bool ${done} = false; if (!${done}) { (void)i2c_configure(${p}_dev, I2C_SPEED_SET(${speed})); ${done} = true; } } `;
65
+ }
66
+
67
+ /**
68
+ * Resolve a HAL i2c.* op to Zephyr C++.
69
+ * Returns `{ code }` for statement ops, `{ expression }` for value-returning ops.
70
+ */
71
+ export function lowerI2c(
72
+ op: HALOpIR,
73
+ chip: ZephyrChipDescriptor,
74
+ ): { code?: string; expression?: string } {
75
+ const o = op as any;
76
+ const idx = parseControllerIndex(o.bus);
77
+ const p = prefix(idx);
78
+
79
+ switch (op.operation) {
80
+ // ── Thin I2C device (hal/i2c-target.ts) Zephyr register verbs ──────
81
+ // One call per op against the controller device handle; the optional
82
+ // construction hz applies once via a guarded i2c_configure (the same
83
+ // call i2c.set_clock lowers to).
84
+ case 'i2c.reg_write': {
85
+ const pre = i2cSpeedGuard(p, o.hz);
86
+ return { code: `${pre} i2c_reg_write_byte(${p}_dev, static_cast<uint16_t>(${o.address}), static_cast<uint8_t>(${o.reg}), static_cast<uint8_t>(${o.value}));` };
87
+ }
88
+ case 'i2c.reg_read': {
89
+ const pre = i2cSpeedGuard(p, o.hz);
90
+ return { expression: `({ ${pre} uint8_t __v = 0; (void)i2c_reg_read_byte(${p}_dev, static_cast<uint16_t>(${o.address}), static_cast<uint8_t>(${o.reg}), &__v); __v; })` };
91
+ }
92
+ case 'i2c.reg_update': {
93
+ const pre = i2cSpeedGuard(p, o.hz);
94
+ return { code: `${pre} (void)i2c_reg_update_byte(${p}_dev, static_cast<uint16_t>(${o.address}), static_cast<uint8_t>(${o.reg}), static_cast<uint8_t>(${o.mask}), static_cast<uint8_t>(${o.value}));` };
95
+ }
96
+ case 'i2c.dev_write': {
97
+ const pre = i2cSpeedGuard(p, o.hz);
98
+ const bytes: unknown[] = o.bytes ?? [];
99
+ // Identifier-shaped only a single-byte literal array arrives as
100
+ // numeric text ("159") and must take the literal path.
101
+ const isBuffer = bytes.length === 1 && typeof bytes[0] === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(bytes[0] as string);
102
+ if (isBuffer) {
103
+ const name = bytes[0] as string;
104
+ // A named user buffer: i2c_write against its storage directly.
105
+ return { code: `${pre} (void)i2c_write(${p}_dev, reinterpret_cast<const uint8_t*>(${name}), sizeof(${name}), static_cast<uint16_t>(${o.address}));` };
106
+ }
107
+ const arr = `static const uint8_t __tc_i2cw[] = { ${bytes.join(', ')} };`;
108
+ return { code: `${pre} ${arr} (void)i2c_write(${p}_dev, __tc_i2cw, sizeof(__tc_i2cw), static_cast<uint16_t>(${o.address}));` };
109
+ }
110
+ default:
111
+ throw new Error(
112
+ `framework-zephyr does not yet support HAL op \`${op.operation}\`. ` +
113
+ `Open an issue or use rawCpp() to emit it manually.`,
114
+ );
115
+ }
116
+ }