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,132 @@
1
+ /**
2
+ * 寄存器路线的时钟配置(F1 全系,按 line 决定上限)。
3
+ *
4
+ * 为什么寄存器路线要自己配时钟:HAL 路线由 CubeMX 生成的 SystemClock_Config() 负责,
5
+ * 而寄存器路线不用 CubeMX、也不用固件包,从模板拷过去的 main.c 里只有 HSI 8 MHz——
6
+ * 72 MHz 的板子在 8 MHz 上跑,串口/延时/定时全要按 8 MHz 算,而且用户会以为"F1 就该这么快"。
7
+ * 所以这里按芯片型号算出一段 clock_init(),生成 main.c 时写进去。
8
+ *
9
+ * 所有数字都查过 RM0008/RM0038/RM0041 和 14 个真实设备头(2026-10-30 实测,见
10
+ * data/cmsis-sources.ts 的哈希表):
11
+ * · 各 line 的 SYSCLK 上限:F100 24 MHz、F101 36 MHz、F102 48 MHz、F103/105/107 72 MHz
12
+ * · Flash 等待周期:≤24 MHz 用 0,≤48 MHz 用 1,72 MHz 用 2(RM0008 §3.3.3)
13
+ * · APB1 上限 36 MHz(F100 是 24 MHz,这里 F100 的 SYSCLK 只有 24 MHz 所以 /1 也够)
14
+ * · F100 的 FLASH_ACR 没有 LATENCY / PRFTBE 字段(只有 HLFCYA),所以 F100 完全不碰 FLASH
15
+ *
16
+ * PLL 一律走 HSE 8 MHz(蓝丸/大多数 F1 小板都是 8 MHz 晶振),算出来正好等于该 line 的上限;
17
+ * HSE 没起(没焊晶振)时退回 HSI/2 4 MHz × 倍频,F103/105/107 因为 4×18 > 16 只能到 64 MHz,
18
+ * 这时候会往 report 里塞一条 warning,让用户知道"没跑在 72"。
19
+ *
20
+ * 为什么不用 RCC_CFGR_PLLMULL9 之类的倍频宏:F100/F101 的可用倍频档位和设备头里定义的宏
21
+ * 并不齐全(实测 f100 没有 PLLMULL6,f105/f107 没有 PLLMULL16),而 PLLMUL 字段的编码
22
+ * 全家族一致(0=×2 … 14=×16,bit21:18)。所以这里统一按 (倍频 - 2) << 18 写,
23
+ * 只依赖全 14 个设备头都有的 RCC_CFGR_PLLMULL_Msk / _Pos。
24
+ */
25
+ /** 实测过的 HSE 频率(蓝丸、绝大多数 F1 最小系统板)。 */
26
+ export const REGISTER_HSE_HZ = 8_000_000;
27
+ /** HSI 出厂频率(RM0008:8 MHz ±1%)。 */
28
+ export const REGISTER_HSI_HZ = 8_000_000;
29
+ /**
30
+ * 按 line 的时钟表。hseMul/hseDiv 是"8 MHz 晶振拿到该 line 上限"的唯一组合:
31
+ * 24 = 8×3 · 36 = 8/2×9 · 48 = 8×6 · 72 = 8×9
32
+ */
33
+ const LINE_CLOCK = {
34
+ "100": { maxMHz: 24, hseMul: 3, hseDiv: 1, apb1Div: 1, hasFlashLatency: false },
35
+ "101": { maxMHz: 36, hseMul: 9, hseDiv: 2, apb1Div: 1, hasFlashLatency: true },
36
+ "102": { maxMHz: 48, hseMul: 6, hseDiv: 1, apb1Div: 2, hasFlashLatency: true },
37
+ "103": { maxMHz: 72, hseMul: 9, hseDiv: 1, apb1Div: 2, hasFlashLatency: true },
38
+ "105": { maxMHz: 72, hseMul: 9, hseDiv: 1, apb1Div: 2, hasFlashLatency: true },
39
+ "107": { maxMHz: 72, hseMul: 9, hseDiv: 1, apb1Div: 2, hasFlashLatency: true },
40
+ };
41
+ /** line 代号:STM32F103 → 103。 */
42
+ function lineOf(chip) {
43
+ return chip.prefix.slice(6);
44
+ }
45
+ /** 等待周期:RM0008 Table 3(0 WS ≤ 24 MHz,1 WS ≤ 48 MHz,2 WS ≤ 72 MHz)。 */
46
+ function latencyFor(hz) {
47
+ if (hz <= 24_000_000)
48
+ return 0;
49
+ if (hz <= 48_000_000)
50
+ return 1;
51
+ return 2;
52
+ }
53
+ /**
54
+ * 给一颗芯片算时钟方案。只读、纯函数;不认识 line 时按 F103 处理并记 warning
55
+ * (宁可给一个能跑的 72 MHz,也不抛异常让整个工程建不出来)。
56
+ */
57
+ export function planRegisterClock(chip) {
58
+ const line = lineOf(chip);
59
+ const warnings = [];
60
+ let spec = LINE_CLOCK[line];
61
+ if (spec === undefined) {
62
+ warnings.push("时钟表里还没有 F" + line + ",先按 F103 的 72 MHz 方案生成;确认这颗芯片能跑到 72 MHz 后请把 line 补进 register-clock.ts 的 LINE_CLOCK。");
63
+ spec = LINE_CLOCK["103"];
64
+ }
65
+ const hseHz = REGISTER_HSE_HZ;
66
+ const pllInHz = hseHz / spec.hseDiv;
67
+ const sysclkHz = pllInHz * spec.hseMul;
68
+ const hsiMul = Math.min(16, Math.max(2, Math.round(spec.maxMHz / (REGISTER_HSI_HZ / 2 / 1_000_000))));
69
+ const hsiSysclkHz = (REGISTER_HSI_HZ / 2) * hsiMul;
70
+ const flashLatency = spec.hasFlashLatency ? latencyFor(Math.max(sysclkHz, hsiSysclkHz)) : 0;
71
+ const apb1Div = sysclkHz > 36_000_000 ? 2 : spec.apb1Div;
72
+ const apb2Div = 1;
73
+ const ahbHz = sysclkHz;
74
+ const apb1Hz = ahbHz / apb1Div;
75
+ const apb2Hz = ahbHz / apb2Div;
76
+ if (sysclkHz !== spec.maxMHz * 1_000_000) {
77
+ warnings.push("内部不一致:按 HSE " + hseHz + " Hz × " + spec.hseMul + " / " + spec.hseDiv + " 算出来是 " + sysclkHz + " Hz,但 F" + line + " 的上限是 " + spec.maxMHz + " MHz;请检查 register-clock.ts 的表。");
78
+ }
79
+ if (hsiSysclkHz < sysclkHz) {
80
+ warnings.push("HSE 没起(常见原因:板上没焊 8 MHz 晶振)时会退回 HSI/2 × " + hsiMul + " = " + Math.round(hsiSysclkHz / 1e6) + " MHz,比 " + Math.round(sysclkHz / 1e6) + " MHz 慢;生成的 clock_init() 已经带兜底,不用改代码。");
81
+ }
82
+ if (!spec.hasFlashLatency) {
83
+ warnings.push("F" + line + " 的 FLASH_ACR 只有 HLFCYA、没有 LATENCY/PRFTBE 字段,生成的 clock_init() 不写 FLASH->ACR(该 line 的 SYSCLK 上限本来就不需要等待周期)。");
84
+ }
85
+ const summary = Math.round(sysclkHz / 1e6) + " MHz(HSE " + Math.round(hseHz / 1e6) + " MHz"
86
+ + (spec.hseDiv === 2 ? " / 2" : "") + " × " + spec.hseMul + ";AHB /" + 1 + "、APB1 /" + apb1Div
87
+ + " = " + Math.round(apb1Hz / 1e6) + " MHz、APB2 /" + apb2Div + " = " + Math.round(apb2Hz / 1e6) + " MHz"
88
+ + (spec.hasFlashLatency ? ";Flash " + flashLatency + " 等待周期" : "") + ")";
89
+ return {
90
+ mcu: chip.cpn,
91
+ line,
92
+ hseHz,
93
+ sysclkHz,
94
+ pllMul: spec.hseMul,
95
+ hseDiv: spec.hseDiv,
96
+ hsiMul,
97
+ hsiSysclkHz,
98
+ flashLatency,
99
+ hasFlashLatency: spec.hasFlashLatency,
100
+ apb1Div,
101
+ apb2Div,
102
+ ahbHz,
103
+ apb1Hz,
104
+ apb2Hz,
105
+ hsiApb1Hz: Math.round(hsiSysclkHz / apb1Div),
106
+ summary,
107
+ warnings,
108
+ };
109
+ }
110
+ /** 生成 main.c 里那一整块时钟代码(含注释、宏、clock_init)。 */
111
+ export function renderClockInit(plan) {
112
+ const lines = [];
113
+ const push = (...text) => {
114
+ for (const t of text)
115
+ lines.push(t);
116
+ };
117
+ push("/* ---------------------------------------------------------------------------", " * 时钟:" + plan.mcu + " @ " + plan.summary, " * HSE " + Math.round(plan.hseHz / 1e6) + " MHz" + (plan.hseDiv === 2 ? " / 2" : "") + " × " + plan.pllMul
118
+ + " = " + Math.round(plan.sysclkHz / 1e6) + " MHz(PLL)", " * HSE 起不来时自动退回 HSI/2 × " + plan.hsiMul + " = " + Math.round(plan.hsiSysclkHz / 1e6) + " MHz,不会卡死", " * 这段是按型号算出来的,不依赖 CubeMX 生成物;换晶振改 DSH_HSE_HZ 一个数即可", " * -------------------------------------------------------------------------*/", "#define DSH_HSE_HZ " + plan.hseHz + "u", "#define DSH_PLL_MUL " + plan.pllMul + "u", "#define DSH_HSI_MUL " + plan.hsiMul + "u", "#define DSH_SYSCLK_HZ " + plan.sysclkHz + "u", "#define DSH_APB1_DIV " + plan.apb1Div + "u");
119
+ if (plan.hseDiv === 2)
120
+ push("#define DSH_HSE_DIV 2u");
121
+ if (plan.hasFlashLatency)
122
+ push("#define DSH_FLASH_LATENCY " + plan.flashLatency + "u");
123
+ push("", "/*", " * 把 SYSCLK 从复位默认的 HSI 8 MHz 切到 PLL。" + (plan.hasFlashLatency ? "顺序不能换:先加 Flash 等待周期,再切时钟。" : ""), " * HSE 就绪用有限次自旋等(不依赖中断,也不会因为没焊晶振死在这里)。", " */", "static void clock_init(void)", "{", " uint32_t cfgr;", " uint32_t spin;", " int use_hse;", "");
124
+ if (plan.hasFlashLatency) {
125
+ push(" /* 1) Flash 等待周期:" + Math.round(plan.sysclkHz / 1e6) + " MHz 用 " + plan.flashLatency + " 个(先设再提速) */", " FLASH->ACR = FLASH_ACR_PRFTBE | (DSH_FLASH_LATENCY << FLASH_ACR_LATENCY_Pos);", "");
126
+ }
127
+ push(" /* 2) 先把 SYSCLK 切回 HSI(重复调用也安全),再动 PLL */", " cfgr = RCC->CFGR;", " cfgr = (cfgr & ~RCC_CFGR_SW_Msk) | RCC_CFGR_SW_HSI;", " RCC->CFGR = cfgr;", " spin = 0u;", " while (((RCC->CFGR & RCC_CFGR_SWS_Msk) != RCC_CFGR_SWS_HSI) && (spin < 100000u)) { spin++; }", "", " /* 3) 开 HSE 并等就绪;等不到就用 HSI/2 当 PLL 源 */", " RCC->CR |= RCC_CR_HSEON;", " spin = 0u;", " while (((RCC->CR & RCC_CR_HSERDY) == 0u) && (spin < 100000u)) { spin++; }", " use_hse = ((RCC->CR & RCC_CR_HSERDY) != 0u) ? 1 : 0;", "", " /* 4) 关 PLL 才能改 PLL 参数(RM0008 要求 PLL 关闭时改 PLLSRC/PLLMUL) */", " RCC->CR &= ~RCC_CR_PLLON;", " spin = 0u;", " while (((RCC->CR & RCC_CR_PLLRDY) != 0u) && (spin < 100000u)) { spin++; }", "", " /* 5) 组 CFGR:AHB /1、APB2 /1、APB1" + (plan.apb1Div === 2 ? " /2" : " /1") + "(F1 的 APB1 上限 36 MHz) */", " cfgr = RCC->CFGR;", " cfgr &= ~(RCC_CFGR_HPRE_Msk | RCC_CFGR_PPRE1_Msk | RCC_CFGR_PPRE2_Msk | RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL_Msk);", " cfgr |= RCC_CFGR_HPRE_DIV1 | RCC_CFGR_PPRE2_DIV1;", " cfgr |= (DSH_APB1_DIV == 2u) ? RCC_CFGR_PPRE1_DIV2 : RCC_CFGR_PPRE1_DIV1;", " if (use_hse != 0) {", " cfgr |= RCC_CFGR_PLLSRC; /* PLL 源 = HSE" + (plan.hseDiv === 2 ? "(先 /2 再进 PLL)" : "") + " */");
128
+ if (plan.hseDiv === 2)
129
+ push(" cfgr |= RCC_CFGR_PLLXTPRE;");
130
+ push(" cfgr |= ((uint32_t)(DSH_PLL_MUL - 2u) << RCC_CFGR_PLLMULL_Pos);", " } else {", " cfgr |= ((uint32_t)(DSH_HSI_MUL - 2u) << RCC_CFGR_PLLMULL_Pos); /* 0 = HSI/2 进 PLL */", " }", " RCC->CFGR = cfgr;", "", " /* 6) 开 PLL 等锁定,然后把 SYSCLK 切到 PLL 并等 SWS 确认 */", " RCC->CR |= RCC_CR_PLLON;", " spin = 0u;", " while (((RCC->CR & RCC_CR_PLLRDY) == 0u) && (spin < 100000u)) { spin++; }", " cfgr = RCC->CFGR;", " cfgr = (cfgr & ~RCC_CFGR_SW_Msk) | RCC_CFGR_SW_PLL;", " RCC->CFGR = cfgr;", " spin = 0u;", " while (((RCC->CFGR & RCC_CFGR_SWS_Msk) != RCC_CFGR_SWS_PLL) && (spin < 100000u)) { spin++; }", "", " /* 7) 让 SystemCoreClock 跟着变,delay_ms / SysTick 才是对的数 */", " SystemCoreClockUpdate();", "}", "");
131
+ return lines.join("\n");
132
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 寄存器路线的链接脚本(按芯片型号渲染一份 <DeviceId>_FLASH.ld)。
3
+ *
4
+ * 为什么必须按型号渲染:templates/scaffold/STM32F103XX_FLASH.ld 是给 F103C8T6 写的——
5
+ * MEMORY 里写死 LENGTH = 64K FLASH / 20K RAM。拿它去链 F103RBT6(128K/20K)还能跑,
6
+ * 但链 F103ZET6(512K/64K)就只用到前 64K,超出部分链接器直接报 overflow;
7
+ * 反过来链 F100C6(16K/4K)更糟:链接器以为有 64K Flash,把 .data/.bss 摆到不存在的
8
+ * 内存上,烧进去就是 HardFault。所以寄存器路线不从模板拷死脚本,而是改 MEMORY 两行。
9
+ *
10
+ * 时间/复杂度上这也是最省的做法:链接脚本是 ASCII 文本,改两行比引一个链接脚本生成器简单。
11
+ */
12
+ /**
13
+ * F100/F101/F102 的 RAM 兜底表(KB),取值来自 STM32CubeMX 的 db/mcu/*.xml:
14
+ * 同一 line+档位在 db 里是一个合并条目,<Ram> 取的是该组内最小封装的值。
15
+ * 为什么用最小值:链接脚本把 RAM 写小只会"少用",写大才会把栈顶伸到不存在的空间;
16
+ * 所以兜底宁可小,同时往 report 里写一条 warning 让用户去确认。
17
+ * (F103/F105/F107 用 stm32f1.ts 里已核对的 RAM_BY_LINE_LETTER,不走这张表。)
18
+ */
19
+ const RAM_FALLBACK_KB = {
20
+ "100x6": 4,
21
+ "100xb": 8,
22
+ "100xe": 24,
23
+ "101x6": 4,
24
+ "101xb": 10,
25
+ "101xe": 32,
26
+ "101xg": 80,
27
+ "102x6": 4,
28
+ "102xb": 10,
29
+ "103x6": 6,
30
+ "103xb": 20,
31
+ "103xe": 48,
32
+ "103xg": 96,
33
+ "105xc": 64,
34
+ "107xc": 64,
35
+ };
36
+ /** line 代号:STM32F103 → 103。 */
37
+ function lineOf(chip) {
38
+ return chip.prefix.slice(6);
39
+ }
40
+ /**
41
+ * ST 的器件代号:完整型号去掉温度/封装尾号换成 x(STM32F103C8T6 → STM32F103C8Tx),
42
+ * 只给容量档的写法(F103)用 STM32F103xB 这种"档位代号"。
43
+ * 为什么要凑出这个名字:CubeMX 生成工程里链接脚本就叫 <DeviceId>_FLASH.ld,
44
+ * 沿用同一约定,用户从 HAL 工程切过来时一眼认得出这是哪颗芯片的脚本。
45
+ */
46
+ export function deviceIdFor(chip) {
47
+ const cpn = chip.cpn.toUpperCase();
48
+ if (/^STM32F\d{3}[A-Z][0-9A-G]/u.test(cpn) && cpn.length >= 11) {
49
+ if (/[67]$/u.test(cpn) && cpn.length >= 12)
50
+ return cpn.slice(0, -1) + "x";
51
+ if (/^STM32F\d{3}[A-Z][0-9A-G]$/u.test(cpn))
52
+ return cpn + "Tx";
53
+ return cpn.slice(0, -1) + "x";
54
+ }
55
+ return chip.prefix + "x" + chip.group.slice(1).toUpperCase();
56
+ }
57
+ function kbOf(bytes) {
58
+ return Math.round(bytes / 1024);
59
+ }
60
+ /** 给一颗芯片算链接脚本参数(只读、纯函数)。 */
61
+ export function planRegisterLinker(chip) {
62
+ const warnings = [];
63
+ const line = lineOf(chip);
64
+ const key = chip.prefix.slice(6) + chip.group;
65
+ const deviceId = deviceIdFor(chip);
66
+ const flashBytes = chip.flashBytes ?? 0;
67
+ if (flashBytes <= 0) {
68
+ warnings.push("这颗芯片的 Flash 大小没收录(stm32f1.ts 的 FLASH_BY_LETTER 里查不到档位 " + chip.group + "),链接脚本按 64K 生成;确认后请补表。");
69
+ }
70
+ const exactRam = chip.ramBytes ?? null;
71
+ const fallbackKb = RAM_FALLBACK_KB[key];
72
+ const ramBytes = exactRam !== null ? exactRam : (fallbackKb ?? 20) * 1024;
73
+ if (exactRam === null && fallbackKb === undefined) {
74
+ warnings.push("F" + line + " 的档位 " + chip.group + " 的 RAM 大小没收录,链接脚本按 20K 兜底;确认后请补 stm32f1.ts 的 RAM_BY_LINE_LETTER 或 register-linker.ts 的 RAM_FALLBACK_KB。");
75
+ }
76
+ else if (exactRam === null) {
77
+ warnings.push("F" + line + " 的档位 " + chip.group + " 的 RAM 没收录在 stm32f1.ts 里,链接脚本按 CubeMX db 的最小值 " + kbOf(ramBytes) + "K 生成(宁可小,栈不会越界);封装更大时可以把 LENGTH 改大。");
78
+ }
79
+ if (ramBytes > 0 && ramBytes <= 8 * 1024) {
80
+ warnings.push("这颗芯片只有 " + kbOf(ramBytes) + "K RAM,链接脚本仍保留默认的 1K 栈 + 512B 堆(_Min_Stack_Size/_Min_Heap_Size),紧张时请调小。");
81
+ }
82
+ const flashKb = flashBytes > 0 ? kbOf(flashBytes) : 64;
83
+ const ramKb = kbOf(ramBytes);
84
+ return {
85
+ mcu: chip.cpn,
86
+ deviceId,
87
+ fileName: deviceId + "_FLASH.ld",
88
+ flashBytes: flashKb * 1024,
89
+ ramBytes: ramBytes,
90
+ ramExact: exactRam !== null,
91
+ summary: flashKb + "K FLASH + " + ramKb + "K RAM",
92
+ warnings,
93
+ };
94
+ }
95
+ /**
96
+ * 把模板链接脚本里写死 C8T6 的四处改掉:
97
+ * 注释 :9 "Linker script for STM32F103C8Tx series"
98
+ * 注释 :10 "64Kbytes FLASH and 20Kbytes RAM"
99
+ * MEMORY :58 RAM LENGTH = 20K
100
+ * MEMORY :59 FLASH LENGTH = 64K
101
+ * 任何一处找不到(模板被人改过)就返回 null,让调用方明确报错,而不是生成一个尺寸错的脚本。
102
+ */
103
+ export function renderLinkerScript(plan, template) {
104
+ const flashKb = kbOf(plan.flashBytes);
105
+ const ramKb = kbOf(plan.ramBytes);
106
+ let text = template;
107
+ let patched = 0;
108
+ const commentTitle = /^(\*\*\s+Abstract\s+:\s+Linker script for ).*$/mu;
109
+ if (commentTitle.test(text)) {
110
+ text = text.replace(commentTitle, "$1" + plan.deviceId + " series");
111
+ patched++;
112
+ }
113
+ const commentSizes = /^(\*\*\s+)([0-9]+Kbytes FLASH and [0-9]+Kbytes RAM)\s*$/mu;
114
+ if (commentSizes.test(text)) {
115
+ text = text.replace(commentSizes, "$1" + flashKb + "Kbytes FLASH and " + ramKb + "Kbytes RAM");
116
+ patched++;
117
+ }
118
+ const ramLine = /^([ \t]*RAM \(xrw\)[ \t]*:[ \t]*ORIGIN = 0x20000000, LENGTH = )[0-9]+[KM][ \t]*$/mu;
119
+ if (ramLine.test(text)) {
120
+ text = text.replace(ramLine, "$1" + ramKb + "K");
121
+ patched++;
122
+ }
123
+ const flashLine = /^([ \t]*FLASH \(rx\)[ \t]*:[ \t]*ORIGIN = 0x8000000, LENGTH = )[0-9]+[KM][ \t]*$/mu;
124
+ if (flashLine.test(text)) {
125
+ text = text.replace(flashLine, "$1" + flashKb + "K");
126
+ patched++;
127
+ }
128
+ return patched === 4 ? text : null;
129
+ }
@@ -13,8 +13,10 @@ import fs from "node:fs";
13
13
  import path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { CMSIS_FAMILIES, cmsisTemplatePlan, startupChoiceFor } from "../data/cmsis-sources.js";
16
- import { cacheRootInfo, checkCacheEntry, findCacheEntry, readCacheIndex, sha256OfFile, upsertCacheEntry } from "./cache.js";
16
+ import { cacheRootInfo, checkCacheEntry, readCacheIndex, resolveCacheEntry, sha256OfFile, upsertCacheEntry } from "./cache.js";
17
17
  import { fetchAll } from "./fetch.js";
18
+ import { planRegisterClock, renderClockInit } from "./register-clock.js";
19
+ import { planRegisterLinker, renderLinkerScript } from "./register-linker.js";
18
20
  import { backupBeforeOverwrite, backupWarning, cleanupAfterFailure, mkdirTracked, preflightTarget, templateDir } from "./scaffold.js";
19
21
  /** 寄存器版模板目录:lib/engine/register-template.js → ../../templates/register。 */
20
22
  export function registerTemplateDir() {
@@ -58,7 +60,9 @@ export async function ensureCmsisTemplate(request = {}) {
58
60
  const { index, error: indexError } = readCacheIndex(env);
59
61
  if (indexError !== null)
60
62
  request.onProgress?.(indexError);
61
- const existing = findCacheEntry(index, "cmsis", plan.id);
63
+ // 用别名解析而不是精确匹配:0.1 建过的 cmsis:F1:startup_stm32f103xb 条目内容完全一样,
64
+ // 认不出就会白下一遍 14 个文件(还可能在慢网里失败)。
65
+ const existing = resolveCacheEntry(index, plan.id);
62
66
  if (existing !== null) {
63
67
  const health = checkCacheEntry(existing);
64
68
  if (health.ok) {
@@ -103,7 +107,10 @@ export async function ensureCmsisTemplate(request = {}) {
103
107
  options.fetchImpl = request.fetchImpl;
104
108
  if (request.signal !== undefined)
105
109
  options.signal = request.signal;
106
- const fetched = await fetchAll(plan.targets, entryDir, options);
110
+ const targets = request.hashes === undefined
111
+ ? plan.targets
112
+ : plan.targets.map((target) => ({ ...target, sha256: request.hashes?.[target.path] }));
113
+ const fetched = await fetchAll(targets, entryDir, options);
107
114
  if (fetched.failed > 0) {
108
115
  const failures = fetched.results.filter((item) => !item.ok).slice(0, 3).map((item) => item.path + ":" + item.error);
109
116
  const failedResults = fetched.results.filter((item) => !item.ok);
@@ -202,8 +209,16 @@ export async function ensureCmsisTemplate(request = {}) {
202
209
  message: "已下载 " + String(files.length) + " 个模板文件到缓存(" + entryDir + "),下次直接用。",
203
210
  };
204
211
  }
205
- /** 从 HAL 骨架模板里借来的**与 HAL 无关**的文件(工具链、presets、链接脚本、.gitignore)。 */
206
- const SHARED_TEMPLATE_FILES = ["CMakePresets.json", ".gitignore", "STM32F103XX_FLASH.ld", "cmake/gcc-arm-none-eabi.cmake"];
212
+ /**
213
+ * 从 HAL 骨架模板里借来的**与 HAL 无关**的文件(工具链、presets、.gitignore)。
214
+ *
215
+ * 链接脚本不在这张表里:它是寄存器路线里唯一必须按型号改的模板(ST 那份写死
216
+ * 64K FLASH / 20K RAM),所以从 HAL 骨架读原文本、改 MEMORY 两行、另存为
217
+ * <DeviceId>_FLASH.ld(见 register-linker.ts)。拷贝数不变,工程文件总数还是 7 个。
218
+ */
219
+ const SHARED_TEMPLATE_FILES = ["CMakePresets.json", ".gitignore", "cmake/gcc-arm-none-eabi.cmake", "openocd.cfg"];
220
+ /** 链接脚本的"源模板"(HAL 骨架里那份,按型号渲染后另存)。 */
221
+ const LINKER_TEMPLATE_FILE = "STM32F103XX_FLASH.ld";
207
222
  function countFiles(root) {
208
223
  let count = 0;
209
224
  const walk = (dir) => {
@@ -236,6 +251,12 @@ export async function createRegisterProject(request) {
236
251
  family: "",
237
252
  startup: "",
238
253
  deviceDefine: "",
254
+ deviceId: "",
255
+ linkerScript: "",
256
+ flashBytes: 0,
257
+ ramBytes: 0,
258
+ sysclkHz: 0,
259
+ clockSummary: "",
239
260
  cacheRoot: cacheRootInfo(request.env ?? process.env).root,
240
261
  cacheHit: false,
241
262
  templateFiles: 0,
@@ -260,6 +281,7 @@ export async function createRegisterProject(request) {
260
281
  ...(request.family === undefined ? {} : { family: request.family }),
261
282
  ...(request.env === undefined ? {} : { env: request.env }),
262
283
  ...(request.fetchImpl === undefined ? {} : { fetchImpl: request.fetchImpl }),
284
+ ...(request.hashes === undefined ? {} : { hashes: request.hashes }),
263
285
  ...(request.signal === undefined ? {} : { signal: request.signal }),
264
286
  ...(request.onProgress === undefined ? {} : { onProgress: request.onProgress }),
265
287
  ...(request.download === undefined ? {} : { download: request.download }),
@@ -269,6 +291,13 @@ export async function createRegisterProject(request) {
269
291
  const choice = resolveStartupChoice({ ...(request.mcu === undefined ? {} : { mcu: request.mcu }), ...(request.family === undefined ? {} : { family: request.family }) });
270
292
  if (choice === null || cmsisTemplatePlan(choice) === null)
271
293
  return fail("内部错误:缓存条目对应的下载清单没了(" + template.family + ")。");
294
+ const chip = choice.chip;
295
+ if (chip === undefined)
296
+ return fail("内部错误:缓存条目没带回芯片信息(" + template.family + ")。");
297
+ // 链接脚本与时钟初始化都按型号现算:寄存器路线没有 CubeMX 替我们算这两样,
298
+ // 写死 C8T6 的 64K/20K 与 8 MHz HSI 会让 F103ZE / F100C6 这类芯片要么链不下、要么跑得莫名其妙。
299
+ const linker = planRegisterLinker(chip);
300
+ const clock = planRegisterClock(chip);
272
301
  const spec = CMSIS_FAMILIES[template.family];
273
302
  if (spec === undefined)
274
303
  return fail("内部错误:这一代没有设备头规格(" + template.family + ")。");
@@ -279,33 +308,49 @@ export async function createRegisterProject(request) {
279
308
  return fail("插件模板目录缺失:" + regTpl + "(重新安装插件)");
280
309
  // 要读的模板文件、要拷的 Drivers,全部在**写盘之前**检查一遍:
281
310
  // 半路才发现插件包缺文件,留下的就是一个比没有更糟的半成品工程。
282
- const sourcesToCheck = [
311
+ // 例外:.gitignore 不在检查列表里——npm 打包永远排除点文件(.gitignore 同时是它的
312
+ // 忽略过滤器),npm 安装的用户模板里必然没有它;缺它只影响 git 状态观感,工程照建。
313
+ const missingOptional = [];
314
+ // 全量预检(0b):把所有缺失的必需文件一次列完,别让用户修一个跑一次再撞下一个。
315
+ const required = [
283
316
  path.join(regTpl, "CMakeLists.txt"),
284
317
  path.join(regTpl, "Core", "Src", "main.c"),
285
- ...SHARED_TEMPLATE_FILES.map((rel) => path.join(halTpl, rel)),
318
+ // 链接脚本模板:按型号渲染的那份是从它改出来的,缺了就只能建 C8T6 尺寸的工程
319
+ path.join(halTpl, LINKER_TEMPLATE_FILE),
320
+ ...SHARED_TEMPLATE_FILES.filter((rel) => rel !== ".gitignore").map((rel) => path.join(halTpl, rel)),
286
321
  ];
287
- for (const source of sourcesToCheck) {
288
- if (!fs.existsSync(source))
289
- return fail("插件模板缺文件:" + source + "(重新安装插件)");
322
+ const missingRequired = required.filter((source) => !fs.existsSync(source));
323
+ if (missingRequired.length > 0) {
324
+ const list = missingRequired.map((source) => " · " + source).join("\n");
325
+ return fail("插件模板缺 " + String(missingRequired.length) + " 个文件(一次列完):\n" + list +
326
+ "\n这是插件包损坏(安装中断或目录被杀毒软件动过),不是工程或配置的问题;" +
327
+ "带插件版本号(见 package.json)反馈最有效。");
290
328
  }
329
+ if (!fs.existsSync(path.join(halTpl, ".gitignore")))
330
+ missingOptional.push(".gitignore");
291
331
  const driversSrc = path.join(template.entryDir, "Drivers");
292
332
  if (!fs.existsSync(driversSrc))
293
333
  return fail("缓存的模板目录不完整(缺 Drivers):" + template.entryDir + "。删掉它再试一次会重新下载。");
294
334
  // 覆盖前先备份将被覆盖的同名文件;备份失败就一个字节都不写(否则用户的 main.c 就没了)。
295
335
  let backup;
296
336
  try {
297
- backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", ...SHARED_TEMPLATE_FILES], "register");
337
+ backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", linker.fileName, ...SHARED_TEMPLATE_FILES], "register");
298
338
  }
299
339
  catch (error) {
300
340
  return fail("没写任何文件:覆盖前的备份失败(" + String(error.message) + ")。目标目录 " + targetDir + " 未被改动。");
301
341
  }
302
342
  const backupNote = backupWarning(backup);
303
- // 1) 寄存器版 CMakeLists:替换四个占位符
343
+ // 1) 寄存器版 CMakeLists / main.c:替换七个占位符
344
+ const chipBanner = (chip.cpn.toUpperCase().startsWith("STM32") ? chip.cpn : "STM32F" + clock.line + "(" + chip.group + " 档)")
345
+ + " · " + linker.summary + " · SYSCLK " + String(Math.round(clock.sysclkHz / 1e6)) + " MHz";
304
346
  const replacements = {
305
347
  __PROJECT_NAME__: projectName,
306
348
  __FAMILY_DIR__: familyDir,
307
349
  __STARTUP_FILE__: template.startup,
308
350
  __DEVICE_DEFINE__: template.deviceDefine,
351
+ __LINKER_SCRIPT__: linker.fileName,
352
+ __MCU_BANNER__: chipBanner,
353
+ __CLOCK_INIT__: renderClockInit(clock),
309
354
  };
310
355
  const fill = (text) => {
311
356
  let out = text;
@@ -313,6 +358,13 @@ export async function createRegisterProject(request) {
313
358
  out = out.split(key).join(value);
314
359
  return out;
315
360
  };
361
+ // 链接脚本先渲染(纯字符串替换):模板被人改过导致四处标记缺一处时,要在写盘之前就拒绝,
362
+ // 而不是生成一个 RAM/Flash 尺寸错的工程——那种工程能编译、烧进去才崩。
363
+ const linkerText = renderLinkerScript(linker, fs.readFileSync(path.join(halTpl, LINKER_TEMPLATE_FILE), "utf8"));
364
+ if (linkerText === null) {
365
+ return fail("链接脚本模板里没找到该改的四处(MEMORY 的 RAM/FLASH 两行 + 注释两行):" + path.join(halTpl, LINKER_TEMPLATE_FILE) +
366
+ "。这是插件模板被改坏,不是工程问题;带插件版本号反馈最有效。一个字节都没写。");
367
+ }
316
368
  const targetExistedBefore = fs.existsSync(targetDir);
317
369
  const driversExistedBefore = fs.existsSync(path.join(targetDir, "Drivers"));
318
370
  const createdDirs = [];
@@ -322,16 +374,21 @@ export async function createRegisterProject(request) {
322
374
  mkdirTracked(path.join(targetDir, "Core", "Inc"), createdDirs);
323
375
  // 1) CMakeLists.txt
324
376
  fs.writeFileSync(path.join(targetDir, "CMakeLists.txt"), fill(fs.readFileSync(path.join(regTpl, "CMakeLists.txt"), "utf8")), "utf8");
325
- // 2) 寄存器版 main.c(PC13 蓝丸示例,无占位符)
326
- fs.writeFileSync(path.join(targetDir, "Core", "Src", "main.c"), fs.readFileSync(path.join(regTpl, "Core", "Src", "main.c"), "utf8"), "utf8");
327
- // 3) 与 HAL 无关的公共文件:工具链 / presets / 链接脚本 / .gitignore
377
+ // 2) 寄存器版 main.c:芯片注释 + 按型号生成的 clock_init()
378
+ fs.writeFileSync(path.join(targetDir, "Core", "Src", "main.c"), fill(fs.readFileSync(path.join(regTpl, "Core", "Src", "main.c"), "utf8")), "utf8");
379
+ // 3) 与 HAL 无关的公共文件:工具链 / presets(.gitignore 缺失时跳过,见上面 missingOptional)
328
380
  for (const rel of SHARED_TEMPLATE_FILES) {
381
+ if (rel === ".gitignore" && missingOptional.includes(rel))
382
+ continue;
329
383
  const dest = path.join(targetDir, rel);
330
384
  mkdirTracked(path.dirname(dest), createdDirs);
331
385
  fs.copyFileSync(path.join(halTpl, rel), dest);
332
386
  templateFiles += 1;
333
387
  }
334
- // 4) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
388
+ // 4) 按型号渲染的链接脚本:MEMORY 两行 + 注释两行换成本芯片的真实 Flash/RAM
389
+ fs.writeFileSync(path.join(targetDir, linker.fileName), linkerText, "utf8");
390
+ templateFiles += 1;
391
+ // 5) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
335
392
  fs.cpSync(driversSrc, path.join(targetDir, "Drivers"), { recursive: true });
336
393
  }
337
394
  catch (error) {
@@ -349,10 +406,17 @@ export async function createRegisterProject(request) {
349
406
  }
350
407
  const driverFiles = countFiles(path.join(targetDir, "Drivers"));
351
408
  const warnings = [];
409
+ if (missingOptional.includes(".gitignore")) {
410
+ warnings.push("插件包里没有 .gitignore(npm 打包会排除它):工程功能不受影响,只是 git 状态会多出 build/ 目录。" +
411
+ "想干净就在工程根目录建一个 .gitignore,内容一行:build/");
412
+ }
352
413
  // 备份清单放第一条:用户看到"覆盖成功"时,第一眼得知道旧文件去哪了。
353
414
  if (backupNote !== null)
354
415
  warnings.push(backupNote);
355
- warnings.push("模板里的 LED 是蓝丸的 PC13;换板子改 Core/Src/main.c 顶部的 LED_PORT / LED_PIN。", "寄存器版没有 .ioc:不需要 CubeMX,也不需要固件包;要换成 HAL 版就用 stm32_project_create route=hal。");
416
+ warnings.push("模板里的 LED 是蓝丸的 PC13;换板子改 Core/Src/main.c 顶部的 LED_PORT / LED_PIN。", "寄存器版没有 .ioc:不需要 CubeMX,也不需要固件包;要换成 HAL 版就用 stm32_project_create route=hal。", "链接脚本已按型号渲染:" + linker.fileName + "(" + linker.summary + "),拷自 templates/scaffold/" + LINKER_TEMPLATE_FILE + "。", "时钟在 main.c 的 clock_init() 里现配:" + clock.summary + "(HSE 不起振就自动退回 HSI/2 ×" + String(clock.hsiMul) + ")。");
417
+ // 链接脚本/时钟的告警来自按型号推导本身(RAM 用了保守下限、F100 没有延迟位、HSI 到不了上限…),
418
+ // 用户需要知道"为什么是 64 MHz 而不是 72"。
419
+ warnings.push(...linker.warnings, ...clock.warnings);
356
420
  if (template.cacheHit)
357
421
  warnings.push("这次用的是缓存模板(" + template.entryDir + "),没有联网。");
358
422
  else
@@ -366,6 +430,12 @@ export async function createRegisterProject(request) {
366
430
  family: template.family,
367
431
  startup: template.startup,
368
432
  deviceDefine: template.deviceDefine,
433
+ deviceId: linker.deviceId,
434
+ linkerScript: linker.fileName,
435
+ flashBytes: linker.flashBytes,
436
+ ramBytes: linker.ramBytes,
437
+ sysclkHz: clock.sysclkHz,
438
+ clockSummary: clock.summary,
369
439
  cacheRoot: template.cacheRoot,
370
440
  cacheHit: template.cacheHit,
371
441
  templateFiles,
@@ -373,6 +443,7 @@ export async function createRegisterProject(request) {
373
443
  durationMs: Date.now() - startedAt,
374
444
  warnings,
375
445
  message: "寄存器版工程已建好(" + String(templateFiles) + " 个工程文件 + " + String(driverFiles) + " 个 CMSIS 文件):" + targetDir +
446
+ ";芯片 " + chipBanner +
376
447
  (backupNote === null ? "" : ";" + backupNote),
377
448
  };
378
449
  }