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.
- package/README.md +567 -516
- package/README_EN.md +544 -510
- package/client/client.js +7033 -682
- package/docs/reading-guide.md +921 -859
- package/lib/client.js +7033 -682
- package/lib/commands/register.js +2 -0
- package/lib/data/firmware-packages.js +35 -0
- package/lib/data/firmware-pins.js +7 -0
- package/lib/data/install-guides.js +110 -0
- package/lib/data/ioc-presets.js +118 -0
- package/lib/engine/artifacts.js +123 -0
- package/lib/engine/breakpoint-hits.js +73 -0
- package/lib/engine/build.js +161 -5
- package/lib/engine/channel-tap.js +227 -0
- package/lib/engine/channels.js +48 -0
- package/lib/engine/clocks.js +192 -0
- package/lib/engine/datasheet/auto.js +74 -0
- package/lib/engine/datasheet/digest.js +74 -0
- package/lib/engine/datasheet/lcsc.js +60 -0
- package/lib/engine/datasheet/pinout.js +119 -0
- package/lib/engine/datasheet/price.js +152 -0
- package/lib/engine/datasheet/search.js +147 -0
- package/lib/engine/datasheet/store.js +371 -0
- package/lib/engine/debug-session.js +48 -2
- package/lib/engine/ecad/autobuild.js +156 -0
- package/lib/engine/ecad/bom.js +238 -0
- package/lib/engine/ecad/brief.js +205 -0
- package/lib/engine/ecad/checks.js +239 -0
- package/lib/engine/ecad/design.js +177 -0
- package/lib/engine/ecad/dfm.js +314 -0
- package/lib/engine/ecad/easyeda.js +454 -0
- package/lib/engine/ecad/fabrication.js +104 -0
- package/lib/engine/ecad/gen/footprint.js +159 -0
- package/lib/engine/ecad/gen/symbol.js +103 -0
- package/lib/engine/ecad/import.js +372 -0
- package/lib/engine/ecad/jlcpcb.js +141 -0
- package/lib/engine/ecad/libs.js +316 -0
- package/lib/engine/ecad/models3d.js +89 -0
- package/lib/engine/ecad/netgate.js +286 -0
- package/lib/engine/ecad/normalize.js +182 -0
- package/lib/engine/ecad/package.js +126 -0
- package/lib/engine/ecad/padmerge.js +128 -0
- package/lib/engine/ecad/padprecheck.js +123 -0
- package/lib/engine/ecad/part-import.js +257 -0
- package/lib/engine/ecad/pcb/apply.js +53 -0
- package/lib/engine/ecad/pcb/emc-deep.js +396 -0
- package/lib/engine/ecad/pcb/emc.js +275 -0
- package/lib/engine/ecad/pcb/geometry.js +63 -0
- package/lib/engine/ecad/pcb/gerber.js +499 -0
- package/lib/engine/ecad/pcb/hand-sync.js +242 -0
- package/lib/engine/ecad/pcb/impedance.js +119 -0
- package/lib/engine/ecad/pcb/ipc-open.js +78 -0
- package/lib/engine/ecad/pcb/ipc-script.js +276 -0
- package/lib/engine/ecad/pcb/ipc.js +129 -0
- package/lib/engine/ecad/pcb/krt.js +182 -0
- package/lib/engine/ecad/pcb/links.js +393 -0
- package/lib/engine/ecad/pcb/mech.js +201 -0
- package/lib/engine/ecad/pcb/model-fix.js +178 -0
- package/lib/engine/ecad/pcb/netlist.js +146 -0
- package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
- package/lib/engine/ecad/pcb/placement.js +140 -0
- package/lib/engine/ecad/pcb/power.js +203 -0
- package/lib/engine/ecad/pcb/render3d.js +208 -0
- package/lib/engine/ecad/pcb/route.js +167 -0
- package/lib/engine/ecad/pcb/router.js +469 -0
- package/lib/engine/ecad/pcb/rules.js +122 -0
- package/lib/engine/ecad/pcb/scene.js +513 -0
- package/lib/engine/ecad/pcb/stackup.js +154 -0
- package/lib/engine/ecad/pcb/swap.js +222 -0
- package/lib/engine/ecad/pcb/tracks.js +70 -0
- package/lib/engine/ecad/runtime.js +227 -0
- package/lib/engine/ecad/toolchain.js +146 -0
- package/lib/engine/ecad/tsci.js +362 -0
- package/lib/engine/ecad/zip.js +98 -0
- package/lib/engine/event-bus.js +158 -0
- package/lib/engine/event-log.js +335 -0
- package/lib/engine/fault-hints.js +146 -0
- package/lib/engine/generate-script.js +4 -1
- package/lib/engine/generate.js +145 -5
- package/lib/engine/interrupts.js +247 -0
- package/lib/engine/ioc-diff.js +369 -0
- package/lib/engine/ioc-plan.js +12 -2
- package/lib/engine/ioc-sync.js +58 -0
- package/lib/engine/mcu-info.js +134 -0
- package/lib/engine/msys2-install.js +31 -6
- package/lib/engine/panel-actions.js +103 -0
- package/lib/engine/pdf/curve.js +321 -0
- package/lib/engine/pdf/png.js +83 -0
- package/lib/engine/pdf/reader.js +336 -0
- package/lib/engine/pdf/schematic.js +93 -0
- package/lib/engine/pdf/tables.js +249 -0
- package/lib/engine/pdf/toolchain.js +50 -0
- package/lib/engine/pinout.js +140 -0
- package/lib/engine/probe-info.js +95 -0
- package/lib/engine/probe.js +45 -0
- package/lib/engine/progress.js +99 -0
- package/lib/engine/project-conf.js +254 -0
- package/lib/engine/project-layout.js +198 -0
- package/lib/engine/project-repair.js +205 -0
- package/lib/engine/schematic/checks.js +153 -0
- package/lib/engine/schematic/draw.js +390 -0
- package/lib/engine/schematic/edit.js +229 -0
- package/lib/engine/schematic/kicad-sch.js +225 -0
- package/lib/engine/schematic/model.js +442 -0
- package/lib/engine/schematic/nets.js +219 -0
- package/lib/engine/schematic/pcb.js +144 -0
- package/lib/engine/schematic/review.js +134 -0
- package/lib/engine/schematic/sexpr.js +134 -0
- package/lib/engine/schematic/to-ioc.js +197 -0
- package/lib/engine/schematic/transform.js +25 -0
- package/lib/engine/session-context.js +106 -0
- package/lib/engine/source-slice.js +59 -0
- package/lib/engine/tool-events.js +119 -0
- package/lib/engine/toolchain-gate.js +8 -0
- package/lib/engine/watch-admin.js +101 -0
- package/lib/engine/watch-record.js +39 -0
- package/lib/engine/watch-recorder.js +116 -0
- package/lib/engine/web-api.js +1123 -4
- package/lib/engine/web-routes.js +18 -1
- package/lib/engine/workspace-memo.js +41 -0
- package/lib/index.js +118 -24
- package/lib/skill/stm32-workflow.js +1 -1
- package/lib/tools/build.js +10 -2
- package/lib/tools/code-patch.js +2 -2
- package/lib/tools/datasheet.js +447 -0
- package/lib/tools/debug-session.js +9 -4
- package/lib/tools/debug.js +2 -2
- package/lib/tools/doctor.js +2 -2
- package/lib/tools/ecad.js +903 -0
- package/lib/tools/flash.js +2 -2
- package/lib/tools/gen.js +166 -0
- package/lib/tools/generate.js +7 -5
- package/lib/tools/import-circuit.js +146 -0
- package/lib/tools/ioc-apply.js +11 -2
- package/lib/tools/ioc-inspect.js +2 -2
- package/lib/tools/ioc-plan.js +2 -2
- package/lib/tools/ioc-verify.js +2 -2
- package/lib/tools/layout.js +92 -0
- package/lib/tools/mcu-info.js +163 -0
- package/lib/tools/part-import.js +182 -0
- package/lib/tools/pcb.js +2316 -0
- package/lib/tools/pdf.js +423 -0
- package/lib/tools/project-create.js +28 -0
- package/lib/tools/project-dir.js +25 -1
- package/lib/tools/regs.js +2 -2
- package/lib/tools/route-plan.js +2 -2
- package/lib/tools/rtt.js +10 -2
- package/lib/tools/sch-draw.js +433 -0
- package/lib/tools/sch-edit.js +145 -0
- package/lib/tools/schematic.js +817 -0
- package/lib/tools/serial.js +22 -0
- package/lib/tools/watch.js +24 -2
- package/package.json +1 -1
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 时钟树:从 .ioc 的 `RCC.*` 键读出各路时钟频率与分频,供调试台的时钟页显示。
|
|
3
|
+
*
|
|
4
|
+
* 与 `src/data/clock-db.ts` 的分工:那个模块按芯片算「目标频率该怎么配 PLL」,
|
|
5
|
+
* 是写 .ioc 之前的规划;这里只读已经写进 .ioc 的结果,不推导、不修改。
|
|
6
|
+
* 频率一律取 CubeMX 自己写下的 `*Freq_Value` 键——插件复算容易与 CubeMX 的取整口径不一致。
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { BUS_LIMITS } from "../data/clock-db.js";
|
|
10
|
+
import { parseIocEntries } from "./ioc.js";
|
|
11
|
+
import { findIocPath } from "./pinout.js";
|
|
12
|
+
const NODE_SPECS = [
|
|
13
|
+
{ label: "SYSCLK", key: "RCC.SYSCLKFreq_VALUE" },
|
|
14
|
+
{ label: "HCLK / AHB", key: "RCC.AHBFreq_Value" },
|
|
15
|
+
{ label: "PCLK1 / APB1", key: "RCC.APB1Freq_Value", dividerKey: "RCC.APB1CLKDivider" },
|
|
16
|
+
{ label: "PCLK2 / APB2", key: "RCC.APB2Freq_Value", dividerKey: "RCC.APB2CLKDivider" },
|
|
17
|
+
{ label: "TIM (APB1)", key: "RCC.APB1TimFreq_Value" },
|
|
18
|
+
{ label: "TIM (APB2)", key: "RCC.APB2TimFreq_Value" },
|
|
19
|
+
{ label: "Cortex 内核", key: "RCC.FCLKCortexFreq_Value" },
|
|
20
|
+
{ label: "ADC", key: "RCC.ADCFreqValue" },
|
|
21
|
+
{ label: "USB", key: "RCC.USBFreq_Value" },
|
|
22
|
+
{ label: "SysTick", key: "RCC.TimSysFreq_Value" },
|
|
23
|
+
{ label: "MCO", key: "RCC.MCOFreq_Value" },
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* 型号 → 总线上限表的键(S66),例如 STM32F103C8T6 → STM32F1、STM32G431CBT6 → STM32G4。
|
|
27
|
+
* 表里没有的族返回空串;此时不做上限判断,而不是猜一个值。
|
|
28
|
+
*/
|
|
29
|
+
export function familyOfCpn(cpn) {
|
|
30
|
+
const match = /^STM32([A-Z])(\d)/u.exec(cpn.trim().toUpperCase());
|
|
31
|
+
if (match === null || match[1] === undefined || match[2] === undefined)
|
|
32
|
+
return "";
|
|
33
|
+
const family = "STM32" + match[1] + match[2];
|
|
34
|
+
return BUS_LIMITS[family] === undefined ? "" : family;
|
|
35
|
+
}
|
|
36
|
+
/** 节点 → 该族总线上限;只有真正受手册约束的三路给出上限。 */
|
|
37
|
+
export function limitForNode(label, limits) {
|
|
38
|
+
if (limits === null)
|
|
39
|
+
return null;
|
|
40
|
+
if (label === "PCLK1 / APB1")
|
|
41
|
+
return limits.apb1Hz;
|
|
42
|
+
if (label === "PCLK2 / APB2")
|
|
43
|
+
return limits.apb2Hz;
|
|
44
|
+
if (label === "ADC")
|
|
45
|
+
return limits.adcHz;
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
/** 各总线允许的分频档;F1 的 APB 分频与 ADC 预分频不是同一组。 */
|
|
49
|
+
const APB_DIVISORS = [2, 4, 8, 16];
|
|
50
|
+
const ADC_DIVISORS = [2, 4, 6, 8];
|
|
51
|
+
/**
|
|
52
|
+
* 超限修法(S71):算出「最小够用的分频档」,让人不必自己除。
|
|
53
|
+
*
|
|
54
|
+
* 只给分频建议,不写 .ioc——改配置仍走 stm32_ioc_plan,那里会重算全部派生键。
|
|
55
|
+
*/
|
|
56
|
+
export function suggestFix(label, hz, limitHz, baseHz = null) {
|
|
57
|
+
if (hz === null || limitHz === null || hz <= limitHz)
|
|
58
|
+
return "";
|
|
59
|
+
const isAdc = label === "ADC";
|
|
60
|
+
const isApb = label === "PCLK1 / APB1" || label === "PCLK2 / APB2";
|
|
61
|
+
if (!isAdc && !isApb)
|
|
62
|
+
return "";
|
|
63
|
+
const divisors = isAdc ? ADC_DIVISORS : APB_DIVISORS;
|
|
64
|
+
// 分频器挂在父时钟上:ADC 预分频除 PCLK2、APB 分频除 HCLK。
|
|
65
|
+
// 直接拿「当前频率 ÷ 分频」会把 36/4=9 这种不存在的档位说给人听。
|
|
66
|
+
const source = baseHz !== null && baseHz > 0 ? baseHz : hz;
|
|
67
|
+
const knob = isAdc ? "ADC 预分频" : label === "PCLK1 / APB1" ? "APB1 分频" : "APB2 分频";
|
|
68
|
+
for (const divisor of divisors) {
|
|
69
|
+
const next = source / divisor;
|
|
70
|
+
if (next <= limitHz) {
|
|
71
|
+
const mhz = (next / 1_000_000).toFixed(1).replace(/\.0$/u, "");
|
|
72
|
+
return "把 " + knob + "改成 ÷" + String(divisor) + "(" + mhz + " MHz)";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return "现有分频档都不够,需要降低源频率";
|
|
76
|
+
}
|
|
77
|
+
/** `.ioc` 的频率值是十进制整数;带小数的写法一律视为没有。 */
|
|
78
|
+
export function parseHz(raw) {
|
|
79
|
+
if (raw === undefined)
|
|
80
|
+
return null;
|
|
81
|
+
const text = raw.trim();
|
|
82
|
+
if (!/^\d+$/u.test(text))
|
|
83
|
+
return null;
|
|
84
|
+
const value = Number(text);
|
|
85
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
86
|
+
}
|
|
87
|
+
/** `RCC_HCLK_DIV2` → `÷2`;`RCC_SYSCLK_DIV1` → `÷1`。认不出就原样返回。 */
|
|
88
|
+
export function dividerLabel(raw) {
|
|
89
|
+
const match = /_DIV(\d+)$/u.exec(raw.trim());
|
|
90
|
+
return match === null || match[1] === undefined ? raw : "÷" + match[1];
|
|
91
|
+
}
|
|
92
|
+
const SYSCLK_SOURCES = {
|
|
93
|
+
RCC_SYSCLKSOURCE_HSI: "HSI",
|
|
94
|
+
RCC_SYSCLKSOURCE_HSE: "HSE",
|
|
95
|
+
RCC_SYSCLKSOURCE_PLLCLK: "PLL",
|
|
96
|
+
RCC_SYSCLKSOURCE_PLLRCLK: "PLLR",
|
|
97
|
+
RCC_SYSCLKSOURCE_MSI: "MSI",
|
|
98
|
+
RCC_SYSCLKSOURCE_HSI48: "HSI48",
|
|
99
|
+
};
|
|
100
|
+
const PLL_SOURCES = {
|
|
101
|
+
RCC_PLLSOURCE_HSI: "HSI",
|
|
102
|
+
RCC_PLLSOURCE_HSE: "HSE",
|
|
103
|
+
RCC_PLLSOURCE_HSI_DIV2: "HSI/2",
|
|
104
|
+
RCC_PLLSOURCE_MSI: "MSI",
|
|
105
|
+
};
|
|
106
|
+
/** `RCC_PLL_MUL9` → `×9`。 */
|
|
107
|
+
export function mulLabel(raw) {
|
|
108
|
+
const match = /_MUL(\d+)$/u.exec(raw.trim());
|
|
109
|
+
return match === null || match[1] === undefined ? raw : "×" + match[1];
|
|
110
|
+
}
|
|
111
|
+
export function readClockTree(projectDir) {
|
|
112
|
+
const dir = projectDir.trim();
|
|
113
|
+
if (dir === "")
|
|
114
|
+
return { ok: false, error: "projectDir 不能为空" };
|
|
115
|
+
const iocPath = findIocPath(dir);
|
|
116
|
+
if (iocPath === "")
|
|
117
|
+
return { ok: false, error: "工程目录里没有可读的 .ioc:" + dir };
|
|
118
|
+
let entries;
|
|
119
|
+
try {
|
|
120
|
+
entries = parseIocEntries(readFileSync(iocPath, "utf8"));
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
124
|
+
return { ok: false, error: "读取 .ioc 失败:" + message };
|
|
125
|
+
}
|
|
126
|
+
const used = new Set();
|
|
127
|
+
const cpn = entries.get("Mcu.CPN") ?? "";
|
|
128
|
+
const hclkHz = parseHz(entries.get("RCC.AHBFreq_Value"));
|
|
129
|
+
// .ioc 里没有 ADC 外设时,ADCFreqValue 只是 CubeMX 顺手算出的派生键,不是真在用的时钟。
|
|
130
|
+
const adcUsed = [...entries.values()].some((value) => /^ADC\d/u.test(value.trim()));
|
|
131
|
+
const apb2Hz = parseHz(entries.get("RCC.APB2Freq_Value"));
|
|
132
|
+
const family = familyOfCpn(cpn);
|
|
133
|
+
const limits = family === "" ? null : (BUS_LIMITS[family] ?? null);
|
|
134
|
+
const nodes = NODE_SPECS.map((spec) => {
|
|
135
|
+
used.add(spec.key);
|
|
136
|
+
if (spec.dividerKey !== undefined)
|
|
137
|
+
used.add(spec.dividerKey);
|
|
138
|
+
const divider = spec.dividerKey === undefined ? "" : dividerLabel(entries.get(spec.dividerKey) ?? "");
|
|
139
|
+
const hz = parseHz(entries.get(spec.key));
|
|
140
|
+
const limitHz = limitForNode(spec.label, limits);
|
|
141
|
+
const overLimit = hz !== null && limitHz !== null && hz > limitHz;
|
|
142
|
+
const baseHz = spec.label === "ADC" ? apb2Hz : spec.label.startsWith("PCLK") ? hclkHz : null;
|
|
143
|
+
return {
|
|
144
|
+
label: spec.label,
|
|
145
|
+
hz,
|
|
146
|
+
key: spec.key,
|
|
147
|
+
divider,
|
|
148
|
+
limitHz,
|
|
149
|
+
overLimit,
|
|
150
|
+
suggest: (() => {
|
|
151
|
+
if (!overLimit)
|
|
152
|
+
return "";
|
|
153
|
+
const fix = suggestFix(spec.label, hz, limitHz, baseHz);
|
|
154
|
+
if (fix === "")
|
|
155
|
+
return "";
|
|
156
|
+
return spec.label === "ADC" && !adcUsed ? "工程没有启用 ADC,这条不影响运行;启用时" + fix : fix;
|
|
157
|
+
})(),
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
const others = [];
|
|
161
|
+
for (const [key, value] of entries) {
|
|
162
|
+
if (!key.startsWith("RCC.") || !/Freq/iu.test(key) || used.has(key))
|
|
163
|
+
continue;
|
|
164
|
+
const hz = parseHz(value);
|
|
165
|
+
if (hz === null)
|
|
166
|
+
continue;
|
|
167
|
+
others.push({ label: key.slice("RCC.".length), hz, key, divider: "", limitHz: null, overLimit: false, suggest: "" });
|
|
168
|
+
}
|
|
169
|
+
others.sort((left, right) => left.key.localeCompare(right.key, "en"));
|
|
170
|
+
const source = entries.get("RCC.SYSCLKSource") ?? "";
|
|
171
|
+
const pllSource = entries.get("RCC.PLLSourceVirtual") ?? entries.get("RCC.PLLSource") ?? "";
|
|
172
|
+
const pllMul = entries.get("RCC.PLLMUL") ?? entries.get("RCC.PLLMultiplier") ?? "";
|
|
173
|
+
return {
|
|
174
|
+
ok: true,
|
|
175
|
+
report: {
|
|
176
|
+
projectDir: dir,
|
|
177
|
+
iocPath,
|
|
178
|
+
cpn,
|
|
179
|
+
sysclkSource: source,
|
|
180
|
+
sysclkSourceLabel: SYSCLK_SOURCES[source] ?? source,
|
|
181
|
+
pll: {
|
|
182
|
+
source: pllSource,
|
|
183
|
+
sourceLabel: PLL_SOURCES[pllSource] ?? pllSource,
|
|
184
|
+
mul: pllMul,
|
|
185
|
+
mulLabel: mulLabel(pllMul),
|
|
186
|
+
},
|
|
187
|
+
nodes,
|
|
188
|
+
others,
|
|
189
|
+
limits: limits === null ? null : { family, apb1Hz: limits.apb1Hz, apb2Hz: limits.apb2Hz, adcHz: limits.adcHz },
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工程级的数据手册补齐(S120)。
|
|
3
|
+
*
|
|
4
|
+
* 判据只有一个:circuit 源码里出现过 `footprint="jlcpcb:C…"`,这颗器件就该有手册。
|
|
5
|
+
* 构建成功后自动补齐;面板与工具也能显式触发同一段逻辑,避免两条路径各写一份。
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { resolveProjectLayout } from "../project-layout.js";
|
|
10
|
+
import { datasheetCacheDir, ensureDatasheet, isLcscCode, readIndex } from "./store.js";
|
|
11
|
+
/** 本工程里出现的全部立创编号(去重、排序):扫 circuit 源码里的 jlcpcb:C… 与 circuit.json 的供应商编号。 */
|
|
12
|
+
export function projectJlcpcbCodes(projectDir) {
|
|
13
|
+
const layout = resolveProjectLayout(projectDir);
|
|
14
|
+
const roots = [join(layout.projectDir, "hardware", "circuit"), join(layout.projectDir, "circuit")];
|
|
15
|
+
const found = new Set();
|
|
16
|
+
const codeOf = /jlcpcb:(C\d+)/gu;
|
|
17
|
+
for (const root of roots) {
|
|
18
|
+
if (!existsSync(root))
|
|
19
|
+
continue;
|
|
20
|
+
for (const name of readdirSync(root)) {
|
|
21
|
+
if (!name.endsWith(".tsx"))
|
|
22
|
+
continue;
|
|
23
|
+
const text = readFileSync(join(root, name), "utf8");
|
|
24
|
+
let match;
|
|
25
|
+
const re = new RegExp(codeOf.source, "gu");
|
|
26
|
+
while ((match = re.exec(text)) !== null)
|
|
27
|
+
found.add(match[1] ?? "");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return [...found].filter((code) => isLcscCode(code)).sort();
|
|
31
|
+
}
|
|
32
|
+
/** 只看本地:哪些编号已有可用手册、哪些还缺(不联网)。 */
|
|
33
|
+
export function datasheetStatus(projectDir, cacheDir = datasheetCacheDir()) {
|
|
34
|
+
const codes = projectJlcpcbCodes(projectDir);
|
|
35
|
+
const index = readIndex(cacheDir);
|
|
36
|
+
const cached = [];
|
|
37
|
+
const missing = [];
|
|
38
|
+
for (const code of codes) {
|
|
39
|
+
if (index.entries[code] !== undefined)
|
|
40
|
+
cached.push(code);
|
|
41
|
+
else
|
|
42
|
+
missing.push(code);
|
|
43
|
+
}
|
|
44
|
+
return { codes, cached, missing };
|
|
45
|
+
}
|
|
46
|
+
/** 补齐本工程全部器件:串行(同域限速在 store 里),失败不阻断构建。 */
|
|
47
|
+
export async function ensureProjectDatasheets(projectDir, options = {}) {
|
|
48
|
+
const cacheDir = options.cacheDir ?? datasheetCacheDir();
|
|
49
|
+
const codes = projectJlcpcbCodes(projectDir);
|
|
50
|
+
const fetched = [];
|
|
51
|
+
const failed = [];
|
|
52
|
+
let cached = 0;
|
|
53
|
+
for (const code of codes) {
|
|
54
|
+
if (!isLcscCode(code))
|
|
55
|
+
continue;
|
|
56
|
+
const result = await ensureDatasheet(code, {
|
|
57
|
+
cacheDir,
|
|
58
|
+
offline: options.offline ?? false,
|
|
59
|
+
refresh: options.refresh ?? false,
|
|
60
|
+
signal: options.signal,
|
|
61
|
+
fetchImpl: options.fetchImpl,
|
|
62
|
+
});
|
|
63
|
+
if (result.ok) {
|
|
64
|
+
if (result.cached ?? false)
|
|
65
|
+
cached += 1;
|
|
66
|
+
else
|
|
67
|
+
fetched.push(code);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
failed.push({ code, error: result.error ?? "未知错误" });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { codes, fetched, cached, failed };
|
|
74
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 手册的关键页索引(S121)。
|
|
3
|
+
*
|
|
4
|
+
* 一份手册几十上百页,真正要看的往往就四五处:引脚、绝对最大额定值、电气特性、时序、封装。
|
|
5
|
+
* 这里只做一件事:把「哪一类信息在第几页」记下来,读的时候直接翻过去,而不是每次全文搜索。
|
|
6
|
+
*
|
|
7
|
+
* 索引是索引:只存页号与命中行,正文仍按需从 PDF 现取——避免把上千页文本塞进缓存。
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { extractPdfText } from "../pdf/reader.js";
|
|
12
|
+
const PATTERNS = [
|
|
13
|
+
{ kind: "pinout", pattern: /^(?:\d+(?:\.\d+)*\s+)?(?:pin ?out|pin configuration|pin description|pin assignments?|pin functions?)\b/iu },
|
|
14
|
+
{ kind: "absolute-maximum", pattern: /^(?:\d+(?:\.\d+)*\s+)?absolute maximum (?:ratings?|values?)\b/iu },
|
|
15
|
+
{ kind: "electrical", pattern: /^(?:\d+(?:\.\d+)*\s+)?(?:electrical characteristics|recommended operating conditions|dc characteristics)\b/iu },
|
|
16
|
+
{ kind: "timing", pattern: /^(?:\d+(?:\.\d+)*\s+)?(?:ac (?:electrical )?characteristics|timing (?:characteristics|diagrams?|specifications?)|switching characteristics)\b/iu },
|
|
17
|
+
{ kind: "package", pattern: /^(?:\d+(?:\.\d+)*\s+)?(?:package (?:outline|mechanical)|mechanical data|ordering information)\b/iu },
|
|
18
|
+
];
|
|
19
|
+
export function detectSections(pages) {
|
|
20
|
+
const found = new Map();
|
|
21
|
+
for (const page of pages) {
|
|
22
|
+
for (const line of page.text.split(/\r?\n/u)) {
|
|
23
|
+
const text = line.trim().replace(/\s{2,}/gu, " ");
|
|
24
|
+
if (text.length < 4 || text.length > 90)
|
|
25
|
+
continue;
|
|
26
|
+
for (const rule of PATTERNS) {
|
|
27
|
+
if (found.has(rule.kind))
|
|
28
|
+
continue;
|
|
29
|
+
if (!rule.pattern.test(text))
|
|
30
|
+
continue;
|
|
31
|
+
found.set(rule.kind, { kind: rule.kind, page: page.page, heading: text });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return [...found.values()].sort((left, right) => left.page - right.page);
|
|
36
|
+
}
|
|
37
|
+
/** 读前 N 页(默认 40)做索引;文字层缺失时只记扫描页数,不假装读到了内容。 */
|
|
38
|
+
export async function buildDigest(subprocess, tools, pdfFile, options = {}) {
|
|
39
|
+
if (!existsSync(pdfFile))
|
|
40
|
+
return { ok: false, error: "PDF 不存在:" + pdfFile };
|
|
41
|
+
const scanned = Math.max(1, options.maxPages ?? 40);
|
|
42
|
+
const text = await extractPdfText(subprocess, tools, pdfFile, { first: 1, last: scanned }, options.signal);
|
|
43
|
+
if (!text.ok)
|
|
44
|
+
return { ok: false, error: text.error };
|
|
45
|
+
const readable = text.pages.filter((page) => page.text.length > 20);
|
|
46
|
+
const sections = detectSections(readable);
|
|
47
|
+
return {
|
|
48
|
+
ok: true,
|
|
49
|
+
digest: {
|
|
50
|
+
pages: scanned,
|
|
51
|
+
textLayer: readable.length > 0,
|
|
52
|
+
scanned,
|
|
53
|
+
sections,
|
|
54
|
+
builtAt: new Date().toISOString(),
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export function digestFile(dir) {
|
|
59
|
+
return join(dir, "digest.json");
|
|
60
|
+
}
|
|
61
|
+
export function readDigest(dir) {
|
|
62
|
+
const file = digestFile(dir);
|
|
63
|
+
if (!existsSync(file))
|
|
64
|
+
return null;
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export function writeDigest(dir, digest) {
|
|
73
|
+
writeFileSync(digestFile(dir), JSON.stringify(digest, null, 2) + "\n", "utf8");
|
|
74
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 立创商城的商品页解析(S119)。
|
|
3
|
+
*
|
|
4
|
+
* 只有商品详情页是稳定入口:`/datasheet/<编号>.pdf` 返回的是反爬 HTML,
|
|
5
|
+
* 真正的 PDF 在 `datasheet.lcsc.com/datasheet/pdf/<hash>.pdf`,链接写在详情页里。
|
|
6
|
+
* 因此这里做两件事:抓详情页、从页面里取「MPN / 品牌 / 正版 PDF 直链」。
|
|
7
|
+
*/
|
|
8
|
+
const PDF_URL = /(https:\/\/datasheet\.lcsc\.com\/datasheet\/pdf\/[A-Za-z0-9]+\.pdf)/u;
|
|
9
|
+
const MPN = /"mpn"\s*:\s*"([^"]{1,80})"/u;
|
|
10
|
+
const BRAND = /"brandName"\s*:\s*"([^"]{1,80})"/u;
|
|
11
|
+
const TITLE = /<title>([^<]{1,200})<\/title>/u;
|
|
12
|
+
export function lcscDetailUrl(code) {
|
|
13
|
+
return "https://www.lcsc.com/product-detail/" + encodeURIComponent(code) + ".html";
|
|
14
|
+
}
|
|
15
|
+
function firstMatch(pattern, text) {
|
|
16
|
+
const found = pattern.exec(text);
|
|
17
|
+
return found === null ? "" : (found[1] ?? "").trim();
|
|
18
|
+
}
|
|
19
|
+
/** 从详情页 HTML 里取元信息;取不到 PDF 直链时返回错误,不猜。 */
|
|
20
|
+
export function parseLcscPage(code, html, sourceUrl = lcscDetailUrl(code)) {
|
|
21
|
+
// 页面里的 JSON 会把斜杠转义成 `\/`,先统一回原样,再按同一套正则取字段。
|
|
22
|
+
const text = html.replace(/\\\//gu, "/");
|
|
23
|
+
const pdfUrl = firstMatch(PDF_URL, text);
|
|
24
|
+
if (pdfUrl === "") {
|
|
25
|
+
return { ok: false, error: "详情页里没有数据手册直链:" + sourceUrl + "(可能是页面结构变化,或该商品没有公开手册)" };
|
|
26
|
+
}
|
|
27
|
+
const title = firstMatch(TITLE, text);
|
|
28
|
+
const parts = title.split("|").map((part) => part.trim());
|
|
29
|
+
const mpn = firstMatch(MPN, text) || (parts[0] ?? "");
|
|
30
|
+
const brand = firstMatch(BRAND, text) || (parts.length >= 3 ? (parts[parts.length - 1] ?? "") : "");
|
|
31
|
+
return { ok: true, product: { code, mpn, brand, title, pdfUrl, sourceUrl } };
|
|
32
|
+
}
|
|
33
|
+
/** 抓详情页并解析。`fetchImpl` 可注入,测试不联网。 */
|
|
34
|
+
export async function fetchLcscProduct(code, options = {}) {
|
|
35
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
38
|
+
const signals = [controller.signal];
|
|
39
|
+
if (options.signal !== undefined)
|
|
40
|
+
signals.push(options.signal);
|
|
41
|
+
const url = lcscDetailUrl(code);
|
|
42
|
+
try {
|
|
43
|
+
const response = await fetchImpl(url, {
|
|
44
|
+
signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals),
|
|
45
|
+
redirect: "follow",
|
|
46
|
+
headers: { "user-agent": "dsh-stm32 datasheet fetcher (lcsc product page)" },
|
|
47
|
+
});
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
return { ok: false, error: "商品页返回 HTTP " + String(response.status) + ":" + url };
|
|
50
|
+
}
|
|
51
|
+
return parseLcscPage(code, await response.text(), url);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
55
|
+
return { ok: false, error: "抓商品页失败:" + reason };
|
|
56
|
+
}
|
|
57
|
+
finally {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { extractPdfTables } from "../pdf/reader.js";
|
|
2
|
+
const PIN_NAME = /^P[A-Z]\d{1,2}$/u;
|
|
3
|
+
const PIN_HEADER = /^(?:pin\s*(?:name|number|no\.?)?|symbol|name|引脚|引脚名)$/iu;
|
|
4
|
+
const FUNC_HEADER = /(?:alternate|additional|function|remap|复用|附加)/iu;
|
|
5
|
+
const FUNCTION_TOKEN = /^[A-Z][A-Z0-9]*(?:[_-][A-Z0-9]+)*$/u;
|
|
6
|
+
const AF_PREFIX = /^(?:AF\d+|ALT\d*)[:_\s-]*/iu;
|
|
7
|
+
/** 引脚名可能写成 "PB9-BOOT0" 或 "PA5/ADC_IN5":取第一段做名字,其余进别名。 */
|
|
8
|
+
function nameParts(value) {
|
|
9
|
+
const parts = value
|
|
10
|
+
.split(/[\s/,-]+/u)
|
|
11
|
+
.map((part) => part.replace(/[^\w]/gu, "").toUpperCase())
|
|
12
|
+
.filter((part) => part !== "");
|
|
13
|
+
return { name: parts[0] ?? "", aliases: parts.slice(1) };
|
|
14
|
+
}
|
|
15
|
+
function cleanName(value) {
|
|
16
|
+
return nameParts(value).name;
|
|
17
|
+
}
|
|
18
|
+
function tokensOfCell(cell) {
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const raw of cell.split(/[\s,;/]+/u)) {
|
|
21
|
+
const token = raw.replace(AF_PREFIX, "").replace(/[^\w]/gu, "");
|
|
22
|
+
if (token === "" || token.length < 3 || token.length > 24)
|
|
23
|
+
continue;
|
|
24
|
+
if (!FUNCTION_TOKEN.test(token))
|
|
25
|
+
continue;
|
|
26
|
+
if (!/\d/u.test(token))
|
|
27
|
+
continue;
|
|
28
|
+
if (out.includes(token))
|
|
29
|
+
continue;
|
|
30
|
+
out.push(token);
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
/** 从一张表里认出「引脚列」与「功能列」,读不出就返回 null。 */
|
|
35
|
+
function readTable(table) {
|
|
36
|
+
const header = table.cells[0];
|
|
37
|
+
if (header === undefined)
|
|
38
|
+
return null;
|
|
39
|
+
let pin = -1;
|
|
40
|
+
const funcs = [];
|
|
41
|
+
header.forEach((cell, index) => {
|
|
42
|
+
if (pin < 0 && PIN_HEADER.test(cell.trim()))
|
|
43
|
+
pin = index;
|
|
44
|
+
else if (FUNC_HEADER.test(cell))
|
|
45
|
+
funcs.push(index);
|
|
46
|
+
});
|
|
47
|
+
if (pin < 0 || funcs.length === 0)
|
|
48
|
+
return null;
|
|
49
|
+
return { pin, funcs };
|
|
50
|
+
}
|
|
51
|
+
/** 把若干张表里的引脚行合并成一张「脚 → 功能」表。 */
|
|
52
|
+
export function readPinoutTables(tables) {
|
|
53
|
+
const pins = new Map();
|
|
54
|
+
const used = [];
|
|
55
|
+
for (const table of tables) {
|
|
56
|
+
const columns = readTable(table);
|
|
57
|
+
if (columns === null)
|
|
58
|
+
continue;
|
|
59
|
+
used.push({ page: table.page, title: table.title, columns: table.columns });
|
|
60
|
+
for (const row of table.cells.slice(1)) {
|
|
61
|
+
const rawName = row[columns.pin] ?? "";
|
|
62
|
+
const name = cleanName(rawName);
|
|
63
|
+
if (!PIN_NAME.test(name))
|
|
64
|
+
continue;
|
|
65
|
+
const aliases = nameParts(rawName).aliases.filter((part) => part !== name);
|
|
66
|
+
const functions = [];
|
|
67
|
+
for (const index of columns.funcs) {
|
|
68
|
+
for (const token of tokensOfCell(row[index] ?? "")) {
|
|
69
|
+
if (!functions.includes(token))
|
|
70
|
+
functions.push(token);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const existing = pins.get(name);
|
|
74
|
+
if (existing === undefined) {
|
|
75
|
+
pins.set(name, { name, aliases, functions, page: table.page, table: table.title });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
for (const token of functions)
|
|
79
|
+
if (!existing.functions.includes(token))
|
|
80
|
+
existing.functions.push(token);
|
|
81
|
+
for (const alias of aliases)
|
|
82
|
+
if (!existing.aliases.includes(alias))
|
|
83
|
+
existing.aliases.push(alias);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const notes = [];
|
|
87
|
+
if (pins.size === 0)
|
|
88
|
+
notes.push("没有认出引脚表:需要表头含「Pin / Pin name / Symbol」与「Alternate / Additional / Function」两列");
|
|
89
|
+
const withFunctions = [...pins.values()].filter((pin) => pin.functions.length > 0).length;
|
|
90
|
+
if (pins.size > 0)
|
|
91
|
+
notes.push(pins.size + " 个引脚,其中 " + String(withFunctions) + " 个带复用功能");
|
|
92
|
+
return { ok: pins.size > 0, error: pins.size === 0 ? notes[0] ?? "" : "", pins: [...pins.values()], tables: used, notes };
|
|
93
|
+
}
|
|
94
|
+
/** 引脚名 → 功能清单,交给 sch_to_ioc 在器件库缺信号时兜底。 */
|
|
95
|
+
export function pinFunctionIndex(report) {
|
|
96
|
+
const map = new Map();
|
|
97
|
+
for (const pin of report.pins) {
|
|
98
|
+
if (pin.functions.length === 0)
|
|
99
|
+
continue;
|
|
100
|
+
map.set(pin.name, [...pin.functions]);
|
|
101
|
+
for (const alias of pin.aliases)
|
|
102
|
+
if (!map.has(alias))
|
|
103
|
+
map.set(alias, [...pin.functions]);
|
|
104
|
+
}
|
|
105
|
+
return map;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* 从缓存里的手册读引脚表。
|
|
109
|
+
*
|
|
110
|
+
* 引脚表通常在手册前部(Pinout and pin description),这里只翻前 16 页:
|
|
111
|
+
* 再往后是电气特性与封装图,翻多了慢且容易把别的表当引脚表。
|
|
112
|
+
*/
|
|
113
|
+
export async function readDatasheetPinout(subprocess, tools, file, options = {}, signal) {
|
|
114
|
+
const tables = await extractPdfTables(subprocess, tools, file, { first: options.first ?? 1, last: options.last ?? 16 }, signal);
|
|
115
|
+
if (!tables.ok)
|
|
116
|
+
return { ok: false, error: tables.error, pins: [], tables: [], notes: tables.notes };
|
|
117
|
+
const report = readPinoutTables(tables.tables);
|
|
118
|
+
return { ...report, notes: [...report.notes, ...tables.notes] };
|
|
119
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 立创商城的元件价格(S156)。
|
|
3
|
+
*
|
|
4
|
+
* 价格只出现在商品详情页的结构化数据里(`<script type="application/ld+json">` 的
|
|
5
|
+
* `Product.offers`):`price` / `priceCurrency` / `inventoryLevel`。这里把它单独缓存成
|
|
6
|
+
* `~/.dsh-stm32/prices.json`,与手册缓存分开——手册是几十 MB 的 PDF、价格是几十字节的数字,
|
|
7
|
+
* 生命周期也不一样(价格 7 天过期,手册长期有效)。
|
|
8
|
+
*
|
|
9
|
+
* 不联网也能用:BOM 先读缓存,缺价的行明确标出来,不猜价格。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
import { lcscDetailUrl } from "./lcsc.js";
|
|
15
|
+
const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
16
|
+
const DEFAULT_GAP_MS = 800;
|
|
17
|
+
/** 价格缓存文件:`DSH_STM32_HOME/prices.json` 优先,否则 `~/.dsh-stm32/prices.json`。 */
|
|
18
|
+
export function priceCachePath(env = process.env) {
|
|
19
|
+
const home = (env["DSH_STM32_HOME"] ?? "").trim();
|
|
20
|
+
const base = home !== "" ? home : join(env["USERPROFILE"]?.trim() || homedir(), ".dsh-stm32");
|
|
21
|
+
return join(base, "prices.json");
|
|
22
|
+
}
|
|
23
|
+
export function readPriceCache(path) {
|
|
24
|
+
if (!existsSync(path))
|
|
25
|
+
return { version: 1, quotes: {} };
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
28
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
29
|
+
return { version: 1, quotes: {} };
|
|
30
|
+
const quotes = parsed.quotes;
|
|
31
|
+
if (typeof quotes !== "object" || quotes === null)
|
|
32
|
+
return { version: 1, quotes: {} };
|
|
33
|
+
const out = {};
|
|
34
|
+
for (const [code, value] of Object.entries(quotes)) {
|
|
35
|
+
const quote = value;
|
|
36
|
+
if (typeof quote.priceUsd !== "number" || !Number.isFinite(quote.priceUsd))
|
|
37
|
+
continue;
|
|
38
|
+
out[code] = {
|
|
39
|
+
priceUsd: quote.priceUsd,
|
|
40
|
+
currency: typeof quote.currency === "string" ? quote.currency : "USD",
|
|
41
|
+
stock: typeof quote.stock === "number" ? quote.stock : null,
|
|
42
|
+
mpn: typeof quote.mpn === "string" ? quote.mpn : "",
|
|
43
|
+
brand: typeof quote.brand === "string" ? quote.brand : "",
|
|
44
|
+
fetchedAt: typeof quote.fetchedAt === "string" ? quote.fetchedAt : "",
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return { version: 1, quotes: out };
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { version: 1, quotes: {} };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export function writePriceCache(path, cache) {
|
|
54
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
55
|
+
writeFileSync(path, JSON.stringify(cache, null, 2) + "\n", "utf8");
|
|
56
|
+
}
|
|
57
|
+
/** 从商品页的 JSON-LD 里取报价;拿不到数字就回 null,不按标题猜。 */
|
|
58
|
+
export function parseLcscPrice(html) {
|
|
59
|
+
const blocks = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/gu) ?? [];
|
|
60
|
+
for (const block of blocks) {
|
|
61
|
+
const json = block.replace(/^<script[^>]*>/u, "").replace(/<\/script>$/u, "");
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = JSON.parse(json);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const product = parsed;
|
|
70
|
+
if (product["@type"] !== "Product")
|
|
71
|
+
continue;
|
|
72
|
+
const offers = product.offers;
|
|
73
|
+
const price = typeof offers?.price === "number" ? offers.price : Number(offers?.price);
|
|
74
|
+
if (!Number.isFinite(price) || price <= 0)
|
|
75
|
+
continue;
|
|
76
|
+
const brand = product.brand;
|
|
77
|
+
return {
|
|
78
|
+
priceUsd: price,
|
|
79
|
+
currency: typeof offers?.priceCurrency === "string" ? offers.priceCurrency : "USD",
|
|
80
|
+
stock: typeof offers?.inventoryLevel === "number" ? offers.inventoryLevel : null,
|
|
81
|
+
mpn: typeof product.mpn === "string" ? product.mpn : "",
|
|
82
|
+
brand: typeof brand?.name === "string" ? brand.name : "",
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
function isFresh(quote, nowMs, ttlMs) {
|
|
88
|
+
if (quote === undefined)
|
|
89
|
+
return false;
|
|
90
|
+
const at = Date.parse(quote.fetchedAt);
|
|
91
|
+
if (!Number.isFinite(at))
|
|
92
|
+
return false;
|
|
93
|
+
return nowMs - at < ttlMs;
|
|
94
|
+
}
|
|
95
|
+
async function fetchPrice(code, options) {
|
|
96
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 20_000);
|
|
99
|
+
const signals = [controller.signal];
|
|
100
|
+
if (options.signal !== undefined)
|
|
101
|
+
signals.push(options.signal);
|
|
102
|
+
try {
|
|
103
|
+
const response = await fetchImpl(lcscDetailUrl(code), {
|
|
104
|
+
signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals),
|
|
105
|
+
redirect: "follow",
|
|
106
|
+
headers: { "user-agent": "dsh-stm32 bom price fetcher (lcsc product page)" },
|
|
107
|
+
});
|
|
108
|
+
if (!response.ok)
|
|
109
|
+
return null;
|
|
110
|
+
return parseLcscPrice(await response.text());
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* 取一批编号的报价:缓存里新鲜的直接用,其余按需联网。
|
|
121
|
+
*
|
|
122
|
+
* 只写成功的结果;失败的编号在返回值里列出来,不写负缓存(价格随时会变,下次还该试)。
|
|
123
|
+
*/
|
|
124
|
+
export async function ensurePrices(codes, options = {}) {
|
|
125
|
+
const path = priceCachePath(options.env);
|
|
126
|
+
const cache = readPriceCache(path);
|
|
127
|
+
const nowMs = (options.now ?? Date.now)();
|
|
128
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
129
|
+
const gapMs = options.gapMs ?? DEFAULT_GAP_MS;
|
|
130
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
131
|
+
const fetched = [];
|
|
132
|
+
const failed = [];
|
|
133
|
+
const unique = [...new Set(codes.filter((code) => code !== ""))];
|
|
134
|
+
let waited = false;
|
|
135
|
+
for (const code of unique) {
|
|
136
|
+
if (isFresh(cache.quotes[code], nowMs, ttlMs))
|
|
137
|
+
continue;
|
|
138
|
+
if (waited)
|
|
139
|
+
await sleep(gapMs);
|
|
140
|
+
waited = true;
|
|
141
|
+
const quote = await fetchPrice(code, options);
|
|
142
|
+
if (quote === null) {
|
|
143
|
+
failed.push(code);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
cache.quotes[code] = { ...quote, fetchedAt: new Date(nowMs).toISOString() };
|
|
147
|
+
fetched.push(code);
|
|
148
|
+
}
|
|
149
|
+
if (fetched.length > 0)
|
|
150
|
+
writePriceCache(path, cache);
|
|
151
|
+
return { quotes: cache.quotes, fetched, failed };
|
|
152
|
+
}
|