dsh-stm32 0.1.1 → 0.1.2

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 (42) hide show
  1. package/README.md +52 -23
  2. package/README_EN.md +50 -21
  3. package/docs/development-notes.md +466 -4
  4. package/docs/reading-guide.md +738 -0
  5. package/lib/commands/register.js +49 -0
  6. package/lib/data/chips.js +134 -4
  7. package/lib/data/clock-f1.js +158 -0
  8. package/lib/data/cmsis-sources.js +211 -42
  9. package/lib/data/f1-ram.generated.js +34 -0
  10. package/lib/data/stm32f1.js +186 -0
  11. package/lib/engine/build.js +115 -16
  12. package/lib/engine/cache.js +56 -0
  13. package/lib/engine/clock-plan.js +608 -0
  14. package/lib/engine/cmake-sources.js +428 -0
  15. package/lib/engine/debug.js +75 -10
  16. package/lib/engine/doctor.js +395 -4
  17. package/lib/engine/fetch.js +174 -30
  18. package/lib/engine/flash.js +95 -6
  19. package/lib/engine/generate.js +11 -0
  20. package/lib/engine/hal-chip.js +230 -0
  21. package/lib/engine/ioc-plan.js +28 -2
  22. package/lib/engine/msys2-install.js +332 -61
  23. package/lib/engine/project-export.js +129 -0
  24. package/lib/engine/register-clock.js +132 -0
  25. package/lib/engine/register-linker.js +129 -0
  26. package/lib/engine/register-template.js +88 -17
  27. package/lib/engine/scaffold.js +104 -28
  28. package/lib/engine/zip.js +142 -0
  29. package/lib/index.js +2 -0
  30. package/lib/skill/stm32-workflow.js +3 -3
  31. package/lib/tools/build.js +12 -0
  32. package/lib/tools/cache.js +39 -8
  33. package/lib/tools/debug.js +7 -0
  34. package/lib/tools/doctor.js +11 -2
  35. package/lib/tools/flash.js +3 -0
  36. package/lib/tools/ioc-plan.js +195 -4
  37. package/lib/tools/project-create.js +26 -1
  38. package/lib/tools/project-export.js +100 -0
  39. package/package.json +5 -3
  40. package/templates/register/CMakeLists.txt +19 -6
  41. package/templates/register/Core/Src/main.c +18 -9
  42. package/templates/scaffold/openocd.cfg +8 -0
