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,225 @@
1
+ /**
2
+ * KiCad 10 原理图读取:把 `.kicad_sch` 拆成「图纸 → 符号实例 / 导线 / 标号 / 结点」。
3
+ *
4
+ * 只解析电气相关的节点,图形元素(矩形、文本、位图)直接丢弃:画不画得好看不是这一层的事。
5
+ * 符号的引脚定义来自文件内嵌的 `lib_symbols`,所以读原理图不需要本机装 KiCad,
6
+ * 也不依赖 `sym-lib-table` 指向的符号库是否还在。
7
+ *
8
+ * 版本口径:只在 KiCad 10(`version 20260306`)上验证;其它版本照常解析,
9
+ * 但由上层给出「未验证版本」告警,不做版本分支适配。
10
+ */
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { dirname, relative, resolve } from "node:path";
13
+ import { atomOf, childOf, childrenOf, headOf, numberOf, parseSexpr } from "./sexpr.js";
14
+ function pointOf(node) {
15
+ const at = Array.isArray(node) ? node : null;
16
+ if (at === null)
17
+ return null;
18
+ const x = numberOf(at, 1);
19
+ const y = numberOf(at, 2);
20
+ if (!Number.isFinite(x) || !Number.isFinite(y))
21
+ return null;
22
+ return { x, y };
23
+ }
24
+ function propertyMap(node) {
25
+ const out = new Map();
26
+ for (const property of childrenOf(node, "property")) {
27
+ const name = atomOf(property, 1);
28
+ const value = atomOf(property, 2);
29
+ if (name !== "")
30
+ out.set(name, value);
31
+ }
32
+ return out;
33
+ }
34
+ /** 符号单元名(`Device_R_1_1`)末尾的 `_unit_style`:引脚只属于某个单元。 */
35
+ function unitOfName(name) {
36
+ const match = /_(\d+)_(\d+)$/u.exec(name);
37
+ return match === null ? 0 : Number(match[1]);
38
+ }
39
+ function readLibPins(doc) {
40
+ const out = new Map();
41
+ const libs = childOf(doc, "lib_symbols");
42
+ for (const lib of childrenOf(libs, "symbol")) {
43
+ const name = atomOf(lib, 1);
44
+ if (name === "")
45
+ continue;
46
+ const pins = [];
47
+ const units = childrenOf(lib, "symbol");
48
+ const collect = (container, unit) => {
49
+ for (const pin of childrenOf(container, "pin")) {
50
+ const at = childOf(pin, "at");
51
+ const x = numberOf(at, 1);
52
+ const y = numberOf(at, 2);
53
+ if (!Number.isFinite(x) || !Number.isFinite(y))
54
+ continue;
55
+ pins.push({
56
+ number: atomOf(childOf(pin, "number"), 1),
57
+ name: atomOf(childOf(pin, "name"), 1),
58
+ x,
59
+ y,
60
+ kind: atomOf(pin, 1),
61
+ unit,
62
+ });
63
+ }
64
+ };
65
+ for (const unit of units) {
66
+ collect(unit, unitOfName(atomOf(unit, 1)));
67
+ }
68
+ collect(lib, 0);
69
+ out.set(name, pins);
70
+ }
71
+ return out;
72
+ }
73
+ function readLibFootprints(doc) {
74
+ const out = new Map();
75
+ const libs = childOf(doc, "lib_symbols");
76
+ for (const lib of childrenOf(libs, "symbol")) {
77
+ const name = atomOf(lib, 1);
78
+ if (name === "")
79
+ continue;
80
+ const footprint = propertyMap(lib).get("Footprint") ?? "";
81
+ if (footprint !== "")
82
+ out.set(name, footprint);
83
+ }
84
+ return out;
85
+ }
86
+ function readSymbol(node, relDir) {
87
+ const libId = atomOf(childOf(node, "lib_id"), 1);
88
+ if (libId === "")
89
+ return null;
90
+ const at = childOf(node, "at");
91
+ const position = pointOf(at) ?? { x: 0, y: 0 };
92
+ const rot = numberOf(at, 3);
93
+ const mirrorNode = childOf(node, "mirror");
94
+ const mirrorRaw = atomOf(mirrorNode, 1);
95
+ const mirror = mirrorRaw === "x" || mirrorRaw === "y" ? mirrorRaw : null;
96
+ const properties = propertyMap(node);
97
+ const ref = properties.get("Reference") ?? "";
98
+ const unit = numberOf(childOf(node, "unit"), 1);
99
+ const dnpNode = childOf(node, "dnp");
100
+ const dnp = atomOf(dnpNode, 1) === "yes";
101
+ void relDir;
102
+ return {
103
+ ref,
104
+ value: properties.get("Value") ?? "",
105
+ libId,
106
+ footprint: properties.get("Footprint") ?? "",
107
+ at: position,
108
+ rot: Number.isFinite(rot) ? rot : 0,
109
+ mirror,
110
+ unit: Number.isFinite(unit) ? unit : 1,
111
+ dnp,
112
+ isPower: libId.startsWith("power:"),
113
+ };
114
+ }
115
+ /** 解析一张图纸。`relFile` 只用于报告,不影响解析。 */
116
+ export function parseSchText(text, file, relFile = file) {
117
+ const doc = parseSexpr(text);
118
+ if (headOf(doc) !== "kicad_sch")
119
+ throw new Error("文件不是 KiCad 原理图(顶层不是 kicad_sch)");
120
+ const symbols = [];
121
+ for (const node of childrenOf(doc, "symbol")) {
122
+ const symbol = readSymbol(node, dirname(relFile));
123
+ if (symbol !== null)
124
+ symbols.push(symbol);
125
+ }
126
+ const wires = [];
127
+ for (const wire of childrenOf(doc, "wire")) {
128
+ const xy = childrenOf(childOf(wire, "pts"), "xy");
129
+ const a = pointOf(xy[0]);
130
+ const b = pointOf(xy[1]);
131
+ if (a !== null && b !== null)
132
+ wires.push({ a, b });
133
+ }
134
+ const labels = [];
135
+ for (const kind of ["label", "global_label", "hierarchical_label"]) {
136
+ for (const label of childrenOf(doc, kind)) {
137
+ const name = atomOf(label, 1);
138
+ const at = pointOf(childOf(label, "at"));
139
+ if (name !== "" && at !== null)
140
+ labels.push({ kind, name, at });
141
+ }
142
+ }
143
+ const noConnects = [];
144
+ for (const marker of childrenOf(doc, "no_connect")) {
145
+ const at = pointOf(childOf(marker, "at"));
146
+ if (at !== null)
147
+ noConnects.push(at);
148
+ }
149
+ const junctions = [];
150
+ for (const junction of childrenOf(doc, "junction")) {
151
+ const at = pointOf(childOf(junction, "at"));
152
+ if (at !== null)
153
+ junctions.push(at);
154
+ }
155
+ const sheetRefs = [];
156
+ for (const sheet of childrenOf(doc, "sheet")) {
157
+ const properties = propertyMap(sheet);
158
+ const name = properties.get("Sheetname") ?? "";
159
+ const sheetFile = properties.get("Sheetfile") ?? "";
160
+ if (sheetFile !== "")
161
+ sheetRefs.push({ name, file: sheetFile });
162
+ }
163
+ const version = numberOf(childOf(doc, "version"), 1);
164
+ return {
165
+ file,
166
+ relFile,
167
+ name: propertiesOf(doc).get("Title") ?? "",
168
+ paper: atomOf(childOf(doc, "paper"), 1),
169
+ version: Number.isFinite(version) ? version : 0,
170
+ generator: atomOf(childOf(doc, "generator"), 1),
171
+ symbols,
172
+ wires,
173
+ labels,
174
+ noConnects,
175
+ junctions,
176
+ sheetRefs,
177
+ libPins: readLibPins(doc),
178
+ libFootprints: readLibFootprints(doc),
179
+ };
180
+ }
181
+ /** 只取图纸的 `title_block` 标题(`(title_block (title "..."))`)。 */
182
+ function propertiesOf(doc) {
183
+ const out = new Map();
184
+ const block = childOf(doc, "title_block");
185
+ const title = atomOf(childOf(block, "title"), 1);
186
+ if (title !== "")
187
+ out.set("Title", title);
188
+ return out;
189
+ }
190
+ /**
191
+ * 从根图纸递归读取所有子图纸。
192
+ *
193
+ * 只跟随 `sheet` 引用,不扫描目录:工程里常见的 `col2.kicad_sch`、`.history/` 下的旧版本
194
+ * 都不在根表里,属于历史文件,不能当成电路的一部分。
195
+ */
196
+ export function readSchTree(rootFile) {
197
+ if (!existsSync(rootFile))
198
+ throw new Error(`原理图不存在:${rootFile}`);
199
+ const baseDir = dirname(rootFile);
200
+ const root = parseSchText(readFileSync(rootFile, "utf8"), rootFile, relative(baseDir, rootFile));
201
+ const sheets = [root];
202
+ const warnings = [];
203
+ const seen = new Set([resolve(rootFile)]);
204
+ const queue = [];
205
+ for (const ref of root.sheetRefs)
206
+ queue.push(ref.file);
207
+ while (queue.length > 0) {
208
+ const next = queue.shift();
209
+ if (next === undefined)
210
+ break;
211
+ const absolute = resolve(baseDir, next);
212
+ if (seen.has(absolute))
213
+ continue;
214
+ seen.add(absolute);
215
+ if (!existsSync(absolute)) {
216
+ warnings.push(`子图纸文件不存在:${next}`);
217
+ continue;
218
+ }
219
+ const parsed = parseSchText(readFileSync(absolute, "utf8"), absolute, relative(baseDir, absolute));
220
+ sheets.push(parsed);
221
+ for (const ref of parsed.sheetRefs)
222
+ queue.push(resolve(dirname(absolute), ref.file));
223
+ }
224
+ return { rootFile, rootName: root.relFile, sheets, warnings };
225
+ }
@@ -0,0 +1,442 @@
1
+ /**
2
+ * 原理图模型:把图纸树合并成「元件 / 引脚 / 网络」三张表,并派生出电路框图。
3
+ *
4
+ * 合并规则:电源网络与全局标号跨图纸按名字合并;本地标号只在所属图纸内有效
5
+ * (这是 KiCad 的语义,跨页同名本地标号并不相连)。层级图纸引脚暂不解析,
6
+ * 多图纸工程会带 `sheet.hierarchy-unresolved` 告警,避免把未连通的网络当成连通。
7
+ *
8
+ * 框图面向人看:MCU、主要 IC、连接器各成一框,两只元件之间有网络就连一条线,
9
+ * 线上写网络名;GND/VCC 这类电源网络画成连线会把图糊掉,单独列为「电源网络」。
10
+ */
11
+ import { readdirSync, statSync } from "node:fs";
12
+ import { basename, dirname, extname, join, resolve } from "node:path";
13
+ import { readSchTree } from "./kicad-sch.js";
14
+ import { buildSheetNets } from "./nets.js";
15
+ /** 工程目录里找根图纸:优先与 `.kicad_pro` 同名的文件,其次取未被其它图纸引用的那张。 */
16
+ export function findRootSchematic(projectDir) {
17
+ let entries;
18
+ try {
19
+ entries = readdirSync(projectDir);
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ const sch = entries.filter((name) => extname(name) === ".kicad_sch").sort();
25
+ if (sch.length === 0)
26
+ return null;
27
+ const pro = entries.find((name) => extname(name) === ".kicad_pro");
28
+ if (pro !== undefined) {
29
+ const expected = `${basename(pro, ".kicad_pro")}.kicad_sch`;
30
+ if (sch.includes(expected))
31
+ return join(projectDir, expected);
32
+ }
33
+ return join(projectDir, sch[0]);
34
+ }
35
+ /**
36
+ * 模块识别规则(按“这块电路在做什么”归类,不按位号)。
37
+ *
38
+ * 先把有明确身份的器件认成种子:主控、NFC 标签与天线、光电与运放、供电、调试接口、
39
+ * 按键;再把电阻电容等无源器件按连接关系并进种子模块。规则只认器件库与网络语义,
40
+ * 换一块板子照样能用;认不出的模块单列,不硬塞。
41
+ */
42
+ const MODULE_SPECS = [
43
+ {
44
+ key: "mcu",
45
+ label: "主控",
46
+ match: (c) => /^STM32|^GD32|^ATSAM|^MSP430|^RP2040|^ESP32/u.test(c.value) ||
47
+ // tscircuit 导出的原理图不写 Value,只剩封装线索(U_chip_qfp48 这种)(S132)。
48
+ /(U_chip|MCU|QFP|LQFP|BGA|WLCSP)/iu.test(c.libId),
49
+ },
50
+ {
51
+ key: "nfc",
52
+ label: "NFC 天线与标签",
53
+ match: (c) => /^RF_NFC:/u.test(c.libId) ||
54
+ /^NFC_Coil:/u.test(c.libId) ||
55
+ /^(ST25D|M24SR|NT3H|PN5|FM11)/u.test(c.value),
56
+ },
57
+ {
58
+ key: "optical",
59
+ label: "光检测",
60
+ match: (c) => /^Sensor_Optical:/u.test(c.libId) ||
61
+ /(Amplifier_Operational|Amplifier:)/u.test(c.libId) ||
62
+ /^Device:(LED|Photodiode|Phototransistor)$/u.test(c.libId),
63
+ },
64
+ {
65
+ key: "power",
66
+ label: "供电与接口",
67
+ match: (c) => /(Regulator_Linear|Regulator_Switching)/u.test(c.libId) ||
68
+ /^Device:Battery/u.test(c.libId) ||
69
+ /(LDO|^AMS1117|^TLV7|^MIC5|^AP2112|^RT9013|^SGM)/iu.test(c.value) ||
70
+ /(USB|Battery|LiPo|CR2032)/iu.test(c.value),
71
+ },
72
+ {
73
+ key: "keys",
74
+ label: "按键与复位",
75
+ match: (c) => /^Switch:/u.test(c.libId) || /^SW_/u.test(c.value),
76
+ },
77
+ ];
78
+ function moduleOf(component, swdRefs) {
79
+ for (const spec of MODULE_SPECS) {
80
+ if (spec.match(component))
81
+ return spec;
82
+ }
83
+ if (INTERFACE_SPEC.match(component))
84
+ return INTERFACE_SPEC;
85
+ if (swdRefs.has(component.ref))
86
+ return INTERFACE_SPEC;
87
+ return null;
88
+ }
89
+ const INTERFACE_SPEC = {
90
+ key: "interface",
91
+ label: "接口与调试口",
92
+ match: (c) => /(J_connector|Connector:)/iu.test(c.libId),
93
+ };
94
+ /**
95
+ * 在主控没有被写出型号时,按「脚数最多、位号以 U 开头」推断(S132)。
96
+ *
97
+ * tscircuit 导出的原理图只保留封装形状(`Device:U_chip_qfp48_…`)与位号,Value 为空;
98
+ * 按脚数推断比按型号名可靠:一个 48 脚的 U 只有主控这一种可能。
99
+ */
100
+ function inferMcu(components) {
101
+ const named = components.find((component) => /^STM32|^GD32|^ATSAM|^MSP430|^RP2040|^ESP32/u.test(component.value));
102
+ if (named !== undefined)
103
+ return named;
104
+ const candidates = components
105
+ .filter((component) => /^U\d/u.test(component.ref) && component.pins.length >= 24)
106
+ .sort((a, b) => b.pins.length - a.pins.length);
107
+ return candidates[0] ?? null;
108
+ }
109
+ const PASSIVE_LIB = /^Device:(R|C|L|FB|Ferrite|Crystal|D_TVS|Polyfuse)/u;
110
+ function humanLabel(component) {
111
+ const value = component.value === "" ? component.ref : component.value;
112
+ return value.length > 26 ? `${value.slice(0, 25)}…` : value;
113
+ }
114
+ /**
115
+ * 读原理图并合成报告。
116
+ *
117
+ * `rootFile` 显式给定时按该文件读;否则在 `projectDir` 里找根图纸。
118
+ */
119
+ export function readSchematic(rootFile) {
120
+ const tree = readSchTree(rootFile);
121
+ const warnings = [...tree.warnings];
122
+ const merged = new Map();
123
+ const localNets = [];
124
+ const sheetNets = new Map();
125
+ for (const sheet of tree.sheets) {
126
+ const result = buildSheetNets(sheet);
127
+ sheetNets.set(sheet.relFile, result);
128
+ for (const net of result.nets) {
129
+ const globalKey = net.kind === "power" || net.global ? `g:${net.name}` : `l:${sheet.relFile}:${net.name}`;
130
+ let entry = merged.get(globalKey);
131
+ if (entry === undefined) {
132
+ entry = { name: net.name, kind: net.kind, sheets: new Set(), labels: new Set(), pins: [] };
133
+ merged.set(globalKey, entry);
134
+ }
135
+ entry.sheets.add(net.sheet);
136
+ for (const label of net.labels)
137
+ entry.labels.add(label);
138
+ for (const pin of net.pins)
139
+ entry.pins.push({ ref: pin.ref, number: pin.number, name: pin.name });
140
+ localNets.push(net);
141
+ }
142
+ if (result.floatingPins.length > 0) {
143
+ warnings.push(`${sheet.relFile}:${result.floatingPins.length} 个引脚没有碰到导线(${result.floatingPins.slice(0, 6).join("、")})`);
144
+ }
145
+ }
146
+ const components = [];
147
+ for (const sheet of tree.sheets) {
148
+ const symPins = new Map();
149
+ for (const symbol of sheet.symbols) {
150
+ if (symbol.isPower || symbol.ref === "" || symbol.ref.startsWith("#"))
151
+ continue;
152
+ const pins = [];
153
+ const libPins = (sheet.libPins.get(symbol.libId) ?? []).filter((pin) => pin.unit === 0 || pin.unit === symbol.unit);
154
+ const placed = libPins.length > 0 ? libPins : sheet.libPins.get(symbol.libId) ?? [];
155
+ const netResult = sheetNets.get(sheet.relFile);
156
+ for (const pin of placed) {
157
+ const key = `${symbol.ref}:${pin.number}`;
158
+ const index = netResult?.pinNet.get(key);
159
+ const source = index === undefined ? undefined : netResult?.nets[index];
160
+ pins.push({
161
+ number: pin.number,
162
+ name: pin.name,
163
+ net: source?.name ?? "",
164
+ type: pin.kind,
165
+ noConnect: source?.hasNoConnect === true,
166
+ });
167
+ }
168
+ symPins.set(symbol.ref, pins);
169
+ components.push({
170
+ ref: symbol.ref,
171
+ value: symbol.value,
172
+ footprint: symbol.footprint,
173
+ libId: symbol.libId,
174
+ sheet: sheet.relFile,
175
+ dnp: symbol.dnp,
176
+ pins,
177
+ });
178
+ }
179
+ }
180
+ const nets = [...merged.values()]
181
+ .filter((net) => net.pins.length > 0 || net.kind !== "unnamed")
182
+ .map((net) => ({
183
+ name: net.name,
184
+ kind: net.kind,
185
+ sheets: [...net.sheets].sort(),
186
+ labels: [...net.labels].sort(),
187
+ pins: net.pins,
188
+ }))
189
+ .sort((a, b) => b.pins.length - a.pins.length || a.name.localeCompare(b.name));
190
+ const mcuComponent = inferMcu(components);
191
+ if (mcuComponent === null) {
192
+ warnings.push("没有识别到主控:框图只按普通元件分组");
193
+ }
194
+ else if (!/^STM32|^GD32|^ATSAM|^MSP430|^RP2040|^ESP32/u.test(mcuComponent.value)) {
195
+ warnings.push("主控按封装脚数与位号推断为 " + mcuComponent.ref + "(原理图里没有写型号);可在电路源码里补 name 或 mpn 提高准确度");
196
+ }
197
+ const multiUnit = new Map();
198
+ for (const sheet of tree.sheets) {
199
+ for (const symbol of sheet.symbols) {
200
+ if (symbol.ref === "" || symbol.ref.startsWith("#"))
201
+ continue;
202
+ multiUnit.set(symbol.ref, (multiUnit.get(symbol.ref) ?? 0) + 1);
203
+ }
204
+ }
205
+ for (const [ref, count] of multiUnit) {
206
+ if (count > 1)
207
+ warnings.push(`元件 ${ref} 在图纸上出现 ${count} 次(多单元符号按同一引用合并)`);
208
+ }
209
+ const hierarchical = tree.sheets.some((sheet) => sheet.labels.some((label) => label.kind === "hierarchical_label"));
210
+ if (hierarchical && tree.sheets.length > 1) {
211
+ warnings.push("多图纸工程含层级标号:层级图纸引脚未跨页解析,跨页连通性请以 PCB 对账为准");
212
+ }
213
+ if (tree.sheets.length > 1)
214
+ warnings.push(`共 ${tree.sheets.length} 张图纸;未在根图纸引用的历史文件不参与解析`);
215
+ const unreferenced = unreferencedSheets(dirname(rootFile), tree.sheets);
216
+ if (unreferenced.length > 0) {
217
+ warnings.push(`目录内还有未引用的图纸(历史版本,按设计不解析):${unreferenced.join("、")}`);
218
+ }
219
+ const diagram = buildDiagram(components, nets);
220
+ const report = {
221
+ rootFile,
222
+ version: tree.sheets[0]?.version ?? 0,
223
+ generator: tree.sheets[0]?.generator ?? "",
224
+ sheets: tree.sheets.map((sheet) => {
225
+ const netsOfSheet = localNets.filter((net) => net.sheet === sheet.relFile);
226
+ return { file: sheet.relFile, paper: sheet.paper, symbols: sheet.symbols.length, nets: netsOfSheet.length };
227
+ }),
228
+ components,
229
+ nets,
230
+ mcu: mcuComponent === null ? null : { ref: mcuComponent.ref, value: mcuComponent.value, pins: mcuComponent.pins },
231
+ diagram,
232
+ warnings,
233
+ };
234
+ const netPins = new Map();
235
+ for (const net of nets)
236
+ netPins.set(net.name, net.pins.map((pin) => ({ ref: pin.ref, number: pin.number })));
237
+ return { report, netPins };
238
+ }
239
+ /** 目录里存在、但没有被任何图纸引用的 `.kicad_sch`(历史版本)。 */
240
+ function unreferencedSheets(projectDir, sheets) {
241
+ const used = new Set(sheets.map((sheet) => resolve(sheet.file)));
242
+ let entries = [];
243
+ try {
244
+ entries = readdirSync(projectDir);
245
+ }
246
+ catch {
247
+ return [];
248
+ }
249
+ return entries
250
+ .filter((name) => extname(name) === ".kicad_sch")
251
+ .map((name) => join(projectDir, name))
252
+ .filter((file) => !used.has(resolve(file)) && statSync(file).isFile())
253
+ .map((file) => basename(file));
254
+ }
255
+ /** 按网络名判断总线类型;认不出来时返回 null,由调用方回落到网络名。 */
256
+ function busOf(nets) {
257
+ const names = nets.map((name) => name.toUpperCase());
258
+ const has = (pattern) => names.some((name) => pattern.test(name));
259
+ if (has(/SCL/u) && has(/SDA/u))
260
+ return "I2C";
261
+ if (has(/MOSI/u) || has(/MISO/u) || has(/SCK/u))
262
+ return "SPI";
263
+ if (has(/TXD?\b/u) && has(/RXD?\b/u))
264
+ return "UART";
265
+ return null;
266
+ }
267
+ /** 把一串网络名归纳成读者先要的信息:总线类型与信号用途,而不是逐个引脚名。 */
268
+ function signalGroups(nets) {
269
+ const names = nets.map((name) => name.toUpperCase());
270
+ const groups = [];
271
+ const has = (pattern) => names.some((name) => pattern.test(name));
272
+ if (has(/SCL/u) && has(/SDA/u))
273
+ groups.push("I2C");
274
+ if (has(/MOSI/u) && has(/MISO/u) && has(/SCK/u))
275
+ groups.push("SPI");
276
+ if (has(/TXD?\b/u) && has(/RXD?\b/u))
277
+ groups.push("UART");
278
+ if (has(/ADC/u))
279
+ groups.push("ADC");
280
+ if (has(/^LED|LED\d/u))
281
+ groups.push("LED");
282
+ if (has(/PWM/u))
283
+ groups.push("PWM");
284
+ if (has(/SWD(IO|CLK)/u))
285
+ groups.push("SWD");
286
+ if (has(/^(NRST|BOOT0)$/u))
287
+ groups.push("复位与启动");
288
+ return groups;
289
+ }
290
+ function buildDiagram(components, nets) {
291
+ // 先找出带 SWDIO / SWCLK 的器件:调试口多数是 4 脚排针,靠网络名比靠位号可靠。
292
+ const swdRefs = new Set();
293
+ for (const net of nets) {
294
+ if (!/SWD(IO|CLK)/iu.test(net.name))
295
+ continue;
296
+ for (const pin of net.pins)
297
+ swdRefs.add(pin.ref);
298
+ }
299
+ const moduleOfRef = new Map();
300
+ for (const component of components) {
301
+ const spec = moduleOf(component, swdRefs);
302
+ if (spec === null)
303
+ continue;
304
+ moduleOfRef.set(component.ref, spec.key);
305
+ }
306
+ // 无源器件与认不出的器件按连接关系并进已有模块。两条规则:
307
+ // 1)两脚器件一脚接电源、一脚接信号 —— 它是去耦或上拉,跟信号那侧走;
308
+ // 2)其余按「和哪个模块共网最多」投票,只数非电源网络,避免 VCC 把所有器件绑到一处。
309
+ const isPowerName = (name) => /^(VCC|VDD\w*|VBUS|GND\w*|VSS|\+3V3|\+5V|3V3|5V)/iu.test(name);
310
+ const pinsOfRef = new Map();
311
+ for (const net of nets) {
312
+ for (const pin of net.pins) {
313
+ const list = pinsOfRef.get(pin.ref) ?? [];
314
+ list.push({ net: net.name, kind: net.kind });
315
+ pinsOfRef.set(pin.ref, list);
316
+ }
317
+ }
318
+ const votes = new Map();
319
+ const bump = (ref, kind, weight = 1) => {
320
+ const bucket = votes.get(ref) ?? new Map();
321
+ bucket.set(kind, (bucket.get(kind) ?? 0) + weight);
322
+ votes.set(ref, bucket);
323
+ };
324
+ for (const net of nets) {
325
+ if (net.kind === "power" || isPowerName(net.name))
326
+ continue;
327
+ for (const pin of net.pins) {
328
+ if (moduleOfRef.has(pin.ref))
329
+ continue;
330
+ for (const other of net.pins) {
331
+ const kind = moduleOfRef.get(other.ref);
332
+ if (kind !== undefined)
333
+ bump(pin.ref, kind);
334
+ }
335
+ }
336
+ }
337
+ // 两脚器件的「一脚电源、一脚信号」规则:信号侧邻居的模块更可信,权重加倍。
338
+ for (const [ref, pins] of pinsOfRef) {
339
+ if (moduleOfRef.has(ref) || pins.length !== 2)
340
+ continue;
341
+ const powerPins = pins.filter((pin) => pin.kind === "power" || isPowerName(pin.net));
342
+ if (powerPins.length !== 1)
343
+ continue;
344
+ const signal = pins.find((pin) => pin !== powerPins[0]);
345
+ if (signal === undefined)
346
+ continue;
347
+ const net = nets.find((item) => item.name === signal.net);
348
+ if (net === undefined)
349
+ continue;
350
+ for (const other of net.pins) {
351
+ const kind = moduleOfRef.get(other.ref);
352
+ if (kind !== undefined)
353
+ bump(ref, kind, 2);
354
+ }
355
+ }
356
+ for (const [ref, bucket] of votes) {
357
+ let best = null;
358
+ let bestCount = 0;
359
+ for (const [kind, count] of bucket) {
360
+ if (count > bestCount) {
361
+ best = kind;
362
+ bestCount = count;
363
+ }
364
+ }
365
+ if (best !== null)
366
+ moduleOfRef.set(ref, best);
367
+ }
368
+ const blocks = new Map();
369
+ const specByKey = new Map([...MODULE_SPECS, INTERFACE_SPEC].map((spec) => [spec.key, spec]));
370
+ for (const component of components) {
371
+ const kind = moduleOfRef.get(component.ref);
372
+ if (kind === undefined)
373
+ continue;
374
+ const spec = specByKey.get(kind);
375
+ const existing = blocks.get(kind);
376
+ if (existing !== undefined) {
377
+ existing.refs.push(component.ref);
378
+ continue;
379
+ }
380
+ blocks.set(kind, {
381
+ id: kind,
382
+ label: spec?.label ?? "其他电路",
383
+ kind,
384
+ refs: [component.ref],
385
+ });
386
+ }
387
+ const blockOfRef = (ref) => moduleOfRef.get(ref) ?? null;
388
+ void blockOfRef;
389
+ const links = new Map();
390
+ const powerNets = new Set();
391
+ const isAnonymous = (name) => /^N\$\d+$/u.test(name);
392
+ for (const net of nets) {
393
+ const refs = [...new Set(net.pins.map((pin) => moduleOfRef.get(pin.ref)).filter((kind) => kind !== undefined))];
394
+ if (refs.length < 2)
395
+ continue;
396
+ if (net.kind === "power" || isPowerName(net.name)) {
397
+ powerNets.add(net.name);
398
+ continue;
399
+ }
400
+ if (refs.length > 6) {
401
+ powerNets.add(net.name);
402
+ continue;
403
+ }
404
+ for (let i = 0; i < refs.length; i += 1) {
405
+ for (let j = i + 1; j < refs.length; j += 1) {
406
+ const a = refs[i];
407
+ const b = refs[j];
408
+ if (a === b)
409
+ continue;
410
+ const key = a < b ? `${a}|${b}` : `${b}|${a}`;
411
+ const existing = links.get(key);
412
+ if (existing === undefined) {
413
+ links.set(key, { from: a < b ? a : b, to: a < b ? b : a, nets: [net.name] });
414
+ }
415
+ else if (!existing.nets.includes(net.name)) {
416
+ existing.nets.push(net.name);
417
+ }
418
+ }
419
+ }
420
+ }
421
+ const degree = new Map();
422
+ for (const link of links.values()) {
423
+ degree.set(link.from, (degree.get(link.from) ?? 0) + link.nets.length);
424
+ degree.set(link.to, (degree.get(link.to) ?? 0) + link.nets.length);
425
+ }
426
+ const allBlocks = [...blocks.values()];
427
+ const ordered = [
428
+ ...allBlocks.filter((block) => block.kind === "mcu"),
429
+ ...allBlocks
430
+ .filter((block) => block.kind !== "mcu")
431
+ .sort((a, b) => (degree.get(b.id) ?? 0) - (degree.get(a.id) ?? 0) || a.id.localeCompare(b.id)),
432
+ ];
433
+ const linksWithLabel = [...links.values()].map((link) => {
434
+ const netsOfLink = [...link.nets].filter((name) => !isAnonymous(name)).sort();
435
+ const groups = signalGroups(netsOfLink);
436
+ const shown = netsOfLink.slice(0, 3).join(" / ");
437
+ const extra = netsOfLink.length > 3 ? ` +${netsOfLink.length - 3}` : "";
438
+ const label = groups.length > 0 ? groups.join(" · ") : shown === "" ? "" : `${shown}${extra}`;
439
+ return { from: link.from, to: link.to, label, nets: netsOfLink };
440
+ });
441
+ return { blocks: ordered, links: linksWithLabel, powerNets: [...powerNets].sort() };
442
+ }