dsh-stm32 0.1.2 → 0.1.4

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 (225) hide show
  1. package/README.md +92 -40
  2. package/README_EN.md +85 -36
  3. package/assets/README.md +85 -0
  4. package/assets/VERSION +1 -0
  5. package/assets/device/c0/chips.json +1108 -0
  6. package/assets/device/f0/chips.json +1570 -0
  7. package/assets/device/f1/chips.json +1238 -0
  8. package/assets/device/f1/svd/100.json +943 -0
  9. package/assets/device/f1/svd/101.json +901 -0
  10. package/assets/device/f1/svd/102.json +522 -0
  11. package/assets/device/f1/svd/103.json +1139 -0
  12. package/assets/device/f1/svd/105.json +1117 -0
  13. package/assets/device/f1/svd/107.json +1195 -0
  14. package/assets/device/f2/chips.json +674 -0
  15. package/assets/device/f3/chips.json +1318 -0
  16. package/assets/device/f4/chips.json +2942 -0
  17. package/assets/device/f7/chips.json +1710 -0
  18. package/assets/device/g0/chips.json +2102 -0
  19. package/assets/device/g4/chips.json +2494 -0
  20. package/assets/device/h5/chips.json +898 -0
  21. package/assets/device/h7/chips.json +1948 -0
  22. package/assets/device/l0/chips.json +2494 -0
  23. package/assets/device/l1/chips.json +1234 -0
  24. package/assets/device/l4/chips.json +2130 -0
  25. package/assets/device/l4+/chips.json +856 -0
  26. package/assets/device/l5/chips.json +226 -0
  27. package/assets/device/u0/chips.json +688 -0
  28. package/assets/device/u3/chips.json +310 -0
  29. package/assets/device/u5/chips.json +884 -0
  30. package/assets/device/wba/chips.json +506 -0
  31. package/assets/device/wl/chips.json +184 -0
  32. package/assets/headers/f1/stm32f100xb.h +5972 -0
  33. package/assets/headers/f1/stm32f100xe.h +6587 -0
  34. package/assets/headers/f1/stm32f101x6.h +5315 -0
  35. package/assets/headers/f1/stm32f101xb.h +5446 -0
  36. package/assets/headers/f1/stm32f101xe.h +6503 -0
  37. package/assets/headers/f1/stm32f101xg.h +6713 -0
  38. package/assets/headers/f1/stm32f102x6.h +6448 -0
  39. package/assets/headers/f1/stm32f102xb.h +6570 -0
  40. package/assets/headers/f1/stm32f103x6.h +10109 -0
  41. package/assets/headers/f1/stm32f103xb.h +10240 -0
  42. package/assets/headers/f1/stm32f103xe.h +11767 -0
  43. package/assets/headers/f1/stm32f103xg.h +11951 -0
  44. package/assets/headers/f1/stm32f105xc.h +14340 -0
  45. package/assets/headers/f1/stm32f107xc.h +15253 -0
  46. package/assets/headers/f1/stm32f1xx.h +273 -0
  47. package/assets/headers/f1/system_stm32f1xx.h +96 -0
  48. package/assets/ioc/family/C0.ioc +82 -0
  49. package/assets/ioc/family/F0.ioc +71 -0
  50. package/assets/ioc/family/F2.ioc +91 -0
  51. package/assets/ioc/family/F3.ioc +94 -0
  52. package/assets/ioc/family/F4.ioc +91 -0
  53. package/assets/ioc/family/F7.ioc +102 -0
  54. package/assets/ioc/family/G0.ioc +90 -0
  55. package/assets/ioc/family/G4.ioc +110 -0
  56. package/assets/ioc/family/H5.ioc +116 -0
  57. package/assets/ioc/family/H7.ioc +133 -0
  58. package/assets/ioc/family/L0.ioc +92 -0
  59. package/assets/ioc/family/L1.ioc +87 -0
  60. package/assets/ioc/family/L4+.ioc +92 -0
  61. package/assets/ioc/family/L4.ioc +93 -0
  62. package/assets/ioc/family/L5.ioc +91 -0
  63. package/assets/ioc/family/U0.ioc +103 -0
  64. package/assets/ioc/family/U3.ioc +113 -0
  65. package/assets/ioc/family/U5.ioc +102 -0
  66. package/assets/ioc/family/WBA.ioc +100 -0
  67. package/assets/ioc/family/WL.ioc +93 -0
  68. package/assets/ioc/minimal/STM32F100C8Tx.ioc +113 -0
  69. package/assets/ioc/minimal/STM32F100RCTx.ioc +113 -0
  70. package/assets/ioc/minimal/STM32F101C4Tx.ioc +113 -0
  71. package/assets/ioc/minimal/STM32F101C8Tx.ioc +113 -0
  72. package/assets/ioc/minimal/STM32F101RCTx.ioc +113 -0
  73. package/assets/ioc/minimal/STM32F101RFTx.ioc +113 -0
  74. package/assets/ioc/minimal/STM32F102C4Tx.ioc +113 -0
  75. package/assets/ioc/minimal/STM32F102C8Tx.ioc +113 -0
  76. package/assets/ioc/minimal/STM32F103C4Tx.ioc +113 -0
  77. package/assets/ioc/minimal/STM32F103C8Tx.ioc +113 -0
  78. package/assets/ioc/minimal/STM32F103RCTx.ioc +113 -0
  79. package/assets/ioc/minimal/STM32F103RFTx.ioc +113 -0
  80. package/assets/ioc/minimal/STM32F105RCTx.ioc +113 -0
  81. package/assets/ioc/minimal/STM32F107RCTx.ioc +113 -0
  82. package/assets/ld/f1/STM32F100C8Tx_FLASH.ld +249 -0
  83. package/assets/ld/f1/STM32F100RCTx_FLASH.ld +249 -0
  84. package/assets/ld/f1/STM32F101C4Tx_FLASH.ld +249 -0
  85. package/assets/ld/f1/STM32F101C8Tx_FLASH.ld +249 -0
  86. package/assets/ld/f1/STM32F101RCTx_FLASH.ld +249 -0
  87. package/assets/ld/f1/STM32F101RFTx_FLASH.ld +249 -0
  88. package/assets/ld/f1/STM32F102C4Tx_FLASH.ld +249 -0
  89. package/assets/ld/f1/STM32F102C8Tx_FLASH.ld +249 -0
  90. package/assets/ld/f1/STM32F103C4Tx_FLASH.ld +249 -0
  91. package/assets/ld/f1/STM32F103C8Tx_FLASH.ld +249 -0
  92. package/assets/ld/f1/STM32F103RCTx_FLASH.ld +249 -0
  93. package/assets/ld/f1/STM32F103RFTx_FLASH.ld +249 -0
  94. package/assets/ld/f1/STM32F105RCTx_FLASH.ld +249 -0
  95. package/assets/ld/f1/STM32F107RCTx_FLASH.ld +249 -0
  96. package/assets/manifest.json +1130 -0
  97. package/assets/startup/f1/startup_stm32f100xb.s +407 -0
  98. package/assets/startup/f1/startup_stm32f100xe.s +449 -0
  99. package/assets/startup/f1/startup_stm32f101x6.s +322 -0
  100. package/assets/startup/f1/startup_stm32f101xb.s +338 -0
  101. package/assets/startup/f1/startup_stm32f101xe.s +423 -0
  102. package/assets/startup/f1/startup_stm32f101xg.s +439 -0
  103. package/assets/startup/f1/startup_stm32f102x6.s +330 -0
  104. package/assets/startup/f1/startup_stm32f102xb.s +346 -0
  105. package/assets/startup/f1/startup_stm32f103x6.s +348 -0
  106. package/assets/startup/f1/startup_stm32f103xb.s +364 -0
  107. package/assets/startup/f1/startup_stm32f103xe.s +470 -0
  108. package/assets/startup/f1/startup_stm32f103xg.s +466 -0
  109. package/assets/startup/f1/startup_stm32f105xc.s +463 -0
  110. package/assets/startup/f1/startup_stm32f107xc.s +472 -0
  111. package/assets/templates/family/C0.ioc +82 -0
  112. package/assets/templates/family/F0.ioc +71 -0
  113. package/assets/templates/family/F2.ioc +91 -0
  114. package/assets/templates/family/F3.ioc +94 -0
  115. package/assets/templates/family/F4.ioc +91 -0
  116. package/assets/templates/family/F7.ioc +102 -0
  117. package/assets/templates/family/G0.ioc +90 -0
  118. package/assets/templates/family/G4.ioc +110 -0
  119. package/assets/templates/family/H5.ioc +116 -0
  120. package/assets/templates/family/H7.ioc +133 -0
  121. package/assets/templates/family/L0.ioc +92 -0
  122. package/assets/templates/family/L1.ioc +87 -0
  123. package/assets/templates/family/L4+.ioc +92 -0
  124. package/assets/templates/family/L4.ioc +93 -0
  125. package/assets/templates/family/L5.ioc +91 -0
  126. package/assets/templates/family/U0.ioc +103 -0
  127. package/assets/templates/family/U3.ioc +113 -0
  128. package/assets/templates/family/U5.ioc +102 -0
  129. package/assets/templates/family/WB.ioc +81 -0
  130. package/assets/templates/family/WBA.ioc +100 -0
  131. package/assets/templates/family/WL.ioc +93 -0
  132. package/docs/reading-guide.md +94 -71
  133. package/lib/data/chips.js +38 -51
  134. package/lib/data/clock-db.js +830 -0
  135. package/lib/data/clock-f1.js +12 -45
  136. package/lib/data/cmsis-sources.js +264 -17
  137. package/lib/data/db-presets.js +252 -0
  138. package/lib/data/device-facts.js +274 -0
  139. package/lib/data/family.js +515 -0
  140. package/lib/data/firmware-packages.js +562 -0
  141. package/lib/data/install-guides.js +2 -2
  142. package/lib/data/ioc-presets.js +248 -0
  143. package/lib/data/ioc-schema.js +1058 -0
  144. package/lib/data/rm-topics/stm32c0.json +227 -0
  145. package/lib/data/rm-topics.js +103 -0
  146. package/lib/data/search-roots.js +42 -1
  147. package/lib/data/stm32f1.js +95 -150
  148. package/lib/data/svd.js +643 -0
  149. package/lib/data/toolchain-config.js +0 -14
  150. package/lib/engine/assets.js +659 -0
  151. package/lib/engine/breakpoints.js +297 -0
  152. package/lib/engine/clock-derived.js +101 -0
  153. package/lib/engine/clock-direct.js +313 -0
  154. package/lib/engine/clock-plan.js +96 -52
  155. package/lib/engine/clock-pllmn.js +319 -0
  156. package/lib/engine/cmake-sources.js +67 -13
  157. package/lib/engine/cube-mx-guard.js +44 -0
  158. package/lib/engine/cube-programmer.js +137 -0
  159. package/lib/engine/cubemx-db.js +273 -0
  160. package/lib/engine/debug-session.js +576 -22
  161. package/lib/engine/debug.js +99 -46
  162. package/lib/engine/doctor.js +162 -19
  163. package/lib/engine/facts-acquire.js +416 -0
  164. package/lib/engine/facts.js +134 -0
  165. package/lib/engine/firmware-install.js +176 -5
  166. package/lib/engine/firmware-official.js +451 -0
  167. package/lib/engine/flash.js +317 -76
  168. package/lib/engine/gdb-mi.js +476 -0
  169. package/lib/engine/generate.js +9 -2
  170. package/lib/engine/hal-chip.js +124 -41
  171. package/lib/engine/ioc-plan.js +1247 -63
  172. package/lib/engine/ioc-rules.js +698 -0
  173. package/lib/engine/ioc-verify.js +706 -0
  174. package/lib/engine/ioc.js +43 -4
  175. package/lib/engine/msys2-install.js +4 -4
  176. package/lib/engine/probe-error.js +231 -0
  177. package/lib/engine/probe-session.js +347 -0
  178. package/lib/engine/probe.js +18 -3
  179. package/lib/engine/register-clock.js +41 -0
  180. package/lib/engine/register-gpio.js +115 -0
  181. package/lib/engine/register-linker.js +12 -7
  182. package/lib/engine/register-template.js +130 -45
  183. package/lib/engine/regs.js +43 -8
  184. package/lib/engine/rm-extract.js +144 -0
  185. package/lib/engine/rm-sources.js +360 -0
  186. package/lib/engine/rm-text.js +56 -0
  187. package/lib/engine/rtt.js +758 -0
  188. package/lib/engine/scaffold.js +185 -18
  189. package/lib/engine/toolchain-gate.js +0 -4
  190. package/lib/engine/watch.js +227 -0
  191. package/lib/index.js +12 -2
  192. package/lib/skill/stm32-workflow.js +2 -2
  193. package/lib/tools/assets.js +272 -0
  194. package/lib/tools/cache.js +8 -0
  195. package/lib/tools/debug-session.js +41 -6
  196. package/lib/tools/debug.js +41 -11
  197. package/lib/tools/doctor.js +65 -4
  198. package/lib/tools/firmware-install.js +31 -6
  199. package/lib/tools/flash.js +47 -10
  200. package/lib/tools/generate.js +25 -0
  201. package/lib/tools/ioc-apply.js +2 -0
  202. package/lib/tools/ioc-inspect.js +2 -0
  203. package/lib/tools/ioc-plan.js +59 -2
  204. package/lib/tools/ioc-verify.js +237 -0
  205. package/lib/tools/project-create.js +63 -3
  206. package/lib/tools/regs.js +453 -61
  207. package/lib/tools/route-plan.js +3 -0
  208. package/lib/tools/rtt.js +470 -0
  209. package/lib/tools/watch.js +256 -0
  210. package/package.json +5 -4
  211. package/templates/openocd/stm32c0x.cfg +83 -0
  212. package/templates/openocd/stm32u0x.cfg +64 -0
  213. package/templates/register/CMakeLists.txt +8 -2
  214. package/templates/register/Core/Inc/rtt.h +138 -0
  215. package/templates/register/Core/Src/main.c +42 -25
  216. package/templates/register/Core/Src/rtt.c +373 -0
  217. package/templates/scaffold/RTT.md +90 -0
  218. package/templates/scaffold/STM32F103XX_FLASH.ld +3 -0
  219. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  220. package/templates/scaffold/openocd.cfg +5 -3
  221. package/templates/scaffold/vscode/launch.json +8 -4
  222. package/docs/development-notes.md +0 -2116
  223. package/docs/dsh-stm32-plugin-/350/247/204/346/240/274.md +0 -673
  224. package/docs/logic-audit.md +0 -607
  225. package/lib/data/f1-ram.generated.js +0 -34
