dsh-stm32 0.1.8 → 0.1.9

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 (127) hide show
  1. package/README.md +567 -409
  2. package/README_EN.md +544 -410
  3. package/client/client.js +7033 -5021
  4. package/docs/reading-guide.md +921 -921
  5. package/lib/client.js +7033 -5021
  6. package/lib/commands/register.js +2 -0
  7. package/lib/data/firmware-packages.js +35 -0
  8. package/lib/data/firmware-pins.js +7 -0
  9. package/lib/data/install-guides.js +110 -0
  10. package/lib/data/ioc-presets.js +118 -0
  11. package/lib/engine/build.js +88 -2
  12. package/lib/engine/datasheet/auto.js +74 -0
  13. package/lib/engine/datasheet/digest.js +74 -0
  14. package/lib/engine/datasheet/lcsc.js +60 -0
  15. package/lib/engine/datasheet/pinout.js +119 -0
  16. package/lib/engine/datasheet/price.js +152 -0
  17. package/lib/engine/datasheet/search.js +147 -0
  18. package/lib/engine/datasheet/store.js +371 -0
  19. package/lib/engine/debug-session.js +2 -1
  20. package/lib/engine/ecad/autobuild.js +156 -0
  21. package/lib/engine/ecad/bom.js +238 -0
  22. package/lib/engine/ecad/brief.js +205 -0
  23. package/lib/engine/ecad/checks.js +239 -0
  24. package/lib/engine/ecad/design.js +177 -0
  25. package/lib/engine/ecad/dfm.js +314 -0
  26. package/lib/engine/ecad/easyeda.js +454 -0
  27. package/lib/engine/ecad/fabrication.js +104 -0
  28. package/lib/engine/ecad/gen/footprint.js +159 -0
  29. package/lib/engine/ecad/gen/symbol.js +103 -0
  30. package/lib/engine/ecad/import.js +372 -0
  31. package/lib/engine/ecad/jlcpcb.js +141 -0
  32. package/lib/engine/ecad/libs.js +316 -0
  33. package/lib/engine/ecad/models3d.js +89 -0
  34. package/lib/engine/ecad/netgate.js +286 -0
  35. package/lib/engine/ecad/normalize.js +182 -0
  36. package/lib/engine/ecad/package.js +126 -0
  37. package/lib/engine/ecad/padmerge.js +128 -0
  38. package/lib/engine/ecad/padprecheck.js +123 -0
  39. package/lib/engine/ecad/part-import.js +257 -0
  40. package/lib/engine/ecad/pcb/apply.js +53 -0
  41. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  42. package/lib/engine/ecad/pcb/emc.js +275 -0
  43. package/lib/engine/ecad/pcb/geometry.js +63 -0
  44. package/lib/engine/ecad/pcb/gerber.js +499 -0
  45. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  46. package/lib/engine/ecad/pcb/impedance.js +119 -0
  47. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  48. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  49. package/lib/engine/ecad/pcb/ipc.js +129 -0
  50. package/lib/engine/ecad/pcb/krt.js +182 -0
  51. package/lib/engine/ecad/pcb/links.js +393 -0
  52. package/lib/engine/ecad/pcb/mech.js +201 -0
  53. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  54. package/lib/engine/ecad/pcb/netlist.js +146 -0
  55. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  56. package/lib/engine/ecad/pcb/placement.js +140 -0
  57. package/lib/engine/ecad/pcb/power.js +203 -0
  58. package/lib/engine/ecad/pcb/render3d.js +208 -0
  59. package/lib/engine/ecad/pcb/route.js +167 -0
  60. package/lib/engine/ecad/pcb/router.js +469 -0
  61. package/lib/engine/ecad/pcb/rules.js +122 -0
  62. package/lib/engine/ecad/pcb/scene.js +513 -0
  63. package/lib/engine/ecad/pcb/stackup.js +154 -0
  64. package/lib/engine/ecad/pcb/swap.js +222 -0
  65. package/lib/engine/ecad/pcb/tracks.js +70 -0
  66. package/lib/engine/ecad/runtime.js +227 -0
  67. package/lib/engine/ecad/toolchain.js +146 -0
  68. package/lib/engine/ecad/tsci.js +362 -0
  69. package/lib/engine/ecad/zip.js +98 -0
  70. package/lib/engine/generate-script.js +4 -1
  71. package/lib/engine/generate.js +145 -5
  72. package/lib/engine/ioc-plan.js +12 -2
  73. package/lib/engine/mcu-info.js +134 -0
  74. package/lib/engine/pdf/curve.js +321 -0
  75. package/lib/engine/pdf/png.js +83 -0
  76. package/lib/engine/pdf/reader.js +336 -0
  77. package/lib/engine/pdf/schematic.js +93 -0
  78. package/lib/engine/pdf/tables.js +249 -0
  79. package/lib/engine/pdf/toolchain.js +50 -0
  80. package/lib/engine/probe.js +45 -0
  81. package/lib/engine/project-conf.js +93 -38
  82. package/lib/engine/project-layout.js +198 -0
  83. package/lib/engine/project-repair.js +205 -0
  84. package/lib/engine/schematic/checks.js +153 -0
  85. package/lib/engine/schematic/draw.js +390 -0
  86. package/lib/engine/schematic/edit.js +229 -0
  87. package/lib/engine/schematic/kicad-sch.js +225 -0
  88. package/lib/engine/schematic/model.js +442 -0
  89. package/lib/engine/schematic/nets.js +219 -0
  90. package/lib/engine/schematic/pcb.js +144 -0
  91. package/lib/engine/schematic/review.js +134 -0
  92. package/lib/engine/schematic/sexpr.js +134 -0
  93. package/lib/engine/schematic/to-ioc.js +197 -0
  94. package/lib/engine/schematic/transform.js +25 -0
  95. package/lib/engine/session-context.js +93 -6
  96. package/lib/engine/toolchain-gate.js +8 -0
  97. package/lib/engine/web-api.js +269 -32
  98. package/lib/index.js +56 -5
  99. package/lib/skill/stm32-workflow.js +1 -1
  100. package/lib/tools/build.js +10 -2
  101. package/lib/tools/code-patch.js +2 -2
  102. package/lib/tools/datasheet.js +447 -0
  103. package/lib/tools/debug-session.js +9 -4
  104. package/lib/tools/debug.js +2 -2
  105. package/lib/tools/doctor.js +2 -2
  106. package/lib/tools/ecad.js +903 -0
  107. package/lib/tools/flash.js +2 -2
  108. package/lib/tools/gen.js +166 -0
  109. package/lib/tools/generate.js +7 -5
  110. package/lib/tools/import-circuit.js +146 -0
  111. package/lib/tools/ioc-apply.js +2 -2
  112. package/lib/tools/ioc-inspect.js +2 -2
  113. package/lib/tools/ioc-plan.js +2 -2
  114. package/lib/tools/ioc-verify.js +2 -2
  115. package/lib/tools/layout.js +92 -0
  116. package/lib/tools/mcu-info.js +163 -0
  117. package/lib/tools/part-import.js +182 -0
  118. package/lib/tools/pcb.js +2316 -0
  119. package/lib/tools/pdf.js +423 -0
  120. package/lib/tools/project-dir.js +19 -1
  121. package/lib/tools/regs.js +2 -2
  122. package/lib/tools/route-plan.js +2 -2
  123. package/lib/tools/rtt.js +2 -2
  124. package/lib/tools/sch-draw.js +433 -0
  125. package/lib/tools/sch-edit.js +145 -0
  126. package/lib/tools/schematic.js +817 -0
  127. package/package.json +1 -1