@@ -0,0 +1,608 @@
1
+ /**
2
+ * L2:F1 时钟规划 —— 把「我要 60 MHz」变成一整套 RCC 键值 + 逐外设频率表。
3
+ *
4
+ * 为什么不是独立工具:时钟就是 .ioc 里的一段键,单开一个 stm32_clock_plan 会让"改引脚"和
5
+ * "改时钟"变成两次 plan、两次 apply,中间还可能出现 PLL 与 APB 分频不自洽的中间态。
6
+ * 所以 clock 作为 stm32_ioc_plan 的一个入参,和 entries/pins 一起算、一起写、一起回滚。
7
+ *
8
+ * 三条硬规则(踩坑换来的):
9
+ * 1) 只改 RCC.PLLMUL 是不够的:CubeMX 按 RCC.*Freq_Value 生成 SystemClock_Config,
10
+ * 20 个派生键必须成套重算,否则 HAL_RCC_ClockConfig 用旧值算错总线频率。
11
+ * 2) 目标频率可能根本不可达(板上 8 MHz HSE 只能出 8 的整数倍)。这时不猜、不静默:取
12
+ * 绝对值最接近的那一档,并在 note 里明写「不可达,已选 X MHz」。
13
+ * 3) F1 的 USB 只能从 PLLCLK÷1.5 得到 48 MHz,所以只有 PLLCLK=72 MHz 时 USB 可用;
14
+ * 其它频率下 USBFreq_Value 退化成 PLLCLK,报告必须点明"USB 不可用"。
15
+ */
16
+ import { F1_ADC_DIVS, F1_APB_DIVS, F1_BAUD_LIST, F1_CLOCK_LIMITS, F1_PERIPHERAL_CLOCKS, F1_PLL_MULS, F1_PLL_SOURCES, F1_USB_PRESCALER, adcDivFromValue, adcDivValue, apbDivFromValue, apbDivValue, pllMulValue, pllSourceById, } from "../data/clock-f1.js";
17
+ const ZERO_CHAIN = {
18
+ pllSource: "",
19
+ pllSourceLabel: "",
20
+ pllInHz: 0,
21
+ pllMul: 0,
22
+ pllClkHz: 0,
23
+ sysclkHz: 0,
24
+ hclkHz: 0,
25
+ apb1Div: 0,
26
+ apb1TimHz: 0,
27
+ apb1Hz: 0,
28
+ apb2Div: 0,
29
+ apb2Hz: 0,
30
+ apb2TimHz: 0,
31
+ adcDiv: 0,
32
+ adcHz: 0,
33
+ usbHz: 0,
34
+ usbAvailable: false,
35
+ usbPrescaled: false,
36
+ mcoHz: 0,
37
+ };
38
+ const ZERO_REQUESTED = {
39
+ targetHz: 0,
40
+ pllSource: "",
41
+ pllMul: 0,
42
+ apb1Div: 0,
43
+ apb2Div: 0,
44
+ adcDiv: 0,
45
+ };
46
+ /** 没有 .ioc / 参数不成立时给宿主一个形状合法的空计划(宿主不接受 null)。 */
47
+ export function emptyClockPlan(note) {
48
+ return {
49
+ mode: "none",
50
+ ok: false,
51
+ reachable: false,
52
+ deltaHz: 0,
53
+ note,
54
+ requested: { ...ZERO_REQUESTED },
55
+ achieved: { ...ZERO_CHAIN },
56
+ alternatives: [],
57
+ peripherals: [],
58
+ bauds: [],
59
+ entries: [],
60
+ unset: [],
61
+ warnings: [],
62
+ errors: [],
63
+ };
64
+ }
65
+ /** Hz → 人读(72 MHz / 10.667 MHz / 250 kHz)。 */
66
+ export function formatHz(hz) {
67
+ if (!Number.isFinite(hz) || hz <= 0)
68
+ return "0 Hz";
69
+ if (hz >= 1_000_000) {
70
+ const mhz = hz / 1_000_000;
71
+ const text = Number.isInteger(mhz) ? String(mhz) : mhz.toFixed(3).replace(/0+$/u, "").replace(/\.$/u, "");
72
+ return text + " MHz";
73
+ }
74
+ if (hz >= 1000)
75
+ return String(Math.round(hz / 1000)) + " kHz";
76
+ return String(hz) + " Hz";
77
+ }
78
+ /** RCC.HSE_VALUE(Hz);没有就按 8 MHz。 */
79
+ function readHseHz(entries) {
80
+ const raw = entries.get("RCC.HSE_VALUE") ?? "";
81
+ const parsed = Number.parseInt(raw.trim(), 10);
82
+ return Number.isFinite(parsed) && parsed >= 1_000_000 && parsed <= 32_000_000 ? parsed : 8_000_000;
83
+ }
84
+ /** .ioc 里配了 HSE 晶振没有:看有没有引脚的 Signal=RCC_OSC_IN。 */
85
+ function detectsHse(entries) {
86
+ for (const [key, value] of entries) {
87
+ if (!key.endsWith(".Signal"))
88
+ continue;
89
+ if (value.trim() === "RCC_OSC_IN" || value.trim() === "RCC_OSC_OUT")
90
+ return true;
91
+ }
92
+ return false;
93
+ }
94
+ /** Mcu.IP* 里启用的外设名集合。 */
95
+ function enabledIps(entries) {
96
+ const names = new Set();
97
+ const count = Number.parseInt(entries.get("Mcu.IPNb") ?? "0", 10);
98
+ if (!Number.isFinite(count) || count <= 0)
99
+ return names;
100
+ for (let index = 0; index < count; index += 1) {
101
+ const name = entries.get("Mcu.IP" + String(index));
102
+ if (name !== undefined)
103
+ names.add(name.trim().toUpperCase());
104
+ }
105
+ return names;
106
+ }
107
+ /** 满足 value/div ≤ limit 的最小分频;没有就 null。 */
108
+ function minimalDiv(divs, value, limit) {
109
+ for (const fact of divs) {
110
+ if (Math.round(value / fact.div) <= limit)
111
+ return fact;
112
+ }
113
+ return null;
114
+ }
115
+ function needDivText(divs, value, limit) {
116
+ const found = minimalDiv(divs, value, limit);
117
+ return found === null ? "无解" : "÷" + String(found.div);
118
+ }
119
+ /** RCC_MCOSource → MCO 输出频率。 */
120
+ function mcoHzFor(mcoSource, values) {
121
+ const source = mcoSource.trim().toUpperCase();
122
+ if (source.includes("PLL"))
123
+ return values.pllClk;
124
+ if (source.includes("HSE"))
125
+ return values.hseHz;
126
+ if (source.includes("HSI"))
127
+ return 8_000_000;
128
+ return values.sysclk;
129
+ }
130
+ function buildChain(input) {
131
+ const errors = [];
132
+ const pllClk = input.pllInHz * input.pllMul;
133
+ const sysclk = pllClk;
134
+ const hclk = sysclk;
135
+ if (sysclk > F1_CLOCK_LIMITS.sysclkHz) {
136
+ errors.push("SYSCLK " + formatHz(sysclk) + " 超过 F1 上限 " + formatHz(F1_CLOCK_LIMITS.sysclkHz) +
137
+ "(" + input.source.label + " ×" + String(input.pllMul) + ")");
138
+ }
139
+ let apb1Div = input.apb1Div;
140
+ if (apb1Div === undefined)
141
+ apb1Div = minimalDiv(F1_APB_DIVS, sysclk, F1_CLOCK_LIMITS.apb1Hz)?.div ?? 16;
142
+ const apb1 = Math.round(sysclk / apb1Div);
143
+ if (apb1 > F1_CLOCK_LIMITS.apb1Hz) {
144
+ errors.push("APB1 " + formatHz(apb1) + " 超过 F1 上限 " + formatHz(F1_CLOCK_LIMITS.apb1Hz) +
145
+ "(APB1CLKDivider 至少要 " + needDivText(F1_APB_DIVS, sysclk, F1_CLOCK_LIMITS.apb1Hz) + ")");
146
+ }
147
+ const apb2Div = input.apb2Div ?? 1;
148
+ const apb2 = Math.round(sysclk / apb2Div);
149
+ if (apb2 > F1_CLOCK_LIMITS.apb2Hz) {
150
+ errors.push("APB2 " + formatHz(apb2) + " 超过 F1 上限 " + formatHz(F1_CLOCK_LIMITS.apb2Hz));
151
+ }
152
+ let adcDiv = input.adcDiv;
153
+ if (adcDiv === undefined)
154
+ adcDiv = minimalDiv(F1_ADC_DIVS, apb2, F1_CLOCK_LIMITS.adcHz)?.div ?? 8;
155
+ const adc = Math.round(apb2 / adcDiv);
156
+ if (adc > F1_CLOCK_LIMITS.adcHz && input.enforceAdc) {
157
+ errors.push("ADC " + formatHz(adc) + " 超过 F1 上限 " + formatHz(F1_CLOCK_LIMITS.adcHz) +
158
+ "(ADCPresc 至少要 " + needDivText(F1_ADC_DIVS, apb2, F1_CLOCK_LIMITS.adcHz) + ")");
159
+ }
160
+ const usbAvailable = pllClk === F1_USB_PRESCALER.requiresPllClkHz;
161
+ const chain = {
162
+ pllSource: input.source.id,
163
+ pllSourceLabel: input.source.label,
164
+ pllInHz: input.pllInHz,
165
+ pllMul: input.pllMul,
166
+ pllClkHz: pllClk,
167
+ sysclkHz: sysclk,
168
+ hclkHz: hclk,
169
+ apb1Div,
170
+ apb1Hz: apb1,
171
+ apb1TimHz: apb1Div === 1 ? apb1 : apb1 * 2,
172
+ apb2Div,
173
+ apb2Hz: apb2,
174
+ apb2TimHz: apb2Div === 1 ? apb2 : apb2 * 2,
175
+ adcDiv,
176
+ adcHz: adc,
177
+ usbHz: usbAvailable ? F1_USB_PRESCALER.hz : pllClk,
178
+ usbAvailable,
179
+ usbPrescaled: false,
180
+ mcoHz: mcoHzFor(input.mcoSource, { hseHz: input.hseHz, pllClk, sysclk }),
181
+ };
182
+ return { chain, errors };
183
+ }
184
+ /** 某个外设最终拿到的时钟(TIM 在 APB≠1 时 ×2 这条规则在这里统一处理)。 */
185
+ export function peripheralClockHz(chain, fact) {
186
+ if (fact.kind === "usb")
187
+ return chain.usbHz;
188
+ if (fact.kind === "adc")
189
+ return chain.adcHz;
190
+ if (fact.bus === "apb1")
191
+ return fact.kind === "tim" ? chain.apb1TimHz : chain.apb1Hz;
192
+ if (fact.bus === "apb2")
193
+ return fact.kind === "tim" ? chain.apb2TimHz : chain.apb2Hz;
194
+ return chain.hclkHz;
195
+ }
196
+ function peripheralReport(chain, enabled, usbWanted) {
197
+ const rows = [];
198
+ for (const fact of F1_PERIPHERAL_CLOCKS) {
199
+ const notes = [];
200
+ if (fact.kind === "adc")
201
+ notes.push("APB2÷" + String(chain.adcDiv));
202
+ if (fact.kind === "tim") {
203
+ if (fact.bus === "apb1" && chain.apb1Div !== 1)
204
+ notes.push("APB1÷" + String(chain.apb1Div) + ",定时器时钟 ×2");
205
+ if (fact.bus === "apb2" && chain.apb2Div !== 1)
206
+ notes.push("APB2÷" + String(chain.apb2Div) + ",定时器时钟 ×2");
207
+ }
208
+ if (fact.kind === "usb") {
209
+ if (chain.usbAvailable) {
210
+ notes.push(chain.usbPrescaled ? "PLLCLK÷1.5=48 MHz(启用 USB)" : "48 MHz 可用(启用 USB 后写 RCC.USBPrescaler=÷1.5)");
211
+ }
212
+ else {
213
+ notes.push("不可用:USB 需要 PLLCLK=72 MHz(÷1.5=48 MHz),当前 PLLCLK " + formatHz(chain.pllClkHz));
214
+ }
215
+ }
216
+ if (fact.kind === "core")
217
+ notes.push("Cortex-M3 内核 / SysTick 跑 HCLK");
218
+ const ip = fact.ip ?? fact.id;
219
+ if (fact.kind !== "core" && !enabled.has(ip.toUpperCase()))
220
+ notes.push("未在 .ioc 启用");
221
+ if (fact.kind === "usb" && usbWanted && !chain.usbAvailable)
222
+ notes.push("已请求 USB 但当前频率下拿不到 48 MHz");
223
+ rows.push({
224
+ id: fact.id,
225
+ label: fact.label,
226
+ bus: fact.bus,
227
+ clockHz: peripheralClockHz(chain, fact),
228
+ note: notes.join(";"),
229
+ });
230
+ }
231
+ return rows;
232
+ }
233
+ function baudTables(chain, bauds) {
234
+ const tables = [];
235
+ for (const fact of F1_PERIPHERAL_CLOCKS) {
236
+ if (fact.kind !== "usart")
237
+ continue;
238
+ const clockHz = fact.bus === "apb2" ? chain.apb2Hz : chain.apb1Hz;
239
+ const rows = [];
240
+ for (const baud of bauds) {
241
+ // F1 用 16 倍过采样:USARTDIV = fCK/(16×baud),BRR = round(USARTDIV×16) = round(fCK/baud)。
242
+ const brr = Math.max(1, Math.round(clockHz / baud));
243
+ const actual = clockHz / brr;
244
+ rows.push({
245
+ baud,
246
+ brr,
247
+ actualBaud: Math.round(actual * 1000) / 1000,
248
+ errorPercent: Math.round(((actual - baud) / baud) * 1_000_000) / 10_000,
249
+ });
250
+ }
251
+ let worst = rows[0];
252
+ for (const row of rows) {
253
+ if (worst === undefined || Math.abs(row.errorPercent) > Math.abs(worst.errorPercent))
254
+ worst = row;
255
+ }
256
+ tables.push({
257
+ id: fact.id,
258
+ clockHz,
259
+ worstBaud: worst?.baud ?? 0,
260
+ worstErrorPercent: worst?.errorPercent ?? 0,
261
+ rows,
262
+ });
263
+ }
264
+ return tables;
265
+ }
266
+ /** RCC.IPParameters 合并:已有名单 ∪ 现存 RCC.* 键 ∪ 本次写入,去掉本次删掉的,按字母序。 */
267
+ function mergeIpParameters(existing, draft, unset) {
268
+ const names = new Set();
269
+ for (const part of (existing ?? "").split(",")) {
270
+ const trimmed = part.trim();
271
+ if (trimmed !== "")
272
+ names.add(trimmed);
273
+ }
274
+ for (const key of draft.keys()) {
275
+ if (key.startsWith("RCC.") && key !== "RCC.IPParameters")
276
+ names.add(key.slice("RCC.".length));
277
+ }
278
+ for (const key of unset) {
279
+ if (key.startsWith("RCC.") && key !== "RCC.IPParameters")
280
+ names.delete(key.slice("RCC.".length));
281
+ }
282
+ return [...names].sort().join(",");
283
+ }
284
+ /**
285
+ * 规划时钟。request 为 undefined 时进入 snapshot 模式:只读 .ioc 现状,产出同样的频率表,
286
+ * entries/unset 为空(一个字节都不改)。
287
+ */
288
+ export function planClock(request, ctx) {
289
+ const entries = ctx.entries;
290
+ const hseHz = request?.hseHz !== undefined && request.hseHz > 0 ? request.hseHz : readHseHz(entries);
291
+ const mcoSource = entries.get("RCC.MCOSource") ?? "";
292
+ const hasHse = detectsHse(entries);
293
+ const enabled = enabledIps(entries);
294
+ const usbWanted = request?.usb === true || enabled.has("USB");
295
+ const bauds = (request?.bauds ?? F1_BAUD_LIST).filter((value) => Number.isFinite(value) && value > 0);
296
+ const detected = pllSourceById(hasHse ? "hse" : "hsi-div2") ?? F1_PLL_SOURCES[0];
297
+ if (request === undefined) {
298
+ // 只读现状:按 .ioc 里记着的源/倍频/分频反推(缺键就用 CubeMX 的缺省值)。
299
+ const storedSource = pllSourceById(entries.get("RCC.PLLSourceVirtual") ?? "");
300
+ const source = storedSource !== null && storedSource.selectable ? storedSource : detected;
301
+ const pllIn = source.id === "hse" ? hseHz : source.defaultHz;
302
+ const mul = Number.parseInt((entries.get("RCC.PLLMUL") ?? "").replace(/^RCC_PLL_MUL/u, ""), 10);
303
+ const pllMul = Number.isFinite(mul) && mul >= 2 && mul <= 16 ? mul : source.id === "hse" ? 9 : 16;
304
+ const apb1Div = apbDivFromValue(entries.get("RCC.APB1CLKDivider") ?? "") ?? undefined;
305
+ const apb2Div = apbDivFromValue(entries.get("RCC.APB2CLKDivider") ?? "") ?? undefined;
306
+ const adcDiv = adcDivFromValue(entries.get("RCC.ADCPresc") ?? "") ?? undefined;
307
+ const built = buildChain({ source, pllInHz: pllIn, pllMul, apb1Div, apb2Div, adcDiv, mcoSource, hseHz, enforceAdc: false });
308
+ const chain = {
309
+ ...built.chain,
310
+ usbPrescaled: built.chain.usbAvailable && entries.get("RCC.USBPrescaler") !== undefined,
311
+ };
312
+ return {
313
+ mode: "snapshot",
314
+ ok: built.errors.length === 0,
315
+ reachable: true,
316
+ deltaHz: 0,
317
+ note: "没请求 clock:这是 .ioc 当前的时钟配置(只读,不写盘)。要改就传 clock:{ targetHz: 72000000 }。",
318
+ requested: {
319
+ targetHz: chain.sysclkHz,
320
+ pllSource: chain.pllSource,
321
+ pllMul: chain.pllMul,
322
+ apb1Div: chain.apb1Div,
323
+ apb2Div: chain.apb2Div,
324
+ adcDiv: chain.adcDiv,
325
+ },
326
+ achieved: chain,
327
+ alternatives: [],
328
+ peripherals: peripheralReport(chain, enabled, usbWanted),
329
+ bauds: baudTables(chain, bauds.length > 0 ? bauds : F1_BAUD_LIST),
330
+ entries: [],
331
+ unset: [],
332
+ warnings: [],
333
+ errors: [...built.errors],
334
+ };
335
+ }
336
+ const wantsTarget = typeof request.targetHz === "number" && Number.isFinite(request.targetHz) && request.targetHz > 0;
337
+ const wantsExplicit = typeof request.pllMul === "number" && request.pllMul >= 2 && request.pllMul <= 16;
338
+ if (!wantsTarget && !wantsExplicit) {
339
+ return {
340
+ ...emptyClockPlan("clock 参数不成立:至少给 targetHz(目标 SYSCLK,Hz,例如 72000000)或 pllMul(×2..×16)"),
341
+ errors: ["clock 参数不成立:至少给 targetHz(目标 SYSCLK,Hz,例如 72000000)或 pllMul(×2..×16)"],
342
+ };
343
+ }
344
+ const errors = [];
345
+ const warnings = [];
346
+ /** 定点模式:直接用给定倍频。 */
347
+ if (wantsExplicit) {
348
+ const source = (request.pllSource === undefined ? detected : pllSourceById(request.pllSource)) ?? detected;
349
+ if (!source.selectable)
350
+ errors.push(source.label + " 不能当 PLL 输入:" + source.note);
351
+ const pllIn = source.id === "hse" ? hseHz : source.defaultHz;
352
+ const built = buildChain({
353
+ source,
354
+ pllInHz: pllIn,
355
+ pllMul: request.pllMul,
356
+ apb1Div: request.apb1Div,
357
+ apb2Div: request.apb2Div,
358
+ adcDiv: request.adcDiv,
359
+ mcoSource,
360
+ hseHz,
361
+ enforceAdc: true,
362
+ });
363
+ errors.push(...built.errors);
364
+ const chain = { ...built.chain };
365
+ if (errors.length > 0) {
366
+ return finish({ mode: "explicit", chain, source, errors, warnings, enabled, bauds, usbWanted, entries, targetHz: request.targetHz ?? chain.sysclkHz, reachable: false, alternatives: [] });
367
+ }
368
+ chain.usbPrescaled = chain.usbAvailable && (usbWanted || entries.get("RCC.USBPrescaler") !== undefined);
369
+ const reachable = request.targetHz === undefined || request.targetHz === chain.sysclkHz;
370
+ const alternatives = reachable ? [] : nearestList([], chain.sysclkHz, request.targetHz, hasHse, hseHz, request);
371
+ return finish({
372
+ mode: "explicit", chain, source, errors, warnings, enabled, bauds, usbWanted, entries,
373
+ targetHz: request.targetHz ?? chain.sysclkHz, reachable, alternatives,
374
+ explicitTargetHz: request.targetHz,
375
+ });
376
+ }
377
+ // 就近搜:只搜 PLL 那条路(SYSCLK 必须来自 PLL,HSE/HSI 直通只在小频率下有意义,不规划)。
378
+ const target = request.targetHz;
379
+ const sources = [];
380
+ const wantedSource = request.pllSource === undefined ? null : pllSourceById(request.pllSource);
381
+ if (wantedSource !== null) {
382
+ if (!wantedSource.selectable)
383
+ return { ...emptyClockPlan(wantedSource.label + " 不能当 PLL 输入:" + wantedSource.note), errors: [wantedSource.note] };
384
+ sources.push(wantedSource);
385
+ }
386
+ else {
387
+ sources.push(detected);
388
+ }
389
+ const candidates = [];
390
+ /** 被上限/显式分频否掉的档:全部不可行时拿最近那档的理由当错误信息,别只说"没有可行组合"。 */
391
+ const rejected = [];
392
+ for (const source of sources) {
393
+ const pllIn = source.id === "hse" ? hseHz : source.defaultHz;
394
+ for (const fact of F1_PLL_MULS) {
395
+ const built = buildChain({
396
+ source,
397
+ pllInHz: pllIn,
398
+ pllMul: fact.mul,
399
+ apb1Div: request.apb1Div,
400
+ apb2Div: request.apb2Div,
401
+ adcDiv: request.adcDiv,
402
+ mcoSource,
403
+ hseHz,
404
+ enforceAdc: true,
405
+ });
406
+ if (built.errors.length > 0) {
407
+ rejected.push({ sysclkHz: built.chain.sysclkHz, errors: built.errors });
408
+ continue;
409
+ }
410
+ if (candidates.some((item) => item.sysclkHz === built.chain.sysclkHz))
411
+ continue;
412
+ candidates.push({ ...built.chain, usbPrescaled: built.chain.usbAvailable && (usbWanted || entries.get("RCC.USBPrescaler") !== undefined) });
413
+ }
414
+ }
415
+ if (candidates.length === 0) {
416
+ rejected.sort((left, right) => Math.abs(left.sysclkHz - target) - Math.abs(right.sysclkHz - target));
417
+ const nearest = rejected[0];
418
+ const reasons = nearest === undefined ? [] : nearest.errors;
419
+ if (reasons.length === 0) {
420
+ const note = "没有可行组合:目标 " + formatHz(target) + " 在 " + sources[0].label + " 下没有任何合法 PLL 档";
421
+ return { ...emptyClockPlan(note), errors: [note] };
422
+ }
423
+ return { ...emptyClockPlan("目标 " + formatHz(target) + " 没有可行组合:" + reasons.join(";")), errors: reasons };
424
+ }
425
+ candidates.sort((left, right) => {
426
+ const gap = Math.abs(left.sysclkHz - target) - Math.abs(right.sysclkHz - target);
427
+ // 距离相同取更高的那档:少失一点总是比多失一点好,也符合"60 → 64"的拍板。
428
+ return gap !== 0 ? gap : right.sysclkHz - left.sysclkHz;
429
+ });
430
+ const chosen = candidates[0];
431
+ const source = pllSourceById(chosen.pllSource) ?? detected;
432
+ const reachable = chosen.sysclkHz === target;
433
+ // 命中了就不再给备选(和 explicit 模式保持一致);不可达才列附近档,方便用户改主意。
434
+ const alternatives = reachable
435
+ ? []
436
+ : candidates
437
+ .filter((item) => item.sysclkHz !== chosen.sysclkHz)
438
+ .slice(0, 6)
439
+ .map((item) => ({
440
+ sysclkHz: item.sysclkHz,
441
+ pllSource: item.pllSource,
442
+ pllSourceLabel: item.pllSourceLabel,
443
+ pllMul: item.pllMul,
444
+ apb1Div: item.apb1Div,
445
+ adcDiv: item.adcDiv,
446
+ usbAvailable: item.usbAvailable,
447
+ deltaHz: item.sysclkHz - target,
448
+ }));
449
+ return finish({
450
+ mode: "nearest", chain: chosen, source, errors, warnings, enabled, bauds, usbWanted, entries,
451
+ targetHz: target, reachable, alternatives,
452
+ });
453
+ }
454
+ /** 收尾:note + 派生键 + IPParameters + 报告。 */
455
+ function finish(input) {
456
+ const chain = input.chain;
457
+ const warnings = [...input.warnings];
458
+ const errors = [...input.errors];
459
+ const parts = [];
460
+ const delta = input.targetHz > 0 ? chain.sysclkHz - input.targetHz : 0;
461
+ if (input.mode === "explicit") {
462
+ parts.push("定点:" + chain.pllSourceLabel + " ×" + String(chain.pllMul) + " → SYSCLK " + formatHz(chain.sysclkHz));
463
+ }
464
+ else if (input.reachable) {
465
+ parts.push("目标 " + formatHz(input.targetHz) + " 可达:" + chain.pllSourceLabel + " ×" + String(chain.pllMul) + " → SYSCLK " + formatHz(chain.sysclkHz));
466
+ }
467
+ else {
468
+ parts.push("目标 " + formatHz(input.targetHz) + " 不可达,已选 " + formatHz(chain.sysclkHz) +
469
+ "(差 " + (delta > 0 ? "+" : "-") + formatHz(Math.abs(delta)) + ")");
470
+ if (input.targetHz > F1_CLOCK_LIMITS.sysclkHz) {
471
+ parts.push("F1 的 SYSCLK 上限是 " + formatHz(F1_CLOCK_LIMITS.sysclkHz));
472
+ }
473
+ else {
474
+ parts.push("F1 的 PLL 只能整数倍频(×2..×16)," + chain.pllSourceLabel + " 拼不出这一档");
475
+ }
476
+ }
477
+ // 换源提示:另一个可用源也许正好凑得出目标,但没说它能替代(HSI 精度差 / 要换晶振)。
478
+ if (!input.reachable && input.targetHz > 0 && input.targetHz <= F1_CLOCK_LIMITS.sysclkHz) {
479
+ for (const other of F1_PLL_SOURCES) {
480
+ if (!other.selectable || other.id === chain.pllSource)
481
+ continue;
482
+ if (other.id === "hse")
483
+ continue; // 板上没晶振就没法凭空变一个出来
484
+ const pllIn = other.defaultHz;
485
+ const mul = input.targetHz / pllIn;
486
+ if (!Number.isInteger(mul) || mul < 2 || mul > 16)
487
+ continue;
488
+ parts.push("(改用 " + other.label + " ×" + String(mul) + " 正好 " + formatHz(input.targetHz) +
489
+ ",但 " + (other.id === "hsi-div2" ? "HSI 精度 ±1%,UART 波特率会跟着漂" : "需要板上换晶振") + ",默认没选它)");
490
+ break;
491
+ }
492
+ }
493
+ if (chain.pllSource === "hsi-div2") {
494
+ warnings.push("用 HSI÷2(内部 RC,±1%)当 PLL 输入:UART 波特率会漂,量产建议接 8 MHz 晶振(HSE)。");
495
+ }
496
+ if (!chain.usbAvailable && input.usbWanted) {
497
+ warnings.push("USB 不可用:F1 的 USB 只能从 PLLCLK÷1.5 得到 48 MHz,需要 PLLCLK=72 MHz;当前 SYSCLK " +
498
+ formatHz(chain.sysclkHz) + "。");
499
+ }
500
+ if (!chain.usbAvailable && input.entries.get("RCC.USBPrescaler") !== undefined) {
501
+ warnings.push("RCC.USBPrescaler 在 SYSCLK " + formatHz(chain.sysclkHz) + " 下无效(拿不到 48 MHz),已删掉这个键。");
502
+ }
503
+ if (chain.adcDiv > 0 && chain.adcDiv * chain.adcHz !== chain.apb2Hz) {
504
+ parts.push("ADC 时钟 " + formatHz(chain.adcHz) + " 不是整数(APB2 " + formatHz(chain.apb2Hz) + " ÷" + String(chain.adcDiv) + "),.ioc 里写成 " + String(chain.adcHz));
505
+ }
506
+ const entries = [];
507
+ const unset = [];
508
+ if (errors.length === 0) {
509
+ const push = (key, value) => {
510
+ entries.push({ key, value });
511
+ };
512
+ push("RCC.SYSCLKSource", "RCC_SYSCLKSOURCE_PLLCLK");
513
+ push("RCC.PLLSourceVirtual", input.source.iocValue);
514
+ push("RCC.PLLMUL", pllMulValue(chain.pllMul));
515
+ push("RCC.SYSCLKFreq_VALUE", String(chain.sysclkHz));
516
+ push("RCC.HCLKFreq_Value", String(chain.hclkHz));
517
+ push("RCC.AHBFreq_Value", String(chain.hclkHz));
518
+ push("RCC.FCLKCortexFreq_Value", String(chain.hclkHz));
519
+ push("RCC.APB1CLKDivider", apbDivValue(chain.apb1Div));
520
+ push("RCC.APB1Freq_Value", String(chain.apb1Hz));
521
+ push("RCC.APB1TimFreq_Value", String(chain.apb1TimHz));
522
+ push("RCC.APB2Freq_Value", String(chain.apb2Hz));
523
+ push("RCC.APB2TimFreq_Value", String(chain.apb2TimHz));
524
+ push("RCC.ADCPresc", adcDivValue(chain.adcDiv));
525
+ push("RCC.ADCFreqValue", String(chain.adcHz));
526
+ push("RCC.PLLCLKFreq_Value", String(chain.pllClkHz));
527
+ push("RCC.PLLMCOFreq_Value", String(Math.round(chain.pllClkHz / 2)));
528
+ push("RCC.VCOOutput2Freq_Value", String(chain.pllInHz));
529
+ push("RCC.MCOFreq_Value", String(chain.mcoHz));
530
+ push("RCC.TimSysFreq_Value", String(chain.apb1TimHz));
531
+ // CubeMX 的写法:没真的用 USB 分频时,USBFreq_Value 记的就是 PLLCLK(不是 48)。
532
+ push("RCC.USBFreq_Value", String(chain.usbPrescaled ? F1_USB_PRESCALER.hz : chain.pllClkHz));
533
+ if (chain.apb2Div !== 1)
534
+ push("RCC.APB2CLKDivider", apbDivValue(chain.apb2Div));
535
+ else if (input.entries.get("RCC.APB2CLKDivider") !== undefined)
536
+ unset.push("RCC.APB2CLKDivider");
537
+ if (chain.usbPrescaled)
538
+ push("RCC.USBPrescaler", F1_USB_PRESCALER.iocValue);
539
+ else if (input.entries.get("RCC.USBPrescaler") !== undefined)
540
+ unset.push("RCC.USBPrescaler");
541
+ const draft = new Map(input.entries);
542
+ for (const entry of entries)
543
+ draft.set(entry.key, entry.value);
544
+ for (const key of unset)
545
+ draft.delete(key);
546
+ entries.push({ key: "RCC.IPParameters", value: mergeIpParameters(input.entries.get("RCC.IPParameters"), draft, unset) });
547
+ }
548
+ return {
549
+ mode: input.mode,
550
+ ok: errors.length === 0,
551
+ reachable: input.reachable,
552
+ deltaHz: delta,
553
+ note: parts.join(";"),
554
+ requested: {
555
+ targetHz: input.targetHz,
556
+ pllSource: chain.pllSource,
557
+ pllMul: chain.pllMul,
558
+ apb1Div: chain.apb1Div,
559
+ apb2Div: chain.apb2Div,
560
+ adcDiv: chain.adcDiv,
561
+ },
562
+ achieved: chain,
563
+ alternatives: input.alternatives,
564
+ peripherals: peripheralReport(chain, input.enabled, input.usbWanted),
565
+ bauds: baudTables(chain, input.bauds.length > 0 ? input.bauds : F1_BAUD_LIST),
566
+ entries,
567
+ unset,
568
+ warnings,
569
+ errors,
570
+ };
571
+ }
572
+ /** 定点模式没命中目标时,顺手给出附近的可选档(方便用户改主意)。 */
573
+ function nearestList(base, chosenHz, targetHz, hasHse, hseHz, request) {
574
+ const sources = [];
575
+ const wantedSource = request.pllSource === undefined ? null : pllSourceById(request.pllSource);
576
+ const detected = pllSourceById(hasHse ? "hse" : "hsi-div2") ?? F1_PLL_SOURCES[0];
577
+ sources.push(wantedSource ?? detected);
578
+ const rows = [...base];
579
+ for (const source of sources) {
580
+ if (!source.selectable)
581
+ continue;
582
+ const pllIn = source.id === "hse" ? hseHz : source.defaultHz;
583
+ for (const fact of F1_PLL_MULS) {
584
+ const sysclk = pllIn * fact.mul;
585
+ if (sysclk > F1_CLOCK_LIMITS.sysclkHz || sysclk === chosenHz)
586
+ continue;
587
+ if (rows.some((row) => row.sysclkHz === sysclk))
588
+ continue;
589
+ const apb1 = minimalDiv(F1_APB_DIVS, sysclk, F1_CLOCK_LIMITS.apb1Hz);
590
+ const apb2 = sysclk;
591
+ const adc = minimalDiv(F1_ADC_DIVS, apb2, F1_CLOCK_LIMITS.adcHz);
592
+ if (apb1 === null || adc === null)
593
+ continue;
594
+ rows.push({
595
+ sysclkHz: sysclk,
596
+ pllSource: source.id,
597
+ pllSourceLabel: source.label,
598
+ pllMul: fact.mul,
599
+ apb1Div: apb1.div,
600
+ adcDiv: adc.div,
601
+ usbAvailable: sysclk === F1_USB_PRESCALER.requiresPllClkHz,
602
+ deltaHz: sysclk - targetHz,
603
+ });
604
+ }
605
+ }
606
+ rows.sort((left, right) => Math.abs(left.deltaHz) - Math.abs(right.deltaHz));
607
+ return rows.slice(0, 6);
608
+ }