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,817 @@
1
+ /**
2
+ * L3:原理图工具 —— 读 KiCad 10 原理图,产出元件/引脚/网络事实,并做检查与对账。
3
+ *
4
+ * 三个工具的分工:
5
+ * stm32_sch_read 看全貌:图纸树、元件、网络、模块框图(给人和模型同一份事实)
6
+ * stm32_sch_pins 看主控:每个引脚的当前网络 + CubeMX 里的复用候选(写 .ioc 前先确认)
7
+ * stm32_sch_check 看问题:原理图自身规则、与 PCB 的连通性对账、与 .ioc 的引脚对照
8
+ *
9
+ * 只读:不改原理图、不写 `.ioc`。要改配置走 `stm32_ioc_plan` 的事务。
10
+ */
11
+ import { locateCubemxDb, readMcuFacts, resolveDbPinName } from "../engine/cubemx-db.js";
12
+ import { resolveSearchConfig } from "../data/search-roots.js";
13
+ import { checkSchematic } from "../engine/schematic/checks.js";
14
+ import { findRootSchematic, readSchematic } from "../engine/schematic/model.js";
15
+ import { draftIoc } from "../engine/schematic/to-ioc.js";
16
+ import { runSchematicReview } from "../engine/schematic/review.js";
17
+ import { locatePoppler } from "../engine/pdf/toolchain.js";
18
+ import { datasheetCacheDir, resolveDatasheetRef } from "../engine/datasheet/store.js";
19
+ import { pinFunctionIndex, readDatasheetPinout } from "../engine/datasheet/pinout.js";
20
+ import { popplerDirs } from "./pdf.js";
21
+ import { resolveProjectDir } from "./project-dir.js";
22
+ import { resolveProjectLayout } from "../engine/project-layout.js";
23
+ export const SCH_READ_TOOL = "stm32_sch_read";
24
+ export const SCH_PINS_TOOL = "stm32_sch_pins";
25
+ export const SCH_CHECK_TOOL = "stm32_sch_check";
26
+ export const SCH_TO_IOC_TOOL = "stm32_sch_to_ioc";
27
+ export const SCH_REVIEW_TOOL = "stm32_sch_review";
28
+ /** 一次最多列出多少个元件/网络;超出部分只给计数,避免报告压垮上下文。 */
29
+ const LIST_LIMIT = 200;
30
+ /** 每个引脚最多给几个复用候选。 */
31
+ const CANDIDATE_LIMIT = 8;
32
+ const pinViewSchema = {
33
+ type: "object",
34
+ additionalProperties: false,
35
+ properties: {
36
+ number: { type: "string" },
37
+ name: { type: "string" },
38
+ net: { type: "string" },
39
+ type: { type: "string" },
40
+ noConnect: { type: "boolean" },
41
+ },
42
+ required: ["number", "name", "net", "type", "noConnect"],
43
+ };
44
+ /**
45
+ * 按 rootFile 或工程目录找入口图纸并解析。
46
+ *
47
+ * 传进来的是**工程根**(S95 约定):KiCad 工程可能在 `hardware/` 下,也可能与程序同级。
48
+ * 具体在哪儿由 `resolveProjectLayout()` 判断,这里只负责「取到目录 → 找入口 → 解析」。
49
+ */
50
+ export function loadSchematic(projectDir, rootFile) {
51
+ let root = rootFile;
52
+ if (root === "") {
53
+ const hardwareDir = resolveProjectLayout(projectDir).hardwareDir;
54
+ if (hardwareDir === "") {
55
+ return {
56
+ report: null,
57
+ error: "工程里没有 KiCad 原理图:把 KiCad 工程放到 hardware/ 下,或在 dsh-stm32.conf 里写 hardware=目录名",
58
+ };
59
+ }
60
+ const found = findRootSchematic(hardwareDir);
61
+ if (found === null || found === "") {
62
+ return { report: null, error: `硬件目录里没有 .kicad_sch:${hardwareDir}` };
63
+ }
64
+ root = found;
65
+ }
66
+ try {
67
+ return { report: readSchematic(root).report, error: "" };
68
+ }
69
+ catch (error) {
70
+ return { report: null, error: `原理图解析失败:${error instanceof Error ? error.message : String(error)}` };
71
+ }
72
+ }
73
+ function sheetsOf(report) {
74
+ return report.sheets.map((sheet) => ({ file: sheet.file, paper: sheet.paper, symbols: sheet.symbols, nets: sheet.nets }));
75
+ }
76
+ function componentList(report) {
77
+ return report.components.slice(0, LIST_LIMIT).map((component) => ({
78
+ ref: component.ref,
79
+ value: component.value,
80
+ footprint: component.footprint,
81
+ sheet: component.sheet,
82
+ isMcu: report.mcu !== null && report.mcu.ref === component.ref,
83
+ pins: component.pins.map((pin) => ({
84
+ number: pin.number,
85
+ name: pin.name,
86
+ net: pin.net,
87
+ type: pin.type,
88
+ noConnect: pin.noConnect,
89
+ })),
90
+ }));
91
+ }
92
+ function formatRead(value) {
93
+ if (value.message !== "")
94
+ return [value.message];
95
+ const lines = [
96
+ `原理图:${value.rootFile}`,
97
+ `版本 ${value.version};图纸 ${value.sheets.length} 张;元件 ${value.components} 个;网络 ${value.nets} 个`,
98
+ `主控:${value.mcu === "" ? "未识别" : value.mcu}`,
99
+ `模块框图:${value.diagram.blocks.length} 个块、${value.diagram.links.length} 条连线`,
100
+ ];
101
+ for (const sheet of value.sheets)
102
+ lines.push(` · ${sheet.file}(${sheet.symbols} 个符号 / ${sheet.nets} 个网络)`);
103
+ for (const warning of value.warnings)
104
+ lines.push(` ! ${warning}`);
105
+ return lines;
106
+ }
107
+ const readOutputSchema = {
108
+ type: "object",
109
+ additionalProperties: false,
110
+ properties: {
111
+ ok: { type: "boolean" },
112
+ message: { type: "string" },
113
+ rootFile: { type: "string" },
114
+ version: { type: "number" },
115
+ generator: { type: "string" },
116
+ components: { type: "number" },
117
+ nets: { type: "number" },
118
+ mcu: { type: "string" },
119
+ sheets: {
120
+ type: "array",
121
+ items: {
122
+ type: "object",
123
+ additionalProperties: false,
124
+ properties: {
125
+ file: { type: "string" },
126
+ paper: { type: "string" },
127
+ symbols: { type: "number" },
128
+ nets: { type: "number" },
129
+ },
130
+ required: ["file", "paper", "symbols", "nets"],
131
+ },
132
+ },
133
+ componentList: {
134
+ type: "array",
135
+ items: {
136
+ type: "object",
137
+ additionalProperties: false,
138
+ properties: {
139
+ ref: { type: "string" },
140
+ value: { type: "string" },
141
+ footprint: { type: "string" },
142
+ sheet: { type: "string" },
143
+ isMcu: { type: "boolean" },
144
+ pins: { type: "array", items: pinViewSchema },
145
+ },
146
+ required: ["ref", "value", "footprint", "sheet", "isMcu", "pins"],
147
+ },
148
+ },
149
+ netList: {
150
+ type: "array",
151
+ items: {
152
+ type: "object",
153
+ additionalProperties: false,
154
+ properties: {
155
+ name: { type: "string" },
156
+ kind: { type: "string" },
157
+ labels: { type: "array", items: { type: "string" } },
158
+ pins: { type: "array", items: { type: "string" } },
159
+ },
160
+ required: ["name", "kind", "labels", "pins"],
161
+ },
162
+ },
163
+ diagram: {
164
+ type: "object",
165
+ additionalProperties: false,
166
+ properties: {
167
+ blocks: {
168
+ type: "array",
169
+ items: {
170
+ type: "object",
171
+ additionalProperties: false,
172
+ properties: {
173
+ id: { type: "string" },
174
+ label: { type: "string" },
175
+ kind: { type: "string" },
176
+ refs: { type: "array", items: { type: "string" } },
177
+ },
178
+ required: ["id", "label", "kind", "refs"],
179
+ },
180
+ },
181
+ links: {
182
+ type: "array",
183
+ items: {
184
+ type: "object",
185
+ additionalProperties: false,
186
+ properties: {
187
+ from: { type: "string" },
188
+ to: { type: "string" },
189
+ label: { type: "string" },
190
+ nets: { type: "array", items: { type: "string" } },
191
+ },
192
+ required: ["from", "to", "label", "nets"],
193
+ },
194
+ },
195
+ powerNets: { type: "array", items: { type: "string" } },
196
+ },
197
+ required: ["blocks", "links", "powerNets"],
198
+ },
199
+ warnings: { type: "array", items: { type: "string" } },
200
+ notes: { type: "array", items: { type: "string" } },
201
+ },
202
+ required: ["ok", "message", "rootFile", "version", "generator", "components", "nets", "mcu", "sheets", "componentList", "netList", "diagram", "warnings", "notes"],
203
+ };
204
+ function emptyRead(message) {
205
+ return {
206
+ ok: false,
207
+ message,
208
+ rootFile: "",
209
+ version: 0,
210
+ generator: "",
211
+ components: 0,
212
+ nets: 0,
213
+ mcu: "",
214
+ sheets: [],
215
+ componentList: [],
216
+ netList: [],
217
+ diagram: { blocks: [], links: [], powerNets: [] },
218
+ warnings: [],
219
+ notes: [],
220
+ };
221
+ }
222
+ const pinSchema = {
223
+ type: "object",
224
+ additionalProperties: false,
225
+ properties: {
226
+ number: { type: "string" },
227
+ name: { type: "string" },
228
+ net: { type: "string" },
229
+ type: { type: "string" },
230
+ noConnect: { type: "boolean" },
231
+ candidates: { type: "array", items: { type: "string" } },
232
+ },
233
+ required: ["number", "name", "net", "type", "noConnect", "candidates"],
234
+ };
235
+ const pinsOutputSchema = {
236
+ type: "object",
237
+ additionalProperties: false,
238
+ properties: {
239
+ ok: { type: "boolean" },
240
+ message: { type: "string" },
241
+ mcu: { type: "string" },
242
+ dbVersion: { type: "string" },
243
+ pins: { type: "array", items: pinSchema },
244
+ notes: { type: "array", items: { type: "string" } },
245
+ },
246
+ required: ["ok", "message", "mcu", "dbVersion", "pins", "notes"],
247
+ };
248
+ /**
249
+ * 复用候选:CubeMX db 里这个引脚的信号名,按与网络名的吻合度排序。
250
+ *
251
+ * 吻合度只看词元(SCL/SDA/TX/RX…):网络名常写成 `PA4/SCL`,库里写 `I2C1_SCL`,
252
+ * 两边共同出现的词元越多越可能是同一个用途。
253
+ */
254
+ export function rankSignals(signals, netName) {
255
+ const tokens = netName.toUpperCase().split(/[^A-Z0-9]+/u).filter((token) => token.length > 1);
256
+ const scored = signals.map((signal) => {
257
+ const upper = signal.toUpperCase();
258
+ let score = tokens.filter((token) => upper.includes(token)).length;
259
+ if (upper.includes("GPIO"))
260
+ score -= 1;
261
+ return { signal, score };
262
+ });
263
+ scored.sort((a, b) => (b.score === a.score ? a.signal.localeCompare(b.signal) : b.score - a.score));
264
+ return scored.map((item) => item.signal).slice(0, CANDIDATE_LIMIT);
265
+ }
266
+ const checkFindingSchema = {
267
+ type: "object",
268
+ additionalProperties: false,
269
+ properties: {
270
+ rule: { type: "string" },
271
+ severity: { type: "string", enum: ["error", "warning", "info"] },
272
+ message: { type: "string" },
273
+ evidence: { type: "string" },
274
+ },
275
+ required: ["rule", "severity", "message", "evidence"],
276
+ };
277
+ const checkOutputSchema = {
278
+ type: "object",
279
+ additionalProperties: false,
280
+ properties: {
281
+ ok: { type: "boolean" },
282
+ message: { type: "string" },
283
+ findings: { type: "array", items: checkFindingSchema },
284
+ errors: { type: "number" },
285
+ warnings: { type: "number" },
286
+ infos: { type: "number" },
287
+ pcbSummary: { type: "string" },
288
+ pcbCompared: { type: "number" },
289
+ pcbMatched: { type: "number" },
290
+ iocConfigured: { type: "number" },
291
+ notes: { type: "array", items: { type: "string" } },
292
+ },
293
+ required: ["ok", "message", "findings", "errors", "warnings", "infos", "pcbSummary", "pcbCompared", "pcbMatched", "iocConfigured", "notes"],
294
+ };
295
+ export function registerSchematicTools(ctx) {
296
+ ctx.tools.register({
297
+ name: SCH_READ_TOOL,
298
+ description: "读 KiCad 10 原理图(.kicad_sch,文件版本 20260306):图纸树、元件与引脚网络、网络表、模块框图(按功能模块聚合:主控、NFC 天线与标签、光检测、供电、调试接口、按键,模块之间按总线类型连线,不逐元件罗列)。只读,不写盘;接 PCB 对账与 .ioc 对照用 stm32_sch_check。",
299
+ parameters: {
300
+ type: "object",
301
+ additionalProperties: false,
302
+ properties: {
303
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
304
+ rootFile: { type: "string", description: "入口 .kicad_sch 路径;缺省按 .kicad_pro 同名文件推断。" },
305
+ includeComponents: { type: "boolean", description: "是否列出元件明细(含每个引脚的当前网络);默认 false,只给主控。" },
306
+ includeNets: { type: "boolean", description: "是否列出网络明细;默认 false,只给数量。" },
307
+ },
308
+ },
309
+ output: { schema: readOutputSchema, render: (_args, value) => [{ type: "text", text: formatRead(value).join("\n") }] },
310
+ timeoutMs: 60_000,
311
+ isConcurrencySafe: () => true,
312
+ async execute(rawArgs, exec) {
313
+ const args = rawArgs ?? {};
314
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
315
+ const loaded = loadSchematic(resolution.projectDir, typeof args.rootFile === "string" ? args.rootFile : "");
316
+ if (loaded.report === null)
317
+ return emptyRead(loaded.error);
318
+ const report = loaded.report;
319
+ const notes = [];
320
+ if (resolution.note !== null)
321
+ notes.push(resolution.note);
322
+ const mcu = report.mcu === null ? "" : `${report.mcu.ref} ${report.mcu.value}`;
323
+ const components = args.includeComponents === true ? componentList(report) : report.components
324
+ .filter((component) => report.mcu !== null && component.ref === report.mcu.ref)
325
+ .map((component) => ({
326
+ ref: component.ref,
327
+ value: component.value,
328
+ footprint: component.footprint,
329
+ sheet: component.sheet,
330
+ isMcu: true,
331
+ pins: component.pins.map((pin) => ({ number: pin.number, name: pin.name, net: pin.net, type: pin.type, noConnect: pin.noConnect })),
332
+ }));
333
+ const netList = args.includeNets === true
334
+ ? report.nets.slice(0, LIST_LIMIT).map((net) => ({
335
+ name: net.name,
336
+ kind: net.kind,
337
+ labels: [...net.labels],
338
+ pins: net.pins.map((pin) => `${pin.ref}.${pin.number}`),
339
+ }))
340
+ : [];
341
+ return {
342
+ ok: true,
343
+ message: "",
344
+ rootFile: report.rootFile,
345
+ version: report.version,
346
+ generator: report.generator,
347
+ components: report.components.length,
348
+ nets: report.nets.length,
349
+ mcu,
350
+ sheets: sheetsOf(report),
351
+ componentList: components,
352
+ netList,
353
+ diagram: {
354
+ blocks: report.diagram.blocks.map((block) => ({ id: block.id, label: block.label, kind: block.kind, refs: [...block.refs] })),
355
+ links: report.diagram.links.map((link) => ({ from: link.from, to: link.to, label: link.label, nets: [...link.nets] })),
356
+ powerNets: [...report.diagram.powerNets],
357
+ },
358
+ warnings: [...report.warnings],
359
+ notes,
360
+ };
361
+ },
362
+ });
363
+ ctx.tools.register({
364
+ name: SCH_PINS_TOOL,
365
+ description: "列出主控每个引脚的当前网络,并从 CubeMX 器件库里给出复用候选(按与网络名的吻合度排序)。写 .ioc 前用它确认引脚用途;只读。",
366
+ parameters: {
367
+ type: "object",
368
+ additionalProperties: false,
369
+ properties: {
370
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
371
+ rootFile: { type: "string", description: "入口 .kicad_sch 路径;缺省按 .kicad_pro 同名文件推断。" },
372
+ cubeMxRoots: { type: "array", items: { type: "string" }, description: "CubeMX 安装根目录候选。" },
373
+ },
374
+ },
375
+ output: { schema: pinsOutputSchema, render: (_args, value) => [{ type: "text", text: formatPins(value).join("\n") }] },
376
+ timeoutMs: 60_000,
377
+ isConcurrencySafe: () => true,
378
+ async execute(rawArgs, exec) {
379
+ const args = rawArgs ?? {};
380
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
381
+ const loaded = loadSchematic(resolution.projectDir, typeof args.rootFile === "string" ? args.rootFile : "");
382
+ if (loaded.report === null || loaded.report.mcu === null) {
383
+ return { ok: false, message: loaded.error !== "" ? loaded.error : "原理图里没有识别到 STM32 主控", mcu: "", dbVersion: "", pins: [], notes: [] };
384
+ }
385
+ const mcu = loaded.report.mcu;
386
+ const notes = [];
387
+ if (resolution.note !== null)
388
+ notes.push(resolution.note);
389
+ const config = resolveSearchConfig(process.env, args.cubeMxRoots === undefined ? {} : { cubeMxRoots: args.cubeMxRoots });
390
+ const db = locateCubemxDb(config.cubeMxRoots);
391
+ if (db === null) {
392
+ notes.push("没有找到 CubeMX 器件库:复用候选为空,其余字段照常。");
393
+ return {
394
+ ok: true,
395
+ message: "",
396
+ mcu: `${mcu.ref} ${mcu.value}`,
397
+ dbVersion: "",
398
+ pins: mcu.pins.map((pin) => ({ number: pin.number, name: pin.name, net: pin.net, type: pin.type, noConnect: pin.noConnect, candidates: [] })),
399
+ notes,
400
+ };
401
+ }
402
+ const facts = readMcuFacts(db, mcu.value);
403
+ if (facts === null) {
404
+ notes.push(`CubeMX 器件库里没有 ${mcu.value}:复用候选为空。`);
405
+ }
406
+ return {
407
+ ok: true,
408
+ message: "",
409
+ mcu: `${mcu.ref} ${mcu.value}`,
410
+ dbVersion: db.version,
411
+ pins: mcu.pins.map((pin) => {
412
+ const dbName = facts === null ? null : resolveDbPinName(facts, pin.name);
413
+ const fact = dbName === null || facts === null ? undefined : facts.pins.get(dbName);
414
+ const signals = fact === undefined ? [] : [...fact.signals.keys()];
415
+ return {
416
+ number: pin.number,
417
+ name: pin.name,
418
+ net: pin.net,
419
+ type: pin.type,
420
+ noConnect: pin.noConnect,
421
+ candidates: rankSignals(signals, pin.net === "" ? pin.name : `${pin.name} ${pin.net}`),
422
+ };
423
+ }),
424
+ notes,
425
+ };
426
+ },
427
+ });
428
+ ctx.tools.register({
429
+ name: SCH_CHECK_TOOL,
430
+ description: "检查 KiCad 原理图:调试口/电源/BOOT0 是否接好、元件缺值、网络冲突;可同时对 PCB 做连通性对账、对 .ioc 做引脚对照。只读。",
431
+ parameters: {
432
+ type: "object",
433
+ additionalProperties: false,
434
+ properties: {
435
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
436
+ rootFile: { type: "string", description: "入口 .kicad_sch 路径;缺省按 .kicad_pro 同名文件推断。" },
437
+ pcbFile: { type: "string", description: "同工程的 .kicad_pcb 路径;缺省不对比。" },
438
+ iocFile: { type: "string", description: "同工程的 .ioc 路径;缺省不对比。" },
439
+ severity: { type: "string", enum: ["all", "warning", "error"], description: "只返回不低于该级别的发现;默认 all。" },
440
+ },
441
+ },
442
+ output: { schema: checkOutputSchema, render: (_args, value) => [{ type: "text", text: formatCheck(value).join("\n") }] },
443
+ timeoutMs: 60_000,
444
+ isConcurrencySafe: () => true,
445
+ async execute(rawArgs, exec) {
446
+ const args = rawArgs ?? {};
447
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
448
+ const loaded = loadSchematic(resolution.projectDir, typeof args.rootFile === "string" ? args.rootFile : "");
449
+ if (loaded.report === null) {
450
+ return {
451
+ ok: false,
452
+ message: loaded.error,
453
+ findings: [],
454
+ errors: 0,
455
+ warnings: 0,
456
+ infos: 0,
457
+ pcbSummary: "",
458
+ pcbCompared: 0,
459
+ pcbMatched: 0,
460
+ iocConfigured: 0,
461
+ notes: [],
462
+ };
463
+ }
464
+ const notes = [];
465
+ if (resolution.note !== null)
466
+ notes.push(resolution.note);
467
+ const check = checkSchematic(loaded.report, {
468
+ ...(typeof args.pcbFile === "string" && args.pcbFile !== "" ? { pcbFile: args.pcbFile } : {}),
469
+ ...(typeof args.iocFile === "string" && args.iocFile !== "" ? { iocFile: args.iocFile } : {}),
470
+ });
471
+ const floor = args.severity === "error" ? 0 : args.severity === "warning" ? 1 : 2;
472
+ const rank = { error: 0, warning: 1, info: 2 };
473
+ const findings = check.findings
474
+ .filter((finding) => rank[finding.severity] <= floor)
475
+ .map((finding) => ({ rule: finding.rule, severity: finding.severity, message: finding.message, evidence: finding.evidence }));
476
+ return {
477
+ ok: true,
478
+ message: "",
479
+ findings,
480
+ errors: check.summary.errors,
481
+ warnings: check.summary.warnings,
482
+ infos: check.summary.infos,
483
+ pcbSummary: check.pcb === null ? "" : check.pcb.summary,
484
+ pcbCompared: check.pcb === null ? 0 : check.pcb.compared,
485
+ pcbMatched: check.pcb === null ? 0 : check.pcb.matched,
486
+ iocConfigured: check.ioc === null ? 0 : check.ioc.configured,
487
+ notes,
488
+ };
489
+ },
490
+ });
491
+ ctx.tools.register({
492
+ name: SCH_TO_IOC_TOOL,
493
+ description: "把原理图的引脚连接转成 .ioc 配置草案:每个主控脚给出建议的 CubeMX 信号、置信度与候选,纯 GPIO 网络给 input/output 建议。只读,不写 .ioc。",
494
+ parameters: {
495
+ type: "object",
496
+ additionalProperties: false,
497
+ properties: {
498
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
499
+ rootFile: { type: "string", description: "入口 .kicad_sch 路径;缺省按 .kicad_pro 同名文件推断。" },
500
+ cubeMxRoots: { type: "array", items: { type: "string" }, description: "CubeMX 安装根目录候选;缺省按默认搜索。" },
501
+ datasheet: {
502
+ type: "string",
503
+ description: "厂商手册的立创编号或型号:器件库缺这个脚的信号时,用手册引脚表兜底;先用 stm32_ds_fetch 缓存。",
504
+ },
505
+ },
506
+ },
507
+ output: {
508
+ schema: {
509
+ type: "object",
510
+ additionalProperties: false,
511
+ properties: {
512
+ ok: { type: "boolean" },
513
+ message: { type: "string" },
514
+ mcu: { type: "string" },
515
+ dbVersion: { type: "string" },
516
+ pins: {
517
+ type: "array",
518
+ items: {
519
+ type: "object",
520
+ additionalProperties: false,
521
+ properties: {
522
+ number: { type: "string" },
523
+ name: { type: "string" },
524
+ net: { type: "string" },
525
+ signal: { type: "string" },
526
+ confidence: { type: "string", enum: ["high", "medium", "low"] },
527
+ candidates: { type: "array", items: { type: "string" } },
528
+ note: { type: "string" },
529
+ source: { type: "string", enum: ["cubemx", "datasheet"] },
530
+ },
531
+ required: ["number", "name", "net", "signal", "confidence", "candidates", "note", "source"],
532
+ },
533
+ },
534
+ peripherals: {
535
+ type: "array",
536
+ items: {
537
+ type: "object",
538
+ additionalProperties: false,
539
+ properties: {
540
+ name: { type: "string" },
541
+ signals: { type: "array", items: { type: "string" } },
542
+ pins: { type: "array", items: { type: "string" } },
543
+ },
544
+ required: ["name", "signals", "pins"],
545
+ },
546
+ },
547
+ gpioPins: {
548
+ type: "array",
549
+ items: {
550
+ type: "object",
551
+ additionalProperties: false,
552
+ properties: {
553
+ pin: { type: "string" },
554
+ signal: { type: "string", enum: ["input", "output"] },
555
+ label: { type: "string" },
556
+ },
557
+ required: ["pin", "signal", "label"],
558
+ },
559
+ },
560
+ softwareFallbacks: {
561
+ type: "array",
562
+ items: {
563
+ type: "object",
564
+ additionalProperties: false,
565
+ properties: {
566
+ pin: { type: "string" },
567
+ net: { type: "string" },
568
+ protocol: { type: "string" },
569
+ suggestion: { type: "string" },
570
+ tradeoff: { type: "string" },
571
+ },
572
+ required: ["pin", "net", "protocol", "suggestion", "tradeoff"],
573
+ },
574
+ },
575
+ unresolved: {
576
+ type: "array",
577
+ items: {
578
+ type: "object",
579
+ additionalProperties: false,
580
+ properties: {
581
+ number: { type: "string" },
582
+ name: { type: "string" },
583
+ net: { type: "string" },
584
+ candidates: { type: "array", items: { type: "string" } },
585
+ },
586
+ required: ["number", "name", "net", "candidates"],
587
+ },
588
+ },
589
+ notes: { type: "array", items: { type: "string" } },
590
+ },
591
+ required: ["ok", "message", "mcu", "dbVersion", "pins", "peripherals", "gpioPins", "softwareFallbacks", "unresolved", "notes"],
592
+ },
593
+ render: (_args, value) => {
594
+ const result = value;
595
+ if (!result.ok)
596
+ return [{ type: "text", text: "配置草案未生成:" + result.message }];
597
+ const lines = ["配置草案(" + result.mcu + ")"];
598
+ for (const pin of result.pins.slice(0, 24)) {
599
+ const mark = pin.source === "datasheet" ? "(手册)" : "";
600
+ lines.push(" " + pin.name.padEnd(6) + " " + pin.net.padEnd(14) + " → " + (pin.signal === "" ? "(未匹配)" : pin.signal) + mark + " [" + pin.confidence + "]");
601
+ }
602
+ for (const pin of result.gpioPins)
603
+ lines.push(" GPIO:" + pin.pin + " 配成 " + pin.signal + ",标签 " + pin.label);
604
+ for (const fallback of result.softwareFallbacks)
605
+ lines.push(" 软件模拟:" + fallback.pin + " " + fallback.net + "(" + fallback.protocol + ")— " + fallback.tradeoff);
606
+ if (result.unresolved.length > 0)
607
+ lines.push(" 待确认:" + result.unresolved.map((pin) => pin.name + "/" + pin.net).join("、"));
608
+ for (const note of result.notes)
609
+ lines.push(" ! " + note);
610
+ return [{ type: "text", text: lines.join("\n") }];
611
+ },
612
+ },
613
+ timeoutMs: 60_000,
614
+ isConcurrencySafe: () => true,
615
+ async execute(rawArgs, exec) {
616
+ const args = rawArgs ?? {};
617
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
618
+ const loaded = loadSchematic(resolution.projectDir, typeof args.rootFile === "string" ? args.rootFile : "");
619
+ const notes = [];
620
+ if (resolution.note !== null)
621
+ notes.push(resolution.note);
622
+ if (loaded.report === null) {
623
+ return { ok: false, message: loaded.error, mcu: "", dbVersion: "", pins: [], peripherals: [], gpioPins: [], softwareFallbacks: [], unresolved: [], notes };
624
+ }
625
+ const config = resolveSearchConfig(process.env, args.cubeMxRoots === undefined ? {} : { cubeMxRoots: args.cubeMxRoots });
626
+ const db = locateCubemxDb(config.cubeMxRoots);
627
+ const facts = db === null || loaded.report.mcu === null ? null : readMcuFacts(db, loaded.report.mcu.value);
628
+ let pinFunctions;
629
+ const wantDatasheet = typeof args.datasheet === "string" ? args.datasheet.trim() : "";
630
+ if (wantDatasheet !== "") {
631
+ const found = resolveDatasheetRef(datasheetCacheDir(), wantDatasheet);
632
+ if (found === null) {
633
+ notes.push("手册 " + wantDatasheet + " 还没缓存:先 stm32_ds_fetch code=" + wantDatasheet + " 再生成草案。");
634
+ }
635
+ else {
636
+ const poppler = locatePoppler(popplerDirs());
637
+ if (poppler.tools === null) {
638
+ notes.push("没有可用的 poppler,读不了手册引脚表:" + poppler.error);
639
+ }
640
+ else {
641
+ const pinout = await readDatasheetPinout(ctx.subprocess, poppler.tools, found.file, {}, exec.signal);
642
+ pinFunctions = pinFunctionIndex(pinout);
643
+ notes.push(pinout.ok ? "手册引脚表:" + String(pinout.pins.length) + " 个脚(" + found.entry.code + ")" : "手册里没有认出引脚表:" + pinout.error);
644
+ }
645
+ }
646
+ }
647
+ const draft = draftIoc(loaded.report, facts, { pinFunctions });
648
+ if (draft.ok && facts === null)
649
+ notes.push(db === null ? "没有找到 CubeMX 器件库:草案里没有信号建议。" : "CubeMX 器件库里没有这颗型号:草案里没有信号建议。");
650
+ return {
651
+ ok: draft.ok,
652
+ message: draft.ok ? "" : draft.error,
653
+ mcu: draft.mcu === null ? "" : draft.mcu.ref + " " + draft.mcu.value,
654
+ dbVersion: db === null ? "" : db.version,
655
+ pins: draft.pins,
656
+ peripherals: draft.peripherals,
657
+ gpioPins: draft.gpioPins,
658
+ softwareFallbacks: draft.softwareFallbacks,
659
+ unresolved: draft.unresolved,
660
+ notes: [...notes, ...draft.notes],
661
+ };
662
+ },
663
+ });
664
+ ctx.tools.register({
665
+ name: SCH_REVIEW_TOOL,
666
+ description: "一键评审原理图:读图 → 规则检查 → 与 .ioc 对账 → 生成 .ioc 配置草案,给出一个总判据(有 error 即不通过)与需要人决策的清单。只读。",
667
+ parameters: {
668
+ type: "object",
669
+ additionalProperties: false,
670
+ properties: {
671
+ projectDir: { type: "string", description: "工程根目录;缺省为会话工作目录。" },
672
+ rootFile: { type: "string", description: "显式指定 .kicad_sch;缺省按工程约定在 hardware/ 下找。" },
673
+ },
674
+ required: [],
675
+ },
676
+ output: {
677
+ schema: {
678
+ type: "object",
679
+ additionalProperties: false,
680
+ properties: {
681
+ ok: { type: "boolean" },
682
+ error: { type: "string" },
683
+ rootFile: { type: "string" },
684
+ components: { type: "number" },
685
+ nets: { type: "number" },
686
+ errors: { type: "number" },
687
+ warnings: { type: "number" },
688
+ mcu: {
689
+ type: "object",
690
+ additionalProperties: false,
691
+ properties: { ref: { type: "string" }, value: { type: "string" } },
692
+ required: ["ref", "value"],
693
+ },
694
+ steps: {
695
+ type: "array",
696
+ items: {
697
+ type: "object",
698
+ additionalProperties: false,
699
+ properties: {
700
+ step: { type: "string" },
701
+ ok: { type: "boolean" },
702
+ detail: { type: "string" },
703
+ ms: { type: "number" },
704
+ },
705
+ required: ["step", "ok", "detail", "ms"],
706
+ },
707
+ },
708
+ decisions: {
709
+ type: "array",
710
+ items: {
711
+ type: "object",
712
+ additionalProperties: false,
713
+ properties: {
714
+ pin: { type: "string" },
715
+ net: { type: "string" },
716
+ reason: { type: "string" },
717
+ },
718
+ required: ["pin", "net", "reason"],
719
+ },
720
+ },
721
+ findings: {
722
+ type: "array",
723
+ items: {
724
+ type: "object",
725
+ additionalProperties: false,
726
+ properties: {
727
+ rule: { type: "string" },
728
+ severity: { type: "string" },
729
+ message: { type: "string" },
730
+ },
731
+ required: ["rule", "severity", "message"],
732
+ },
733
+ },
734
+ ioc: {
735
+ type: "object",
736
+ additionalProperties: false,
737
+ properties: {
738
+ pins: { type: "number" },
739
+ unresolved: { type: "array", items: { type: "string" } },
740
+ softwareFallbacks: { type: "array", items: { type: "string" } },
741
+ },
742
+ required: ["pins", "unresolved", "softwareFallbacks"],
743
+ },
744
+ notes: { type: "array", items: { type: "string" } },
745
+ },
746
+ required: ["ok", "error", "rootFile", "components", "nets", "errors", "warnings", "steps", "decisions", "findings", "notes"],
747
+ },
748
+ render: (_args, value) => {
749
+ const result = value;
750
+ const lines = [
751
+ (result.ok ? "评审通过" : "评审未通过:") + (result.error === "" ? "" : " " + result.error),
752
+ "元件 " + String(result.components) + " / 网络 " + String(result.nets) + " / 错误 " + String(result.errors) + " / 警告 " + String(result.warnings),
753
+ ];
754
+ for (const step of result.steps)
755
+ lines.push(" " + (step.ok ? "OK " : "FAIL") + " " + step.step + ":" + step.detail + "(" + String(step.ms) + " ms)");
756
+ if (result.ioc !== null)
757
+ lines.push(" 配置草案:" + String(result.ioc.pins) + " 个脚,待确认 " + String(result.ioc.unresolved.length) + " 个");
758
+ for (const item of result.decisions.slice(0, 12))
759
+ lines.push(" ? " + item.pin + "(" + item.net + "):" + item.reason);
760
+ for (const note of result.notes)
761
+ lines.push(" ! " + note);
762
+ return [{ type: "text", text: lines.join("\n") }];
763
+ },
764
+ },
765
+ timeoutMs: 120_000,
766
+ isConcurrencySafe: () => true,
767
+ execute: async (args, exec) => {
768
+ const resolution = await resolveProjectDir(ctx, args.projectDir, exec);
769
+ if (resolution.projectDir === "") {
770
+ return {
771
+ ok: false,
772
+ error: resolution.note ?? "projectDir 不能为空",
773
+ rootFile: "",
774
+ components: 0,
775
+ nets: 0,
776
+ errors: 0,
777
+ warnings: 0,
778
+ mcu: null,
779
+ steps: [],
780
+ decisions: [],
781
+ findings: [],
782
+ ioc: null,
783
+ notes: [],
784
+ };
785
+ }
786
+ return runSchematicReview({
787
+ projectDir: resolution.projectDir,
788
+ ...(args.rootFile === undefined ? {} : { rootFile: args.rootFile }),
789
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
790
+ });
791
+ },
792
+ });
793
+ }
794
+ function formatPins(value) {
795
+ if (!value.ok)
796
+ return [value.message];
797
+ const lines = [`主控:${value.mcu}${value.dbVersion === "" ? "" : `(CubeMX 器件库 ${value.dbVersion})`}`];
798
+ for (const pin of value.pins) {
799
+ const candidates = pin.candidates.length === 0 ? "" : ` 候选:${pin.candidates.join(" / ")}`;
800
+ lines.push(` ${pin.number.padStart(2)}. ${pin.name}${pin.net === "" ? "(未接)" : ` → ${pin.net}`}${candidates}`);
801
+ }
802
+ for (const note of value.notes)
803
+ lines.push(` ! ${note}`);
804
+ return lines;
805
+ }
806
+ function formatCheck(value) {
807
+ if (!value.ok)
808
+ return [value.message];
809
+ const lines = [`发现 ${value.errors} 个错误 / ${value.warnings} 个告警 / ${value.infos} 条信息`];
810
+ if (value.pcbSummary !== "")
811
+ lines.push(`PCB 对账:${value.pcbSummary}`);
812
+ for (const finding of value.findings)
813
+ lines.push(` [${finding.severity}] ${finding.rule}:${finding.message}(${finding.evidence})`);
814
+ for (const note of value.notes)
815
+ lines.push(` ! ${note}`);
816
+ return lines;
817
+ }