package/README_EN.md CHANGED
@@ -1,410 +1,544 @@
1
- # dsh-stm32
2
-
3
- [![GitHub stars](https://img.shields.io/github/stars/JingYu-er/dsh-stm32?color=4a6cf7)](https://github.com/JingYu-er/dsh-stm32)
4
- [![license](https://img.shields.io/github/license/JingYu-er/dsh-stm32)](LICENSE)
5
- [![platform](https://img.shields.io/badge/platform-Windows%2010%2F11-4a6cf7)](#known-limitations)
6
- [![MCU](https://img.shields.io/badge/MCU-STM32%20family-4a6cf7)](#known-limitations)
7
- [![version](https://img.shields.io/badge/version-0.1.8-orange)](https://github.com/JingYu-er/dsh-stm32/releases)
8
-
9
- Full-chain STM32 tooling distributed as a [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) plugin: 25 tools, 7 slash commands and one bundled SKILL that hand the chain "probe toolchain → scaffold a project → edit `.ioc` (clocks included) → generate code → build → flash → debug → read registers back" to the model, plus serial interaction (Windows) and an in-session debug console panel.
10
-
11
- Within the supported range the same tools behave the same way from F1 to H7; for an unsupported family or capability the call states what is missing instead of returning a guessed result.
12
-
13
- | Capability | Coverage |
14
- | --- | --- |
15
- | Chip families | 27 families: C0 / F0 / F1 / F2 / F3 / F4 / F7 / G0 / G4 / H5 / H7 / L0 / L1 / L4 / L4+ / L5 / MP1 / MP2 / N6 / U0 / U3 / U5 / WB / WB0 / WBA / WL / WL3 |
16
- | HAL scaffolding | 21 single-core families: C0 / F0 / F1 / F2 / F3 / F4 / F7 / G0 / G4 / H5 / H7 / L0 / L1 / L4 / L4+ / L5 / U0 / U3 / U5 / WBA / WL |
17
- | Register scaffolding | 21 families, all passing the create→build matrix |
18
- | Clock planning | 18 families; PLL1 on H5 / U5 / WBA / L4+ |
19
- | `.ioc` peripheral presets | Derived from official CubeMX data: USART / TIM PWM / ADC |
20
- | Register names and bitfields | F1 |
21
-
22
- **中文:** [README.md](./README.md)
23
-
24
- [Quick start](#quick-start-minimal-end-to-end-check) · [Tool reference](#tool-reference) · [Slash commands](#slash-commands) · [Debug console](#debug-console-panel) · [Configuration](#configuration) · [Known limitations](#known-limitations) · [Troubleshooting](#troubleshooting)
25
-
26
- ## What it does
27
-
28
- Most "AI writes STM32 code" setups stop at the source level: a `main.c` is produced, and whether it compiles and blinks is still confirmed by hand across CubeMX, a terminal and a debugger. The model cannot see the board, so it cannot be accountable for the result.
29
-
30
- This plugin puts the hardware side inside DSH: the `.ioc` is readable and writable (transaction with rollback), code goes only into `USER CODE` blocks, generation and builds return real error lines, flashing never holds the probe a debugger needs, and register state is read back after flashing. Every step returns something checkable (a plan id, `file:line:col`, `Verified OK`, bit13 of `GPIOC.ODR`, reported as `ODR13=1` when register tables are present), which the model uses to decide the next step.
31
-
32
- | Step | Manual flow | This plugin |
33
- | --- | --- | --- |
34
- | Scaffold | Configure clocks, pins and project settings in the GUI, generate CMake, hand-write `launch.json` | `stm32_project_create` produces a template project in about 2 s, matching CubeMX GUI output, with both `.vscode` configs in place |
35
- | Reconfigure | Edit in the GUI, regenerate, hope `USER CODE` survives | `stm32_ioc_plan` shows the diff without writing → confirm → `stm32_ioc_apply` with checks, backup and rollback |
36
- | Write code | Whole-file edits that can land in generated regions and vanish on regeneration | `stm32_code_patch` writes only inside `USER CODE` blocks; bytes outside are preserved |
37
- | Build | Keil, or hand-maintained CMake and VS Code tasks | `/stm32-build [dir] [--clean]` |
38
- | Flash | Keil, or a hand-written `tasks.json` calling openocd | `/stm32-flash [dir]` |
39
- | Verify | Breakpoints and manual register inspection | `stm32_regs_read` reads state back: two `GPIOC.ODR` samples confirm the counter advances, `AFIO.MAPR` confirms firmware did not disable SWD |
40
- | Debug | F5, manual breakpoints, close the session afterwards | `stm32_debug_run` halts at `main`, captures one snapshot and releases the probe; continuous work uses `stm32_debug_session`, which closes when idle |
41
-
42
- ## Install
43
-
44
- ### Install the plugin
45
-
46
- Only DSH itself is required at this point; the toolchain can be added later.
47
-
48
- ```powershell
49
- dsh plugin --profile desktop add dsh-stm32
50
- ```
51
-
52
- `dsh plugin` runs `pnpm add` inside the profile directory and appends `dsh-stm32` to that profile's `dsh.profile.bundles`. Exit DSH completely and start it again afterwards; bundle layers load at process start only.
53
-
54
- - Verify: `dsh plugin --profile desktop why dsh-stm32` prints `0.1.8`
55
- - Uninstall: `dsh plugin --profile desktop remove dsh-stm32`, then restart DSH
56
- - Web profile: replace `desktop` with `web`
57
-
58
- ### Add the toolchain
59
-
60
- With the plugin installed, parsing `.ioc` files, inspecting pins / clocks / interrupts and previewing plans all work already. Compilers and probe tools are needed only when building, flashing or debugging.
61
-
62
- | Task | Requires | How to add |
63
- | --- | --- | --- |
64
- | Build | `arm-none-eabi-gcc`, `cmake`, `ninja` | `/stm32-setup` installs everything (MSYS2 plus toolchain, about 300 MB); a manual installation is discovered automatically |
65
- | Flash, debug | `openocd`, `arm-none-eabi-gdb` (or `gdb-multiarch`), a CMSIS-DAP / ST-Link probe | Same command; probe drivers are supplied by the OS |
66
- | Generate code, scaffold HAL projects | STM32CubeMX (with bundled JRE) and its firmware package | Install CubeMX from the ST website (ST account required); the plugin locates it automatically; install firmware packages in the CubeMX package manager |
67
-
68
- When the missing piece is unclear, check the diagnosis first:
69
-
70
- ```text
71
- /stm32-env # what build / flash / debug / generate are missing, where things install, how to install
72
- /stm32-setup # plan first, install after confirmation, self-check when done
73
- ```
74
-
75
- `/stm32-env` works with no toolchain at all: it only runs version queries and writes nothing.
76
-
77
- ### Pre-flight check
78
-
79
- ```text
80
- /stm32-doctor
81
- ```
82
-
83
- Read-only checks: toolchain completeness, leftover openocd / gdb processes holding the probe, gdb port usage, whether `.elf` and `.ioc` exist in the project, and whether the `.ioc` has a configuration that would lose SWD after flashing.
84
-
85
- ### Bundled assets
86
-
87
- The mapping from part number to startup file, device macro and Flash / RAM size ships with the plugin, together with `.ioc` templates, linker scripts and register tables. Everything works offline after installation; no resource download is involved. `stm32_assets verify` checks integrity and points to a reinstall when files are missing.
88
-
89
- ### Install from source
90
-
91
- Only for development or when the code itself must change. Build and test commands are listed under [Development and testing](#development-and-testing).
92
-
93
- ```powershell
94
- git clone https://github.com/JingYu-er/dsh-stm32.git
95
- cd dsh-stm32
96
- npm install --no-audit --no-fund # typescript only
97
- npm run build # tsc -> lib/, required before committing
98
- ```
99
-
100
- Mount a working copy with `link:`, not `file:`:
101
-
102
- ```powershell
103
- cd "$env:USERPROFILE\.dsh\profiles\desktop"
104
- pnpm add "link:D:\path\to\dsh-stm32"
105
-
106
- # append "dsh-stm32" to dsh.profile.bundles in that directory's package.json
107
- # restart dsh afterwards (bundle layers load at process start only)
108
- ```
109
-
110
- Reason: under `nodeLinker: hoisted`, `file:` copies the package into a real directory, so a freshly built `lib/` is never read by the host, which shows up as "code changed, behaviour unchanged". `link:` reads `lib/` from the working copy; DSH still has to restart to reload the plugin.
111
-
112
- ## Quick start: minimal end-to-end check
113
-
114
- This chain was verified on real hardware, driven entirely by tool calls. Every step uses the same tools; blinking an LED is simply the cheapest sample.
115
-
116
- | Step | Action | Tool | Measured |
117
- | --- | --- | --- | --- |
118
- | 1 | Probe: toolchain, occupied probes, ports, `.elf`, `.ioc` warnings | `stm32_doctor` | about 2 s |
119
- | 2 | Scaffold a CMake project in an empty directory (`.ioc` with SWD configured) | `stm32_project_create` | about 2 s |
120
- | 3 | Run CubeMX headless; output lands in `Core/` | `stm32_generate` | 130–175 s first run; skipped (< 1 s) when nothing changed |
121
- | 4 | Build (first run configures with `cmake --preset`) | `stm32_build` | about 5 s configure + 3 s compile |
122
- | 5 | Flash only: program + verify + reset | `stm32_flash` | 2.1–2.6 s |
123
- | 6 | Read `GPIOC.ODR` (or address `0x4001100C`) and confirm the state toggles | `stm32_regs_read` | 0.4–1.3 s |
124
-
125
- Step 6 uses symbolic names, which rely on the bundled register tables. With an incomplete installation the address form `0x4001100C` still works, but the report carries no register names or bitfields.
126
-
127
- On the model side a single sentence suffices: "Create an STM32F103C8T6 blink project in `D:\work\blink`, build it and flash it".
128
-
129
- The minimal check covers scaffold → generate → build → flash → read-back; no step is blink-specific. Real projects follow the same chain, differing only in the number of peripherals in the `.ioc`, the number of `USER CODE` blocks and the code size.
130
-
131
- | Real-project task | Path | Verification status |
132
- | --- | --- | --- |
133
- | Peripheral setup: GPIO / timers / USART / I2C / SPI / ADC / DMA / interrupts | `stm32_ioc_plan` (GPIO checked against the pin table) → `stm32_ioc_apply` → `stm32_generate` | GPIO, clocks and SWD measured on hardware; other peripherals use the same mechanism, not measured individually |
134
- | Add HAL sources for new peripherals | Add `stm32f1xx_hal_<peripheral>.c` to `STM32_Drivers_Src` in `cmake/stm32cubemx/CMakeLists.txt`, or write into `cmake/user/CMakeLists.txt` | Manual step: the plugin places only `Src/` and `Inc/`, never CubeMX-generated `cmake/**` |
135
- | Multiple sources and custom modules | Write into `cmake/user/CMakeLists.txt` (placeholder provided) | Placeholder in place; not measured separately |
136
- | Application code | `stm32_code_patch` writes per block and carries blocks back on regeneration | Measured (append / replace; an unknown tag lists all available tags) |
137
- | Tuning, clock changes | `.ioc` transaction: diff → checks → backup → rollback on failure | Measured |
138
- | Confirm peripherals run | `stm32_regs_read` reads any peripheral register by symbol (`TIM2.CNT`, `USART1.SR`, `ADC1.DR`) or address (`0x40000024`); naming only `GPIOC` dumps all its registers | Address form measured on hardware; symbolic names and bitfields being retested |
139
- | Inspect a failure | `stm32_debug_run` halts at `main` once; continuous work uses `stm32_debug_session` + `stm32_debug_eval` | Measured (halted at `main () at main.c:67`) |
140
-
141
- Boundaries are listed under [Known limitations](#known-limitations): HAL scaffolding covers 21 single-core families, register scaffolding 21 (validation board is C8T6), the host is verified on Windows only, the default probe is CMSIS-DAP, and new peripherals need manual HAL sources. Peripheral variety is not a tool limitation: whatever the `.ioc` can express follows the same chain; peripherals other than the blink sample have not been measured individually on hardware, so running `/stm32-doctor` before starting a project is recommended.
142
-
143
- ## Tool reference
144
-
145
- ### Environment and projects
146
-
147
- | Tool | Purpose |
148
- | --- | --- |
149
- | `stm32_doctor` | Read-only health check: toolchain completeness, leftover openocd / gdb processes, gdb port usage, `.elf` and `.ioc` status; per-chip capabilities and known issues |
150
- | `stm32_route_plan` | Estimates HAL versus register cost for a specific project and requirement; separates auto-installable gaps from manual ones |
151
- | `stm32_env_install` | Installs MSYS2 and toolchain components (gcc / gdb / openocd / cmake / ninja); plan only by default, executes with `dryRun:false` + `confirm:true`; writes user-level PATH only, no administrator rights |
152
- | `stm32_download` | Download without installing: J-Link direct link with checksum; CubeMX / CubeProgrammer open the official page or validate a local file |
153
- | `stm32_firmware_install` | Downloads and assembles STM32Cube firmware packages, official archive first, GitHub assembly as fallback; plan only by default |
154
- | `stm32_assets` | Lists, verifies and prunes bundled assets (chip data, `.ioc` templates, linker scripts, startup files, register tables) |
155
- | `stm32_cache` | Lists, verifies, fetches and prunes the download cache (register-route CMSIS templates) |
156
- | `stm32_project_create` | Scaffolds a project: `route:"hal"` from templates plus firmware package, `route:"register"` without CubeMX; both emit `openocd.cfg` |
157
- | `stm32_project_export` | Packs a project as a zip, excluding `build/`, `.dsh-stm32/`, `node_modules/`, `.git/` by default, optionally with prebuilt artifacts |
158
-
159
- ### `.ioc`: inspect and edit
160
-
161
- | Tool | Purpose |
162
- | --- | --- |
163
- | `stm32_ioc_inspect` | Read-only parse: part number, pins, signals, enabled peripherals, interrupts, clock tree, project settings, risk notes |
164
- | `stm32_ioc_plan` | Computes a per-key diff without writing: peripheral presets, pins, interrupts, debug port, clock planning, bulk entries |
165
- | `stm32_ioc_apply` | Applies a plan: source checks → backup → atomic replace; rollback from backup |
166
- | `stm32_ioc_verify` | Has CubeMX re-read the `.ioc` and points out silently dropped peripherals and missing init calls |
167
-
168
- ### Code and build
169
-
170
- | Tool | Purpose |
171
- | --- | --- |
172
- | `stm32_code_patch` | Writes only inside `USER CODE BEGIN/END` blocks, preserving all other bytes; backs up first |
173
- | `stm32_generate` | Runs CubeMX headless, places output in `Core/`, carries `USER CODE` back by tag; skips when `.ioc` is unchanged |
174
- | `stm32_build` | Builds: infers build directory and `.elf`, returns error lines, warning count, FLASH / RAM usage; optional hex / bin |
175
-
176
- ### Flash, debug and runtime
177
-
178
- | Tool | Purpose |
179
- | --- | --- |
180
- | `stm32_flash` | Flash only: program + verify + reset, then releases the probe; checks Serial Wire first; failures return the probe error class and a suggested action |
181
- | `stm32_debug_run` | Flashes, halts at `main`, captures registers, stack and locals, then resets, runs and releases the probe |
182
- | `stm32_debug_session` | Opens a long-lived debug session (idle and total limits) for repeated `stm32_debug_eval` calls |
183
- | `stm32_debug_eval` | Executes gdb commands in the session: variables, registers, backtrace, memory |
184
- | `stm32_debug_stop` | Closes the session and releases the probe |
185
- | `stm32_regs_read` | Reads registers by address or symbol, resolving bitfields when register tables are present; pauses briefly to read, then resumes without resetting |
186
- | `stm32_watch` | Registers and samples expressions (with deltas); `kind=write/read/access` installs hardware watchpoints, limited by the chip's watchpoint count |
187
- | `stm32_rtt` | RTT channel: firmware keeps the control block in RAM, the host reads it through openocd, output carries level and timestamp |
188
- | `stm32_serial` | Serial interaction (Windows): `list` / `open` / `read` / `send` / `transact` / `status` / `close` |
189
-
190
- ### RTT on the firmware side (shortest example)
191
-
192
- ```c
193
- /* USER CODE BEGIN 0 */
194
- static char rtt_buf[3][1024];
195
- static void rtt_init(void) {
196
- /* Control block follows the SEGGER convention in RAM: acId / acName / three rings, see rtt.h in templates/ */
197
- }
198
- /* USER CODE END 0 */
199
- ```
200
-
201
- The full implementation ships in `templates/`; channel count and ring size are controlled by `RTT_UP_CHANNELS` / `RTT_BUF_SIZE` (default 3×1 KB = 3 KB `.bss`; C8T6 has 20 KB RAM).
202
-
203
- ## Slash commands
204
-
205
- | Command | Description |
206
- | --- | --- |
207
- | `/stm32-doctor` | Health check: toolchain, leftover processes, ports, `.elf` and `.ioc` warnings |
208
- | `/stm32-env` | Toolchain check: what build / flash / debug / generate are missing, where things install, how to install |
209
- | `/stm32-setup` | Probe → install plan → install after confirmation → self-check |
210
- | `/stm32-build [dir] [--clean]` | Build (CMake + Ninja, `build/Debug` by default); `--clean` wipes first |
211
- | `/stm32-flash [dir]` | Flash only: program + verify + reset, then release the probe |
212
- | `/stm32-debug [dir]` | Flash and enter debugging, halted at `main`; then use `stm32_debug_eval` |
213
- | `/stm32-stop` | Close the debug session and release the probe for VS Code F5 |
214
-
215
- ## Debug console (panel)
216
-
217
- The in-session debug console shows one timeline for both sides: the start, success, failure and duration of `stm32_*` calls, plus serial, RTT, watch, pin, clock, interrupt and `.ioc` state.
218
-
219
- | Tab | Content | Actions |
220
- | --- | --- | --- |
221
- | Overview | Project, part number, SYSCLK, capacity, debug session, toolchain, build and flash, evidence usage, alert summary | Jump to failed events or the live channel, export an operation log as Markdown |
222
- | Events | Call start and end, duration, slow-call marker, argument summary | Failures only, filter by tool, sort by duration, bulk quoting, JSONL export, event deep links |
223
- | Live channels | Serial / RTT / watch output | Pause, clear, keyword filter, RTT level filter, send a serial line, persistent capture, export |
224
- | Pins | Grouped by peripheral, by port, or as a package outline | Filter, copy references, inspect `.ioc` keys, CSV export |
225
- | Clocks | Tree and flow views, per-node frequency and divider | Over-limit markers and "change to ÷N" advice computed from the parent clock |
226
- | Interrupts | NVIC enablement, preemption and sub-priority | Filter, sort, edit in place, bulk edit |
227
- | Faults | Raw failure events, rule decoding, grouping by rule | Category filter, copy group hint, CSV export |
228
- | Artifacts | elf / hex / bin, size, checksum, capacity, build-to-build comparison | Copy checksums |
229
- | Changes | `.ioc` differences against a baseline | Record a baseline, restore one key, restore all |
230
-
231
- Opening the panel first loads the most recent records for the session, then appends live. Events are written every 30 seconds to `~/.dsh-stm32/evidence/<date>/<session>/` for replay and export, retained for 7 days and the last 20 sessions by default, all configurable. The panel shows only this plugin's own tool calls.
232
-
233
- ## Serial (Windows)
234
-
235
- `stm32_serial` exposes seven actions: `list` / `open` / `read` / `send` / `transact` / `status` / `close`. Once opened, the port is held by the plugin, one port at a time; 115200 8N1 by default, no flow control, DTR / RTS not asserted, closed at the end of a turn.
236
-
237
- - Platform: Windows only. Linux and macOS return `unsupported-platform`.
238
- - Ports: `list` enumerates available ports; parameters are remembered per device, so a different COM number still reuses them.
239
- - Read: `read` accepts a cursor and returns only newer lines.
240
- - Write: `send` writes one line; `transact` writes and waits for a matching reply (regular expression).
241
- - Retention: `persist=true` keeps the port open across turns.
242
-
243
- The reference validation board uses a CH340 (`1A86:7523`, COM5, 115200). The DAPLink virtual serial port on the same board (`c251:f001`, COM4) does not carry application data.
244
-
245
- ## Design notes
246
-
247
- - **Own files only**: the `.ioc` goes through a transaction (plan → checks → backup → replace); generated regions receive only `USER CODE` content; no other generated file is modified.
248
- - **Flash and debug are separate**: `stm32_flash` never opens a debug session and releases the probe immediately; debugging opens `stm32_debug_session` on demand and closes it when idle, so VS Code is not locked out.
249
- - **Conclusions carry evidence**: failures return compiler `file:line:col`, probe error class and register values rather than vague prose.
250
- - **Say what is missing**: when a chip, a clock plan or a debug script is unsupported, the error names the missing piece instead of guessing or silently skipping.
251
- - **No host takeover**: the panel displays state and performs explicit project actions; it does not edit code or run Git operations.
252
-
253
- ## Configuration
254
-
255
- ### Config file (`~/.dsh-stm32/config.json`)
256
-
257
- Toolchain locations are maintained by the plugin: `stm32_env_install` writes this file and later tools read it, with no DSH restart and no environment variables required. Manual editing is supported:
258
-
259
- ```json
260
- {
261
- "version": 1,
262
- "msys64": "E:/msys64",
263
- "binDirs": [],
264
- "packages": ["mingw-w64-ucrt-x86_64-arm-none-eabi-gcc", "mingw-w64-ucrt-x86_64-cmake"],
265
- "cubeMxRoot": "",
266
- "updatedAt": "2026-02-01T00:00:00.000Z"
267
- }
268
- ```
269
-
270
- An empty `binDirs` derives `<msys64>/ucrt64/bin` from `msys64`. A corrupt file (invalid JSON) is treated as absent and does not break other features.
271
-
272
- Precedence: tool arguments (`binDirs` / `cubeMxRoots`) > environment variables > config file > built-in defaults. Built-in defaults contain only common Windows locations, never machine-specific paths.
273
-
274
- ### Settings panel
275
-
276
- The "STM32 toolchain" page under DSH settings offers three cards:
277
-
278
- - **Locations**: reads and saves `msys64` / `cubeMxRoot` / extra `binDirs`; the next tool call sees the change.
279
- - **Missing pieces**: runs a probe (version queries only) and lists path, version and reason per item, plus badges for build / flash / debug / generate.
280
- - **Install toolchain**: emits a plan first (steps, download size, PATH and config changes), executes after confirmation, and streams steps with a log tail.
281
-
282
- ### Download cache and firmware packages
283
-
284
- - Register-route CMSIS templates are downloaded on first use into the cache (default `%LOCALAPPDATA%\dsh-stm32\cache`) and reused afterwards; files are verified and mismatches rejected. `stm32_cache` lists, verifies, fetches and prunes entries.
285
- - The HAL route uses locally installed CubeMX firmware packages: F1 defaults to `STM32Cube_FW_F1_V1.8.7`, other families use the highest installed version; `firmwarePackage` overrides. When missing, install it through the CubeMX package manager or use `stm32_firmware_install`.
286
- - `stm32_download` only downloads or verifies installers (default directory `%LOCALAPPDATA%\dsh-stm32\downloads`); it never executes them and never requests administrator rights.
287
-
288
- ### Environment variables (optional)
289
-
290
- | Variable | Purpose | Default |
291
- | --- | --- | --- |
292
- | `STM32_BIN_DIRS` | Toolchain directory candidates, `;`-separated, replaces the built-in list entirely (auto-discovery still appends) | `C:/msys64/ucrt64/bin`, `C:/msys64/mingw64/bin` |
293
- | `STM32_CUBEMX_ROOT` | CubeMX root, replaces the built-in list | `C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeMX` |
294
- | `STM32_NO_DISCOVER` | Set to `1` to disable auto-discovery (built-in list only) | unset |
295
- | `DSH_STM32_CONFIG` | Alternate config file path | `%USERPROFILE%\.dsh-stm32\config.json` |
296
- | `DSH_STM32_NO_CONFIG` | Set to `1` to ignore the config file entirely | unset |
297
- | `DSH_STM32_CACHE` | Download cache root, supports `~` | `%LOCALAPPDATA%\dsh-stm32\cache` |
298
- | `DSH_STM32_DOWNLOADS` | Installer download directory, supports `~` | `%LOCALAPPDATA%\dsh-stm32\downloads` |
299
- | `DSH_STM32_HOME` | Plugin data root (config, evidence, snapshots, memo) | `%USERPROFILE%\.dsh-stm32` |
300
- | `DSH_STM32_EVIDENCE` | Evidence directory | `~/.dsh-stm32/evidence` |
301
- | `DSH_STM32_EVIDENCE_FLUSH_SECONDS` | Flush interval (5–3600 s) | 30 |
302
- | `DSH_STM32_EVIDENCE_KEEP_DAYS` | Evidence retention in days (0–365, 0 = keep) | 7 |
303
- | `DSH_STM32_EVIDENCE_KEEP_SESSIONS` | Evidence retention in sessions (1–200) | 20 |
304
- | `DSH_STM32_SNAPSHOTS` | `.ioc` baseline directory | `~/.dsh-stm32/ioc-snapshots` |
305
- | `DSH_STM32_OFFLINE` | Set to `1` to forbid network downloads (cache only) | unset |
306
- | `MSYS2_MIRROR` | Installer mirror; must be set together with `MSYS2_INSTALLER_SHA256` | official → TUNA → NJU → Aliyun |
307
- | `MSYS2_INSTALLER_URL` / `MSYS2_INSTALLER_SHA256` | Installer URL and checksum overrides; must be set together | official pinned release |
308
- | `DSH_STM32_JLINK_URL` / `DSH_STM32_JLINK_SHA256` | J-Link direct link and checksum overrides; must be set together | SEGGER official |
309
-
310
- Tool arguments mirror these variables: flash and debug tools accept `binDirs`, `elfPath`, `buildDir`, `configFile`, `adapterSpeed`; generation and scaffolding accept `cubeMxRoots`, `firmwarePackage`.
311
-
312
- Toolchain locations usually need no configuration: when `binDirs` / `STM32_BIN_DIRS` are absent, the plugin searches common locations and appends candidates — `ucrt64/bin`, `mingw64/bin` and `clang64/bin` under `<drive>/msys64`, `<drive>/msys2`, `<drive>/app/msys64`, `<drive>/tools/msys64`, `%LOCALAPPDATA%/Programs/msys64`; and CubeMX under the `STM32CubeMX_PATH` environment variable, its uninstall registration, and `Program Files\STMicroelectronics\STM32Cube`. When nothing is found, errors and `stm32_doctor` list the directories that were checked.
313
-
314
- ### openocd.cfg (project-level, takes precedence)
315
-
316
- CMSIS-DAP (default):
317
-
318
- ```text
319
- source [find interface/cmsis-dap.cfg]
320
- source [find target/stm32f1x.cfg]
321
- adapter speed 4000
322
- ```
323
-
324
- ST-Link:
325
-
326
- ```text
327
- source [find interface/stlink.cfg]
328
- transport select hla_swd
329
- source [find target/stm32f1x.cfg]
330
- ```
331
-
332
- Without `openocd.cfg`, the debug script follows the chip family in the `.ioc` (F1 → `stm32f1x`, F4 → `stm32f4x`, G4 → `stm32g4x`; L4 and L4+ share `stm32l4x`). C0 / U0 scripts ship with the plugin and are copied into the project's `openocd/` directory during scaffolding; H5 / N6 / U3 / WBA / WB0 / WL3 / MP2 have no scripts and flashing is refused explicitly.
333
-
334
- ### Two hard requirements on the `.ioc`
335
-
336
- 1. **SYS debug port set to Serial Wire** (PA13 = `SYS_JTMS-SWDIO`, PA14 = `SYS_JTCK-SWCLK`); use `stm32_ioc_plan` with `serialWire: true` when missing.
337
- 2. **`ProjectManager.KeepUserCode=true`**; otherwise `USER CODE` content is lost on regeneration.
338
-
339
- ## Known limitations
340
-
341
- | Limitation | Detail | Handling |
342
- | --- | --- | --- |
343
- | Verified on Windows only | Code generation depends on the Windows installation of CubeMX | No alternative yet; flash, debug and register reads may work elsewhere with a complete toolchain, unverified |
344
- | Some chips have no official debug script | C0 / U0 use plugin-supplied scripts (not verified on hardware); H5 / N6 / U3 / WBA / WB0 / WL3 / MP2 have none | Flashing states this explicitly instead of failing silently |
345
- | HAL scaffolding excludes dual-core and MPU families | Dual-core WB, MP1 / MP2 / N6, WB0 / WL3 are out of scope | Scaffolding reports the chip as unsupported |
346
- | Depth is graded per family | HAL 21 families, register 21, clocks 18; register names and bitfields currently F1 only | The missing capability is named at call time |
347
- | Probes selected from what USB reports | ST-Link, DAPLink / CMSIS-DAP and J-Link are distinguished automatically; a project `openocd.cfg` wins | Write `openocd.cfg` to pin a choice |
348
- | New peripherals need manual HAL sources | The plugin places only `Src/` and `Inc/`; CubeMX-generated `cmake/**` is not carried over | Edit `STM32_Drivers_Src` or write into `cmake/user/CMakeLists.txt` |
349
- | Generation and scaffolding need CubeMX plus the family firmware package | F1 defaults to `STM32Cube_FW_F1_V1.8.7` | Pass `firmwarePackage`, or install the package in CubeMX first |
350
- | RTT is channel 0 only with a custom frame | 13-byte header (length, level, timestamp, UTF-8 text) | Filter by level; put structured data in the text; channels and ring size in `rtt.h` |
351
- | Serial is Windows-only | No streaming UI, no auto-reconnect, one port at a time | Use a system serial tool, or a later release |
352
- | Register names and bitfields need the bundled register tables | Covers F1 lines 100 / 101 / 102 / 103 / 105 / 107 | Use `0x` addresses; `stm32_assets verify` checks the installation |
353
-
354
- ## Troubleshooting
355
-
356
- | Symptom | Cause | Action |
357
- | --- | --- | --- |
358
- | Plugin not loaded | `dsh.profile.bundles` lacks `dsh-stm32`, or DSH was not restarted | Reinstall and restart; verify with `dsh plugin --profile desktop why dsh-stm32` |
359
- | Code changes have no effect | Installed via `file:`, so the host reads a copy | Switch to `link:`, rebuild with `npm run build`, restart DSH |
360
- | Missing toolchain reported | Not installed, or path not discovered | Run `/stm32-env` to see what is missing, then `/stm32-setup`; or set `binDirs` manually |
361
- | Flash reports the probe is busy | Another debugger (VS Code, leftover openocd) holds the probe | `/stm32-stop`, close other debuggers, retry; `stm32_doctor` lists leftover processes |
362
- | SWD is lost after flashing | `.ioc` did not enable Serial Wire | Add `serialWire: true` via `stm32_ioc_plan`, regenerate, flash again |
363
- | Peripherals dropped after generation | `.ioc` keys inconsistent with peripheral derivation | Run `stm32_ioc_verify` for a CubeMX-side diagnosis |
364
- | Panel is blank or stale | Server-side change without restart, or `lib` newer than the process | Fully exit DSH and start again; the status bar flags "new build available" |
365
- | No serial data | Wrong port (for example the DAPLink virtual port) | Confirm with `stm32_serial list`; application serial usually lives on a CH340-class adapter |
366
-
367
- ## Development and testing
368
-
369
- | Command | Purpose |
370
- | --- | --- |
371
- | `npm run build` | `tsc` into `lib/`, copying client and data assets |
372
- | `node test/run-units.mjs` | Offline unit tests: 80 suites / 1088 cases, no board required |
373
- | `node .dsh-stm32/acceptance.mjs` | Local acceptance script: panel API, event stream, evidence, artifacts, faults, interrupts, serial, probe |
374
- | `npm run test:pack` | Pack, unpack and scaffold a register project with the unpacked build |
375
- | `npm run test:size` | Package and asset guards |
376
-
377
- Release shape: published content is limited to `files` in `package.json` (`lib`, `client`, `templates`, `assets`, `docs/reading-guide.md`, `cordis.patch.yml`, both READMEs, `LICENSE`). `docs/`, `test/` and `scripts/` stay out of the package.
378
-
379
- Development-only environment variables (not needed in daily use): `DSH_STM32_ASSETS` and `DSH_STM32_FACTS` override asset directories, `DSH_STM32_SERIAL_BRIDGE` and `DSH_STM32_SERIAL_POWERSHELL` override the serial bridge path, `DSH_STM32_PYTHON` selects the Python interpreter used for parsing.
380
-
381
- ## Repository layout
382
-
383
- ```text
384
- src/
385
- index.ts plugin entry: tools, slash commands, panel API, SKILL
386
- tools/ registration and argument validation for 25 tools
387
- engine/ engines: project, .ioc, generation, build, flash, debug, events, panel API
388
- data/ chip data, CubeMX data, clocks, search roots, toolchain config
389
- commands/ 7 slash commands
390
- skill/ bundled stm32-workflow SKILL
391
- client/client.js panel source (plain JS + react, no bundler)
392
- lib/ tsc output and copied assets (published)
393
- assets/ chip data, .ioc templates, linker scripts, startup files, register tables
394
- templates/ scaffolding templates, register route, serial bridge, RTT
395
- test/ 80 offline suites and e2e scripts
396
- scripts/ build, pack, size and smoke scripts
397
- docs/ development notes, reading guide, spec, diagrams
398
- ```
399
-
400
- ## Documentation
401
-
402
- - [Specification](docs/dsh-stm32-plugin-规格.md): tool contracts, state machine, acceptance criteria
403
- - [Development notes](docs/development-notes.md): milestones, host-contract issues, per-tool implementation details and measurements
404
- - [Source reading guide](docs/reading-guide.md): layered reading order, per-file responsibilities and exports, diagrams and invariants
405
- - Release notes: provided per release on the release page; history lives in git and the development notes
406
- - Visuals: [architecture](docs/diagrams/dsh-stm32-architecture.html) / [main journey](docs/diagrams/dsh-stm32-journey.html) — single-file HTML, opens offline
407
-
408
- ## License
409
-
410
- [MIT](LICENSE)
1
+ # dsh-stm32
2
+
3
+ [![GitHub stars](https://img.shields.io/github/stars/JingYu-er/dsh-stm32?color=4a6cf7)](https://github.com/JingYu-er/dsh-stm32)
4
+ [![license](https://img.shields.io/github/license/JingYu-er/dsh-stm32)](LICENSE)
5
+ [![platform](https://img.shields.io/badge/platform-Windows%2010%2F11-4a6cf7)](#known-limitations)
6
+ [![MCU](https://img.shields.io/badge/MCU-STM32%20family-4a6cf7)](#known-limitations)
7
+ [![version](https://img.shields.io/badge/version-0.1.8-orange)](https://github.com/JingYu-er/dsh-stm32/releases)
8
+
9
+ Full-chain STM32 tooling distributed as a [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) plugin: 37 tools, 7 slash commands and one bundled SKILL that hand the chain "probe toolchain → scaffold a project → edit `.ioc` (clocks included) → generate code → build → flash → debug → read registers back" to the model, plus serial interaction (Windows) and an in-session debug console panel.
10
+
11
+ Within the supported range the same tools behave the same way from F1 to H7; for an unsupported family or capability the call states what is missing instead of returning a guessed result.
12
+
13
+ | Capability | Coverage |
14
+ | --- | --- |
15
+ | Chip families | 27 families: C0 / F0 / F1 / F2 / F3 / F4 / F7 / G0 / G4 / H5 / H7 / L0 / L1 / L4 / L4+ / L5 / MP1 / MP2 / N6 / U0 / U3 / U5 / WB / WB0 / WBA / WL / WL3 |
16
+ | HAL scaffolding | 21 single-core families: C0 / F0 / F1 / F2 / F3 / F4 / F7 / G0 / G4 / H5 / H7 / L0 / L1 / L4 / L4+ / L5 / U0 / U3 / U5 / WBA / WL |
17
+ | Register scaffolding | 21 families, all passing the create→build matrix |
18
+ | Clock planning | 18 families; PLL1 on H5 / U5 / WBA / L4+ |
19
+ | `.ioc` peripheral presets | Derived from official CubeMX data: USART / SPI (full-duplex, TX-only, RX-only) / I2C / TIM PWM / ADC |
20
+ | Register names and bitfields | F1 |
21
+
22
+ **中文:** [README.md](./README.md)
23
+
24
+ [Quick start](#quick-start-minimal-end-to-end-check) · [Tool reference](#tool-reference) · [Slash commands](#slash-commands) · [Debug console](#debug-console-panel) · [Configuration](#configuration) · [Known limitations](#known-limitations) · [Troubleshooting](#troubleshooting)
25
+
26
+ ## Split note (since 0.1.9)
27
+
28
+ Hardware-side capabilities (schematic authoring, PCB, Gerber, 3D, BOM, stackup/impedance, EMC, mechanical) moved to the separate **dsh-ecad** plugin. This plugin keeps the firmware side: toolchains, `.ioc` transactions, project scaffolding, build, flash, debug, serial/RTT/watch, evidence and the debug console — plus the read-only schematic capabilities the firmware loop needs (read a KiCad schematic, map pins, one-click review, export an `.ioc` draft).
29
+
30
+ The two plugins exchange MCU facts through `<project>/dsh/mcu.json` (`schema: dsh-mcu/1`, with the `.ioc` sha256 fingerprint); no tool names collide.
31
+
32
+ ## What it does
33
+
34
+ Most "AI writes STM32 code" setups stop at the source level: a `main.c` is produced, and whether it compiles and blinks is still confirmed by hand across CubeMX, a terminal and a debugger. The model cannot see the board, so it cannot be accountable for the result.
35
+
36
+ This plugin puts the hardware side inside DSH: the `.ioc` is readable and writable (transaction with rollback), code goes only into `USER CODE` blocks, generation and builds return real error lines, flashing never holds the probe a debugger needs, and register state is read back after flashing. Every step returns something checkable (a plan id, `file:line:col`, `Verified OK`, bit13 of `GPIOC.ODR`, reported as `ODR13=1` when register tables are present), which the model uses to decide the next step.
37
+
38
+ | Step | Manual flow | This plugin |
39
+ | --- | --- | --- |
40
+ | Scaffold | Configure clocks, pins and project settings in the GUI, generate CMake, hand-write `launch.json` | `stm32_project_create` produces a template project in about 2 s, matching CubeMX GUI output, with both `.vscode` configs in place |
41
+ | Reconfigure | Edit in the GUI, regenerate, hope `USER CODE` survives | `stm32_ioc_plan` shows the diff without writing → confirm → `stm32_ioc_apply` with checks, backup and rollback |
42
+ | Write code | Whole-file edits that can land in generated regions and vanish on regeneration | `stm32_code_patch` writes only inside `USER CODE` blocks; bytes outside are preserved |
43
+ | Build | Keil, or hand-maintained CMake and VS Code tasks | `/stm32-build [dir] [--clean]` |
44
+ | Flash | Keil, or a hand-written `tasks.json` calling openocd | `/stm32-flash [dir]` |
45
+ | Verify | Breakpoints and manual register inspection | `stm32_regs_read` reads state back: two `GPIOC.ODR` samples confirm the counter advances, `AFIO.MAPR` confirms firmware did not disable SWD |
46
+ | Debug | F5, manual breakpoints, close the session afterwards | `stm32_debug_run` halts at `main`, captures one snapshot and releases the probe; continuous work uses `stm32_debug_session`, which closes when idle |
47
+
48
+ ## Install
49
+
50
+ ### Install the plugin
51
+
52
+ Only DSH itself is required at this point; the toolchain can be added later.
53
+
54
+ ```powershell
55
+ dsh plugin --profile desktop add dsh-stm32
56
+ ```
57
+
58
+ `dsh plugin` runs `pnpm add` inside the profile directory and appends `dsh-stm32` to that profile's `dsh.profile.bundles`. Exit DSH completely and start it again afterwards; bundle layers load at process start only.
59
+
60
+ - Verify: `dsh plugin --profile desktop why dsh-stm32` prints `0.1.8`
61
+ - Uninstall: `dsh plugin --profile desktop remove dsh-stm32`, then restart DSH
62
+ - Web profile: replace `desktop` with `web`
63
+
64
+ ### Add the toolchain
65
+
66
+ With the plugin installed, parsing `.ioc` files, inspecting pins / clocks / interrupts and previewing plans all work already. Compilers and probe tools are needed only when building, flashing or debugging.
67
+
68
+ | Task | Requires | How to add |
69
+ | --- | --- | --- |
70
+ | Build | `arm-none-eabi-gcc`, `cmake`, `ninja` | `/stm32-setup` installs everything (MSYS2 plus toolchain, about 300 MB); a manual installation is discovered automatically |
71
+ | Flash, debug | `openocd`, `arm-none-eabi-gdb` (or `gdb-multiarch`), a CMSIS-DAP / ST-Link probe | Same command; probe drivers are supplied by the OS |
72
+ | Generate code, scaffold HAL projects | STM32CubeMX (with bundled JRE) and its firmware package | Install CubeMX from the ST website (ST account required); the plugin locates it automatically; install firmware packages in the CubeMX package manager |
73
+
74
+ When the missing piece is unclear, check the diagnosis first:
75
+
76
+ ```text
77
+ /stm32-env # what build / flash / debug / generate are missing, where things install, how to install
78
+ /stm32-setup # plan first, install after confirmation, self-check when done
79
+ ```
80
+
81
+ `/stm32-env` works with no toolchain at all: it only runs version queries and writes nothing.
82
+
83
+ ### Pre-flight check
84
+
85
+ ```text
86
+ /stm32-doctor
87
+ ```
88
+
89
+ Read-only checks: toolchain completeness, leftover openocd / gdb processes holding the probe, gdb port usage, whether `.elf` and `.ioc` exist in the project, and whether the `.ioc` has a configuration that would lose SWD after flashing.
90
+
91
+ ### Bundled assets
92
+
93
+ The mapping from part number to startup file, device macro and Flash / RAM size ships with the plugin, together with `.ioc` templates, linker scripts and register tables. Everything works offline after installation; no resource download is involved. `stm32_assets verify` checks integrity and points to a reinstall when files are missing.
94
+
95
+ ### Install from source
96
+
97
+ Only for development or when the code itself must change. Build and test commands are listed under [Development and testing](#development-and-testing).
98
+
99
+ ```powershell
100
+ git clone https://github.com/JingYu-er/dsh-stm32.git
101
+ cd dsh-stm32
102
+ npm install --no-audit --no-fund # typescript only
103
+ npm run build # tsc -> lib/, required before committing
104
+ ```
105
+
106
+ Mount a working copy with `link:`, not `file:`:
107
+
108
+ ```powershell
109
+ cd "$env:USERPROFILE\.dsh\profiles\desktop"
110
+ pnpm add "link:D:\path\to\dsh-stm32"
111
+
112
+ # append "dsh-stm32" to dsh.profile.bundles in that directory's package.json
113
+ # restart dsh afterwards (bundle layers load at process start only)
114
+ ```
115
+
116
+ Reason: under `nodeLinker: hoisted`, `file:` copies the package into a real directory, so a freshly built `lib/` is never read by the host, which shows up as "code changed, behaviour unchanged". `link:` reads `lib/` from the working copy; DSH still has to restart to reload the plugin.
117
+
118
+ ## Quick start: minimal end-to-end check
119
+
120
+ This chain was verified on real hardware, driven entirely by tool calls. Every step uses the same tools; blinking an LED is simply the cheapest sample.
121
+
122
+ | Step | Action | Tool | Measured |
123
+ | --- | --- | --- | --- |
124
+ | 1 | Probe: toolchain, occupied probes, ports, `.elf`, `.ioc` warnings | `stm32_doctor` | about 2 s |
125
+ | 2 | Scaffold a CMake project in an empty directory (`.ioc` with SWD configured) | `stm32_project_create` | about 2 s |
126
+ | 3 | Run CubeMX headless; output lands in `Core/` | `stm32_generate` | 130–175 s first run; skipped (< 1 s) when nothing changed |
127
+ | 4 | Build (first run configures with `cmake --preset`) | `stm32_build` | about 5 s configure + 3 s compile |
128
+ | 5 | Flash only: program + verify + reset | `stm32_flash` | 2.1–2.6 s |
129
+ | 6 | Read `GPIOC.ODR` (or address `0x4001100C`) and confirm the state toggles | `stm32_regs_read` | 0.4–1.3 s |
130
+
131
+ Step 6 uses symbolic names, which rely on the bundled register tables. With an incomplete installation the address form `0x4001100C` still works, but the report carries no register names or bitfields.
132
+
133
+ On the model side a single sentence suffices: "Create an STM32F103C8T6 blink project in `D:\work\blink`, build it and flash it".
134
+
135
+ The minimal check covers scaffold → generate → build → flash → read-back; no step is blink-specific. Real projects follow the same chain, differing only in the number of peripherals in the `.ioc`, the number of `USER CODE` blocks and the code size.
136
+
137
+ | Real-project task | Path | Verification status |
138
+ | --- | --- | --- |
139
+ | Peripheral setup: GPIO / timers / USART / I2C / SPI / ADC / DMA / interrupts | `stm32_ioc_plan` (GPIO checked against the pin table) → `stm32_ioc_apply` → `stm32_generate` | GPIO, clocks and SWD measured on hardware; other peripherals use the same mechanism, not measured individually |
140
+ | Add HAL sources for new peripherals | Add `stm32f1xx_hal_<peripheral>.c` to `STM32_Drivers_Src` in `cmake/stm32cubemx/CMakeLists.txt`, or write into `cmake/user/CMakeLists.txt` | Manual step: the plugin places only `Src/` and `Inc/`, never CubeMX-generated `cmake/**` |
141
+ | Multiple sources and custom modules | Write into `cmake/user/CMakeLists.txt` (placeholder provided) | Placeholder in place; not measured separately |
142
+ | Application code | `stm32_code_patch` writes per block and carries blocks back on regeneration | Measured (append / replace; an unknown tag lists all available tags) |
143
+ | Tuning, clock changes | `.ioc` transaction: diff → checks → backup → rollback on failure | Measured |
144
+ | Confirm peripherals run | `stm32_regs_read` reads any peripheral register by symbol (`TIM2.CNT`, `USART1.SR`, `ADC1.DR`) or address (`0x40000024`); naming only `GPIOC` dumps all its registers | Address form measured on hardware; symbolic names and bitfields being retested |
145
+ | Inspect a failure | `stm32_debug_run` halts at `main` once; continuous work uses `stm32_debug_session` + `stm32_debug_eval` | Measured (halted at `main () at main.c:67`) |
146
+
147
+ Boundaries are listed under [Known limitations](#known-limitations): HAL scaffolding covers 21 single-core families, register scaffolding 21 (validation board is C8T6), the host is verified on Windows only, the default probe is CMSIS-DAP, and new peripherals need manual HAL sources. Peripheral variety is not a tool limitation: whatever the `.ioc` can express follows the same chain; peripherals other than the blink sample have not been measured individually on hardware, so running `/stm32-doctor` before starting a project is recommended.
148
+
149
+ ## Tool reference
150
+
151
+ ### Environment and projects
152
+
153
+ | Tool | Purpose |
154
+ | --- | --- |
155
+ | `stm32_doctor` | Read-only health check: toolchain completeness, leftover openocd / gdb processes, gdb port usage, `.elf` and `.ioc` status; per-chip capabilities and known issues |
156
+ | `stm32_route_plan` | Estimates HAL versus register cost for a specific project and requirement; separates auto-installable gaps from manual ones |
157
+ | `stm32_env_install` | Installs MSYS2 and toolchain components (gcc / gdb / openocd / cmake / ninja); plan only by default, executes with `dryRun:false` + `confirm:true`; writes user-level PATH only, no administrator rights |
158
+ | `stm32_download` | Download without installing: J-Link direct link with checksum; CubeMX / CubeProgrammer open the official page or validate a local file |
159
+ | `stm32_firmware_install` | Downloads and assembles STM32Cube firmware packages, official archive first, GitHub assembly as fallback; plan only by default |
160
+ | `stm32_assets` | Lists, verifies and prunes bundled assets (chip data, `.ioc` templates, linker scripts, startup files, register tables) |
161
+ | `stm32_cache` | Lists, verifies, fetches and prunes the download cache (register-route CMSIS templates) |
162
+ | `stm32_project_create` | Scaffolds a project: `route:"hal"` from templates plus firmware package, `route:"register"` without CubeMX; both emit `openocd.cfg` |
163
+ | `stm32_layout_fix` | Check and normalise the config files: the workspace index lives in `<workspace>/.dsh-stm32/workspace.conf`, the project description in the project root; dry run unless `apply=true` (backing up each rewritten file as `.bak`) |
164
+ | `stm32_project_export` | Packs a project as a zip, excluding `build/`, `.dsh-stm32/`, `node_modules/`, `.git/` by default, optionally with prebuilt artifacts |
165
+
166
+ ### `.ioc`: inspect and edit
167
+
168
+ | Tool | Purpose |
169
+ | --- | --- |
170
+ | `stm32_ioc_inspect` | Read-only parse: part number, pins, signals, enabled peripherals, interrupts, clock tree, project settings, risk notes |
171
+ | `stm32_ioc_plan` | Computes a per-key diff without writing: peripheral presets, pins, interrupts, debug port, clock planning, bulk entries |
172
+ | `stm32_ioc_apply` | Applies a plan: source checks → backup → atomic replace; rollback from backup |
173
+ | `stm32_ioc_verify` | Has CubeMX re-read the `.ioc` and points out silently dropped peripherals and missing init calls |
174
+
175
+ ### Diagram rules
176
+
177
+ The diagram is a functional frame, not a per-component schematic:
178
+
179
+ - Groups: MCU, NFC antenna and tag, optical sensing, power, debug interface, keys; links inside a group are not drawn.
180
+ - Links only between groups; labels collapse to bus names such as I2C, SPI, UART, ADC, LED, PWM, SWD.
181
+ - Power nets (VCC, GND) are listed separately and never drawn; nets with too many endpoints are left out.
182
+ - Layout is generated by the plugin: MCU in the middle, modules around it, links leave the side facing the peer and stay straight when they can.
183
+
184
+ The same rules ship in the plugin skill text, so reading and drawing the diagram use one convention.
185
+
186
+ ### Schematic (KiCad 10)
187
+
188
+ | Tool | Purpose |
189
+ | --- | --- |
190
+ | `stm32_sch_read` | Read a KiCad project: sheet tree, components, nets, power nets and a block diagram (which circuits connect, over which bus) |
191
+ | `stm32_sch_pins` | MCU pin matrix: net name, pin type, whether the pin is left open, plus reusable signal candidates from the CubeMX database |
192
+ | `stm32_sch_check` | Check the schematic itself and reconcile it with `.ioc` and `.kicad_pcb`: missing values, missing footprints, missing SWD / BOOT0 / power, split nets |
193
+ | `stm32_sch_to_ioc` | Turn pin connections into a `.ioc` draft: suggested signal, confidence and candidates per pin, input/output hints for plain GPIO nets, plus a software-emulation fallback with its cost when no hardware function fits; read-only, never writes `.ioc` |
194
+
195
+ Scope is KiCad 10 (`version 20260306`). Symbol libraries are embedded in the sheets, so KiCad does not need to be installed and `sym-lib-table` is not read; only sheets referenced from the root sheet are parsed, and `.history/` plus other historical versions are ignored. Reconciliation is based on connectivity: pads on one PCB net must belong to one schematic net, and name differences are reported as hints only. The tools are read-only: the schematic and the project configuration are never modified. A draft from `stm32_sch_to_ioc` only lands on disk through `stm32_ioc_plan`, and pins that match no library signal are listed for confirmation.
196
+
197
+ ### Circuit design (tscircuit + KiCad)
198
+
199
+ Write circuits under `hardware/` with tscircuit, export a real KiCad project, then verify it with KiCad's own checkers. Checks follow JLCPCB's standard process: track width and clearance ≥ 0.2 mm, drill ≥ 0.3 mm, silkscreen text height ≥ 0.8 mm. The rules are written into the project's `.kicad_dru`, so the report answers "can this be fabbed in that tier", together with a prototype cost estimate.
200
+
201
+ | Tool | Purpose |
202
+ | --- | --- |
203
+ | `stm32_ecad_init` | Create `hardware/{circuit,kicad,libs,out}` with a minimal `package.json`; dependencies come from the shared runtime (see below), not one copy per project |
204
+ | `stm32_sch_review` | One-shot schematic review: read, rule check, `.ioc` draft and the pins that need a human decision; read-only |
205
+ | `stm32_ecad_design` | One-shot design: build → merge pads (optional) → export libs → ERC/DRC → manufacturability and cost → STEP and fabrication files, reported step by step; pass `pcb=true` to autoroute after lib export (needs KiCadRoutingTools, skipped when missing) |
206
+ | `stm32_ecad_build` | Run `tsci build` with KiCad's bundled bun: `.circuit.tsx` → `circuit.json`, SVGs and `kicad/*.kicad_sch|.kicad_pcb`; with `footprint="kicad:…"` it also renames generated `tscircuit:` names back to the real library and copies the official footprints into `hardware/libs`; JLC footprints (`footprint="jlcpcb:C…"`) are vendored into the library per reference and recorded in `libs/sources.json`; before building it pre-checks the footprint for coincident pads (the A1/B12 pair of a 16P USB-C), and when found it skips autorouting and ignores the placement-clearance warning while still producing the board; pass `mergePads=true` to merge coincident same-net pads into one multi-number pad |
207
+ | `stm32_ecad_check` | Export the project libraries first, then run `kicad-cli sch erc` and `pcb drc`, collapsing violations into rule, severity and affected items; unnamed nets are reported too |
208
+ | `stm32_ecad_libs` | Extract embedded footprints and symbols into real libraries under `hardware/libs` and fill in `fp-lib-table` / `sym-lib-table` |
209
+ | `stm32_ecad_step` | Export STEP into `hardware/out`; resolves models through official 3D dir → `hardware/libs/3d` → cache and rewrites their paths; missing models are reported, not fatal |
210
+ | `stm32_ecad_export` | Export Gerbers, drill files, pick-and-place coordinates and STEP into `hardware/out` in one go |
211
+ | `stm32_ds_fetch` | Fetch non-STM32 datasheets into the local cache: by LCSC code, for every part used by the project, or from a manually imported PDF |
212
+ | `stm32_ds_lookup` | Look up a cached datasheet by purpose: pinout, absolute maximum ratings, electrical characteristics, timing, package — page number, heading and the start of that page |
213
+ | `stm32_ds_list` | List the local datasheet cache: code, MPN, size, fetch time and source |
214
+ | `stm32_pdf_read` | Read a PDF: `info` for page count and text layer, `text` for page text (layout preserved), `figures` to list figures, `table` to cut parameter tables into rows and columns, `render` to rasterise a page or region into PNG for visual reading, `curve` to digitize a curve figure into an auditable (x, y) series |
215
+ | `stm32_pcb_place` | Plan component placement from `circuit.json` and move the footprints in `.kicad_pcb` (drops stale tracks by default, keeps a `.bak`) |
216
+ | `stm32_pcb_autoroute` | Route with KiCadRoutingTools (Rust grid router): planes, fanout, then routing; reports open nets. Dry-run by default |
217
+ | `stm32_pcb_render` | Draw a `.kicad_pcb` as an SVG board view: outline, top and bottom copper, pads, vias, silkscreen; returns size and counts unless `saveAs` is given |
218
+ | `stm32_brief` | Generate the three-document skeleton: `docs/01-MRD.md` (why), `02-hardware-PRD.md` (electrical targets), `03-design-brief.md` (how). MCU, clocks, peripherals, board size and BOM cost are filled from the project; requirements and acceptance stay "TBD" instead of being invented. Existing files are not overwritten by default |
219
+ | `stm32_power` | Power-tree current budget: per-rail voltage, current, the parts on it, and the narrowest track vs the IPC-2221 width. Only currents you supply are summed; name-based guesses are reported separately and unknown rails stay "TBD" |
220
+ | `stm32_pcb_links` | Routing review: differential-pair length skew and via counts, per-layer copper pour and signal count, decoupling-cap distance to the IC power pin; geometry only, no simulation |
221
+ | `stm32_pcb_3d` | 3D preview: renders the board to PNG with KiCad's `kicad-cli pcb render` (top/bottom/left/right/front/back, optional perspective and rotation), and names the refs whose referenced 3D model files are missing (those parts are blank in the render); for missing models it suggests official footprints with the same family/pin count/pitch and marks whether their STEP exists; the panel offers top/bottom/iso presets |
222
+ | `stm32_pcb_swap` | Swap footprint: replaces a ref with a footprint from the official KiCad library, keeping ref/value/position/rotation and carrying nets over by pad number; dry-run by default, `apply` writes (with a `.bak`), and a pad-size change is reported as "re-route around this part" |
223
+ | `stm32_pcb_gerber` | Manufacturing-file review: read the Gerber and drill files produced by `stm32_ecad_export` back into one SVG (optional layer filter) to check outline, copper, silk and holes before shipping; unsupported constructs are listed in notes |
224
+ | `stm32_impedance` | Impedance write-back: compute the track width and gap for 50 Ω single-ended and 90 Ω differential from the stackup and write them as custom rules in `.kicad_dru` (named nets only); KiCad DRC has no impedance constraint, so the rules carry geometry |
225
+ | `stm32_netgate` | Keep schematic and PCB in step: stale board, split nets, missing pads |
226
+ | `stm32_sch_import` | Absorb KiCad board edits back into `circuit.tsx`: netlist and parts only, positions are re-laid out on build |
227
+ | `stm32_sch_edit` | Hand edits to the schematic: stored as instructions in `schematic-edits.json` and replayed at the end of each build |
228
+ | `stm32_sch_sync` | Push parts added in the hand layer onto the board: reads refs/values/footprints/nets from `hardware/schematic/*.kicad_sch`, plans with `planHandSync`, and on `apply: true` runs KiCad's bundled python to `FootprintLoad` + `Add` them into the latest built `.kicad_pcb` (leaves a `.bak`). Skips refs already on the board, refuses `tscircuit:` and footprint-less parts, assigns only nets the board already declares, and parks new parts below the board outline with a note to move them before routing |
229
+ | `stm32_sch_draw` | Schematic hand layer: `wire` between pins or points, `label` nets, `clone` a part with a new reference, `place` a new part from a symbol library (embeds `lib_symbols`), `move`/`remove`; writes `hardware/schematic/*.kicad_sch` (never touched by builds) with no KiCad process required, then validates with `kicad-cli sch export netlist` |
230
+ | `stm32_part_import` | Part import: copy a footprint from the KiCad libraries by `Lib:Name`; when it is missing and an LCSC code is given, convert the EasyEDA package from the LCSC page into a `.kicad_mod` (`source=kicad` forces library-only). Generates a symbol skeleton from pad numbers, copies the footprint's referenced 3D model into `hardware/libs/3d` and rewrites it as a `${KIPRJMOD}` relative path, records the LCSC part as footprint properties (`LCSC`/`MPN`/`Brand`/`Datasheet`), and registers `fp-lib-table`/`sym-lib-table` |
231
+ | `stm32_symbol_footprint` | Symbol and footprint generation: emit `.kicad_sym` from a pin list and `.kicad_mod` from package dimensions (QFP / SOIC / two-pad parts); dimensions and pin numbers must be supplied, missing one is an error |
232
+ | `stm32_part_search` | Part search: look up LCSC codes, stock, price ladders and datasheet links by MPN, parameters or code; results cached 24 h, package field left blank when the API omits it |
233
+ | `stm32_mech` | Enclosure and mechanical constraints: outline size, mounting-hole coordinates and drills, minimum hole-to-edge distance, board area; `export` writes a DXF (R12, outline + mounting holes) for mechanical tools |
234
+ | `stm32_pcb_ipc` | Local edits inside the **open KiCad PCB editor**: board status, move a footprint by reference, draw a track, add a via, refill zones, save. Uses KiCad's official IPC, so edits land in its undo stack. Plan-only by default; `apply: true` plus `expectBoard` to change the board. When nothing is open it launches pcbnew with this project's board and waits (`open: false` to disable) |
235
+ | `stm32_pcb_route` | Grid A* routing (0.5 mm grid) that avoids pads and existing tracks; preview by default, writes only with `apply: true` (run DRC after) |
236
+ | `stm32_ecad_package` | Pack `hardware/` into a deliverable zip (skips `node_modules`, `dist`, `.history`) and read it back to self-check |
237
+
238
+ There is exactly one writer: `.kicad_sch` / `.kicad_pcb` are produced by tscircuit and only read by the plugin. tscircuit embeds symbols and footprints in the project under generated names such as `tscircuit`, so checks first export them into real libraries under `hardware/libs` and complete the library tables; otherwise the report is dominated by "library not in configuration" noise. Unnamed nets (`.R1 > .pin1 to .C1 > .pin1`) are listed separately with the `<net name="VDD" />` fix. Building requires KiCad 10 and its bundled `bun.exe`.
239
+
240
+ Dependencies are installed once: `tscircuit` and `typescript` live in a shared runtime at `~/.dsh-stm32/ecad-runtime` (`DSH_STM32_ECAD_RUNTIME` overrides), and each project's `hardware/circuit/node_modules` is a directory junction to it — ESM resolution needs `node_modules` inside the project tree, the junction satisfies that, and the disk holds one copy (~730 MB). `DSH_STM32_ECAD_AUTO_INSTALL` controls the first install: `auto` installs, `off` never does, default `ask` only prints the command.
241
+
242
+ When circuit sources change, the plugin builds once at the end of the turn (build + checks only, no artifacts), so KiCad shows the latest schematic and PCB. Guards: only when sources are newer than products or the last build failed, at most once per turn, at least 60 s apart. The last result appears in the panel header and in `<project>/.dsh-stm32/ecad-state.json`. Prefer KiCad's own libraries (`footprint="kicad:..."`) and fall back to JLCPCB part numbers only when needed.
243
+
244
+ PCB routing uses an external engine, `KiCadRoutingTools` (MIT, Rust grid router). It is not shipped with the plugin: install once, shared by every project:
245
+
246
+ ```bash
247
+ git clone --depth 1 https://github.com/drandyhaas/KiCadRoutingTools ~/.dsh-stm32/kicad-routing-tools
248
+ # Rust module: `python build_router.py` downloads a prebuilt binary; when the GitHub API is rate-limited,
249
+ # fetch `grid_router-windows-x86_64.pyd` from the release and drop it into KiCad python's Lib/site-packages.
250
+ "D:/app/KiCad/10.0/bin/python.exe" -m pip install numpy scipy shapely
251
+ ```
252
+
253
+ Override the location with `DSH_STM32_KRT_ROOT`. Without it `stm32_pcb_autoroute` reports that the engine is missing and everything else keeps working.
254
+
255
+ Design rules follow the **copper layer count** at JLCPCB's standard tier: 0.127 mm for 1–2 layers, 0.10 mm for multilayer, the same table the router uses. Routing and DRC share the tier, so `clearance` is not reported board-wide; the `.kicad_dru` threshold is 0.003 mm below the tier to absorb grid quantization (measured minimum 0.0974 mm). Measured on a 41-part / 35-net / 4-layer board through design-with-routing: 0 open nets, DRC down from 259 errors to **0 errors / 132 warnings**, 52 s build and 32 s routing.
256
+
257
+ ### Code and build
258
+
259
+ | Tool | Purpose |
260
+ | --- | --- |
261
+ | `stm32_code_patch` | Writes only inside `USER CODE BEGIN/END` blocks, preserving all other bytes; backs up first |
262
+ | `stm32_generate` | Runs CubeMX headless, places output in `Core/`, carries `USER CODE` back by tag; skips when `.ioc` is unchanged |
263
+ | `stm32_build` | Builds: infers build directory and `.elf`, returns error lines, warning count, FLASH / RAM usage; optional hex / bin; when `CMakeCache.txt` no longer matches the project it names the reason, and `reconfigure: true` clears the cache and reconfigures |
264
+
265
+ ### Flash, debug and runtime
266
+
267
+ | Tool | Purpose |
268
+ | --- | --- |
269
+ | `stm32_flash` | Flash only: program + verify + reset, then releases the probe; checks Serial Wire first; failures return the probe error class and a suggested action |
270
+ | `stm32_debug_run` | Flashes, halts at `main`, captures registers, stack and locals, then resets, runs and releases the probe |
271
+ | `stm32_debug_session` | Opens a long-lived debug session (idle and total limits) for repeated `stm32_debug_eval` calls |
272
+ | `stm32_debug_eval` | Executes gdb commands in the session: variables, registers, backtrace, memory |
273
+ | `stm32_debug_stop` | Closes the session and releases the probe |
274
+ | `stm32_regs_read` | Reads registers by address or symbol, resolving bitfields when register tables are present; pauses briefly to read, then resumes without resetting |
275
+ | `stm32_watch` | Registers and samples expressions (with deltas); `kind=write/read/access` installs hardware watchpoints, limited by the chip's watchpoint count |
276
+ | `stm32_rtt` | RTT channel: firmware keeps the control block in RAM, the host reads it through openocd, output carries level and timestamp |
277
+ | `stm32_serial` | Serial interaction (Windows): `list` / `open` / `read` / `send` / `transact` / `status` / `close` |
278
+
279
+ ### RTT on the firmware side (shortest example)
280
+
281
+ ```c
282
+ /* USER CODE BEGIN 0 */
283
+ static char rtt_buf[3][1024];
284
+ static void rtt_init(void) {
285
+ /* Control block follows the SEGGER convention in RAM: acId / acName / three rings, see rtt.h in templates/ */
286
+ }
287
+ /* USER CODE END 0 */
288
+ ```
289
+
290
+ The full implementation ships in `templates/`; channel count and ring size are controlled by `RTT_UP_CHANNELS` / `RTT_BUF_SIZE` (default 3×1 KB = 3 KB `.bss`; C8T6 has 20 KB RAM).
291
+
292
+ ## PDF reading and the datasheet cache
293
+
294
+ `stm32_pdf_read` needs poppler (`pdftotext` / `pdfinfo` / `pdftoppm`):
295
+
296
+ ```
297
+ pacman -S --needed mingw-w64-ucrt-x86_64-poppler
298
+ ```
299
+
300
+ `stm32_doctor` reports the version. Modes: `info` (pages, paper, text layer), `text` (page text with layout preserved), `figures` (figure and table captions with page numbers), `table` (parameter tables cut into rows and columns) and `render` (page or region as PNG for visual reading, 300–400 dpi when you need to read numbers off a chart).
301
+
302
+ Charts are read as images: shape and order of magnitude (about ±0.5 of a minor tick), not exact values. For exact numbers use a table on the same page.
303
+
304
+ Non-STM32 parts are fetched once and cached:
305
+
306
+ - `stm32_ds_fetch code=C25137` fetches by LCSC code; `all=true` fetches every `jlcpcb:` part the project uses; `file=` imports a PDF by hand.
307
+ - Cache: `~/.dsh-stm32/datasheets/<code>/` (`meta.json` plus a PDF named after its content sha256); `DSH_STM32_DATASHEETS` relocates it. Cache hits make **no network calls**; failures are remembered for 24 hours and `refresh=true` retries.
308
+ - `stm32_ecad_build` fetches the datasheets the project uses after a successful build; the Circuit design tab shows `datasheets 2/3` in its header and the same logic behind its "fetch datasheets" button.
309
+ - A 16P USB-C footprint splits one piece of copper into two pads (A1/B12); the autorouter cannot pick a unique pad and drops the whole board. When the pre-check finds such a pair, the build skips routing and ignores the placement-clearance warning, leaving routing to KiCad.
310
+ - `stm32_ds_lookup code=C25137 kind=electrical` jumps to the electrical characteristics page: the first 40 pages are indexed once (page numbers only), then text is read per page.
311
+ - `stm32_ds_list` shows what is cached and how much space it takes.
312
+ - The datasheet pin table can back `stm32_sch_to_ioc`: pass `datasheet=C25137` and pins whose signals are missing from the CubeMX database get candidates from the "Pin name / Alternate functions" columns, marked `(datasheet)`.
313
+ - Cache cleanup: `stm32_ds_list remove=C25137` or `olderThanDays=180` reports what was deleted and how many bytes were freed; the panel shows "handbooks x/y (N.N MB)" read-only, deletion stays in the tool.
314
+ - Curves do not have to be eyeballed: `stm32_pdf_read file=DS14721.pdf mode=curve page=44` groups pixels by hue, calibrates a linear mapping from the axis ticks and returns an (x, y) series; legend text is not decoded, so series are named by hue.
315
+ - Afterwards `stm32_pdf_read file=C25137` (or the MPN) reads the cached copy directly, so pinout, limits and timing come from the document.
316
+
317
+ ## Slash commands
318
+
319
+ | Command | Description |
320
+ | --- | --- |
321
+ | `/stm32-doctor` | Health check: toolchain, leftover processes, ports, `.elf` and `.ioc` warnings |
322
+ | `/stm32-env` | Toolchain check: what build / flash / debug / generate are missing, where things install, how to install |
323
+ | `/stm32-setup` | Probe → install plan → install after confirmation → self-check |
324
+ | `/stm32-build [dir] [--clean]` | Build (CMake + Ninja, `build/Debug` by default); `--clean` wipes first |
325
+ | `/stm32-flash [dir]` | Flash only: program + verify + reset, then release the probe |
326
+ | `/stm32-debug [dir]` | Flash and enter debugging, halted at `main`; then use `stm32_debug_eval` |
327
+ | `/stm32-stop` | Close the debug session and release the probe for VS Code F5 |
328
+
329
+ ## Debug console (panel)
330
+
331
+ The in-session debug console shows one timeline for both sides: the start, success, failure and duration of `stm32_*` calls, plus serial, RTT, watch, pin, clock, interrupt and `.ioc` state.
332
+
333
+ | Tab | Content | Actions |
334
+ | --- | --- | --- |
335
+ | Overview | Project, part number, SYSCLK, capacity, debug session, toolchain, build and flash, evidence usage, alert summary | Jump to failed events or the live channel, export an operation log as Markdown |
336
+ | Events | Call start and end, duration, slow-call marker, argument summary | Failures only, filter by tool, sort by duration, bulk quoting, JSONL export, event deep links |
337
+ | Live channels | Serial / RTT / watch output | Pause, clear, keyword filter, RTT level filter, send a serial line, persistent capture, export |
338
+ | Pins | Grouped by peripheral, by port, or drawn as the package (chip part number, package name, four sides of pin bars, pin-1 dot) | Filter, copy references, inspect `.ioc` keys, CSV export |
339
+ | Diagram | Hub-and-spoke flow diagram grouped by function (MCU in the centre, NFC antenna and tag, light sensing, power, debug port and keys around it; when the schematic carries no part numbers the MCU is inferred from pad count and refdes, and the footer says so); links leave any of the four sides and are labelled by bus and signal purpose, with check results | Read-only; parts are not boxes of their own; power nets are listed separately; the "Review" button runs read + rule check + `.ioc` draft and lists pins that need a human decision |
340
+ | Circuit design | tscircuit workspace state: initialisation, dependencies, entries, latest build, libraries, exported artifacts | trigger build, check, library export, STEP export, Gerber packaging, deliverable packaging and datasheet fetching from the tab; a build takes tens of seconds |
341
+ | Clocks | Tree and flow views, per-node frequency and divider | Over-limit markers and "change to ÷N" advice computed from the parent clock |
342
+ | Interrupts | NVIC enablement, preemption and sub-priority | Filter, sort, edit in place, bulk edit |
343
+ | Faults | Raw failure events, rule decoding, grouping by rule | Category filter, copy group hint, CSV export |
344
+ | Artifacts | elf / hex / bin, size, checksum, capacity, build-to-build comparison | Copy checksums |
345
+ | Changes | `.ioc` differences against a baseline | Record a baseline, restore one key, restore all |
346
+
347
+ Project directories are resolved by convention, and the locations can be set explicitly: firmware lives in `program/`, `firmware/`, `app/`, `user/`, `fw/`, `code/`, or the project root; when none of them match, `*.ioc` is scanned two levels deep and its parent directory becomes the firmware directory (the name is yours to choose); the KiCad project lives in `hardware/`, `kicad/`, `hw/`, or `pcb/` (otherwise `*.kicad_pro` is scanned); configuration and baselines stay in `.dsh-stm32/` at the project root. Both locations can be written to `dsh-stm32.conf` (`firmware=` / `hardware=`), and an `ioc=` entry wins over all conventions. The workspace index always lives in `<workspace>/.dsh-stm32/workspace.conf` and the project description in the project root; `stm32_layout_fix` moves misplaced files (backing them up first).
348
+
349
+ Opening the panel first loads the most recent records for the session, then appends live. Events are written every 30 seconds to `~/.dsh-stm32/evidence/<date>/<session>/` for replay and export, retained for 7 days and the last 20 sessions by default, all configurable. The panel shows only this plugin's own tool calls. The panel shows only this session's project and debug session: in a session from another workspace, the panel stays empty instead of borrowing another session's project or debug output.
350
+
351
+ ## Serial (Windows)
352
+
353
+ `stm32_serial` exposes seven actions: `list` / `open` / `read` / `send` / `transact` / `status` / `close`. Once opened, the port is held by the plugin, one port at a time; 115200 8N1 by default, no flow control, DTR / RTS not asserted, closed at the end of a turn.
354
+
355
+ - Platform: Windows only. Linux and macOS return `unsupported-platform`.
356
+ - Ports: `list` enumerates available ports; parameters are remembered per device, so a different COM number still reuses them.
357
+ - Read: `read` accepts a cursor and returns only newer lines.
358
+ - Write: `send` writes one line; `transact` writes and waits for a matching reply (regular expression).
359
+ - Retention: `persist=true` keeps the port open across turns.
360
+
361
+ The reference validation board uses a CH340 (`1A86:7523`, COM5, 115200). The DAPLink virtual serial port on the same board (`c251:f001`, COM4) does not carry application data.
362
+
363
+ ## Design notes
364
+
365
+ - **Own files only**: the `.ioc` goes through a transaction (plan → checks → backup → replace); generated regions receive only `USER CODE` content; no other generated file is modified.
366
+ - **Flash and debug are separate**: `stm32_flash` never opens a debug session and releases the probe immediately; debugging opens `stm32_debug_session` on demand and closes it when idle, so VS Code is not locked out.
367
+ - **Conclusions carry evidence**: failures return compiler `file:line:col`, probe error class and register values rather than vague prose.
368
+ - **Say what is missing**: when a chip, a clock plan or a debug script is unsupported, the error names the missing piece instead of guessing or silently skipping.
369
+ - **No host takeover**: the panel displays state and performs explicit project actions; it does not edit code or run Git operations.
370
+
371
+ ## Configuration
372
+
373
+ ### Config file (`~/.dsh-stm32/config.json`)
374
+
375
+ Toolchain locations are maintained by the plugin: `stm32_env_install` writes this file and later tools read it, with no DSH restart and no environment variables required. Manual editing is supported:
376
+
377
+ ```json
378
+ {
379
+ "version": 1,
380
+ "msys64": "E:/msys64",
381
+ "binDirs": [],
382
+ "packages": ["mingw-w64-ucrt-x86_64-arm-none-eabi-gcc", "mingw-w64-ucrt-x86_64-cmake"],
383
+ "cubeMxRoot": "",
384
+ "updatedAt": "2026-02-01T00:00:00.000Z"
385
+ }
386
+ ```
387
+
388
+ An empty `binDirs` derives `<msys64>/ucrt64/bin` from `msys64`. A corrupt file (invalid JSON) is treated as absent and does not break other features.
389
+
390
+ Precedence: tool arguments (`binDirs` / `cubeMxRoots`) > environment variables > config file > built-in defaults. Built-in defaults contain only common Windows locations, never machine-specific paths.
391
+
392
+ ### Settings panel
393
+
394
+ The "STM32 toolchain" page under DSH settings offers three cards:
395
+
396
+ - **Locations**: reads and saves `msys64` / `cubeMxRoot` / extra `binDirs`; the next tool call sees the change.
397
+ - **Missing pieces**: runs a probe (version queries only) and lists path, version and reason per item, plus badges for build / flash / debug / generate.
398
+ - **Install toolchain**: emits a plan first (steps, download size, PATH and config changes), executes after confirmation, and streams steps with a log tail.
399
+
400
+ ### Download cache and firmware packages
401
+
402
+ - Register-route CMSIS templates are downloaded on first use into the cache (default `%LOCALAPPDATA%\dsh-stm32\cache`) and reused afterwards; files are verified and mismatches rejected. `stm32_cache` lists, verifies, fetches and prunes entries.
403
+ - The HAL route uses locally installed CubeMX firmware packages: F1 defaults to `STM32Cube_FW_F1_V1.8.7`, other families use the highest installed version; `firmwarePackage` overrides. When missing, install it through the CubeMX package manager or use `stm32_firmware_install`.
404
+ - `stm32_download` only downloads or verifies installers (default directory `%LOCALAPPDATA%\dsh-stm32\downloads`); it never executes them and never requests administrator rights.
405
+
406
+ ### Environment variables (optional)
407
+
408
+ | Variable | Purpose | Default |
409
+ | --- | --- | --- |
410
+ | `STM32_BIN_DIRS` | Toolchain directory candidates, `;`-separated, replaces the built-in list entirely (auto-discovery still appends) | `C:/msys64/ucrt64/bin`, `C:/msys64/mingw64/bin` |
411
+ | `STM32_CUBEMX_ROOT` | CubeMX root, replaces the built-in list | `C:/Program Files/STMicroelectronics/STM32Cube/STM32CubeMX` |
412
+ | `STM32_NO_DISCOVER` | Set to `1` to disable auto-discovery (built-in list only) | unset |
413
+ | `DSH_STM32_CONFIG` | Alternate config file path | `%USERPROFILE%\.dsh-stm32\config.json` |
414
+ | `DSH_STM32_NO_CONFIG` | Set to `1` to ignore the config file entirely | unset |
415
+ | `DSH_STM32_CACHE` | Download cache root, supports `~` | `%LOCALAPPDATA%\dsh-stm32\cache` |
416
+ | `DSH_STM32_DOWNLOADS` | Installer download directory, supports `~` | `%LOCALAPPDATA%\dsh-stm32\downloads` |
417
+ | `DSH_STM32_HOME` | Plugin data root (config, evidence, snapshots, memo) | `%USERPROFILE%\.dsh-stm32` |
418
+ | `DSH_STM32_EVIDENCE` | Evidence directory | `~/.dsh-stm32/evidence` |
419
+ | `DSH_STM32_EVIDENCE_FLUSH_SECONDS` | Flush interval (5–3600 s) | 30 |
420
+ | `DSH_STM32_EVIDENCE_KEEP_DAYS` | Evidence retention in days (0–365, 0 = keep) | 7 |
421
+ | `DSH_STM32_EVIDENCE_KEEP_SESSIONS` | Evidence retention in sessions (1–200) | 20 |
422
+ | `DSH_STM32_SNAPSHOTS` | `.ioc` baseline directory | `~/.dsh-stm32/ioc-snapshots` |
423
+ | `DSH_STM32_OFFLINE` | Set to `1` to forbid network downloads (cache only) | unset |
424
+ | `MSYS2_MIRROR` | Installer mirror; must be set together with `MSYS2_INSTALLER_SHA256` | official → TUNA → NJU → Aliyun |
425
+ | `MSYS2_INSTALLER_URL` / `MSYS2_INSTALLER_SHA256` | Installer URL and checksum overrides; must be set together | official pinned release |
426
+ | `DSH_STM32_JLINK_URL` / `DSH_STM32_JLINK_SHA256` | J-Link direct link and checksum overrides; must be set together | SEGGER official |
427
+
428
+ Tool arguments mirror these variables: flash and debug tools accept `binDirs`, `elfPath`, `buildDir`, `configFile`, `adapterSpeed`; generation and scaffolding accept `cubeMxRoots`, `firmwarePackage`.
429
+
430
+ Toolchain locations usually need no configuration: when `binDirs` / `STM32_BIN_DIRS` are absent, the plugin searches common locations and appends candidates — `ucrt64/bin`, `mingw64/bin` and `clang64/bin` under `<drive>/msys64`, `<drive>/msys2`, `<drive>/app/msys64`, `<drive>/tools/msys64`, `%LOCALAPPDATA%/Programs/msys64`; and CubeMX under the `STM32CubeMX_PATH` environment variable, its uninstall registration, and `Program Files\STMicroelectronics\STM32Cube`. When nothing is found, errors and `stm32_doctor` list the directories that were checked.
431
+
432
+ ### openocd.cfg (project-level, takes precedence)
433
+
434
+ CMSIS-DAP (default):
435
+
436
+ ```text
437
+ source [find interface/cmsis-dap.cfg]
438
+ source [find target/stm32f1x.cfg]
439
+ adapter speed 4000
440
+ ```
441
+
442
+ ST-Link:
443
+
444
+ ```text
445
+ source [find interface/stlink.cfg]
446
+ transport select hla_swd
447
+ source [find target/stm32f1x.cfg]
448
+ ```
449
+
450
+ Without `openocd.cfg`, the debug script follows the chip family in the `.ioc` (F1 → `stm32f1x`, F4 → `stm32f4x`, G4 → `stm32g4x`; L4 and L4+ share `stm32l4x`). C0 / U0 scripts ship with the plugin and are copied into the project's `openocd/` directory during scaffolding; H5 / N6 / U3 / WBA / WB0 / WL3 / MP2 have no scripts and flashing is refused explicitly.
451
+
452
+ ### Two hard requirements on the `.ioc`
453
+
454
+ 1. **SYS debug port set to Serial Wire** (PA13 = `SYS_JTMS-SWDIO`, PA14 = `SYS_JTCK-SWCLK`); use `stm32_ioc_plan` with `serialWire: true` when missing.
455
+ 2. **`ProjectManager.KeepUserCode=true`**; otherwise `USER CODE` content is lost on regeneration.
456
+
457
+ ## Known limitations
458
+
459
+ | Limitation | Detail | Handling |
460
+ | --- | --- | --- |
461
+ | Verified on Windows only | Code generation depends on the Windows installation of CubeMX | No alternative yet; flash, debug and register reads may work elsewhere with a complete toolchain, unverified |
462
+ | Some chips have no official debug script | C0 / U0 use plugin-supplied scripts (not verified on hardware); H5 / N6 / U3 / WBA / WB0 / WL3 / MP2 have none | Flashing states this explicitly instead of failing silently |
463
+ | HAL scaffolding excludes dual-core and MPU families | Dual-core WB, MP1 / MP2 / N6, WB0 / WL3 are out of scope | Scaffolding reports the chip as unsupported |
464
+ | Depth is graded per family | HAL 21 families, register 21, clocks 18; register names and bitfields currently F1 only | The missing capability is named at call time |
465
+ | Probes selected from what USB reports | ST-Link, DAPLink / CMSIS-DAP and J-Link are distinguished automatically; a project `openocd.cfg` wins | Write `openocd.cfg` to pin a choice |
466
+ | New peripherals need manual HAL sources | The plugin places only `Src/` and `Inc/`; CubeMX-generated `cmake/**` is not carried over | Edit `STM32_Drivers_Src` or write into `cmake/user/CMakeLists.txt` |
467
+ | Generation and scaffolding need CubeMX plus the family firmware package | F1 defaults to `STM32Cube_FW_F1_V1.8.7` | Pass `firmwarePackage`, or install the package in CubeMX first |
468
+ | RTT is channel 0 only with a custom frame | 13-byte header (length, level, timestamp, UTF-8 text) | Filter by level; put structured data in the text; channels and ring size in `rtt.h` |
469
+ | Serial is Windows-only | No streaming UI, no auto-reconnect, one port at a time | Use a system serial tool, or a later release |
470
+ | Register names and bitfields need the bundled register tables | Covers F1 lines 100 / 101 / 102 / 103 / 105 / 107 | Use `0x` addresses; `stm32_assets verify` checks the installation |
471
+
472
+ ## Troubleshooting
473
+
474
+ | Symptom | Cause | Action |
475
+ | --- | --- | --- |
476
+ | Plugin not loaded | `dsh.profile.bundles` lacks `dsh-stm32`, or DSH was not restarted | Reinstall and restart; verify with `dsh plugin --profile desktop why dsh-stm32` |
477
+ | Code changes have no effect | Installed via `file:`, so the host reads a copy | Switch to `link:`, rebuild with `npm run build`, restart DSH |
478
+ | Missing toolchain reported | Not installed, or path not discovered | Run `/stm32-env` to see what is missing, then `/stm32-setup`; or set `binDirs` manually |
479
+ | Flash reports the probe is busy | Another debugger (VS Code, leftover openocd) holds the probe | `/stm32-stop`, close other debuggers, retry; `stm32_doctor` lists leftover processes |
480
+ | SWD is lost after flashing | `.ioc` did not enable Serial Wire | Add `serialWire: true` via `stm32_ioc_plan`, regenerate, flash again |
481
+ | Peripherals dropped after generation | `.ioc` keys inconsistent with peripheral derivation | Run `stm32_ioc_verify` for a CubeMX-side diagnosis |
482
+ | Panel is blank or stale | Server-side change without restart, or `lib` newer than the process | Fully exit DSH and start again; the status bar flags "new build available" |
483
+ | No serial data | Wrong port (for example the DAPLink virtual port) | Confirm with `stm32_serial list`; application serial usually lives on a CH340-class adapter |
484
+
485
+ ## Development and testing
486
+
487
+ | Command | Purpose |
488
+ | --- | --- |
489
+ | `npm run build` | `tsc` into `lib/`, copying client and data assets |
490
+ | `node test/run-units.mjs` | Offline unit tests: 81 suites / 1101 cases, no board required |
491
+ | `node .dsh-stm32/acceptance.mjs` | Local acceptance script: panel API, event stream, evidence, artifacts, faults, interrupts, serial, probe |
492
+ | `npm run test:pack` | Pack, unpack and scaffold a register project with the unpacked build |
493
+ | `npm run test:size` | Package and asset guards |
494
+
495
+ Release shape: published content is limited to `files` in `package.json` (`lib`, `client`, `templates`, `assets`, `docs/reading-guide.md`, `cordis.patch.yml`, both READMEs, `LICENSE`). `docs/`, `test/` and `scripts/` stay out of the package.
496
+
497
+ Development-only environment variables (not needed in daily use): `DSH_STM32_ASSETS` and `DSH_STM32_FACTS` override asset directories, `DSH_STM32_SERIAL_BRIDGE` and `DSH_STM32_SERIAL_POWERSHELL` override the serial bridge path, `DSH_STM32_PYTHON` selects the Python interpreter used for parsing.
498
+
499
+ ## Repository layout
500
+
501
+ ```text
502
+ src/
503
+ index.ts plugin entry: tools, slash commands, panel API, SKILL
504
+ tools/ registration and argument validation for 66 tools
505
+ engine/ engines: project, .ioc, generation, build, flash, debug, events, panel API
506
+ data/ chip data, CubeMX data, clocks, search roots, toolchain config
507
+ commands/ 7 slash commands
508
+ skill/ bundled stm32-workflow SKILL
509
+ client/client.js panel source (plain JS + react, no bundler)
510
+ lib/ tsc output and copied assets (published)
511
+ assets/ chip data, .ioc templates, linker scripts, startup files, register tables
512
+ templates/ scaffolding templates, register route, serial bridge, RTT
513
+ test/ 80 offline suites and e2e scripts
514
+ scripts/ build, pack, size and smoke scripts
515
+ docs/ development notes, reading guide, spec, diagrams
516
+ ```
517
+
518
+ ## Documentation
519
+
520
+ - [Specification](docs/dsh-stm32-plugin-规格.md): tool contracts, state machine, acceptance criteria
521
+ - [Development notes](docs/development-notes.md): milestones, host-contract issues, per-tool implementation details and measurements
522
+ - [Source reading guide](docs/reading-guide.md): layered reading order, per-file responsibilities and exports, diagrams and invariants
523
+ - Release notes: provided per release on the release page; history lives in git and the development notes
524
+ - Visuals: [architecture](docs/diagrams/dsh-stm32-architecture.html) / [main journey](docs/diagrams/dsh-stm32-journey.html) — single-file HTML, opens offline
525
+
526
+ ## Acknowledgements
527
+
528
+ Parts of the circuit-design and PCB design are modelled on these two open-source projects (design ideas only; any code is used under its own licence):
529
+
530
+ - [oh-my-embedded](https://github.com/captainluzik/oh-my-embedded) (MIT): expert knowledge packaged as small callable tools (power budget, decoupling advice, pin mapping, impedance). The decoupling and placement advice here follows that idea.
531
+ - [PCB-Agent-Teams](https://github.com/Zane456/PCB-Agent-Teams) (PolyForm Noncommercial 1.0.0): a phased pipeline with "roll back when a gate fails, verify every conclusion twice, never draw before assets exist" discipline. The workflow design is borrowed; no code is copied.
532
+
533
+ Thanks also to the upstream projects this plugin depends on or follows:
534
+
535
+ - [KiCad](https://www.kicad.org/): schematic and PCB access, `kicad-cli` and the `pcbnew` Python API.
536
+ - [kicad-happy](https://github.com/aklofas/kicad-happy) (MIT): source of the EMC, thermal and lifecycle rules.
537
+ - [KiCadRoutingTools](https://github.com/drandyhaas/KiCadRoutingTools) (MIT): reference implementation for grid autorouting.
538
+ - [ngspice](https://ngspice.sourceforge.io/): SPICE verification.
539
+ - [poppler](https://poppler.freedesktop.org/): PDF text, tables and rendering.
540
+ - [tscircuit](https://tscircuit.com/): circuit source to KiCad project generation.
541
+
542
+ ## License
543
+
544
+ [MIT](LICENSE)