dsh-stm32 0.1.7 → 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 (153) hide show
  1. package/README.md +567 -516
  2. package/README_EN.md +544 -510
  3. package/client/client.js +7033 -682
  4. package/docs/reading-guide.md +921 -859
  5. package/lib/client.js +7033 -682
  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/artifacts.js +123 -0
  12. package/lib/engine/breakpoint-hits.js +73 -0
  13. package/lib/engine/build.js +161 -5
  14. package/lib/engine/channel-tap.js +227 -0
  15. package/lib/engine/channels.js +48 -0
  16. package/lib/engine/clocks.js +192 -0
  17. package/lib/engine/datasheet/auto.js +74 -0
  18. package/lib/engine/datasheet/digest.js +74 -0
  19. package/lib/engine/datasheet/lcsc.js +60 -0
  20. package/lib/engine/datasheet/pinout.js +119 -0
  21. package/lib/engine/datasheet/price.js +152 -0
  22. package/lib/engine/datasheet/search.js +147 -0
  23. package/lib/engine/datasheet/store.js +371 -0
  24. package/lib/engine/debug-session.js +48 -2
  25. package/lib/engine/ecad/autobuild.js +156 -0
  26. package/lib/engine/ecad/bom.js +238 -0
  27. package/lib/engine/ecad/brief.js +205 -0
  28. package/lib/engine/ecad/checks.js +239 -0
  29. package/lib/engine/ecad/design.js +177 -0
  30. package/lib/engine/ecad/dfm.js +314 -0
  31. package/lib/engine/ecad/easyeda.js +454 -0
  32. package/lib/engine/ecad/fabrication.js +104 -0
  33. package/lib/engine/ecad/gen/footprint.js +159 -0
  34. package/lib/engine/ecad/gen/symbol.js +103 -0
  35. package/lib/engine/ecad/import.js +372 -0
  36. package/lib/engine/ecad/jlcpcb.js +141 -0
  37. package/lib/engine/ecad/libs.js +316 -0
  38. package/lib/engine/ecad/models3d.js +89 -0
  39. package/lib/engine/ecad/netgate.js +286 -0
  40. package/lib/engine/ecad/normalize.js +182 -0
  41. package/lib/engine/ecad/package.js +126 -0
  42. package/lib/engine/ecad/padmerge.js +128 -0
  43. package/lib/engine/ecad/padprecheck.js +123 -0
  44. package/lib/engine/ecad/part-import.js +257 -0
  45. package/lib/engine/ecad/pcb/apply.js +53 -0
  46. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  47. package/lib/engine/ecad/pcb/emc.js +275 -0
  48. package/lib/engine/ecad/pcb/geometry.js +63 -0
  49. package/lib/engine/ecad/pcb/gerber.js +499 -0
  50. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  51. package/lib/engine/ecad/pcb/impedance.js +119 -0
  52. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  53. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  54. package/lib/engine/ecad/pcb/ipc.js +129 -0
  55. package/lib/engine/ecad/pcb/krt.js +182 -0
  56. package/lib/engine/ecad/pcb/links.js +393 -0
  57. package/lib/engine/ecad/pcb/mech.js +201 -0
  58. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  59. package/lib/engine/ecad/pcb/netlist.js +146 -0
  60. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  61. package/lib/engine/ecad/pcb/placement.js +140 -0
  62. package/lib/engine/ecad/pcb/power.js +203 -0
  63. package/lib/engine/ecad/pcb/render3d.js +208 -0
  64. package/lib/engine/ecad/pcb/route.js +167 -0
  65. package/lib/engine/ecad/pcb/router.js +469 -0
  66. package/lib/engine/ecad/pcb/rules.js +122 -0
  67. package/lib/engine/ecad/pcb/scene.js +513 -0
  68. package/lib/engine/ecad/pcb/stackup.js +154 -0
  69. package/lib/engine/ecad/pcb/swap.js +222 -0
  70. package/lib/engine/ecad/pcb/tracks.js +70 -0
  71. package/lib/engine/ecad/runtime.js +227 -0
  72. package/lib/engine/ecad/toolchain.js +146 -0
  73. package/lib/engine/ecad/tsci.js +362 -0
  74. package/lib/engine/ecad/zip.js +98 -0
  75. package/lib/engine/event-bus.js +158 -0
  76. package/lib/engine/event-log.js +335 -0
  77. package/lib/engine/fault-hints.js +146 -0
  78. package/lib/engine/generate-script.js +4 -1
  79. package/lib/engine/generate.js +145 -5
  80. package/lib/engine/interrupts.js +247 -0
  81. package/lib/engine/ioc-diff.js +369 -0
  82. package/lib/engine/ioc-plan.js +12 -2
  83. package/lib/engine/ioc-sync.js +58 -0
  84. package/lib/engine/mcu-info.js +134 -0
  85. package/lib/engine/msys2-install.js +31 -6
  86. package/lib/engine/panel-actions.js +103 -0
  87. package/lib/engine/pdf/curve.js +321 -0
  88. package/lib/engine/pdf/png.js +83 -0
  89. package/lib/engine/pdf/reader.js +336 -0
  90. package/lib/engine/pdf/schematic.js +93 -0
  91. package/lib/engine/pdf/tables.js +249 -0
  92. package/lib/engine/pdf/toolchain.js +50 -0
  93. package/lib/engine/pinout.js +140 -0
  94. package/lib/engine/probe-info.js +95 -0
  95. package/lib/engine/probe.js +45 -0
  96. package/lib/engine/progress.js +99 -0
  97. package/lib/engine/project-conf.js +254 -0
  98. package/lib/engine/project-layout.js +198 -0
  99. package/lib/engine/project-repair.js +205 -0
  100. package/lib/engine/schematic/checks.js +153 -0
  101. package/lib/engine/schematic/draw.js +390 -0
  102. package/lib/engine/schematic/edit.js +229 -0
  103. package/lib/engine/schematic/kicad-sch.js +225 -0
  104. package/lib/engine/schematic/model.js +442 -0
  105. package/lib/engine/schematic/nets.js +219 -0
  106. package/lib/engine/schematic/pcb.js +144 -0
  107. package/lib/engine/schematic/review.js +134 -0
  108. package/lib/engine/schematic/sexpr.js +134 -0
  109. package/lib/engine/schematic/to-ioc.js +197 -0
  110. package/lib/engine/schematic/transform.js +25 -0
  111. package/lib/engine/session-context.js +106 -0
  112. package/lib/engine/source-slice.js +59 -0
  113. package/lib/engine/tool-events.js +119 -0
  114. package/lib/engine/toolchain-gate.js +8 -0
  115. package/lib/engine/watch-admin.js +101 -0
  116. package/lib/engine/watch-record.js +39 -0
  117. package/lib/engine/watch-recorder.js +116 -0
  118. package/lib/engine/web-api.js +1123 -4
  119. package/lib/engine/web-routes.js +18 -1
  120. package/lib/engine/workspace-memo.js +41 -0
  121. package/lib/index.js +118 -24
  122. package/lib/skill/stm32-workflow.js +1 -1
  123. package/lib/tools/build.js +10 -2
  124. package/lib/tools/code-patch.js +2 -2
  125. package/lib/tools/datasheet.js +447 -0
  126. package/lib/tools/debug-session.js +9 -4
  127. package/lib/tools/debug.js +2 -2
  128. package/lib/tools/doctor.js +2 -2
  129. package/lib/tools/ecad.js +903 -0
  130. package/lib/tools/flash.js +2 -2
  131. package/lib/tools/gen.js +166 -0
  132. package/lib/tools/generate.js +7 -5
  133. package/lib/tools/import-circuit.js +146 -0
  134. package/lib/tools/ioc-apply.js +11 -2
  135. package/lib/tools/ioc-inspect.js +2 -2
  136. package/lib/tools/ioc-plan.js +2 -2
  137. package/lib/tools/ioc-verify.js +2 -2
  138. package/lib/tools/layout.js +92 -0
  139. package/lib/tools/mcu-info.js +163 -0
  140. package/lib/tools/part-import.js +182 -0
  141. package/lib/tools/pcb.js +2316 -0
  142. package/lib/tools/pdf.js +423 -0
  143. package/lib/tools/project-create.js +28 -0
  144. package/lib/tools/project-dir.js +25 -1
  145. package/lib/tools/regs.js +2 -2
  146. package/lib/tools/route-plan.js +2 -2
  147. package/lib/tools/rtt.js +10 -2
  148. package/lib/tools/sch-draw.js +433 -0
  149. package/lib/tools/sch-edit.js +145 -0
  150. package/lib/tools/schematic.js +817 -0
  151. package/lib/tools/serial.js +22 -0
  152. package/lib/tools/watch.js +24 -2
  153. package/package.json +1 -1
