traceforge-pcb 1.0.0__py3-none-any.whl

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 (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,466 @@
1
+ """Project scaffolds for Arduino, PlatformIO, ESP-IDF, STM32 (bare CMake/Make) and AVR."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+
9
+ from traceforge.firmware.drivers import HAL_H, generate_driver, hal_arduino
10
+ from traceforge.firmware.pinmap import HEADER_FILES, PinAssignment, PinMap, render_header
11
+
12
+ TARGETS = ("arduino", "platformio", "esp-idf", "stm32", "avr")
13
+ MANIFEST = "tf_firmware.json"
14
+
15
+ # The pin header style per target (C++ sketches take the C header too).
16
+ _STYLE = {"arduino": "c", "platformio": "c", "esp-idf": "c", "stm32": "c", "avr": "c"}
17
+
18
+
19
+ class ScaffoldError(Exception):
20
+ pass
21
+
22
+
23
+ def default_target(pm: PinMap) -> str:
24
+ return {"avr": "avr", "esp32": "platformio", "stm32": "stm32"}[pm.mcu.family]
25
+
26
+
27
+ def _usable(pm: PinMap) -> tuple[list[PinAssignment], list[PinAssignment]]:
28
+ """(outputs, inputs) that the demo main may drive: plain GPIO nets with a pin number."""
29
+ outs: list[PinAssignment] = []
30
+ ins: list[PinAssignment] = []
31
+ for a in pm.assignments:
32
+ if a.function != "GPIO" or a.number is None:
33
+ continue
34
+ if any("not usable" in w or "RESET pin" in w or "strapping" in w for w in a.warnings):
35
+ continue
36
+ if a.net.upper() in {"RESET", "NRST", "EN"}:
37
+ continue
38
+ (ins if a.direction == "in" else outs).append(a)
39
+ return outs, ins
40
+
41
+
42
+ def _files_arduino_like(pm: PinMap, outs, ins) -> str:
43
+ lines = ["#include <Arduino.h>", '#include "pins.h"', "", "void setup() {"]
44
+ for a in outs:
45
+ lines.append(f" pinMode(PIN_{a.macro}, OUTPUT);")
46
+ for a in ins:
47
+ lines.append(f" pinMode(PIN_{a.macro}, {'INPUT_PULLUP' if a.pull_up else 'INPUT'});")
48
+ lines += ["}", "", "void loop() {"]
49
+ if outs and ins:
50
+ lines += [
51
+ f" // {outs[0].net} follows {ins[0].net} (pressed = low)",
52
+ f" digitalWrite(PIN_{outs[0].macro}, digitalRead(PIN_{ins[0].macro}) ? LOW : HIGH);",
53
+ " delay(10);",
54
+ ]
55
+ elif outs:
56
+ lines += [
57
+ f" digitalWrite(PIN_{outs[0].macro}, HIGH);",
58
+ " delay(500);",
59
+ f" digitalWrite(PIN_{outs[0].macro}, LOW);",
60
+ " delay(500);",
61
+ ]
62
+ else:
63
+ lines += [" delay(1000);"]
64
+ lines += ["}", ""]
65
+ return "\n".join(lines)
66
+
67
+
68
+ def _main_avr(pm: PinMap, outs, ins) -> str:
69
+ lines = [
70
+ f"#ifndef F_CPU\n#define F_CPU {pm.mcu.f_cpu}UL\n#endif",
71
+ "#include <avr/io.h>",
72
+ "#include <util/delay.h>",
73
+ '#include "pins.h"',
74
+ "",
75
+ "int main(void) {",
76
+ ]
77
+ for a in outs:
78
+ lines.append(f" PIN_{a.macro}_DDR |= _BV(PIN_{a.macro}_BIT);")
79
+ for a in ins:
80
+ lines.append(f" PIN_{a.macro}_PORT |= _BV(PIN_{a.macro}_BIT); /* pull-up */")
81
+ lines += [" for (;;) {"]
82
+ if outs and ins:
83
+ o, i = outs[0].macro, ins[0].macro
84
+ lines += [
85
+ f" if (PIN_{i}_PINREG & _BV(PIN_{i}_BIT)) PIN_{o}_PORT &= ~_BV(PIN_{o}_BIT);",
86
+ f" else PIN_{o}_PORT |= _BV(PIN_{o}_BIT);",
87
+ " _delay_ms(10);",
88
+ ]
89
+ elif outs:
90
+ o = outs[0].macro
91
+ lines += [f" PIN_{o}_PORT ^= _BV(PIN_{o}_BIT);", " _delay_ms(500);"]
92
+ else:
93
+ lines += [" _delay_ms(1000);"]
94
+ lines += [" }", "}", ""]
95
+ return "\n".join(lines)
96
+
97
+
98
+ def _main_idf(pm: PinMap, outs, ins) -> str:
99
+ lines = [
100
+ '#include "driver/gpio.h"',
101
+ '#include "freertos/FreeRTOS.h"',
102
+ '#include "freertos/task.h"',
103
+ '#include "pins.h"',
104
+ "",
105
+ "void app_main(void) {",
106
+ ]
107
+ for a in outs:
108
+ lines.append(f" gpio_set_direction(PIN_{a.macro}, GPIO_MODE_OUTPUT);")
109
+ for a in ins:
110
+ lines.append(f" gpio_set_direction(PIN_{a.macro}, GPIO_MODE_INPUT);")
111
+ lines.append(f" gpio_set_pull_mode(PIN_{a.macro}, GPIO_PULLUP_ONLY);")
112
+ lines.append(" for (;;) {")
113
+ if outs and ins:
114
+ lines.append(
115
+ f" gpio_set_level(PIN_{outs[0].macro}, !gpio_get_level(PIN_{ins[0].macro}));"
116
+ )
117
+ lines.append(" vTaskDelay(pdMS_TO_TICKS(10));")
118
+ elif outs:
119
+ lines += [
120
+ f" gpio_set_level(PIN_{outs[0].macro}, 1);",
121
+ " vTaskDelay(pdMS_TO_TICKS(500));",
122
+ f" gpio_set_level(PIN_{outs[0].macro}, 0);",
123
+ " vTaskDelay(pdMS_TO_TICKS(500));",
124
+ ]
125
+ else:
126
+ lines.append(" vTaskDelay(pdMS_TO_TICKS(1000));")
127
+ lines += [" }", "}", ""]
128
+ return "\n".join(lines)
129
+
130
+
131
+ def _main_stm32(pm: PinMap, outs, ins) -> str:
132
+ lines = [
133
+ "/* Register-level STM32F1 GPIO (RM0008 section 9). No vendor library needed. */",
134
+ "#include <stdint.h>",
135
+ '#include "pins.h"',
136
+ "",
137
+ "#define RCC_APB2ENR (*(volatile uint32_t *)0x40021018u)",
138
+ "#define GPIO_BASE(p) (0x40010800u + 0x400u * (uint32_t)((p) - 'A'))",
139
+ "#define GPIO_CR(p, pin) (*(volatile uint32_t *)(GPIO_BASE(p) + ((pin) >= 8 ? 4u : 0u)))",
140
+ "#define GPIO_IDR(p) (*(volatile uint32_t *)(GPIO_BASE(p) + 0x08u))",
141
+ "#define GPIO_BSRR(p) (*(volatile uint32_t *)(GPIO_BASE(p) + 0x10u))",
142
+ "",
143
+ "static void mode(char port, int pin, uint32_t cnf_mode) {",
144
+ " RCC_APB2ENR |= 1u << (2 + (port - 'A'));",
145
+ " uint32_t shift = (uint32_t)(pin % 8) * 4u;",
146
+ " GPIO_CR(port, pin) = (GPIO_CR(port, pin) & ~(0xFu << shift)) | (cnf_mode << shift);",
147
+ "}",
148
+ 'static void delay(volatile uint32_t n) { while (n--) { __asm__ volatile("nop"); } }',
149
+ "",
150
+ "int main(void) {",
151
+ ]
152
+ for a in outs:
153
+ lines.append(
154
+ f" mode(PIN_{a.macro}_PORT, PIN_{a.macro}_PIN, 0x2u); /* output 2 MHz push-pull */"
155
+ )
156
+ for a in ins:
157
+ m = a.macro
158
+ lines.append(f" mode(PIN_{m}_PORT, PIN_{m}_PIN, 0x8u); /* input pull-up/down */")
159
+ lines.append(f" GPIO_BSRR(PIN_{m}_PORT) = 1u << PIN_{m}_PIN; /* pull-up */")
160
+ lines.append(" for (;;) {")
161
+ if outs:
162
+ o = outs[0].macro
163
+ if ins:
164
+ i = ins[0].macro
165
+ lines += [
166
+ f" if (GPIO_IDR(PIN_{i}_PORT) & (1u << PIN_{i}_PIN)) GPIO_BSRR(PIN_{o}_PORT) = 1u << (PIN_{o}_PIN + 16);",
167
+ f" else GPIO_BSRR(PIN_{o}_PORT) = 1u << PIN_{o}_PIN;",
168
+ ]
169
+ else:
170
+ lines += [
171
+ f" GPIO_BSRR(PIN_{o}_PORT) = 1u << PIN_{o}_PIN;",
172
+ " delay(400000);",
173
+ f" GPIO_BSRR(PIN_{o}_PORT) = 1u << (PIN_{o}_PIN + 16);",
174
+ " delay(400000);",
175
+ ]
176
+ lines += [" }", "}", ""]
177
+ return "\n".join(lines)
178
+
179
+
180
+ _STM32_STARTUP = """\
181
+ /* Minimal Cortex-M3 start-up: vector table, data/bss init, call main. */
182
+ #include <stdint.h>
183
+ extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
184
+ int main(void);
185
+ void Reset_Handler(void) {
186
+ uint32_t *src = &_sidata;
187
+ for (uint32_t *dst = &_sdata; dst < &_edata;) *dst++ = *src++;
188
+ for (uint32_t *dst = &_sbss; dst < &_ebss;) *dst++ = 0;
189
+ main();
190
+ for (;;) {}
191
+ }
192
+ void Default_Handler(void) { for (;;) {} }
193
+ __attribute__((section(".isr_vector"), used))
194
+ const void *const vectors[] = {&_estack, Reset_Handler, Default_Handler, Default_Handler};
195
+ """
196
+
197
+ _STM32_LD = """\
198
+ /* STM32F103C8: 64 KB flash, 20 KB RAM (datasheet DS5319 table 2; many boards have 128 KB). */
199
+ MEMORY {
200
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K
201
+ RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 20K
202
+ }
203
+ _estack = ORIGIN(RAM) + LENGTH(RAM);
204
+ SECTIONS {
205
+ .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
206
+ .text : { *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
207
+ _sidata = LOADADDR(.data);
208
+ .data : { _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT > FLASH
209
+ .bss : { _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
210
+ }
211
+ """
212
+
213
+ _STM32_MAKEFILE = """\
214
+ # Bare-metal STM32F103 (Cortex-M3) project: no HAL, no CMSIS, register-level code only.
215
+ # Limits: no clock setup (runs on the 8 MHz HSI), no interrupts, no peripherals besides GPIO.
216
+ # For real work add STM32Cube (HAL/LL) and replace startup.c and link.ld with ST's files.
217
+ PREFIX ?= arm-none-eabi-
218
+ CC = $(PREFIX)gcc
219
+ CFLAGS = -mcpu=cortex-m3 -mthumb -Os -Wall -Wextra -ffreestanding -ffunction-sections -fdata-sections
220
+ LDFLAGS = -nostdlib -T link.ld -Wl,--gc-sections -Wl,-Map=firmware.map
221
+
222
+ all: firmware.elf firmware.bin size
223
+
224
+ firmware.elf: main.c startup.c pins.h link.ld
225
+ \t$(CC) $(CFLAGS) main.c startup.c $(LDFLAGS) -o $@
226
+
227
+ firmware.bin: firmware.elf
228
+ \t$(PREFIX)objcopy -O binary $< $@
229
+
230
+ size: firmware.elf
231
+ \t$(PREFIX)size $<
232
+
233
+ flash: firmware.bin
234
+ \tst-flash write firmware.bin 0x8000000
235
+
236
+ clean:
237
+ \trm -f firmware.elf firmware.bin firmware.map
238
+ """
239
+
240
+ _STM32_CMAKE = """\
241
+ cmake_minimum_required(VERSION 3.16)
242
+ set(CMAKE_SYSTEM_NAME Generic)
243
+ set(CMAKE_SYSTEM_PROCESSOR arm)
244
+ set(CMAKE_C_COMPILER arm-none-eabi-gcc)
245
+ set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
246
+ project({name} C)
247
+ add_executable(firmware main.c startup.c)
248
+ target_compile_options(firmware PRIVATE -mcpu=cortex-m3 -mthumb -Os -Wall -ffreestanding)
249
+ target_link_options(firmware PRIVATE -nostdlib -T${{CMAKE_SOURCE_DIR}}/link.ld -Wl,--gc-sections)
250
+ """
251
+
252
+
253
+ def _avr_makefile(pm: PinMap, name: str, sources: list[str]) -> str:
254
+ mcu = pm.mcu.key
255
+ return f"""\
256
+ # avr-gcc build for {pm.mcu.name} ({mcu}). Flash with an ISP programmer (the board's ISP header).
257
+ MCU = {mcu}
258
+ F_CPU = {pm.mcu.f_cpu}UL
259
+ PROGRAMMER ?= usbasp
260
+ SRC = {" ".join(sources)}
261
+
262
+ CFLAGS = -mmcu=$(MCU) -DF_CPU=$(F_CPU) -Os -Wall -Wextra -std=gnu11 -ffunction-sections -fdata-sections
263
+ LDFLAGS = -mmcu=$(MCU) -Wl,--gc-sections
264
+
265
+ all: firmware.hex size
266
+
267
+ firmware.elf: $(SRC) pins.h
268
+ \tavr-gcc $(CFLAGS) $(SRC) $(LDFLAGS) -o $@
269
+
270
+ firmware.hex: firmware.elf
271
+ \tavr-objcopy -O ihex -R .eeprom $< $@
272
+
273
+ size: firmware.elf
274
+ \tavr-size --mcu=$(MCU) -C $<
275
+
276
+ flash: firmware.hex
277
+ \tavrdude -c $(PROGRAMMER) -p {mcu} -U flash:w:firmware.hex:i
278
+
279
+ clean:
280
+ \trm -f firmware.elf firmware.hex
281
+ """
282
+
283
+
284
+ def scaffold(
285
+ pm: PinMap,
286
+ out: str | Path,
287
+ target: str | None = None,
288
+ name: str | None = None,
289
+ drivers: list[str] | None = None,
290
+ source: str = "the netlist",
291
+ overwrite: bool = False,
292
+ ) -> list[Path]:
293
+ """Write a project for ``target`` into ``out``; return the files written."""
294
+ target = target or default_target(pm)
295
+ if target not in TARGETS:
296
+ raise ScaffoldError(f"unknown target {target!r} (use {', '.join(TARGETS)})")
297
+ fam = pm.mcu.family
298
+ allowed = {
299
+ "avr": {"avr"},
300
+ "esp-idf": {"esp32"},
301
+ "stm32": {"stm32"},
302
+ "arduino": {"avr", "esp32"},
303
+ "platformio": {"avr", "esp32"},
304
+ }[target]
305
+ if fam not in allowed:
306
+ raise ScaffoldError(f"target {target} does not fit {pm.mcu.name} ({fam})")
307
+ name = re.sub(r"[^A-Za-z0-9_]", "_", name or "firmware")
308
+ out = Path(out)
309
+ files: dict[str, str] = {}
310
+ outs, ins = _usable(pm)
311
+ header = render_header(pm, _STYLE[target], source)
312
+ drivers = drivers or []
313
+ driver_files: dict[str, str] = {}
314
+ for part in drivers:
315
+ driver_files.update(generate_driver(part))
316
+ if driver_files:
317
+ driver_files["tf_hal.h"] = HAL_H
318
+
319
+ def put(rel: str, text: str) -> None:
320
+ files[rel] = text
321
+
322
+ sources_c = [f for f in driver_files if f.endswith(".c")]
323
+ if target == "arduino":
324
+ base = f"{name}/"
325
+ put(f"{base}{name}.ino", _files_arduino_like(pm, outs, ins))
326
+ put(f"{base}pins.h", header)
327
+ for f, t in driver_files.items():
328
+ put(base + f, t)
329
+ if driver_files:
330
+ put(f"{base}tf_hal_arduino.cpp", hal_arduino())
331
+ put(MANIFEST, json.dumps(_manifest(pm, target, name, fqbn=pm.mcu.fqbn), indent=2) + "\n")
332
+ elif target == "platformio":
333
+ pio = pm.mcu.platformio
334
+ ini = [f"[env:{pio['board']}]", f"platform = {pio['platform']}", f"board = {pio['board']}",
335
+ f"framework = {pio['framework']}"] # fmt: skip
336
+ if fam == "avr":
337
+ ini.append(f"board_build.f_cpu = {pm.mcu.f_cpu}L")
338
+ if fam == "esp32":
339
+ ini += ["monitor_speed = 115200", "build_flags = -DARDUINO_USB_CDC_ON_BOOT=1"]
340
+ put("platformio.ini", "\n".join(ini) + "\n")
341
+ put("include/pins.h", header)
342
+ put("src/main.cpp", _files_arduino_like(pm, outs, ins))
343
+ for f, t in driver_files.items():
344
+ put(f"{'include' if f.endswith('.h') else 'src'}/{f}", t)
345
+ if driver_files:
346
+ put("src/tf_hal_arduino.cpp", hal_arduino())
347
+ put(MANIFEST, json.dumps(_manifest(pm, target, name), indent=2) + "\n")
348
+ elif target == "esp-idf":
349
+ put("CMakeLists.txt", "cmake_minimum_required(VERSION 3.16)\n"
350
+ "include($ENV{IDF_PATH}/tools/cmake/project.cmake)\n" f"project({name})\n") # fmt: skip
351
+ srcs = " ".join(f'"{s}"' for s in ["main.c", *sources_c])
352
+ put("main/CMakeLists.txt", f'idf_component_register(SRCS {srcs} INCLUDE_DIRS ".")\n')
353
+ put("main/main.c", _main_idf(pm, outs, ins))
354
+ put("main/pins.h", header)
355
+ for f, t in driver_files.items():
356
+ put(f"main/{f}", t)
357
+ if driver_files:
358
+ put("main/tf_hal_idf.c", _hal_idf())
359
+ put(
360
+ "main/CMakeLists.txt",
361
+ f'idf_component_register(SRCS {srcs} "tf_hal_idf.c" INCLUDE_DIRS ".")\n',
362
+ )
363
+ put("sdkconfig.defaults", 'CONFIG_IDF_TARGET="esp32s3"\n')
364
+ put(MANIFEST, json.dumps(_manifest(pm, target, name), indent=2) + "\n")
365
+ elif target == "stm32":
366
+ put("main.c", _main_stm32(pm, outs, ins))
367
+ put("pins.h", header)
368
+ put("startup.c", _STM32_STARTUP)
369
+ put("link.ld", _STM32_LD)
370
+ put("Makefile", _STM32_MAKEFILE)
371
+ put("CMakeLists.txt", _STM32_CMAKE.format(name=name))
372
+ put(MANIFEST, json.dumps(_manifest(pm, target, name), indent=2) + "\n")
373
+ else: # avr
374
+ put("main.c", _main_avr(pm, outs, ins))
375
+ put("pins.h", header)
376
+ for f, t in driver_files.items():
377
+ put(f, t)
378
+ put("Makefile", _avr_makefile(pm, name, ["main.c", *sources_c]))
379
+ put(MANIFEST, json.dumps(_manifest(pm, target, name), indent=2) + "\n")
380
+ put("README.md", _readme(pm, target, name, drivers))
381
+ written: list[Path] = []
382
+ for rel in files:
383
+ path = out / rel
384
+ if path.exists() and not overwrite:
385
+ raise ScaffoldError(f"{path} exists (use --overwrite)")
386
+ for rel, text in files.items():
387
+ path = out / rel
388
+ path.parent.mkdir(parents=True, exist_ok=True)
389
+ path.write_text(text, encoding="utf-8")
390
+ written.append(path)
391
+ return written
392
+
393
+
394
+ def _manifest(pm: PinMap, target: str, name: str, fqbn: str = "") -> dict:
395
+ data = {"target": target, "mcu": pm.mcu.key, "name": name, "header": HEADER_FILES["c"]}
396
+ if fqbn:
397
+ data["fqbn"] = fqbn
398
+ return data
399
+
400
+
401
+ def _hal_idf() -> str:
402
+ return """\
403
+ /* ESP-IDF implementation of tf_hal.h (new I2C master driver, port 0). Fill in the pins
404
+ with PIN_I2C_SDA / PIN_I2C_SCL from pins.h and create the bus in app_main. */
405
+ #include "driver/i2c_master.h"
406
+ #include "esp_rom_sys.h"
407
+ #include "freertos/FreeRTOS.h"
408
+ #include "freertos/task.h"
409
+ #include "tf_hal.h"
410
+
411
+ i2c_master_bus_handle_t tf_i2c_bus;
412
+ static i2c_master_dev_handle_t dev_for(uint8_t addr) {
413
+ i2c_master_dev_handle_t dev;
414
+ i2c_device_config_t cfg = {.dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = addr, .scl_speed_hz = 100000};
415
+ return i2c_master_bus_add_device(tf_i2c_bus, &cfg, &dev) == ESP_OK ? dev : NULL;
416
+ }
417
+ int tf_i2c_write(uint8_t addr, const uint8_t *data, size_t len) {
418
+ i2c_master_dev_handle_t d = dev_for(addr);
419
+ int r = d ? i2c_master_transmit(d, data, len, 100) : 1;
420
+ if (d) i2c_master_bus_rm_device(d);
421
+ return r != ESP_OK;
422
+ }
423
+ int tf_i2c_read(uint8_t addr, uint8_t *data, size_t len) {
424
+ i2c_master_dev_handle_t d = dev_for(addr);
425
+ int r = d ? i2c_master_receive(d, data, len, 100) : 1;
426
+ if (d) i2c_master_bus_rm_device(d);
427
+ return r != ESP_OK;
428
+ }
429
+ void tf_delay_ms(uint32_t ms) { vTaskDelay(pdMS_TO_TICKS(ms)); }
430
+ void tf_delay_us(uint32_t us) { esp_rom_delay_us(us); }
431
+ void tf_pin_output_low(int pin) {}
432
+ void tf_pin_release(int pin) {}
433
+ int tf_pin_read(int pin) { return 0; }
434
+ """
435
+
436
+
437
+ def _readme(pm: PinMap, target: str, name: str, drivers: list[str]) -> str:
438
+ build = {
439
+ "arduino": f"arduino-cli compile --fqbn {pm.mcu.fqbn or '<board fqbn>'} {name}",
440
+ "platformio": "pio run",
441
+ "esp-idf": "idf.py set-target esp32s3 && idf.py build",
442
+ "stm32": "make (needs arm-none-eabi-gcc)",
443
+ "avr": "make (needs avr-gcc and avr-libc)",
444
+ }[target]
445
+ lines = [
446
+ f"# {name}",
447
+ "",
448
+ f"Firmware scaffold for {pm.mcu.name} ({pm.ref}), target `{target}`, generated by",
449
+ "`traceforge firmware scaffold`. The pin header is generated from the schematic nets;",
450
+ "regenerate it with `traceforge firmware pins` instead of editing it.",
451
+ "",
452
+ f"Build: `{build}`",
453
+ "",
454
+ "## Pins",
455
+ "",
456
+ "| Net | MCU pin | Function |",
457
+ "| --- | --- | --- |",
458
+ ]
459
+ for a in pm.assignments:
460
+ lines.append(f"| {a.net} | {a.pin_name} (pin {a.pin}) | {a.function} |")
461
+ if drivers:
462
+ lines += ["", "## Drivers", "", "Generated: " + ", ".join(drivers) + ". They call `tf_hal.h`;"
463
+ " the project includes an implementation for this target."] # fmt: skip
464
+ if pm.warnings:
465
+ lines += ["", "## Warnings", ""] + [f"- {w}" for w in pm.warnings]
466
+ return "\n".join(lines) + "\n"