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
@@ -0,0 +1,433 @@
1
+ /**
2
+ * 图纸手绘工具(S174):在 `.kicad_sch` 文本上连线、标名、克隆元件、挪元件。
3
+ *
4
+ * 不需要 KiCad 进程:只改文件;校验用 `kicad-cli sch export netlist`(命令行,不开窗口)。
5
+ * 目标文件固定在 `hardware/schematic/<name>.kicad_sch`,构建从不触碰它。
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { dirname, join } from "node:path";
9
+ import { tmpdir } from "node:os";
10
+ import { resolveProjectDir } from "./project-dir.js";
11
+ import { resolveProjectLayout } from "../engine/project-layout.js";
12
+ import { findLatestKicadBuild, planEcadWorkspace } from "../engine/ecad/tsci.js";
13
+ import { locateEcadToolchain } from "../engine/ecad/toolchain.js";
14
+ import { runCapture } from "../engine/subprocess-runner.js";
15
+ import { drawOnSheet, drawSheetPath, readDrawSheet, seedDrawSheet, writeDrawSheet, } from "../engine/schematic/draw.js";
16
+ import { backupBoardFile, buildHandSyncScript, parseHandSyncOutput, planHandSync, } from "../engine/ecad/pcb/hand-sync.js";
17
+ export const SCH_DRAW_TOOL = "stm32_sch_draw";
18
+ export const SCH_SYNC_TOOL = "stm32_sch_sync";
19
+ function describeOp(op) {
20
+ if (op.op === "wire")
21
+ return "wire";
22
+ if (op.op === "label")
23
+ return "label " + op.text;
24
+ if (op.op === "clone")
25
+ return "clone " + op.from + " → " + op.ref;
26
+ if (op.op === "place")
27
+ return "place " + op.libId + " → " + op.ref;
28
+ if (op.op === "move")
29
+ return "move " + op.ref;
30
+ return "remove " + op.ref;
31
+ }
32
+ /**
33
+ * 符号库来源:先工程里的 `libs/symbols/<Name>.kicad_sym`(S173 器件导入的落点),
34
+ * 再 KiCad 官方库 `symbolDir/<Lib>.kicad_sym`。找不到返回 null,由调用方报错。
35
+ */
36
+ function symbolLibrary(projectDir, symbolDir) {
37
+ const cache = new Map();
38
+ return (libId) => {
39
+ if (cache.has(libId))
40
+ return cache.get(libId) ?? null;
41
+ const colon = libId.indexOf(":");
42
+ const lib = colon >= 0 ? libId.slice(0, colon) : libId;
43
+ const name = colon >= 0 ? libId.slice(colon + 1) : libId;
44
+ const candidates = [
45
+ join(projectDir, "libs", "symbols", name + ".kicad_sym"),
46
+ join(projectDir, "libs", "symbols", lib + ".kicad_sym"),
47
+ join(symbolDir, lib + ".kicad_sym"),
48
+ ];
49
+ for (const file of candidates) {
50
+ if (!existsSync(file))
51
+ continue;
52
+ const text = readFileSync(file, "utf8");
53
+ if (text.includes('(symbol "' + name + '"')) {
54
+ cache.set(libId, text);
55
+ return text;
56
+ }
57
+ }
58
+ if (existsSync(symbolDir)) {
59
+ for (const file of readdirSync(symbolDir)) {
60
+ if (!file.endsWith(".kicad_sym"))
61
+ continue;
62
+ const full = join(symbolDir, file);
63
+ if (!file.startsWith(lib))
64
+ continue;
65
+ const text = readFileSync(full, "utf8");
66
+ if (text.includes('(symbol "' + name + '"')) {
67
+ cache.set(libId, text);
68
+ return text;
69
+ }
70
+ }
71
+ }
72
+ cache.set(libId, null);
73
+ return null;
74
+ };
75
+ }
76
+ /** 用 kicad-cli 导一次网表当验收;没装工具链就跳过,不判失败。 */
77
+ async function checkNetlist(subprocess, sheet, outDir) {
78
+ const located = locateEcadToolchain(process.env);
79
+ if (!located.ok || located.toolchain === null)
80
+ return { ok: true, note: "没找到 KiCad:跳过网表校验" };
81
+ const capture = await runCapture(subprocess, {
82
+ argv: [located.toolchain.kicadCli, "sch", "export", "netlist", "--output", outDir, sheet],
83
+ timeoutMs: 60_000,
84
+ });
85
+ const text = capture.stdout + capture.stderr;
86
+ if (capture.exitCode !== 0)
87
+ return { ok: false, note: "kicad-cli 网表校验失败:" + text.trim().split("\n").slice(-2).join(" ") };
88
+ return { ok: true, note: "kicad-cli 网表已导出:" + outDir };
89
+ }
90
+ export function registerSchDrawTools(ctx) {
91
+ ctx.tools.register({
92
+ name: SCH_DRAW_TOOL,
93
+ description: "在原理图手绘层上画东西(不需要打开 KiCad):wire 连两脚或两点、label 标网络名、clone 从图纸里已有元件复制一个(新位号/新位置)、move 挪元件、remove 删元件。文件固定在 hardware/schematic/<name>.kicad_sch,构建不会重写它;首次用 seed=true 从最近一次构建拷一份底图。写盘后用 kicad-cli 导一次网表校验(check 默认 true)。",
94
+ parameters: {
95
+ type: "object",
96
+ additionalProperties: false,
97
+ properties: {
98
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
99
+ name: { type: "string", description: "手绘图纸文件名(不含扩展名),默认 schematic。" },
100
+ seed: { type: "boolean", description: "为 true 时,若手绘层不存在就从最近一次构建的图纸拷一份底图。" },
101
+ check: { type: "boolean", description: "写盘后用 kicad-cli 导网表校验,默认 true。" },
102
+ ops: {
103
+ type: "array",
104
+ description: "要执行的动作,按顺序应用。",
105
+ items: {
106
+ type: "object",
107
+ additionalProperties: false,
108
+ properties: {
109
+ op: { type: "string", enum: ["wire", "label", "clone", "move", "remove", "place"] },
110
+ a: { type: "object", additionalProperties: true, description: "wire 起点:{ref,pin} 或 {x,y}。" },
111
+ b: { type: "object", additionalProperties: true, description: "wire 终点:{ref,pin} 或 {x,y}。" },
112
+ at: { type: "object", additionalProperties: true, description: "label 位置 {ref,pin}|{x,y};clone/move 的目标坐标 {x,y}。" },
113
+ text: { type: "string", description: "label 的网络名。" },
114
+ from: { type: "string", description: "clone 的源位号。" },
115
+ libId: { type: "string", description: "place 的符号库编号,形如 Device:R_Small 或 MyLib:SOIC-8(来自 libs/symbols 或 KiCad 官方库)。" },
116
+ footprint: { type: "string", description: "clone/place 时写进 Footprint 属性的封装 Lib:Name(补到 PCB 时按它找库)。" },
117
+ rotation: { type: "number", description: "place 的旋转角度,默认 0。" },
118
+ ref: { type: "string", description: "clone 的新位号,或 move/remove 的目标位号。" },
119
+ value: { type: "string", description: "clone 时顺手改 Value(如 10k)。" },
120
+ },
121
+ required: ["op"],
122
+ },
123
+ },
124
+ },
125
+ },
126
+ output: {
127
+ schema: {
128
+ type: "object",
129
+ additionalProperties: false,
130
+ properties: {
131
+ ok: { type: "boolean" },
132
+ error: { type: "string" },
133
+ sheet: { type: "string" },
134
+ seeded: { type: "boolean" },
135
+ applied: { type: "number" },
136
+ skipped: { type: "number" },
137
+ failed: { type: "array", items: { type: "string" } },
138
+ notes: { type: "array", items: { type: "string" } },
139
+ netlist: { type: "string" },
140
+ },
141
+ required: ["ok", "error", "sheet", "seeded", "applied", "skipped", "failed", "notes", "netlist"],
142
+ },
143
+ render: (_args, value) => {
144
+ const report = value;
145
+ const lines = [];
146
+ if (!report.ok && report.error !== "")
147
+ lines.push(report.error);
148
+ lines.push(`手绘图纸:${report.sheet}`);
149
+ if (report.seeded)
150
+ lines.push("已从最近一次构建拷来底图");
151
+ if (report.applied > 0)
152
+ lines.push(`这次画上 ${String(report.applied)} 个动作`);
153
+ if (report.skipped > 0)
154
+ lines.push(`已在图上跳过 ${String(report.skipped)} 个`);
155
+ for (const failure of report.failed)
156
+ lines.push(`失败:${failure}`);
157
+ for (const note of report.notes)
158
+ lines.push(note);
159
+ if (report.netlist !== "")
160
+ lines.push(report.netlist);
161
+ return [{ type: "text", text: lines.join("\n") }];
162
+ },
163
+ },
164
+ timeoutMs: 90_000,
165
+ isConcurrencySafe: () => false,
166
+ async execute(rawArgs, exec) {
167
+ const args = rawArgs ?? {};
168
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
169
+ const projectDir = resolution.projectDir;
170
+ const layout = resolveProjectLayout(projectDir);
171
+ const workspace = planEcadWorkspace(projectDir, layout.hardwareDir);
172
+ const sheet = drawSheetPath(projectDir, (args.name ?? "schematic").trim() || "schematic");
173
+ const notes = [];
174
+ if (resolution.note !== null)
175
+ notes.push(resolution.note);
176
+ let seeded = false;
177
+ if (args.seed === true && !existsSync(sheet)) {
178
+ const latest = findLatestKicadBuild(workspace);
179
+ if (!latest.ok) {
180
+ return {
181
+ ok: false,
182
+ error: "还没有构建产物,无法拷底图:先跑一次 stm32_ecad_build",
183
+ sheet,
184
+ seeded: false,
185
+ applied: 0,
186
+ skipped: 0,
187
+ failed: [],
188
+ notes,
189
+ netlist: "",
190
+ };
191
+ }
192
+ const seededResult = seedDrawSheet(latest.schematicFile, sheet);
193
+ if (!seededResult.ok) {
194
+ return {
195
+ ok: false,
196
+ error: seededResult.error,
197
+ sheet,
198
+ seeded: false,
199
+ applied: 0,
200
+ skipped: 0,
201
+ failed: [],
202
+ notes,
203
+ netlist: "",
204
+ };
205
+ }
206
+ seeded = seededResult.seeded;
207
+ if (seeded)
208
+ notes.push("底图来自 " + latest.schematicFile);
209
+ }
210
+ const text = readDrawSheet(sheet);
211
+ if (text === "") {
212
+ return {
213
+ ok: false,
214
+ error: "手绘图纸还不存在:" + sheet + "。先带 seed=true 从构建产物拷一份底图。",
215
+ sheet,
216
+ seeded,
217
+ applied: 0,
218
+ skipped: 0,
219
+ failed: [],
220
+ notes,
221
+ netlist: "",
222
+ };
223
+ }
224
+ const ops = Array.isArray(args.ops) ? args.ops : [];
225
+ if (ops.length === 0) {
226
+ return { ok: true, error: "", sheet, seeded, applied: 0, skipped: 0, failed: [], notes: [...notes, "没有给 ops:只看了图纸"], netlist: "" };
227
+ }
228
+ const toolchain = locateEcadToolchain(process.env);
229
+ const library = symbolLibrary(projectDir, toolchain.ok && toolchain.toolchain !== null ? toolchain.toolchain.symbolDir : "");
230
+ const report = drawOnSheet(text, sheet, ops, library);
231
+ if (report.applied > 0)
232
+ writeDrawSheet(sheet, report.text);
233
+ notes.push(...report.notes.map((note) => "· " + note));
234
+ notes.push("动作:" + ops.map(describeOp).join("、"));
235
+ let netlist = "";
236
+ if (args.check !== false) {
237
+ const outDir = sheet.replace(/\.kicad_sch$/u, ".netlist.xml");
238
+ const checked = await checkNetlist(ctx.subprocess, sheet, outDir);
239
+ netlist = checked.note;
240
+ if (!checked.ok)
241
+ notes.push("网表校验没过:图纸可能还没连完整,这不等于写盘失败");
242
+ }
243
+ return {
244
+ ok: report.ok,
245
+ error: report.error,
246
+ sheet,
247
+ seeded,
248
+ applied: report.applied,
249
+ skipped: report.skipped,
250
+ failed: [...report.failed],
251
+ notes,
252
+ netlist,
253
+ };
254
+ },
255
+ });
256
+ // 手绘层新放的器件补到板子上(S177):默认只出计划,apply 才写盘。
257
+ const syncOutput = {
258
+ type: "object",
259
+ additionalProperties: false,
260
+ properties: {
261
+ ok: { type: "boolean" },
262
+ error: { type: "string" },
263
+ schematicFile: { type: "string" },
264
+ boardFile: { type: "string" },
265
+ applied: { type: "boolean" },
266
+ added: { type: "number" },
267
+ skipped: { type: "array", items: { type: "string" } },
268
+ missingLib: { type: "array", items: { type: "string" } },
269
+ unassigned: { type: "number" },
270
+ parts: {
271
+ type: "array",
272
+ items: {
273
+ type: "object",
274
+ additionalProperties: false,
275
+ properties: {
276
+ ref: { type: "string" },
277
+ value: { type: "string" },
278
+ footprint: { type: "string" },
279
+ x: { type: "number" },
280
+ y: { type: "number" },
281
+ nets: { type: "number" },
282
+ },
283
+ required: ["ref", "value", "footprint", "x", "y", "nets"],
284
+ },
285
+ },
286
+ alreadyOnBoard: { type: "number" },
287
+ noFootprint: { type: "array", items: { type: "string" } },
288
+ notes: { type: "array", items: { type: "string" } },
289
+ },
290
+ required: ["ok", "error", "schematicFile", "boardFile", "applied", "added", "skipped", "missingLib", "unassigned", "parts", "alreadyOnBoard", "noFootprint", "notes"],
291
+ };
292
+ ctx.tools.register({
293
+ name: SCH_SYNC_TOOL,
294
+ description: "把手绘层(hardware/schematic)里新放的器件补到 PCB:按位号找板上没有的元件,按 Footprint 属性从库加载封装,赋板上已有的同名网络。默认只出计划(apply=false),写盘前留 .bak。",
295
+ parameters: {
296
+ type: "object",
297
+ additionalProperties: false,
298
+ properties: {
299
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
300
+ boardFile: { type: "string", description: "指定 .kicad_pcb;缺省取最近一次构建的板子。" },
301
+ schematicFile: { type: "string", description: "指定手绘层;缺省 hardware/schematic/schematic.kicad_sch。" },
302
+ apply: { type: "boolean", description: "true 才真的写进板子(默认 false,只出计划)。" },
303
+ },
304
+ required: [],
305
+ },
306
+ output: {
307
+ schema: syncOutput,
308
+ render: (_args, value) => {
309
+ const report = value;
310
+ if (!report.ok)
311
+ return [{ type: "text", text: "补封装没跑起来:" + report.error }];
312
+ const lines = [];
313
+ lines.push(report.applied ? "已补进板子:" + String(report.added) + " 个" : "计划(未写盘):" + String(report.parts.length) + " 个");
314
+ for (const part of report.parts.slice(0, 12)) {
315
+ lines.push(" " + part.ref + " · " + part.footprint + " @ " + String(part.x) + "," + String(part.y) + " · " + String(part.nets) + " 个网络");
316
+ }
317
+ if (report.parts.length > 12)
318
+ lines.push(" 另有 " + String(report.parts.length - 12) + " 个");
319
+ lines.push("已在板上:" + String(report.alreadyOnBoard));
320
+ if (report.missingLib.length > 0)
321
+ lines.push("库里找不到封装:" + report.missingLib.join("、"));
322
+ if (report.skipped.length > 0)
323
+ lines.push("跳过(已存在):" + report.skipped.join("、"));
324
+ if (report.unassigned > 0)
325
+ lines.push("有 " + String(report.unassigned) + " 个引脚的网络在板上不存在,没赋上");
326
+ for (const note of report.notes)
327
+ lines.push(note);
328
+ return [{ type: "text", text: lines.join("\n") }];
329
+ },
330
+ },
331
+ isConcurrencySafe: () => false,
332
+ async execute(args, exec) {
333
+ const shaped = args;
334
+ const project = await resolveProjectDir(ctx, shaped.projectDir, exec);
335
+ const located = locateEcadToolchain();
336
+ const toolchain = located.toolchain;
337
+ const footprintDirs = located.ok && toolchain !== null ? [toolchain.footprintDir] : [];
338
+ const plan = planHandSync(project.projectDir, {
339
+ boardFile: shaped.boardFile,
340
+ schematicFile: shaped.schematicFile,
341
+ footprintDirs,
342
+ });
343
+ const empty = {
344
+ ok: false,
345
+ error: "",
346
+ schematicFile: plan.schematicFile,
347
+ boardFile: plan.boardFile,
348
+ applied: false,
349
+ added: 0,
350
+ skipped: [],
351
+ missingLib: [],
352
+ unassigned: 0,
353
+ parts: [],
354
+ alreadyOnBoard: plan.alreadyOnBoard.length,
355
+ noFootprint: [...plan.noFootprint],
356
+ notes: [...plan.notes],
357
+ };
358
+ if (!plan.ok)
359
+ return { ...empty, error: plan.error };
360
+ const shapedParts = plan.parts.map((part) => ({
361
+ ref: part.ref,
362
+ value: part.value,
363
+ footprint: part.footprint,
364
+ x: part.x,
365
+ y: part.y,
366
+ nets: part.nets.length,
367
+ }));
368
+ if (shaped.apply !== true) {
369
+ return { ...empty, ok: true, parts: shapedParts, notes: [...plan.notes, "这是计划:加 apply=true 才写进板子"] };
370
+ }
371
+ if (!located.ok || toolchain === null)
372
+ return { ...empty, ok: false, error: "没有找到 KiCad 工具链:补封装要用 KiCad 自带的 python", parts: shapedParts };
373
+ if (plan.parts.length === 0)
374
+ return { ...empty, ok: true, applied: false, parts: shapedParts };
375
+ backupBoardFile(plan.boardFile);
376
+ const stamp = String(Date.now());
377
+ const scriptFile = join(tmpdir(), "dsh-stm32-handsync-" + stamp + ".py");
378
+ const resultFile = join(tmpdir(), "dsh-stm32-handsync-" + stamp + ".json");
379
+ writeFileSync(scriptFile, buildHandSyncScript(plan), "utf8");
380
+ const payload = JSON.stringify({
381
+ boardFile: plan.boardFile,
382
+ libraryDirs: [...plan.libraryDirs],
383
+ parts: plan.parts.map((part) => ({
384
+ ref: part.ref,
385
+ value: part.value,
386
+ library: part.library,
387
+ footprintName: part.footprintName,
388
+ x: part.x,
389
+ y: part.y,
390
+ nets: part.nets.map((net) => ({ number: net.number, net: net.net })),
391
+ })),
392
+ });
393
+ const run = await runCapture(ctx.subprocess, {
394
+ argv: [toolchain.python, scriptFile, payload, resultFile],
395
+ cwd: dirname(plan.boardFile),
396
+ env: toolchain.env,
397
+ timeoutMs: 120_000,
398
+ maxBytes: 256_000,
399
+ signal: exec.signal,
400
+ });
401
+ if (run.exitCode !== 0) {
402
+ return {
403
+ ...empty,
404
+ ok: false,
405
+ error: "KiCad python 执行失败:" + (run.stderr === "" ? run.stdout : run.stderr).slice(-400),
406
+ parts: shapedParts,
407
+ };
408
+ }
409
+ const parsed = existsSync(resultFile) ? parseHandSyncOutput(readFileSync(resultFile, "utf8")) : null;
410
+ if (parsed === null || !parsed.ok) {
411
+ return { ...empty, ok: false, error: "没读到补封装结果:脚本没有写出结果文件(板子可能被锁定或路径不可写)", parts: shapedParts };
412
+ }
413
+ const notes = [...plan.notes];
414
+ if (parsed.unassigned > 0)
415
+ notes.push("有 " + String(parsed.unassigned) + " 个引脚的网络在板上不存在,没赋上");
416
+ return {
417
+ ok: true,
418
+ error: "",
419
+ schematicFile: plan.schematicFile,
420
+ boardFile: plan.boardFile,
421
+ applied: true,
422
+ added: parsed.added,
423
+ skipped: parsed.skipped,
424
+ missingLib: parsed.missingLib,
425
+ unassigned: parsed.unassigned,
426
+ parts: shapedParts,
427
+ alreadyOnBoard: plan.alreadyOnBoard.length,
428
+ noFootprint: [...plan.noFootprint],
429
+ notes,
430
+ };
431
+ },
432
+ });
433
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 原理图编辑工具(S170):把「连两根引脚、给引脚起名」存成指令,构建收尾时重放。
3
+ *
4
+ * 不直接改 `.kicad_sch`:那是 tscircuit 的产物,每次构建都会重写;
5
+ * 直接改等于骗自己——下一次构建就没了。
6
+ */
7
+ import { resolveProjectDir } from "./project-dir.js";
8
+ import { resolveProjectLayout } from "../engine/project-layout.js";
9
+ import { findLatestKicadBuild, planEcadWorkspace } from "../engine/ecad/tsci.js";
10
+ import { editStorePath, readSchEdits, replaySchEditsTo, writeSchEdits, } from "../engine/schematic/edit.js";
11
+ export const SCH_EDIT_TOOL = "stm32_sch_edit";
12
+ function describe(edit) {
13
+ if (edit.op === "connect") {
14
+ return { op: "connect", a: `${edit.a.ref}.${edit.a.pin}`, b: `${edit.b.ref}.${edit.b.pin}`, text: "" };
15
+ }
16
+ return { op: "label", a: `${edit.at.ref}.${edit.at.pin}`, b: "", text: edit.text };
17
+ }
18
+ /** 把指令重放到当前最新构建出来的原理图上;没有构建产物就只存指令。 */
19
+ function replayNow(projectDir, edits) {
20
+ const layout = resolveProjectLayout(projectDir);
21
+ const workspace = planEcadWorkspace(projectDir, layout.hardwareDir);
22
+ const latest = findLatestKicadBuild(workspace);
23
+ const kicadDir = latest.ok ? latest.kicadDir : "";
24
+ return replaySchEditsTo(kicadDir, edits);
25
+ }
26
+ export function registerSchEditTools(ctx) {
27
+ ctx.tools.register({
28
+ name: SCH_EDIT_TOOL,
29
+ description: "编辑原理图的电气连接:把两个引脚连起来(connect),或给某个引脚标网络名(label)。指令存在 circuit/schematic-edits.json,每次 stm32_ecad_build 收尾重放,因此不会被下一次构建抹掉;重放失败会明确报出是哪个引脚找不到。mode=list 看已有指令,clear 清空。",
30
+ parameters: {
31
+ type: "object",
32
+ additionalProperties: false,
33
+ properties: {
34
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
35
+ mode: { type: "string", enum: ["list", "add", "clear"], description: "默认 list。" },
36
+ a: {
37
+ type: "object",
38
+ additionalProperties: false,
39
+ description: "connect 的第一端,或 label 的目标引脚。",
40
+ properties: { ref: { type: "string" }, pin: { type: "string" } },
41
+ },
42
+ b: {
43
+ type: "object",
44
+ additionalProperties: false,
45
+ description: "connect 的第二端。",
46
+ properties: { ref: { type: "string" }, pin: { type: "string" } },
47
+ },
48
+ text: { type: "string", description: "label 的网络名。" },
49
+ },
50
+ },
51
+ output: {
52
+ schema: {
53
+ type: "object",
54
+ additionalProperties: false,
55
+ properties: {
56
+ ok: { type: "boolean" },
57
+ error: { type: "string" },
58
+ store: { type: "string" },
59
+ edits: {
60
+ type: "array",
61
+ items: {
62
+ type: "object",
63
+ additionalProperties: false,
64
+ properties: { op: { type: "string" }, a: { type: "string" }, b: { type: "string" }, text: { type: "string" } },
65
+ required: ["op", "a", "b", "text"],
66
+ },
67
+ },
68
+ applied: { type: "number" },
69
+ skipped: { type: "number" },
70
+ failed: { type: "array", items: { type: "string" } },
71
+ notes: { type: "array", items: { type: "string" } },
72
+ },
73
+ required: ["ok", "error", "store", "edits", "applied", "skipped", "failed", "notes"],
74
+ },
75
+ render: (_args, value) => {
76
+ const report = value;
77
+ const lines = [];
78
+ if (!report.ok)
79
+ return [{ type: "text", text: report.error }];
80
+ lines.push(`原理图指令:${String(report.edits.length)} 条(${report.store})`);
81
+ for (const edit of report.edits) {
82
+ lines.push(edit.op === "connect" ? ` 连线 ${edit.a} ↔ ${edit.b}` : ` 标名 ${edit.a} → ${edit.text}`);
83
+ }
84
+ if (report.applied > 0)
85
+ lines.push(`这次画上 ${String(report.applied)} 条`);
86
+ if (report.skipped > 0)
87
+ lines.push(`已在图上 ${String(report.skipped)} 条`);
88
+ for (const failure of report.failed)
89
+ lines.push(`失败:${failure}`);
90
+ for (const note of report.notes)
91
+ lines.push(note);
92
+ return [{ type: "text", text: lines.join("\n") }];
93
+ },
94
+ },
95
+ timeoutMs: 60_000,
96
+ isConcurrencySafe: () => false,
97
+ async execute(rawArgs, exec) {
98
+ const args = rawArgs ?? {};
99
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
100
+ const projectDir = resolution.projectDir;
101
+ const layout = resolveProjectLayout(projectDir);
102
+ const workspace = planEcadWorkspace(projectDir, layout.hardwareDir);
103
+ const store = editStorePath(workspace.circuitDir);
104
+ const existing = readSchEdits(store);
105
+ const mode = args.mode ?? "list";
106
+ const base = () => ({
107
+ ok: true,
108
+ error: "",
109
+ store,
110
+ edits: existing.map(describe),
111
+ applied: 0,
112
+ skipped: 0,
113
+ failed: [],
114
+ notes: resolution.note === null ? [] : [resolution.note],
115
+ });
116
+ if (mode === "clear") {
117
+ writeSchEdits(store, []);
118
+ return { ...base(), edits: [], notes: [...base().notes, "指令表已清空;已经画在图纸上的线要等下次构建才会消失"] };
119
+ }
120
+ const next = [...existing];
121
+ if (mode === "add") {
122
+ const a = { ref: (args.a?.ref ?? "").trim(), pin: (args.a?.pin ?? "").trim() };
123
+ if (a.ref === "" || a.pin === "") {
124
+ return { ...base(), ok: false, error: "a.ref 与 a.pin 都要给:先说明连哪个元件的哪一脚" };
125
+ }
126
+ if ((args.text ?? "").trim() !== "") {
127
+ next.push({ op: "label", at: a, text: (args.text ?? "").trim() });
128
+ }
129
+ else {
130
+ const b = { ref: (args.b?.ref ?? "").trim(), pin: (args.b?.pin ?? "").trim() };
131
+ if (b.ref === "" || b.pin === "") {
132
+ return { ...base(), ok: false, error: "connect 需要 a 与 b 两端;只给一端就带 text 当 label 用" };
133
+ }
134
+ if (a.ref === b.ref && a.pin === b.pin) {
135
+ return { ...base(), ok: false, error: "两端是同一个引脚:这不是连线" };
136
+ }
137
+ next.push({ op: "connect", a, b });
138
+ }
139
+ writeSchEdits(store, next);
140
+ }
141
+ const replay = replayNow(projectDir, next);
142
+ return { ...base(), edits: next.map(describe), applied: replay.applied, skipped: replay.skipped, failed: [...replay.failed], notes: [...replay.notes] };
143
+ },
144
+ });
145
+ }