@@ -0,0 +1,336 @@
1
+ /**
2
+ * PDF 读取(S117):把一份 PDF 摊成三种可核对的东西。
3
+ *
4
+ * 1. 元信息 —— pdfinfo:页数、纸张大小、是否加密、是否带文字层;
5
+ * 2. 文字 —— pdftotext(-layout 保版面,-f/-l 限定页):章节标题、表格、参数都靠它;
6
+ * 3. 页面图像 —— pdftoppm:整页或局部渲染成 PNG,交给视觉读图(曲线、框图、丝印)。
7
+ *
8
+ * 不在这里做的事:把曲线数字化。渲染出来的像素由读图的一方解释,本模块只保证
9
+ * 「给的是真实页面上那一块」,不猜坐标。
10
+ */
11
+ import { existsSync, readFileSync, statSync } from "node:fs";
12
+ import { createHash } from "node:crypto";
13
+ import { dirname, join } from "node:path";
14
+ import { tmpdir } from "node:os";
15
+ import { runCapture } from "../subprocess-runner.js";
16
+ import { extractTablesFromWords, parseBboxXml } from "./tables.js";
17
+ import { decodePng } from "./png.js";
18
+ import { calibrateFromWords, chromaBounds, digitizeCurves, legendLabels } from "./curve.js";
19
+ import { readPdfSchematicWords } from "./schematic.js";
20
+ function numberFrom(text, key) {
21
+ const match = new RegExp("^" + key + ":\\s*(.+)$", "mu").exec(text);
22
+ return match === null ? "" : (match[1] ?? "").trim();
23
+ }
24
+ /** 页面文字里的控制字符比例:描边字体导出的 PDF 正文是 \u0001 这类码位。 */
25
+ function looksLikeGlyphCodes(text) {
26
+ if (text.trim() === "")
27
+ return true;
28
+ let control = 0;
29
+ let total = 0;
30
+ for (const char of text) {
31
+ total += 1;
32
+ const code = char.codePointAt(0) ?? 0;
33
+ if (code < 0x20 && char !== "\n" && char !== "\r" && char !== "\t")
34
+ control += 1;
35
+ }
36
+ return total > 0 && control / total > 0.2;
37
+ }
38
+ export async function readPdfInfo(subprocess, tools, file, signal) {
39
+ const blank = {
40
+ ok: false,
41
+ file,
42
+ bytes: 0,
43
+ pages: 0,
44
+ title: "",
45
+ producer: "",
46
+ pageSize: "",
47
+ encrypted: false,
48
+ hasTextLayer: true,
49
+ notes: [],
50
+ };
51
+ if (!existsSync(file))
52
+ return { ...blank, error: "PDF 不存在:" + file };
53
+ const size = statSync(file).size;
54
+ const info = await runCapture(subprocess, {
55
+ argv: [tools.pdfinfo, file],
56
+ timeoutMs: 30_000,
57
+ ...(signal === undefined ? {} : { signal }),
58
+ });
59
+ if (info.exitCode !== 0) {
60
+ return { ...blank, bytes: size, error: "pdfinfo 执行失败:" + (info.stderr.trim() || String(info.exitCode)) };
61
+ }
62
+ const pages = Number(numberFrom(info.stdout, "Pages"));
63
+ const notes = [];
64
+ // 抽查第一页的文字层:只跑一页,避免整本转文本。
65
+ const probe = await runCapture(subprocess, {
66
+ argv: [tools.pdftotext, "-f", "1", "-l", "1", file, "-"],
67
+ timeoutMs: 30_000,
68
+ ...(signal === undefined ? {} : { signal }),
69
+ });
70
+ const hasTextLayer = probe.exitCode === 0 ? !looksLikeGlyphCodes(probe.stdout) : false;
71
+ if (!hasTextLayer)
72
+ notes.push("第一页取不到正常文字:正文可能是描边字形(KiCad 默认 PDF 字体),文字类问题只能按图看");
73
+ return {
74
+ ok: true,
75
+ error: "",
76
+ file,
77
+ bytes: size,
78
+ pages: Number.isFinite(pages) ? pages : 0,
79
+ title: numberFrom(info.stdout, "Title"),
80
+ producer: numberFrom(info.stdout, "Producer"),
81
+ pageSize: numberFrom(info.stdout, "Page size"),
82
+ encrypted: /^Encrypted:\s*yes$/mu.test(info.stdout),
83
+ hasTextLayer,
84
+ notes,
85
+ };
86
+ }
87
+ export async function extractPdfText(subprocess, tools, file, options = {}, signal) {
88
+ const first = Math.max(1, Math.floor(options.first ?? 1));
89
+ const last = Math.max(first, Math.floor(options.last ?? first));
90
+ const blank = { ok: false, file, first, last, chars: 0, pages: [], notes: [] };
91
+ if (!existsSync(file))
92
+ return { ...blank, error: "PDF 不存在:" + file };
93
+ const argv = [tools.pdftotext];
94
+ if (options.layout !== false)
95
+ argv.push("-layout");
96
+ argv.push("-f", String(first), "-l", String(last), file, "-");
97
+ const out = await runCapture(subprocess, {
98
+ argv,
99
+ timeoutMs: 60_000,
100
+ maxBytes: 8 * 1024 * 1024,
101
+ ...(signal === undefined ? {} : { signal }),
102
+ });
103
+ if (out.exitCode !== 0) {
104
+ return { ...blank, error: "pdftotext 执行失败:" + (out.stderr.trim() || String(out.exitCode)) };
105
+ }
106
+ const raw = out.stdout;
107
+ const notes = [];
108
+ if (looksLikeGlyphCodes(raw))
109
+ notes.push("这一段的文字是字形码(描边字体),读不出可读正文:改用 render 模式看图");
110
+ const pages = [];
111
+ const chunks = raw.split("\f");
112
+ for (const [index, chunk] of chunks.entries()) {
113
+ const page = first + index;
114
+ if (page > last)
115
+ break;
116
+ const text = chunk.replace(/[ \t]+$/gmu, "").trim();
117
+ if (text !== "" || index === 0)
118
+ pages.push({ page, text });
119
+ }
120
+ return { ok: true, error: "", file, first, last, chars: raw.length, pages, notes };
121
+ }
122
+ /** 图注与目录行:「Figure 14. VREFINT vs. temperature …… 44」。 */
123
+ export function listFigures(text, limit = 40) {
124
+ const out = [];
125
+ const seen = new Set();
126
+ for (const line of text.split(/\r?\n/u)) {
127
+ const match = /^\s*(Figure|Table)\s+([0-9]+[a-z]?)\s*[.:]?\s*(.+)$/iu.exec(line);
128
+ if (match === null)
129
+ continue;
130
+ const kind = (match[1] ?? "").toLowerCase();
131
+ if (kind !== "figure")
132
+ continue;
133
+ const number = match[2] ?? "";
134
+ const rest = (match[3] ?? "").replace(/[.…\s]{2,}[0-9]+\s*$/u, "").trim();
135
+ const pageMatch = /\s([0-9]{1,4})\s*$/u.exec(line);
136
+ const page = pageMatch === null ? 0 : Number(pageMatch[1]);
137
+ const key = number + "|" + (rest.slice(0, 24) || "");
138
+ if (seen.has(key))
139
+ continue;
140
+ seen.add(key);
141
+ out.push({ number, title: rest.slice(0, 120), page: Number.isFinite(page) ? page : 0 });
142
+ if (out.length >= limit)
143
+ break;
144
+ }
145
+ return out;
146
+ }
147
+ function pngSize(file) {
148
+ try {
149
+ const head = readFileSync(file).subarray(0, 33);
150
+ if (head.length < 24)
151
+ return { width: 0, height: 0 };
152
+ return { width: head.readUInt32BE(16), height: head.readUInt32BE(20) };
153
+ }
154
+ catch {
155
+ return { width: 0, height: 0 };
156
+ }
157
+ }
158
+ /** 取若干页的表:-bbox 拿词框 → 按行列聚 → 返回表与同段原文。 */
159
+ export async function extractPdfTables(subprocess, tools, file, options = {}, signal) {
160
+ const first = Math.max(1, Math.floor(options.first ?? 1));
161
+ const last = Math.max(first, Math.floor(options.last ?? first));
162
+ const blank = { ok: false, file, first, last, tables: [], pages: [], notes: [] };
163
+ if (!existsSync(file))
164
+ return { ...blank, error: "PDF 不存在:" + file };
165
+ const bbox = await runCapture(subprocess, {
166
+ argv: [tools.pdftotext, "-bbox", "-f", String(first), "-l", String(last), file, "-"],
167
+ timeoutMs: 90_000,
168
+ maxBytes: 16 * 1024 * 1024,
169
+ ...(signal === undefined ? {} : { signal }),
170
+ });
171
+ if (bbox.exitCode !== 0) {
172
+ return { ...blank, error: "pdftotext -bbox 执行失败:" + (bbox.stderr.trim() || String(bbox.exitCode)) };
173
+ }
174
+ const parsed = parseBboxXml(bbox.stdout);
175
+ const tables = [];
176
+ for (const [index, page] of parsed.entries()) {
177
+ tables.push(...extractTablesFromWords(page, { page: first + index }));
178
+ }
179
+ const text = await extractPdfText(subprocess, tools, file, { first, last }, signal);
180
+ const notes = [];
181
+ if (tables.length === 0)
182
+ notes.push("这一段没有切出表:可能是正文页,或表格由图片构成;改用 render 看图");
183
+ const medium = tables.filter((table) => table.confidence !== "high").length;
184
+ if (medium > 0)
185
+ notes.push("有 " + String(medium) + " 张表是 medium:合并单元格或单元格换行会被展开,逐格核对原文");
186
+ return {
187
+ ok: true,
188
+ error: "",
189
+ file,
190
+ first,
191
+ last,
192
+ tables,
193
+ pages: text.ok ? text.pages : [],
194
+ notes,
195
+ };
196
+ }
197
+ export async function renderPdfPage(subprocess, tools, file, options, signal) {
198
+ const page = Math.max(1, Math.floor(options.page));
199
+ const dpi = Math.min(600, Math.max(72, Math.floor(options.dpi ?? 150)));
200
+ const blank = {
201
+ ok: false,
202
+ file,
203
+ page,
204
+ dpi,
205
+ imageFile: "",
206
+ width: 0,
207
+ height: 0,
208
+ bytes: 0,
209
+ notes: [],
210
+ };
211
+ if (!existsSync(file))
212
+ return { ...blank, error: "PDF 不存在:" + file };
213
+ const dir = options.outDir ?? join(tmpdir(), "dsh-stm32-pdf");
214
+ const stamp = createHash("sha1").update(file).digest("hex").slice(0, 10);
215
+ const prefix = join(dir, stamp + "-p" + String(page) + "-r" + String(dpi));
216
+ const { mkdirSync } = await import("node:fs");
217
+ mkdirSync(dir, { recursive: true });
218
+ const argv = [tools.pdftoppm, "-f", String(page), "-l", String(page), "-r", String(dpi), "-png", "-singlefile"];
219
+ if (options.crop !== undefined) {
220
+ const c = options.crop;
221
+ argv.push("-x", String(Math.max(0, Math.floor(c.x))), "-y", String(Math.max(0, Math.floor(c.y))));
222
+ argv.push("-W", String(Math.max(1, Math.floor(c.width))), "-H", String(Math.max(1, Math.floor(c.height))));
223
+ }
224
+ argv.push(file, prefix);
225
+ const out = await runCapture(subprocess, {
226
+ argv,
227
+ timeoutMs: 120_000,
228
+ ...(signal === undefined ? {} : { signal }),
229
+ });
230
+ const imageFile = prefix + ".png";
231
+ if (out.exitCode !== 0 || !existsSync(imageFile)) {
232
+ return {
233
+ ...blank,
234
+ error: "pdftoppm 渲染失败:" + (out.stderr.trim() || String(out.exitCode)),
235
+ };
236
+ }
237
+ const { width, height } = pngSize(imageFile);
238
+ return {
239
+ ok: true,
240
+ error: "",
241
+ file,
242
+ page,
243
+ dpi,
244
+ imageFile,
245
+ width,
246
+ height,
247
+ bytes: statSync(imageFile).size,
248
+ notes: options.crop === undefined ? [] : ["已按 crop 裁切:坐标按该 dpi 渲染后的像素计"],
249
+ };
250
+ }
251
+ /** 取一页曲线图并数字化:渲染位图 → 认刻度 → 按色相采样每条曲线(S122)。 */
252
+ export async function readPdfCurves(subprocess, tools, file, options) {
253
+ const dpi = options.dpi ?? 200;
254
+ const empty = {
255
+ ok: false,
256
+ error: "",
257
+ file,
258
+ page: options.page,
259
+ dpi,
260
+ imageFile: "",
261
+ calibration: null,
262
+ series: [],
263
+ notes: [],
264
+ };
265
+ const rendered = await renderPdfPage(subprocess, tools, file, { page: options.page, dpi }, options.signal);
266
+ if (!rendered.ok)
267
+ return { ...empty, error: rendered.error };
268
+ const image = decodePng(readFileSync(rendered.imageFile));
269
+ if (!image.ok)
270
+ return { ...empty, error: "渲染图无法解码:" + image.error, imageFile: rendered.imageFile };
271
+ const boxed = await runCapture(subprocess, {
272
+ argv: [tools.pdftotext, "-bbox", "-f", String(options.page), "-l", String(options.page), file, "-"],
273
+ cwd: dirname(file),
274
+ env: {},
275
+ timeoutMs: 60_000,
276
+ maxBytes: 16 * 1024 * 1024,
277
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
278
+ });
279
+ if (boxed.exitCode !== 0) {
280
+ return { ...empty, error: "取不到刻度文字:" + (boxed.stderr || boxed.spawnError || "pdftotext 失败"), imageFile: rendered.imageFile };
281
+ }
282
+ const pages = parseBboxXml(boxed.stdout);
283
+ const words = pages[0]?.words ?? [];
284
+ const scale = dpi / 72;
285
+ // 先把彩色像素的外接框量出来:同页有两张图时,刻度只认这一块附近的(S124)。
286
+ const bounds = chromaBounds(image.image, Math.round(8 * scale));
287
+ const calibrated = calibrateFromWords(words, bounds === null ? { scale } : { scale, bounds });
288
+ if (!calibrated.ok) {
289
+ return { ...empty, error: calibrated.error, imageFile: rendered.imageFile };
290
+ }
291
+ const digitized = digitizeCurves(image.image, calibrated.calibration, options.maxPoints === undefined ? {} : { maxPoints: options.maxPoints });
292
+ const labels = legendLabels(words, image.image, bounds, { scale });
293
+ for (const item of digitized.series) {
294
+ const index = ["red", "orange", "yellow", "green", "cyan", "blue", "violet", "magenta"].indexOf(item.hue);
295
+ const label = labels.get(index);
296
+ if (label !== undefined)
297
+ item.label = label;
298
+ }
299
+ if (labels.size === 0)
300
+ digitized.notes.push("图例文字没认出来(可能是字形轮廓),序列按色相命名");
301
+ return {
302
+ ok: digitized.series.length > 0,
303
+ error: digitized.series.length > 0 ? "" : "没有采样到曲线像素",
304
+ file,
305
+ page: options.page,
306
+ dpi,
307
+ imageFile: rendered.imageFile,
308
+ calibration: calibrated.calibration,
309
+ series: digitized.series,
310
+ notes: [...calibrated.calibration.notes, ...digitized.notes],
311
+ };
312
+ }
313
+ /**
314
+ * 原理图 PDF 的元件与标签清单(S125)。
315
+ *
316
+ * 只做清单:PDF 里没有「谁连谁」,网表从 KiCad 工程读。
317
+ */
318
+ export async function readPdfSchematic(subprocess, tools, file, options = {}, signal) {
319
+ const first = Math.max(1, Math.floor(options.first ?? 1));
320
+ const last = Math.max(first, Math.floor(options.last ?? first));
321
+ const blank = { ok: false, error: "", file, pages: 0, components: [], labels: [], words: 0, notes: [] };
322
+ if (!existsSync(file))
323
+ return { ...blank, error: "PDF 不存在:" + file };
324
+ const run = await runCapture(subprocess, {
325
+ argv: [tools.pdftotext, "-bbox", "-f", String(first), "-l", String(last), file, "-"],
326
+ timeoutMs: 120_000,
327
+ maxBytes: 16 * 1024 * 1024,
328
+ ...(signal === undefined ? {} : { signal }),
329
+ });
330
+ if (run.exitCode !== 0) {
331
+ return { ...blank, error: "取不到文字:" + (run.stderr || run.spawnError || "pdftotext 失败") };
332
+ }
333
+ const parsed = parseBboxXml(run.stdout);
334
+ const report = readPdfSchematicWords(parsed.map((page, index) => ({ page: first + index, words: page.words })));
335
+ return { ...report, file, pages: parsed.length };
336
+ }
@@ -0,0 +1,93 @@
1
+ const NUMERIC_REF = /^(?:R|C|L|D|Q|U|J|SW|Y|X|FB|TP|F|K)\d{1,4}$/u;
2
+ // 型号/阻值:不含下划线(下划线多半是网络名),且必须含数字(NRST 这种纯字母是标签)
3
+ const VALUE = /^(?=[A-Za-z0-9./+-]{4,40}$)(?=[^\s]*\d)[A-Za-z0-9][A-Za-z0-9./+-]*$/u;
4
+ const LABEL = /^[A-Z][A-Z0-9_]{1,24}$/u;
5
+ /** 按基线(y 中心)把词聚成行:PDF 里同一行的 y 只差零点几 pt。 */
6
+ function clusterLines(words, page) {
7
+ const buckets = [];
8
+ for (const word of [...words].sort((a, b) => (a.y0 - b.y0) || (a.x0 - b.x0))) {
9
+ const center = (word.y0 + word.y1) / 2;
10
+ const last = buckets[buckets.length - 1];
11
+ if (last !== undefined && Math.abs(last.y - center) <= 2.4) {
12
+ last.parts.push(word);
13
+ last.y = (last.y * (last.parts.length - 1) + center) / last.parts.length;
14
+ if (word.x0 < last.x0)
15
+ last.x0 = word.x0;
16
+ continue;
17
+ }
18
+ buckets.push({ page, y: center, x0: word.x0, parts: [word] });
19
+ }
20
+ return buckets;
21
+ }
22
+ export function readPdfSchematicWords(pages) {
23
+ const components = [];
24
+ const labels = new Map();
25
+ let words = 0;
26
+ const notes = [];
27
+ for (const page of pages) {
28
+ words += page.words.length;
29
+ for (const line of clusterLines(page.words, page.page)) {
30
+ const sorted = [...line.parts]
31
+ .map((part) => ({ ...part, text: part.text.trim() }))
32
+ .filter((part) => part.text !== "")
33
+ .sort((a, b) => a.x0 - b.x0);
34
+ for (let index = 0; index < sorted.length; index += 1) {
35
+ const current = sorted[index];
36
+ if (current === undefined)
37
+ continue;
38
+ const token = current.text;
39
+ // 只认常见前缀的位号:KiCad 原理图里 BGA 的球号(A1、B1、AC0)也长这样,
40
+ // 用「前缀白名单」把它们排掉,比按字母个数猜靠谱。
41
+ if (NUMERIC_REF.test(token)) {
42
+ // 型号/值必须是紧贴右侧的同一个词(≤14 pt):同一行可能有别的元件,
43
+ // 取「这行后面第一个像型号的词」会把隔壁器件的型号安错了——宁可空着。
44
+ const next = sorted[index + 1];
45
+ const right = next !== undefined && next.x0 - current.x1 <= 14 && VALUE.test(next.text) && !NUMERIC_REF.test(next.text)
46
+ ? next.text
47
+ : "";
48
+ // KiCad 把型号/值放在位号正下方:同一列、下移 2–16 pt 的那个词才是它的值。
49
+ const below = page.words.find((word) => {
50
+ const text = word.text.trim();
51
+ return (Math.abs(word.x0 - current.x0) <= 4 &&
52
+ word.y0 - current.y1 >= 1 &&
53
+ word.y0 - current.y1 <= 16 &&
54
+ VALUE.test(text) &&
55
+ !NUMERIC_REF.test(text));
56
+ });
57
+ const value = right !== "" ? right : (below === undefined ? "" : below.text.trim());
58
+ if (!components.some((item) => item.ref === token)) {
59
+ components.push({ ref: token, value, page: page.page });
60
+ }
61
+ continue;
62
+ }
63
+ if (LABEL.test(token) && token.length >= 3 && !NUMERIC_REF.test(token)) {
64
+ const existing = labels.get(token);
65
+ if (existing === undefined)
66
+ labels.set(token, { name: token, pages: [page.page], count: 1 });
67
+ else {
68
+ existing.count += 1;
69
+ if (!existing.pages.includes(page.page))
70
+ existing.pages.push(page.page);
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ if (words === 0)
77
+ notes.push("这张 PDF 没有可取的文字(描边字形):先用 kicad-cli sch export pdf --default-font Arial 重新导出");
78
+ if (components.length === 0 && words > 0)
79
+ notes.push("没有认出位号:原理图 PDF 的文字可能是字形轮廓,或元件被画成了图片");
80
+ notes.push("PDF 只给清单:连通性要从 KiCad 工程读(stm32_sch_read),线条与引脚号本身不含「谁连谁」");
81
+ components.sort((a, b) => a.ref.localeCompare(b.ref, "en", { numeric: true }));
82
+ const labelList = [...labels.values()].sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
83
+ return {
84
+ ok: components.length > 0 || labelList.length > 0,
85
+ error: components.length === 0 && labelList.length === 0 ? notes[0] ?? "没有认出元件或标签" : "",
86
+ file: "",
87
+ pages: pages.length,
88
+ components,
89
+ labels: labelList,
90
+ words,
91
+ notes,
92
+ };
93
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * 从 pdftotext -bbox 的词矩形里还原二维表(S118)。
3
+ *
4
+ * 为什么不用 -layout 文本按空格切:版面上「同一列的空白」会被跨列长单元格、图形线条
5
+ * 和单元格内换行打断,切出来的常是半张表。改用词框坐标后,行按 y 聚、列按「同行里
6
+ * 词与词之间的大间隙」聚——行与列都是几何量,不受空格排布影响。
7
+ *
8
+ * 局限(写在文档里,不藏在代码里):合并单元格会被展开成「左上格有字、其余为空」;
9
+ * 单元格内换行会变成两行文字落进同一列。两种情况都会写进 warnings。
10
+ */
11
+ const WORD = /<word[^>]*xMin="([0-9.]+)"[^>]*yMin="([0-9.]+)"[^>]*xMax="([0-9.]+)"[^>]*yMax="([0-9.]+)"[^>]*>([^<]*)<\/word>/gu;
12
+ const PAGE = /<page[^>]*width="([0-9.]+)"[^>]*height="([0-9.]+)"[^>]*>/gu;
13
+ function decodeXml(text) {
14
+ return text
15
+ .replace(/&lt;/gu, "<")
16
+ .replace(/&gt;/gu, ">")
17
+ .replace(/&quot;/gu, "\"")
18
+ .replace(/&apos;/gu, "'")
19
+ .replace(/&amp;/gu, "&");
20
+ }
21
+ /** 解析 -bbox 输出:每页的宽度、高度与词框。 */
22
+ export function parseBboxXml(xml) {
23
+ const pageStarts = [...xml.matchAll(PAGE)];
24
+ const pages = [];
25
+ for (const [index, match] of pageStarts.entries()) {
26
+ const from = match.index ?? 0;
27
+ const to = pageStarts[index + 1]?.index ?? xml.length;
28
+ const chunk = xml.slice(from, to);
29
+ const words = [];
30
+ for (const word of chunk.matchAll(WORD)) {
31
+ words.push({
32
+ x0: Number(word[1]),
33
+ y0: Number(word[2]),
34
+ x1: Number(word[3]),
35
+ y1: Number(word[4]),
36
+ text: decodeXml(word[5] ?? ""),
37
+ });
38
+ }
39
+ pages.push({ page: index + 1, width: Number(match[1]), height: Number(match[2]), words });
40
+ }
41
+ return pages;
42
+ }
43
+ /** 按 y 聚行:同一行内的词基线相差不超过 tol。 */
44
+ function clusterRows(words, tol = 3.2) {
45
+ const sorted = [...words].sort((a, b) => a.y0 - b.y0 || a.x0 - b.x0);
46
+ const rows = [];
47
+ for (const word of sorted) {
48
+ const last = rows[rows.length - 1];
49
+ if (last !== undefined && Math.abs(last.y - word.y0) <= tol) {
50
+ last.words.push(word);
51
+ continue;
52
+ }
53
+ rows.push({ y: word.y0, words: [word] });
54
+ }
55
+ for (const row of rows)
56
+ row.words.sort((a, b) => a.x0 - b.x0);
57
+ return rows;
58
+ }
59
+ /**
60
+ * 列分隔点:同一行里词与词之间的间隙 ≥ gapPt 算候选,跨行聚位置;
61
+ * 在足够多行都出现的候选才是列边界。
62
+ *
63
+ * 按间隙而不是按词左边界:一个单元格里的多个词也各自左对齐,
64
+ * 按左边界聚会把一个格子拆成很多列。
65
+ */
66
+ function headerRow(rows) {
67
+ return rows.find((row) => row.words.length >= 3 && row.words.some((word) => /[A-Za-z]{2,}/u.test(word.text)));
68
+ }
69
+ /** 表头那一行的间隙直接给出列边界:表头通常只占一行,词与词之间就是列的分界。 */
70
+ function headerSeparators(row, gapPt = 6) {
71
+ const mids = [];
72
+ for (let index = 1; index < row.words.length; index += 1) {
73
+ const previous = row.words[index - 1];
74
+ const current = row.words[index];
75
+ if (previous === undefined || current === undefined)
76
+ continue;
77
+ if (current.x0 - previous.x1 >= gapPt)
78
+ mids.push((previous.x1 + current.x0) / 2);
79
+ }
80
+ return mids;
81
+ }
82
+ function columnSeparators(rows, gapPt = 8) {
83
+ const perRow = [];
84
+ for (const row of rows) {
85
+ const mids = [];
86
+ for (let index = 1; index < row.words.length; index += 1) {
87
+ const previous = row.words[index - 1];
88
+ const current = row.words[index];
89
+ if (previous === undefined || current === undefined)
90
+ continue;
91
+ if (current.x0 - previous.x1 >= gapPt)
92
+ mids.push((previous.x1 + current.x0) / 2);
93
+ }
94
+ if (mids.length > 0)
95
+ perRow.push(mids);
96
+ }
97
+ const clusters = [];
98
+ for (const mids of perRow) {
99
+ for (const mid of mids) {
100
+ const hit = clusters.find((cluster) => Math.abs(cluster.x - mid) <= 8);
101
+ if (hit === undefined)
102
+ clusters.push({ x: mid, support: 1 });
103
+ else {
104
+ hit.x = (hit.x * hit.support + mid) / (hit.support + 1);
105
+ hit.support += 1;
106
+ }
107
+ }
108
+ }
109
+ const need = Math.max(2, Math.ceil(rows.length * 0.3));
110
+ const body = clusters
111
+ .filter((cluster) => cluster.support >= need)
112
+ .map((cluster) => cluster.x)
113
+ .sort((a, b) => a - b);
114
+ const header = headerRow(rows);
115
+ const base = header === undefined ? [] : headerSeparators(header);
116
+ const merged = [...base];
117
+ for (const x of body) {
118
+ if (!merged.some((existing) => Math.abs(existing - x) <= 30))
119
+ merged.push(x);
120
+ }
121
+ return merged.sort((a, b) => a - b);
122
+ }
123
+ /** 竖排单元格(「Main / flash memory」)会被切成两行:把只有一格有字的行并进下一行同列。 */
124
+ function mergeVertical(cells) {
125
+ const dense = (row) => row !== undefined && row.filter((cell) => cell !== "").length >= 2;
126
+ const out = [];
127
+ for (const [position, row] of cells.entries()) {
128
+ const filled = row.filter((cell) => cell !== "");
129
+ if (filled.length === 1) {
130
+ const index = row.findIndex((cell) => cell !== "");
131
+ const cell = row[index] ?? "";
132
+ // 往上找:上一行够密就并进去(竖排单元格的下半截);否则看下一行(上半截先出现的情形)。
133
+ const previous = out[out.length - 1];
134
+ if (previous !== undefined && dense(previous)) {
135
+ previous[index] = (previous[index] === "" ? cell : previous[index] + " " + cell).trim();
136
+ continue;
137
+ }
138
+ const next = cells[position + 1];
139
+ if (next !== undefined && dense(next)) {
140
+ next[index] = (next[index] === "" ? cell : cell + " " + next[index]).trim();
141
+ continue;
142
+ }
143
+ }
144
+ out.push([...row]);
145
+ }
146
+ return out;
147
+ }
148
+ /** 按分隔点把一行的词分进格子:词中心落在哪一段就归哪一格。 */
149
+ function assign(row, separators) {
150
+ const buckets = separators.map(() => []);
151
+ const last = [];
152
+ buckets.push(last);
153
+ for (const word of row.words) {
154
+ const center = (word.x0 + word.x1) / 2;
155
+ let index = separators.length;
156
+ for (const [position, x] of separators.entries()) {
157
+ if (center < x) {
158
+ index = position;
159
+ break;
160
+ }
161
+ }
162
+ buckets[index]?.push(word.text);
163
+ }
164
+ return buckets.map((parts) => parts.join(" ").trim());
165
+ }
166
+ /**
167
+ * 切表。要求至少 minRows 行、minColumns 列;表块之间由标题行或长正文行分隔。
168
+ * page 只记录来源页。
169
+ */
170
+ export function extractTablesFromWords(page, options = {}) {
171
+ const pageNumber = options.page ?? 0;
172
+ const minRows = Math.max(2, options.minRows ?? 3);
173
+ const minColumns = Math.max(2, options.minColumns ?? 2);
174
+ const rows = clusterRows(page.words);
175
+ const tables = [];
176
+ let block = [];
177
+ let blockTitle = "";
178
+ let pendingTitle = "";
179
+ const flush = () => {
180
+ const usable = block.filter((row) => row.words.length > 0);
181
+ block = [];
182
+ if (usable.length < minRows)
183
+ return;
184
+ const separators = columnSeparators(usable);
185
+ if (separators.length + 1 < minColumns)
186
+ return;
187
+ const cells = mergeVertical(usable.map((row) => assign(row, separators)));
188
+ const filled = cells.filter((row) => row.filter((cell) => cell !== "").length >= 2);
189
+ if (filled.length < minRows)
190
+ return;
191
+ const warnings = [];
192
+ const empties = cells.reduce((count, row) => count + row.filter((cell) => cell === "").length, 0);
193
+ if (empties > 0)
194
+ warnings.push("有 " + String(empties) + " 个空单元格:合并单元格会被展开");
195
+ // 「像数字」指单元格以数字(或 ≤ ≥ ± 之类的量号)开头;RM0490 这种型号不算。
196
+ const looksNumeric = (cell) => /^[≤≥±<>~\s]*[0-9]/u.test(cell.trim());
197
+ const numeric = cells.filter((row) => row.some((cell) => looksNumeric(cell))).length;
198
+ const flat = cells.flat().filter((cell) => cell !== "");
199
+ const averageLength = flat.reduce((sum, cell) => sum + cell.length, 0) / Math.max(1, flat.length);
200
+ const longRatio = flat.filter((cell) => cell.length > 30).length / Math.max(1, flat.length);
201
+ // 正文段落与编号步骤也会被切成「两列」:句子长、几乎没有数字。这类块直接丢掉,不冒充表格。
202
+ if (longRatio >= 0.5)
203
+ return;
204
+ if (numeric / cells.length < 0.3)
205
+ return;
206
+ if (averageLength > 35 && numeric / cells.length < 0.5)
207
+ return;
208
+ if (numeric / cells.length < 0.5)
209
+ warnings.push("多数行不含数字:这块可能是文字段落而不是参数表");
210
+ tables.push({
211
+ title: blockTitle !== ""
212
+ ? blockTitle
213
+ : (pageNumber === 0 ? "" : "第 " + String(pageNumber) + " 页表 ") + String(tables.length + 1),
214
+ page: pageNumber,
215
+ rows: cells.length,
216
+ columns: cells[0] ?? [],
217
+ cells,
218
+ confidence: warnings.length === 0 && separators.length + 1 >= 3 ? "high" : "medium",
219
+ warnings,
220
+ });
221
+ };
222
+ for (const row of rows) {
223
+ const text = row.words.map((word) => word.text).join(" ");
224
+ const looksLikeCaption = /^(Table|Figure)\s+[0-9]+/iu.test(text);
225
+ // 正文段落与表格行的区别在间距:表格的列之间一定有大间隙,句子内部的词间距很小。
226
+ let maxGap = 0;
227
+ for (let index = 1; index < row.words.length; index += 1) {
228
+ const previous = row.words[index - 1];
229
+ const current = row.words[index];
230
+ if (previous === undefined || current === undefined)
231
+ continue;
232
+ maxGap = Math.max(maxGap, current.x0 - previous.x1);
233
+ }
234
+ const looksLikeProse = (row.words.length >= 3 && maxGap < 14) || (row.words.length <= 2 && text.length > 24);
235
+ if (looksLikeCaption || looksLikeProse) {
236
+ flush();
237
+ if (looksLikeCaption)
238
+ pendingTitle = text.replace(/\s+[0-9]{1,4}$/u, "").trim();
239
+ continue;
240
+ }
241
+ if (block.length === 0 && pendingTitle !== "") {
242
+ blockTitle = pendingTitle;
243
+ pendingTitle = "";
244
+ }
245
+ block.push(row);
246
+ }
247
+ flush();
248
+ return tables;
249
+ }