@@ -0,0 +1,830 @@
1
+ /**
2
+ * 从 CubeMX db 读时钟事实(PLL 倍频/分频枚举、PLL 源、SYSCLK 上限、PLL 模型)。
3
+ *
4
+ * 为什么要有这一层:`clock-f1.ts` 里的 `F1_PLL_MULS` / `F1_APB_DIVS` / `F1_ADC_DIVS` / `F1_PLL_SOURCES`
5
+ * 全是「某个 db 版本枚举值的手抄快照」。db 里这些恰好都有:
6
+ * - `db/mcu/<Mcu.Name>.xml` 的 `<Frequency>` 就是该型号的 SYSCLK 上限(MHz);
7
+ * - `db/mcu/IP/RCC-*.xml`(Modes)里 `<RefParameter Name="PLLMUL" Type="list">` 的
8
+ * `<PossibleValue Value="RCC_PLL_MUL2" Comment="2"/>` 就是倍频枚举,分频同理。
9
+ * 抄快照的问题与预设表一样:换族/换 db 版本就失真(F1 的 `S_TIM2_CH1_ETR` 已经栽过一次)。
10
+ *
11
+ * 早先以为「APB1/APB2/ADC 的频率上限 db 里没有」,实测是错的:`RCC-*_Modes.xml` 里
12
+ * `<RefParameter Name="APB1Freq_Value" Max="30000000">`、`APB2Freq_Value`、`ADCFreq_Value`、
13
+ * `VCOOutputFreq_Value`、`VCOInputFreq_Value`、`SYSCLKFreq_VALUE` 的 Min/Max 就是
14
+ * CubeMX 自己校验的上限,所以这里按族从 db 读(见 readClockDbFacts)。
15
+ * 但 db 是**按 RCC IP 版本**给值,个别族偏保守(F103 走 RCC-STM32F102,APB2 只给 36/48 MHz,
16
+ * 实际 72 MHz),所以核过手册/真机的族用 BUS_LIMITS / PLL_VCO_LIMITS 的 override。
17
+ * db 里确实没有的:USB 需要的 48 MHz 规则。
18
+ */
19
+ import { existsSync, readFileSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ import { ipModesPath } from "../engine/cubemx-db.js";
22
+ import { F1_BAUD_LIST, F1_PERIPHERAL_CLOCKS } from "./clock-f1.js";
23
+ function readTextOrNull(file) {
24
+ if (file === null || !existsSync(file))
25
+ return null;
26
+ try {
27
+ return readFileSync(file, "utf8");
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** RCC 实例的 Modes 文件路径(IP 的 Version 属性本身就带族名,例如 STM32F102_rcc_v1_0)。 */
34
+ function rccModesPath(db, facts) {
35
+ for (const [instance, ip] of facts.ips) {
36
+ const name = (ip.name ?? instance).toUpperCase();
37
+ if (name !== "RCC")
38
+ continue;
39
+ return ipModesPath(db, facts, instance);
40
+ }
41
+ return null;
42
+ }
43
+ function numberOf(text) {
44
+ const matched = /(-?[0-9]+(?:\.[0-9]+)?)/u.exec(text);
45
+ return matched === null ? null : Number(matched[1]);
46
+ }
47
+ /** 取某个 list 型 RefParameter 的 PossibleValue(属性顺序不固定,按名字各取)。 */
48
+ function enumOf(text, parameterName) {
49
+ const open = new RegExp('<RefParameter[^>]*Name="' + parameterName + '"[^>]*>', "u").exec(text);
50
+ if (open === null)
51
+ return [];
52
+ // 自闭合 = integer 型(PLLM/PLLN 在 F4 上就是 Min=2 Max=63 这种),没有 PossibleValue。
53
+ // 不挡住的话正则会把**下一个** RefParameter 的块当成它的 children —— F4 的 PLLM 曾因此拿到 PLLP 的枚举名。
54
+ if (open[0].trimEnd().endsWith("/>"))
55
+ return [];
56
+ const from = (open.index ?? 0) + open[0].length;
57
+ const close = text.indexOf("</RefParameter>", from);
58
+ const block = close < 0 ? null : text.slice(from, close);
59
+ const body = block;
60
+ if (body === null)
61
+ return [];
62
+ const out = [];
63
+ for (const matched of body.matchAll(/<PossibleValue([^>]*)\/?>/gu)) {
64
+ const attrs = matched[1] ?? "";
65
+ const value = /Value="([^"]*)"/u.exec(attrs)?.[1] ?? "";
66
+ const comment = /Comment="([^"]*)"/u.exec(attrs)?.[1] ?? "";
67
+ if (value === "")
68
+ continue;
69
+ out.push({ value, comment, num: numberOf(comment) ?? numberOf(value) });
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * 读某一棵时钟树里「由 CubeMX 自己算」的频率槽名(`db/plugins/clock/<ClockTree>.xml` 的 refParameter)。
75
+ *
76
+ * 为什么需要:这些名字**不带** Freq_Value 后缀(H5 的 `EPOD_VALUE` 就是 PLL 源频率信号),
77
+ * 只看名字认不出是派生量。真机证据(2026-11 H5 @250 MHz 往返):计划没碰 `RCC.EPOD_VALUE`,
78
+ * CubeMX 保存时把它从 4 MHz 改成 8 MHz(跟随 PLL 源换成 HSE),ioc_verify 却记成 valueChanged
79
+ * → benign 翻 false。名字从 db 取而不是手抄,才能覆盖 27 族。
80
+ */
81
+ export function readClockTreeDerivedNames(db, clockTree) {
82
+ if (clockTree === "")
83
+ return [];
84
+ const file = join(db.root, "plugins", "clock", clockTree + ".xml");
85
+ if (!existsSync(file))
86
+ return [];
87
+ const text = readFileSync(file, "utf8");
88
+ const names = new Set();
89
+ for (const match of text.matchAll(/refParameter="([^"]+)"/gu))
90
+ names.add(match[1]);
91
+ return [...names];
92
+ }
93
+ /**
94
+ * 读「每个 SYSCLK 源各自的分频器」——从时钟树定义里走一遍 SYSCLK 多路选择器的每条输入。
95
+ *
96
+ * 为什么不能按名字猜:WB0/WL3 的 `SYSCLK32Divider`/`SYSCLK64Divider` **不是** SYSCLK 分频器,
97
+ * 而是 CLKSYS 那一路的预分频(STM32WB0.xml 里 `SYSCLK32Prescaler` 的输入是 SYSCLK、输出是 CLKSYS32)。
98
+ * 按名字猜会在 WB0 上写出 `SYSCLK64Divider=÷2` 以为 SYSCLK 变 32 MHz,而 CubeMX 实际把 CLKSYS 改成 24 MHz、
99
+ * SYSCLK 仍按源值(2026-11 合成 .ioc 往返实测:SysCLKFreq_VALUE 32000000→48000000)。
100
+ *
101
+ * 判据(全部来自 db/plugins/clock/<ClockTree>.xml):
102
+ * 1. 找 refParameter=SYSCLKSource(WL3 叫 ROOTClkSource)的 multiplexor;
103
+ * 2. 它的每条 <Input refValue=...> 是一条源(refValue 决定是 hse/hsi/rc64/…);
104
+ * 3. 顺着 from= 往回走,只有 type="devisor" 的元素才算这一路的分频器,走到源(fixedSource/variedSource)为止。
105
+ * C0 的 HSISYSCLKDivider 就在 HSI → SysClkSource 中间,所以仍能读到;WB0/WL3 走回去第一个就是源,读出来是空。
106
+ *
107
+ * 返回值语义要分清(关系到能不能信它):
108
+ * - null = 没读到时钟树(db 里没有该树的 xml、或 xml 里没有 SYSCLK 多路选择器)→ 调用方可以按名字兜底;
109
+ * - 空 Map = **读到了**、而且这些源确实没有 SYSCLK 分频器(WB0/WL3 就是这样)→ 调用方必须当真,不能兜底。
110
+ * 早先两者都返回空 Map,WB0 因此仍然走按名字猜的兜底、把 CLKSYS 预分频当成 SYSCLK 分频。
111
+ */
112
+ export function readClockTreeSysclkDividers(db, clockTree) {
113
+ if (clockTree === "")
114
+ return null;
115
+ const file = join(db.root, "plugins", "clock", clockTree + ".xml");
116
+ if (!existsSync(file))
117
+ return null;
118
+ const out = new Map();
119
+ const text = readFileSync(file, "utf8");
120
+ const byId = new Map();
121
+ for (const matched of text.matchAll(/<Element\b([^>]*?)(?:\/>|>([\s\S]*?)<\/Element>)/gu)) {
122
+ const attrs = matched[1] ?? "";
123
+ const body = matched[2] ?? "";
124
+ const id = attrOf(attrs, "id");
125
+ if (id === "")
126
+ continue;
127
+ const inputs = [];
128
+ for (const input of body.matchAll(/<Input\b([^>]*)\/?>/gu)) {
129
+ const inputAttrs = input[1] ?? "";
130
+ const from = attrOf(inputAttrs, "from");
131
+ if (from === "")
132
+ continue;
133
+ inputs.push({ from, refValue: attrOf(inputAttrs, "refValue") });
134
+ }
135
+ byId.set(id, { id, type: attrOf(attrs, "type"), ref: attrOf(attrs, "refParameter"), inputs });
136
+ }
137
+ const mux = [...byId.values()].find((item) => item.ref === "SYSCLKSource" || item.ref === "ROOTClkSource");
138
+ if (mux === undefined)
139
+ return null;
140
+ for (const input of mux.inputs) {
141
+ const source = directSourceIdOf(input.refValue);
142
+ if (source === null)
143
+ continue;
144
+ const names = [];
145
+ let current = input.from;
146
+ for (let guard = 0; guard < 32 && current !== null; guard += 1) {
147
+ const element = byId.get(current);
148
+ if (element === undefined || element.type !== "devisor")
149
+ break;
150
+ if (element.ref !== "")
151
+ names.push(element.ref);
152
+ const upstream = element.inputs[0];
153
+ current = upstream === undefined ? null : upstream.from;
154
+ }
155
+ if (names.length > 0 && !out.has(source))
156
+ out.set(source, names);
157
+ }
158
+ return out;
159
+ }
160
+ /** 同义参数名按顺序试(F4 的 RCC.PLLP 与 H5 的 RCC.PLL1P 是同一件事)。 */
161
+ function enumAlias(text, names) {
162
+ for (const name of names) {
163
+ const entries = enumOf(text, name);
164
+ if (entries.length > 0)
165
+ return { entries, name };
166
+ }
167
+ return { entries: [], name: "" };
168
+ }
169
+ /** 依次试同义名,先看 list 枚举、再看 Min/Max 数值范围(U5 的 PLL1P 就是 integer 1..128)。 */
170
+ function divsWithName(text, names) {
171
+ for (const name of names) {
172
+ const listed = enumOf(text, name)
173
+ .map((entry) => ({ div: entry.num ?? 0, iocValue: entry.value }))
174
+ .filter((item) => item.div >= 1 && item.iocValue !== "")
175
+ .sort((left, right) => left.div - right.div);
176
+ if (listed.length > 0)
177
+ return { divs: listed, name };
178
+ const range = rangeOf(text, name);
179
+ if (range !== null) {
180
+ const divs = [];
181
+ for (let div = range.min; div <= range.max; div += 1)
182
+ divs.push({ div, iocValue: String(div) });
183
+ return { divs, name };
184
+ }
185
+ }
186
+ return { divs: [], name: "" };
187
+ }
188
+ /**
189
+ * SYSCLK 走 PLL 的哪一路输出(PLLP 还是 PLLR)。
190
+ *
191
+ * 从时钟树定义读:db/plugins/clock/<ClockTree>.xml 里 Signal id="PLLCLK" 的 refParameter
192
+ * 就是喂给 SYSCLK 多路选择器的那路。实测 L4RS 与 U5 都指向 PLLRCLKFreq_Value,
193
+ * 而 U5 的 PLLP 只有 PLLPoutputFreq_Value(供 SAI/其它外设)——按 PLLP 规划会把
194
+ * SYSCLK 接到错的分频上。读不到(老 db)返回 null,调用方回退旧启发式。
195
+ */
196
+ export function readSysclkPllOutput(db, clockTree) {
197
+ if (clockTree === "")
198
+ return null;
199
+ const file = join(db.root, "plugins", "clock", clockTree + ".xml");
200
+ if (!existsSync(file))
201
+ return null;
202
+ const text = readFileSync(file, "utf8");
203
+ const signal = /<Signal\b[^>]*\bid="PLLCLK"[^>]*>/u.exec(text);
204
+ if (signal === null)
205
+ return null;
206
+ const ref = /refParameter="([^"]+)"/u.exec(signal[0])?.[1] ?? "";
207
+ if (/PLLR/u.test(ref))
208
+ return "R";
209
+ if (/PLLP/u.test(ref))
210
+ return "P";
211
+ return null;
212
+ }
213
+ /**
214
+ * 这一族的 Cortex(SysTick)时钟能不能当成 HCLK 来写。
215
+ *
216
+ * 判据是 db 里有没有 Cortex 的选择/分频参数(CortexCLockSelectionVirtual / CortexCLockSelection /
217
+ * Cortex_Div)。有就不能写:那几档(÷1 与 ÷8 都在选项里,.ioc 里的默认值不一定是 CubeMX 保存时
218
+ * 实际用的那个)—— 实测四次往返都很任性:H5 写 HCLK 被改成 HCLK÷8,U5 写 HCLK÷8 又被改回 HCLK,
219
+ * 同一个键两次反着来。这类「CubeMX 自己按树算」的派生量交给它算,我们只写确定等于 HCLK 的那些键,
220
+ * verify 里它会归到 derivedRecomputed(不参与 benign)。
221
+ */
222
+ function cortexFollowsHclk(text) {
223
+ return !/\bName="(?:CortexCLockSelectionVirtual|CortexCLockSelection|Cortex_Div)"/u.test(text);
224
+ }
225
+ /** 取数值型 RefParameter 的 Min/Max(F4 的 PLLN 这种不是 list,而是 2..432 的范围)。 */
226
+ function rangeOf(text, parameterName) {
227
+ const matched = new RegExp('<RefParameter[^>]*Name="' + parameterName + '"[^>]*/?>', "u").exec(text);
228
+ if (matched === null)
229
+ return null;
230
+ const min = numberOf(/Min="([^"]*)"/u.exec(matched[0])?.[1] ?? "");
231
+ const max = numberOf(/Max="([^"]*)"/u.exec(matched[0])?.[1] ?? "");
232
+ if (min === null || max === null || min >= max)
233
+ return null;
234
+ return { min, max };
235
+ }
236
+ /** 取 RefParameter 的数值属性;`Max="=SYSCLKFreq_VALUE"` 这类表达式直接丢弃(不是数字)。 */
237
+ function numAttr(attrs, key) {
238
+ const raw = new RegExp('\\b' + key + '="([^"]*)"', "u").exec(attrs)?.[1];
239
+ if (raw === undefined)
240
+ return null;
241
+ const text = raw.trim();
242
+ if (text === "" || text.startsWith("="))
243
+ return null;
244
+ const value = Number(text);
245
+ return Number.isFinite(value) ? value : null;
246
+ }
247
+ /**
248
+ * 取同名 RefParameter 的 Min/Max("APB1Freq_Value" 这种)。
249
+ *
250
+ * 同名参数在 Modes xml 里常常有多个**变体**,各自带 `<Condition Expression="scale1">`
251
+ * (G0/U0 的 ADC 35000000/16000000/80000000、G4 的 APB1 150M/170M 都是这种)。
252
+ * 这里取「最小的 Min + 最大的 Max」:CubeMX 允许多少就给多少,规划出来的档位不会因为
253
+ * 取错变体而被无故拒绝;真正的兜底还有后面的 SYSCLK 上限与 CubeMX 自己的校验。
254
+ * 名字按顺序试,先读出 Max 的优先(APB1Freq_Value 优先于单 APB 族的 APBFreq_Value)。
255
+ */
256
+ function limitOf(text, names) {
257
+ const re = (name) => new RegExp('<RefParameter[^>]*Name="' + name + '"[^>]*>', "gu");
258
+ for (const name of names) {
259
+ let min = null;
260
+ let max = null;
261
+ for (const matched of text.matchAll(re(name))) {
262
+ const one = numAttr(matched[0], "Min");
263
+ const other = numAttr(matched[0], "Max");
264
+ if (one !== null)
265
+ min = min === null ? one : Math.min(min, one);
266
+ if (other !== null)
267
+ max = max === null ? other : Math.max(max, other);
268
+ }
269
+ if (max !== null)
270
+ return { min, max };
271
+ }
272
+ return null;
273
+ }
274
+ /** 把 Modes xml 里所有 <RefParameter> 块按顺序拆出来(同名多块是常态:每个 Condition 一块)。 */
275
+ function refParamBlocks(text) {
276
+ const out = [];
277
+ const re = /<RefParameter\b([^>]*?)(\/>|>)/gu;
278
+ let matched = re.exec(text);
279
+ while (matched !== null) {
280
+ const attrs = matched[1] ?? "";
281
+ if ((matched[2] ?? "") === "/>") {
282
+ out.push({ attrs, body: "" });
283
+ matched = re.exec(text);
284
+ continue;
285
+ }
286
+ const close = text.indexOf("</RefParameter>", re.lastIndex);
287
+ const body = close < 0 ? "" : text.slice(re.lastIndex, close);
288
+ out.push({ attrs, body });
289
+ re.lastIndex = close < 0 ? text.length : close + "</RefParameter>".length;
290
+ matched = re.exec(text);
291
+ }
292
+ return out;
293
+ }
294
+ function attrOf(attrs, key) {
295
+ return new RegExp('\\b' + key + '="([^"]*)"', "u").exec(attrs)?.[1] ?? "";
296
+ }
297
+ /** 比较枚举名时忽略大小写与下划线:db 自己就两种写法混用(RCC_PLL1_VCIRANGE_0 / RCC_PLL1VCIRANGE_0)。 */
298
+ function looseName(value) {
299
+ return value.replace(/[^A-Za-z0-9]/gu, "").toUpperCase();
300
+ }
301
+ /** Condition 表达式里的 VCIRANGE 枚举引用(H5 的 VCO_SEL 块写 RCC_PLL1VCIRANGE_0,少一个下划线)。 */
302
+ function vciTokens(condition) {
303
+ return [...condition.matchAll(/RCC[^A-Za-z0-9]?PLL[0-9]?[^A-Za-z0-9]?VCIRANGE[^A-Za-z0-9]?[0-9]+/giu)].map((item) => looseName(item[0]));
304
+ }
305
+ /**
306
+ * 读 PLL 输入频段(PLL1_VCI_Range):H5 是 1–2/2–4/4–8/≥8 MHz 四段,每段 VCO 上限不同
307
+ * (150–420 MHz 与 128–560 MHz)。db 把「段」写成四个同名 RefParameter,各带一个 Condition;
308
+ * 段的枚举值在 PossibleValue,段的频率边界在 Condition 的数字里,段的 VCO 区间在
309
+ * VCOOutputFreq_Value 的变体里(按 Condition 引用哪个 VCIRANGE 认)。
310
+ */
311
+ function readVcoBands(text) {
312
+ const blocks = refParamBlocks(text);
313
+ const rawBands = [];
314
+ let vciRangeKey = "";
315
+ for (const block of blocks) {
316
+ const name = attrOf(block.attrs, "Name");
317
+ if (!/^PLL[0-9]?_VCI_Range$/u.test(name))
318
+ continue;
319
+ const condition = /<Condition[^>]*Expression="([^"]*)"/u.exec(block.body)?.[1] ?? "";
320
+ if (!/VCOInputFreq_Value/u.test(condition))
321
+ continue;
322
+ const value = /<PossibleValue[^>]*\bValue="([^"]+)"/u.exec(block.body)?.[1] ?? attrOf(block.attrs, "DefaultValue");
323
+ const nums = [...condition.matchAll(/[0-9]{5,}/gu)].map((item) => Number(item[0]));
324
+ if (value === "" || nums.length === 0)
325
+ continue;
326
+ vciRangeKey = "RCC." + name;
327
+ rawBands.push({ value, inMinHz: Math.min(...nums), inMaxHz: Math.max(...nums) });
328
+ }
329
+ if (rawBands.length === 0)
330
+ return { bands: [], vciRangeKey: "", vcoSelKey: "" };
331
+ // "RCC.PLL1_VCI_Range" → "PLL1_"(VCO_SEL / 其它同号参数都按这个前缀认)
332
+ const vciPrefix = vciRangeKey.slice("RCC.".length, vciRangeKey.length - "_VCI_Range".length) + "_";
333
+ rawBands.sort((left, right) => left.inMinHz - right.inMinHz);
334
+ const lastBand = rawBands[rawBands.length - 1];
335
+ const inMaxFallback = limitOf(text, ["VCOInputFreq_Value"])?.max ?? lastBand.inMaxHz;
336
+ // 最后一段的 Condition 常常是残缺表达式(H5 的 range3 只有下界),上界按 VCOInput 的 Max 补。
337
+ for (let index = 0; index < rawBands.length; index += 1) {
338
+ const band = rawBands[index];
339
+ if (band.inMaxHz > band.inMinHz)
340
+ continue;
341
+ band.inMaxHz = rawBands[index + 1]?.inMinHz ?? inMaxFallback;
342
+ }
343
+ // 每段的 VCO 区间:VCOOutputFreq_Value 的变体里,Condition 引用哪个 VCIRANGE 就是哪一段。
344
+ const bandLimits = new Map();
345
+ let defaultLimits = null;
346
+ const bandSel = new Map();
347
+ let vcoSelKey = "";
348
+ for (const block of blocks) {
349
+ const name = attrOf(block.attrs, "Name");
350
+ const condition = /<Condition[^>]*Expression="([^"]*)"/u.exec(block.body)?.[1] ?? "";
351
+ if (name === "VCOOutputFreq_Value") {
352
+ const minHz = numAttr(block.attrs, "Min");
353
+ const maxHz = numAttr(block.attrs, "Max");
354
+ if (minHz === null || maxHz === null || minHz >= maxHz)
355
+ continue;
356
+ const tokens = vciTokens(condition);
357
+ if (tokens.length === 0)
358
+ defaultLimits = defaultLimits ?? { minHz, maxHz };
359
+ for (const token of tokens)
360
+ bandLimits.set(token, { minHz, maxHz });
361
+ continue;
362
+ }
363
+ if (!/^PLL[0-9]?_VCO_SEL$/u.test(name))
364
+ continue;
365
+ // 同号才算:PLL1 的输入档只能配 PLL1_VCO_SEL(文件里还有 PLL2/PLL3 的,后出现的会盖掉)
366
+ if (!name.startsWith(vciPrefix))
367
+ continue;
368
+ const value = /<PossibleValue[^>]*\bValue="([^"]+)"/u.exec(block.body)?.[1] ?? attrOf(block.attrs, "DefaultValue");
369
+ for (const token of vciTokens(condition)) {
370
+ if (value === "")
371
+ continue;
372
+ vcoSelKey = "RCC." + name;
373
+ bandSel.set(token, value);
374
+ }
375
+ }
376
+ const bands = [];
377
+ for (const band of rawBands) {
378
+ const limits = bandLimits.get(looseName(band.value)) ?? defaultLimits;
379
+ if (limits === null || limits === undefined)
380
+ continue;
381
+ const sel = bandSel.get(looseName(band.value));
382
+ bands.push({
383
+ value: band.value,
384
+ inMinHz: band.inMinHz,
385
+ inMaxHz: band.inMaxHz,
386
+ minHz: limits.minHz,
387
+ maxHz: limits.maxHz,
388
+ ...(sel === undefined ? {} : { vcoSel: sel }),
389
+ });
390
+ }
391
+ return { bands, vciRangeKey, vcoSelKey };
392
+ }
393
+ /** RCC_PLLSOURCE_HSE → "hse";只认频率已知的三种。 */
394
+ function sourceIdOf(value) {
395
+ const upper = value.toUpperCase();
396
+ // PLL1 族的枚举名是 RCC_PLL1_SOURCE_HSE(U5 还有 RCC_PLLSOURCE_MSI 这种),
397
+ // 所以按后缀认而不是整串相等。
398
+ if (/SOURCE_HSE$/u.test(upper))
399
+ return "hse";
400
+ if (/SOURCE_HSI_DIV2$/u.test(upper))
401
+ return "hsi-div2";
402
+ if (/SOURCE_HSI$/u.test(upper))
403
+ return "hsi";
404
+ return null;
405
+ }
406
+ /**
407
+ * RCC_SYSCLKSOURCE_HSE / _HSI → "hse" / "hsi"(direct 模型的源)。
408
+ * 无线族(WB0/WL3)的 HSE 直连叫 RCC_SYSCLKSOURCE_DIRECT_HSE,内部 64 MHz RC 叫 _RC64MPLL。
409
+ * LSE/LSI 是 32 kHz 级,规划 MHz 目标时用不上,返回 null 让调用方跳过。
410
+ */
411
+ function directSourceIdOf(value) {
412
+ const upper = value.toUpperCase();
413
+ if (upper === "RCC_SYSCLKSOURCE_HSE" || upper === "RCC_SYSCLKSOURCE_DIRECT_HSE")
414
+ return "hse";
415
+ if (upper === "RCC_SYSCLKSOURCE_HSI")
416
+ return "hsi";
417
+ if (upper === "RCC_SYSCLKSOURCE_RC64MPLL")
418
+ return "rc64";
419
+ return null;
420
+ }
421
+ /**
422
+ * 读一颗芯片的时钟事实。读不到 RCC Modes 文件返回 null(调用方按「这一族没有 db 时钟事实」处理)。
423
+ */
424
+ export function readClockDbFacts(db, facts) {
425
+ const path = rccModesPath(db, facts);
426
+ const text = readTextOrNull(path);
427
+ if (text === null)
428
+ return null;
429
+ const notes = [];
430
+ const muls = enumOf(text, "PLLMUL")
431
+ .map((entry) => ({ mul: entry.num ?? 0, iocValue: entry.value }))
432
+ .filter((item) => item.mul >= 2 && item.iocValue !== "")
433
+ .sort((left, right) => left.mul - right.mul);
434
+ // PLLM 的三种写法都要认:PLLM(F4/F2/H5)、PLLM1(L4+ 的 PLL 叫 PLL1,输入分频是 PLLM1)、
435
+ // 以及 integer 型 Min/Max(U5 是 1..16 的整数,不是枚举)—— 原来只认 PLLM 的枚举,L4+ 直接读空。
436
+ const mFact = divsWithName(text, ["PLLM", "PLLM1", "PLLM2"]);
437
+ const pllM = mFact.divs;
438
+ const pllRAlias = divsWithName(text, ["PLLR", "PLL1R"]);
439
+ // PLLP 可能是枚举(F4 的 RCC_PLLP_DIV2..)也可能是整数区间(U5 的 PLL1P 1..128)。
440
+ const pllPAlias = divsWithName(text, ["PLLP", "PLL1P"]);
441
+ const pll1Naming = pllRAlias.name === "PLL1R" || pllPAlias.name === "PLL1P";
442
+ const pllR = pllRAlias.divs;
443
+ const pllP = pllPAlias.divs;
444
+ const pllN = rangeOf(text, "PLLN");
445
+ // SYSCLK 走 PLLP 还是 PLLR:优先按时钟树(db 里 Signal id="PLLCLK" 接的那路)判,
446
+ // 读不到才回退旧启发式「PLLP 只有 DIV7/DIV17 = 那是 PLLSAI 的输出,SYSCLK 走 PLLR」。
447
+ const pllPIsSai = pllP.length > 0 && pllP.every((item) => item.div === 7 || item.div === 17);
448
+ const sysclkOutput = readSysclkPllOutput(db, facts.clockTree) ?? (pllPIsSai && pllR.length > 0 ? "R" : "P");
449
+ const sources = [];
450
+ for (const entry of enumAlias(text, ["PLLSource", "PLLSourceVirtual"]).entries) {
451
+ const id = sourceIdOf(entry.value);
452
+ if (id === null)
453
+ continue;
454
+ const dup = sources.some((source) => source.id === id);
455
+ if (dup)
456
+ continue;
457
+ sources.push({
458
+ id,
459
+ label: id === "hse" ? "HSE(外部晶振)" : id === "hsi" ? "HSI(内部 RC)" : "HSI÷2(内部 RC 二分频)",
460
+ iocValue: entry.value,
461
+ // HSI 的绝对频率 db 不给(各族 8/16/48 MHz 都有),默认值只是占位:调用方要用 HSI 时必须从 .ioc 的 RCC.HSI_VALUE 拿真值。
462
+ defaultHz: id === "hse" ? 8_000_000 : id === "hsi" ? 8_000_000 : 4_000_000,
463
+ selectable: true,
464
+ note: id === "hse"
465
+ ? "外部晶振:频率以 .ioc 的 RCC.HSE_VALUE 为准(缺省 8 MHz)"
466
+ : "内部 RC:" + (id === "hsi" ? "" : "二分频后") + "频率以 .ioc 的 RCC.HSI_VALUE 为准(db 不写各族 HSI 频率)",
467
+ });
468
+ }
469
+ // F0/L0 这类族只有 RCC_PLLSOURCE_HSI 一档,硬件上它就是 HSI/2 进 PLL(不是 HSI 直连):
470
+ // 少了这一步,规划会把 HSI 8 MHz 当 8 MHz 源算,CubeMX 回写时按 /2 重算 → 频率对不上(F0 实测 48→24 MHz)。
471
+ if (sources.some((source) => source.id === "hsi") && !sources.some((source) => source.id === "hsi-div2")) {
472
+ for (const source of sources) {
473
+ if (source.id !== "hsi")
474
+ continue;
475
+ source.divider = 2;
476
+ source.note += ";该族的 RCC_PLLSOURCE_HSI 实际是 HSI/2 进 PLL(硬件固定二分频)";
477
+ }
478
+ }
479
+ const toDivs = (entries) => entries
480
+ .map((entry) => ({ div: entry.num ?? 0, iocValue: entry.value }))
481
+ .filter((item) => item.div >= 1 && item.iocValue !== "")
482
+ .sort((left, right) => left.div - right.div);
483
+ const apbDivs = toDivs(enumOf(text, "APB1CLKDivider"));
484
+ const ahbDivs = toDivs(enumOf(text, "AHBCLKDivider"));
485
+ const apb2Divs = toDivs(enumOf(text, "APB2CLKDivider"));
486
+ const adcDivs = toDivs(enumOf(text, "ADCPresc"));
487
+ // db 里某个 RefParameter 的 DefaultValue(Hz):HSE_VALUE/PLL64_VALUE 这类「源标称频率」用它当缺省。
488
+ const defaultOf = (name) => {
489
+ for (const block of refParamBlocks(text)) {
490
+ if (attrOf(block.attrs, "Name") !== name)
491
+ continue;
492
+ const parsed = Number.parseInt(attrOf(block.attrs, "DefaultValue"), 10);
493
+ if (Number.isFinite(parsed) && parsed > 0)
494
+ return parsed;
495
+ }
496
+ return null;
497
+ };
498
+ // direct 模型:SYSCLK 直接取源,没有 PLL。能当源的只有 SYSCLKSource 里的 HSE/HSI
499
+ // (LSE/LSI 是 32 kHz 级,规划到 MHz 目标用不上,也不该被当成「凑不到就选最近的」兜底)。
500
+ // 无线族(WB0/WL3)不叫 SYSCLKSource:WL3 是 ROOTClkSource;WL3 的 HSE 直连是 DIRECT_HSE,
501
+ // 内部 64 MHz RC 是 RC64MPLL(频率取 db 的 PLL64_VALUE,不读 .ioc)。
502
+ const directSourceEnum = enumAlias(text, ["SYSCLKSource", "ROOTClkSource"]);
503
+ const directSources = [];
504
+ for (const entry of directSourceEnum.entries) {
505
+ const id = directSourceIdOf(entry.value);
506
+ if (id === null)
507
+ continue;
508
+ if (directSources.some((source) => source.id === id))
509
+ continue;
510
+ const hseDefaultHz = defaultOf("HSE_VALUE") ?? 8_000_000;
511
+ const hsiDefaultHz = defaultOf("HSI_VALUE") ?? 16_000_000;
512
+ const rc64Hz = defaultOf("PLL64_VALUE") ?? 64_000_000;
513
+ directSources.push({
514
+ id,
515
+ label: id === "hse" ? "HSE(外部晶振)" : id === "hsi" ? "HSI(内部 RC)" : "RC64MPLL(64 MHz 内部 RC)",
516
+ iocValue: entry.value,
517
+ // 真值从 .ioc 的 RCC.HSE_VALUE / RCC.HSI_VALUE 读;这里给 db 的 DefaultValue 当缺省。
518
+ defaultHz: id === "hse" ? hseDefaultHz : id === "hsi" ? hsiDefaultHz : rc64Hz,
519
+ // RC64MPLL 是固定频率源,.ioc 没有它的频率键(PLL64_VALUE 是派生值,写它等于跟自己较劲)。
520
+ ...(id === "rc64" ? {} : { hzKey: id === "hse" ? "RCC.HSE_VALUE" : "RCC.HSI_VALUE" }),
521
+ selectable: true,
522
+ note: id === "hse"
523
+ ? "外部晶振:频率以 .ioc 的 RCC.HSE_VALUE 为准"
524
+ : id === "hsi"
525
+ ? "内部 RC:频率以 .ioc 的 RCC.HSI_VALUE 为准"
526
+ : "内部 64 MHz RC 多相时钟(固定频率,只能靠源分频往下分)",
527
+ });
528
+ }
529
+ // 源分频:哪一路有分频器、键叫什么,全从时钟树走(readClockTreeSysclkDividers)。
530
+ // 走不出来(db 没有该树的 xml)才回落到按名字猜的老路——WB0/WL3 的 SYSCLK32/64Divider
531
+ // 是 CLKSYS 预分频不是 SYSCLK 分频,名字猜法在它们身上是错的,所以只能当兜底。
532
+ const srcDivBySource = {};
533
+ const treeDividers = readClockTreeSysclkDividers(db, facts.clockTree);
534
+ for (const [source, names] of treeDividers ?? new Map()) {
535
+ for (const name of names) {
536
+ const divs = toDivs(enumOf(text, name));
537
+ if (divs.length === 0)
538
+ continue;
539
+ srcDivBySource[source] = { key: "RCC." + name, divs };
540
+ break;
541
+ }
542
+ }
543
+ if (treeDividers === null) {
544
+ for (const [source, names] of [
545
+ ["hse", ["SYSCLK32Divider", "SYSCLK48Divider"]],
546
+ ["rc64", ["SYSCLK64Divider"]],
547
+ ["hsi", ["HSISYSCLKDivider"]],
548
+ ]) {
549
+ for (const name of names) {
550
+ const divs = toDivs(enumOf(text, name));
551
+ if (divs.length === 0)
552
+ continue;
553
+ srcDivBySource[source] = { key: "RCC." + name, divs };
554
+ break;
555
+ }
556
+ }
557
+ }
558
+ const srcDivs = srcDivBySource.hsi?.divs ?? [];
559
+ const srcDivKey = srcDivBySource.hsi?.key ?? "";
560
+ const srcDivSources = srcDivs.length > 0 ? ["hsi"] : [];
561
+ // 派生频率参数名:RefParameter 里以 Freq_Value/FreqValue 结尾的那批(C0 有 25 个)。
562
+ const derivedNames = [];
563
+ // 三种写法都有:APBFreq_Value(驼峰)、ADCFreqValue(连写)、SysCLKFreq_VALUE(全大写带下划线)。
564
+ for (const matched of text.matchAll(/<RefParameter[^>]*\bName="([A-Za-z0-9_]+(?:Freq_Value|FreqValue|Freq_VALUE))"/gu)) {
565
+ const name = matched[1];
566
+ if (!derivedNames.includes(name))
567
+ derivedNames.push(name);
568
+ }
569
+ let model = muls.length > 0 ? "pllmul" : pllM.length > 0 || pllN !== null ? "pllmn" : directSources.length > 0 ? "direct" : "unknown";
570
+ // direct 模型只对「SYSCLK 直接取一个固定标称频率的源」成立。两种情况下它看着像 direct、其实是假直连:
571
+ // · 分相 PLL(H7:DIVM1/DIVN1/DIVP1 + PLL1/2/3 三套 6 参数,SYSCLKSource 里也有 PLLCLK);
572
+ // · MSI 直连(U3:SYSCLKSource 只有 MSIS/HSI/HSE,MSIS 最高 96 MHz、频率可配,不是固定标称值)。
573
+ // 两种都归到 unknown 并写清原因:宁可明确拒绝,也不给一个「按 HSI 猜出来」的档位 ——
574
+ // 那种计划写进 .ioc 后 CubeMX 会照它算出一个更低的 SYSCLK,verify 还可能因为派生键被重算而看不出错。
575
+ let unknownNote = "";
576
+ if (model === "direct") {
577
+ const refNames = [...new Set([...text.matchAll(/<RefParameter[^>]*\bName="([A-Za-z0-9_]+)"/gu)].map((matched) => matched[1]))];
578
+ // 分相 PLL 的参数名是 DIVM<n>/DIVN<n>/DIVP<n>/PLL<k> 开头的那批。
579
+ // 无线族的 PLL64_VALUE 是 64 MHz RC 的派生值(PLL6 后面是数字 4),不能被误判成分相 PLL。
580
+ // 只按「组」去重并把原始名截到组号:DIVM1/DIVM2/DIVM3 是同一组输入分频,
581
+ // 全列出来既刷屏又会混进 DIVP1Freq_Value 这种派生值名。
582
+ // PLL[1-9](?![0-9]):PLL64_VALUE(无线族 64 MHz RC 派生值)不算,PLL1R/PLL2M 算。
583
+ const phasePllNames = refNames.filter((name) => /^(?:DIV[MPNQ]\d|PLL[1-9](?![0-9]))/u.test(name));
584
+ const phasePllKeys = [...new Set(phasePllNames.map((name) => /^(?:DIV[MPNQ]\d|PLL[1-9](?![0-9]))/u.exec(name)?.[0] ?? name))].sort();
585
+ const phasePll = phasePllKeys.slice(0, 5);
586
+ const phasePllMore = phasePllKeys.length > phasePll.length ? " 等" : "";
587
+ const msiSources = directSourceEnum.entries.filter((entry) => directSourceIdOf(entry.value) === null && /_MSI[S]?$/u.test(entry.value.toUpperCase()));
588
+ if (phasePll.length > 0) {
589
+ unknownNote =
590
+ "db 里这一族的 PLL 是分相模型(参数 " + phasePll.join(" / ") + phasePllMore + ":DIVM/DIVN/DIVP 三组 + 多路 PLL):这个模型还没实现,不会给时钟计划";
591
+ }
592
+ else if (msiSources.length > 0) {
593
+ unknownNote =
594
+ "SYSCLK 还能直连 MSI(db 的 SYSCLKSource 里有 " + msiSources.map((entry) => entry.value).join(" / ") + "),MSI 的频率是可配置的源、直连模型只认固定标称频率的 HSE/HSI:这个形状还没建模,不会给时钟计划";
595
+ }
596
+ if (unknownNote !== "")
597
+ model = "unknown";
598
+ }
599
+ if (model === "unknown" && unknownNote === "") {
600
+ notes.push("db 的 RCC Modes 里既没有 PLLMUL、也没有 PLLM/PLLN、也没有能直连的 SYSCLKSource(HSE/HSI):这一族的时钟模型不在已实现的三种之内");
601
+ }
602
+ if (unknownNote !== "")
603
+ notes.push(unknownNote);
604
+ // 总线上限与 VCO 区间:都在同一份 Modes xml 的 RefParameter Max/Min 里(CubeMX 自己校验用)。
605
+ // 无线族(WB0/WL3)的 SYSCLK 上限参数叫 SysCLKFreq_VALUE(注意大小写与 Freq_VALUE 写法)。
606
+ const sysclkMaxDbHz = limitOf(text, ["SYSCLKFreq_VALUE", "SysCLKFreq_VALUE", "HCLKFreq_Value"])?.max ?? 0;
607
+ const apb1 = limitOf(text, ["APB1Freq_Value", "APBFreq_Value"]);
608
+ const apb2 = limitOf(text, ["APB2Freq_Value", "APBFreq_Value"]);
609
+ const adcLimit = limitOf(text, ["ADCFreq_Value", "ADC12outputFreq_Value", "synchADCFreq_Value"]);
610
+ const apb1Max = apb1?.max ?? null;
611
+ const busLimits = apb1Max === null
612
+ ? null
613
+ : {
614
+ apb1Hz: apb1Max,
615
+ apb2Hz: apb2?.max ?? apb1Max,
616
+ // 没有独立 ADC 上限的族(L1 的 ADCFreq_Value 没有 Max)先按 APB2 顶住,
617
+ // 反正 adcDivs 为空时 planner 不写 ADCPresc,这条不会生效。
618
+ adcHz: adcLimit?.max ?? apb2?.max ?? apb1Max,
619
+ };
620
+ if (busLimits === null) {
621
+ notes.push("db 的 RCC Modes 里没有 APB1Freq_Value/APBFreq_Value 的 Max:这一族的总线上限读不出来");
622
+ }
623
+ const vcoOut = limitOf(text, ["VCOOutputFreq_Value"]);
624
+ const vcoIn = limitOf(text, ["VCOInputFreq_Value"]);
625
+ const vcoMinHz = vcoOut?.min ?? null;
626
+ const vcoMaxHz = vcoOut?.max ?? null;
627
+ const vco = vcoMinHz === null || vcoMaxHz === null || vcoMinHz <= 0 || vcoMinHz >= vcoMaxHz
628
+ ? null
629
+ : {
630
+ minHz: vcoMinHz,
631
+ maxHz: vcoMaxHz,
632
+ ...(vcoIn?.min === null || vcoIn?.min === undefined ? {} : { inMinHz: vcoIn.min }),
633
+ ...(vcoIn?.max === null || vcoIn?.max === undefined ? {} : { inMaxHz: vcoIn.max }),
634
+ };
635
+ // SYSCLK 源按 db 的 RefParameter 名字决定:有 SYSCLKSourceVirtual 就只能写它(F303),
636
+ // 无线族(WL3)根本没有 SYSCLKSource,源键叫 ROOTClkSource。
637
+ const sysclkSourceKey = /\bName="SYSCLKSourceVirtual"/u.test(text)
638
+ ? "RCC.SYSCLKSourceVirtual"
639
+ : /\bName="ROOTClkSource"/u.test(text)
640
+ ? "RCC.ROOTClkSource"
641
+ : "RCC.SYSCLKSource";
642
+ // PLL1 族(H5/U5/WBA/L4+):输入分频叫 PLL1P/PLL1R、VCO 分两档(PLL1_VCO_SEL)、
643
+ // 输入按频段选档(PLL1_VCI_Range)、PLL 要显式打开(PLLUsed/PLLState)。
644
+ const bandInfo = readVcoBands(text);
645
+ // PLLUsed/PLLState 在 Modes xml 里各有两个变体(0/1、OFF/ON),属性顺序也不固定
646
+ // (H5 的 PLLState 是 DefaultValue 在 Name 前面),所以按块读、取"打开"那个变体。
647
+ const paramBlocks = refParamBlocks(text);
648
+ const pllUsedBlock = paramBlocks.find((block) => attrOf(block.attrs, "Name") === "PLLUsed");
649
+ const pllStateBlocks = paramBlocks.filter((block) => attrOf(block.attrs, "Name") === "PLLState");
650
+ const pllStateOn = pllStateBlocks.map((block) => attrOf(block.attrs, "DefaultValue")).find((value) => /ON$/u.test(value)) ??
651
+ pllStateBlocks.map((block) => attrOf(block.attrs, "DefaultValue")).find((value) => value !== "") ??
652
+ "";
653
+ const pllEnable = pllUsedBlock === undefined || pllStateOn === ""
654
+ ? null
655
+ : { usedKey: "RCC.PLLUsed", usedValue: "1", stateKey: "RCC.PLLState", stateValue: pllStateOn };
656
+ return {
657
+ model,
658
+ sysclkMaxHz: Math.round((facts.frequencyMhz ?? 0) * 1_000_000),
659
+ sysclkMaxDbHz,
660
+ sysclkSourceKey,
661
+ busLimits,
662
+ vco,
663
+ muls,
664
+ sources,
665
+ directSources,
666
+ srcDivs,
667
+ srcDivKey,
668
+ srcDivSources,
669
+ srcDivBySource,
670
+ // 读不到 APB 分频就留空:WB0/WL3 根本没有 APB1CLKDivider,早先这里填 RCC_HCLK_DIV1..16
671
+ // 的假枚举,planner 会把它写进 .ioc,CubeMX 当成未知键丢掉(= 计划里的键凭空消失)。
672
+ apbDivs,
673
+ hasApbDivider: apbDivs.length > 0,
674
+ ahbDivs,
675
+ apb2Divs,
676
+ derivedNames,
677
+ adcDivs,
678
+ pllM,
679
+ pllN,
680
+ pllP,
681
+ pllR,
682
+ sysclkOutput,
683
+ pll1Naming,
684
+ pllMKey: mFact.name === "" ? "" : "RCC." + mFact.name,
685
+ pllPKey: pllPAlias.name === "" ? "" : "RCC." + pllPAlias.name,
686
+ pllRKey: pllRAlias.name === "" ? "" : "RCC." + pllRAlias.name,
687
+ cortexFollowsHclk: cortexFollowsHclk(text),
688
+ vcoBands: bandInfo.bands,
689
+ vciRangeKey: bandInfo.vciRangeKey,
690
+ vcoSelKey: bandInfo.vcoSelKey,
691
+ pllEnable,
692
+ notes,
693
+ sourceFile: path ?? "",
694
+ };
695
+ }
696
+ export const BUS_LIMITS = {
697
+ // RM0090(F4):APB1 ≤42 MHz、APB2 ≤84 MHz、ADC ≤36 MHz(ADC 走 APB2 再分频)
698
+ STM32F4: { apb1Hz: 42_000_000, apb2Hz: 84_000_000, adcHz: 36_000_000 },
699
+ // RM0385/RM0410(F7):APB1 ≤54 MHz、APB2 ≤108 MHz、ADC ≤36 MHz
700
+ STM32F7: { apb1Hz: 54_000_000, apb2Hz: 108_000_000, adcHz: 36_000_000 },
701
+ // RM0440(G4):APB1/APB2 都能跑到 SYSCLK;ADC 时钟不走 RCC 预分频(由 ADC12CLockSelection 选)
702
+ STM32G4: { apb1Hz: 170_000_000, apb2Hz: 170_000_000, adcHz: 60_000_000 },
703
+ // RM0351(L4):APB1/APB2 = AHB(≤80 MHz);ADC 时钟来自 PLLSAI1 或 SYSCLK
704
+ STM32L4: { apb1Hz: 80_000_000, apb2Hz: 80_000_000, adcHz: 80_000_000 },
705
+ // RM0008(F1):APB1 ≤36 MHz、APB2 = SYSCLK、ADC ≤14 MHz
706
+ STM32F1: { apb1Hz: 36_000_000, apb2Hz: 72_000_000, adcHz: 14_000_000 },
707
+ // RM0091(F0):APB1 = AHB(F0 的 APB1 不再二分频)、ADC ≤14 MHz
708
+ STM32F0: { apb1Hz: 48_000_000, apb2Hz: 48_000_000, adcHz: 14_000_000 },
709
+ // RM0377(L0):APB1/APB2 = AHB(≤32 MHz)、ADC ≤16 MHz
710
+ STM32L0: { apb1Hz: 32_000_000, apb2Hz: 32_000_000, adcHz: 16_000_000 },
711
+ };
712
+ export const PLL_VCO_LIMITS = {
713
+ // RM0090:VCO 输出 100–432 MHz,PLL 输入 1–2 MHz
714
+ STM32F4: { minHz: 100_000_000, maxHz: 432_000_000, inMinHz: 1_000_000, inMaxHz: 2_000_000 },
715
+ // RM0385/RM0410(F7):同 F4 的 PLL 结构
716
+ STM32F7: { minHz: 100_000_000, maxHz: 432_000_000, inMinHz: 1_000_000, inMaxHz: 2_000_000 },
717
+ // RM0440(G4):PLL 输入 2.66–16 MHz,VCO 96–344 MHz
718
+ STM32G4: { minHz: 96_000_000, maxHz: 344_000_000, inMinHz: 2_660_000, inMaxHz: 16_000_000 },
719
+ // RM0351(L4):PLL 输入 4–16 MHz,VCO 64–344 MHz
720
+ STM32L4: { minHz: 64_000_000, maxHz: 344_000_000, inMinHz: 4_000_000, inMaxHz: 16_000_000 },
721
+ };
722
+ /**
723
+ * db 事实 + 该族总线上限 → planClock 认的 ClockFacts。
724
+ * 返回 null 表示这一族还不能规划(没有总线上限、或 PLL 模型不是 pllmul)。
725
+ */
726
+ export function clockFactsFromDb(facts, familyId) {
727
+ const family = familyId.trim().toUpperCase();
728
+ // SYSCLK 上限三级回退:MCU xml 的 <Frequency> → db 的 SYSCLKFreq_VALUE Max → APB2 上限。
729
+ // 第三级是兜底(G4/U0 的 <Frequency> 读出来是 0,但它们的 SYSCLKFreq_VALUE Max 是有的)。
730
+ const sysclkMaxNow = facts.sysclkMaxHz > 0 ? facts.sysclkMaxHz : facts.sysclkMaxDbHz;
731
+ const limits = BUS_LIMITS[family] ??
732
+ facts.busLimits ??
733
+ // direct 族可能连 APB 频率上限参数都没有(WB0/WL3 总线不分频,db 里只有 SysCLKFreq_VALUE):
734
+ // 此时总线跟着 SYSCLK 走,用 SYSCLK 上限兜住。
735
+ (facts.model === "direct" && sysclkMaxNow > 0
736
+ ? { apb1Hz: sysclkMaxNow, apb2Hz: sysclkMaxNow, adcHz: sysclkMaxNow }
737
+ : null);
738
+ if (limits === null)
739
+ return null;
740
+ // direct 模型没有 PLL,也就没有 PLLSource 参数:源从 SYSCLKSource 来。
741
+ if (facts.sources.length === 0 && facts.model !== "direct")
742
+ return null;
743
+ const sysclkHz = sysclkMaxNow > 0 ? sysclkMaxNow : limits.apb2Hz;
744
+ const base = {
745
+ sources: facts.sources,
746
+ apbDivs: facts.apbDivs,
747
+ sysclkSourceKey: facts.sysclkSourceKey,
748
+ ...(facts.ahbDivs.length > 0 ? { ahbDivs: facts.ahbDivs } : {}),
749
+ ...(facts.apb2Divs.length > 0 ? { apb2Divs: facts.apb2Divs } : {}),
750
+ adcDivs: facts.adcDivs.length > 0 ? facts.adcDivs : [{ div: 1, iocValue: "" }],
751
+ limits: {
752
+ sysclkHz,
753
+ apb1Hz: limits.apb1Hz,
754
+ apb2Hz: limits.apb2Hz,
755
+ adcHz: limits.adcHz,
756
+ },
757
+ // USB 规则:db 不写,且各族的 48 MHz 来源不同(F1 要 PLL=72 再 ÷1.5;F0/L0 直接 PLL=48)。
758
+ // 这里给「未建模」(requiresPllClkHz = 0 ⇒ planClock 认为 USB 不可用,不会写 RCC.USBPrescaler)。
759
+ usb: { hz: 48_000_000, requiresPllClkHz: 0, iocValue: "" },
760
+ peripheralClocks: F1_PERIPHERAL_CLOCKS,
761
+ baudList: F1_BAUD_LIST,
762
+ };
763
+ if (facts.model === "pllmn") {
764
+ const vco = PLL_VCO_LIMITS[family] ?? facts.vco;
765
+ if (vco === null)
766
+ return null;
767
+ const outputDivs = facts.sysclkOutput === "R" ? facts.pllR : facts.pllP;
768
+ if (facts.pllM.length === 0 || outputDivs.length === 0 || facts.pllN === null)
769
+ return null;
770
+ return {
771
+ ...base,
772
+ model: "pllmn",
773
+ vco,
774
+ muls: [],
775
+ pllM: facts.pllM,
776
+ pllN: facts.pllN,
777
+ pllP: facts.pllP,
778
+ pllR: facts.pllR,
779
+ sysclkOutput: facts.sysclkOutput,
780
+ ...(facts.pll1Naming ? { pll1Naming: true } : {}),
781
+ ...(facts.pllMKey === "" ? {} : { pllMKey: facts.pllMKey }),
782
+ ...(facts.pllPKey === "" ? {} : { pllPKey: facts.pllPKey }),
783
+ ...(facts.pllRKey === "" ? {} : { pllRKey: facts.pllRKey }),
784
+ ...(facts.cortexFollowsHclk ? {} : { cortexFollowsHclk: false }),
785
+ ...((facts.vcoBands ?? []).length > 0 ? { vcoBands: facts.vcoBands, vciRangeKey: facts.vciRangeKey, vcoSelKey: facts.vcoSelKey } : {}),
786
+ ...(facts.pllEnable === null ? {} : { pllEnable: facts.pllEnable }),
787
+ ...(facts.derivedNames.length > 0 ? { knownDerivedNames: facts.derivedNames } : {}),
788
+ };
789
+ }
790
+ if (facts.model === "direct") {
791
+ if (facts.directSources.length === 0)
792
+ return null;
793
+ return {
794
+ ...base,
795
+ model: "direct",
796
+ muls: [],
797
+ sources: facts.directSources,
798
+ ...(facts.srcDivs.length > 0 ? { srcDivs: facts.srcDivs, srcDivKey: facts.srcDivKey } : {}),
799
+ ...(facts.srcDivSources.length > 0 ? { srcDivSources: facts.srcDivSources } : {}),
800
+ ...(Object.keys(facts.srcDivBySource).length > 0 ? { srcDivBySource: facts.srcDivBySource } : {}),
801
+ // 没有 APB 分频参数的族(WB0/WL3):清掉 base 里的 APB 分频,planner 就不会去写那个键。
802
+ ...(facts.hasApbDivider ? {} : { apbDivs: [] }),
803
+ derivedClockNames: facts.derivedNames,
804
+ };
805
+ }
806
+ if (facts.model !== "pllmul")
807
+ return null;
808
+ if (facts.muls.length === 0)
809
+ return null;
810
+ return {
811
+ muls: facts.muls,
812
+ sources: facts.sources,
813
+ apbDivs: facts.apbDivs,
814
+ sysclkSourceKey: facts.sysclkSourceKey,
815
+ ...(facts.ahbDivs.length > 0 ? { ahbDivs: facts.ahbDivs } : {}),
816
+ adcDivs: facts.adcDivs.length > 0 ? facts.adcDivs : [{ div: 1, iocValue: "" }],
817
+ limits: {
818
+ sysclkHz: facts.sysclkMaxHz > 0 ? facts.sysclkMaxHz : limits.apb2Hz,
819
+ apb1Hz: limits.apb1Hz,
820
+ apb2Hz: limits.apb2Hz,
821
+ adcHz: limits.adcHz,
822
+ },
823
+ // USB 规则:db 不写,且各族的 48 MHz 来源不同(F1 要 PLL=72 再 ÷1.5;F0/L0 直接 PLL=48)。
824
+ // 这里给「未建模」(requiresPllClkHz = 0 ⇒ planClock 认为 USB 不可用,不会写 RCC.USBPrescaler),
825
+ // 由调用方按族补规则 —— 宁可报 USB 不可用,也不拿 F1 的 72 MHz 规则套到别的族。
826
+ usb: { hz: 48_000_000, requiresPllClkHz: 0, iocValue: "" },
827
+ peripheralClocks: F1_PERIPHERAL_CLOCKS,
828
+ baudList: F1_BAUD_LIST,
829
+ };
830
+ }