dsh-stm32 0.1.4 → 0.1.6

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 (38) hide show
  1. package/README.md +517 -459
  2. package/README_EN.md +510 -453
  3. package/assets/device/h7/chips.json +831 -140
  4. package/assets/device/u5/chips.json +375 -64
  5. package/assets/manifest.json +4 -4
  6. package/docs/reading-guide.md +114 -16
  7. package/lib/commands/register.js +1 -1
  8. package/lib/data/cmsis-sources.js +136 -4
  9. package/lib/data/device-facts.js +14 -0
  10. package/lib/data/family.js +14 -14
  11. package/lib/data/firmware-packages.js +35 -14
  12. package/lib/data/firmware-pins.js +128 -0
  13. package/lib/data/search-roots.js +17 -3
  14. package/lib/data/serial-config.js +430 -0
  15. package/lib/engine/doctor.js +85 -8
  16. package/lib/engine/download.js +242 -0
  17. package/lib/engine/fetch.js +1 -1
  18. package/lib/engine/firmware-install.js +158 -35
  19. package/lib/engine/firmware-official.js +113 -65
  20. package/lib/engine/ioc-plan.js +28 -6
  21. package/lib/engine/msys2-install.js +237 -88
  22. package/lib/engine/probe.js +4 -2
  23. package/lib/engine/register-gpio.js +18 -1
  24. package/lib/engine/register-linker.js +25 -6
  25. package/lib/engine/register-template.js +25 -1
  26. package/lib/engine/serial.js +1696 -0
  27. package/lib/engine/tar.js +235 -3
  28. package/lib/index.js +12 -0
  29. package/lib/skill/stm32-workflow.js +2 -2
  30. package/lib/tools/assets.js +8 -3
  31. package/lib/tools/build.js +0 -1
  32. package/lib/tools/doctor.js +9 -3
  33. package/lib/tools/download.js +303 -0
  34. package/lib/tools/ioc-plan.js +17 -7
  35. package/lib/tools/project-create.js +1 -1
  36. package/lib/tools/serial.js +737 -0
  37. package/package.json +70 -70
  38. package/templates/serial/bridge.ps1 +477 -0
@@ -0,0 +1,430 @@
1
+ /**
2
+ * 串口配置与「端口记忆」(数据层):%USERPROFILE%/.dsh-stm32/serial.json
3
+ *
4
+ * 为什么不塞进 config.json:那份记的是「这台机器把工具装在哪」,是安装器写的、变一次要重装;
5
+ * 这份记的是「这块板子上次用什么参数通的」,每 open 一次就可能写一次。读写频率差两个数量级,
6
+ * 混在一起会让安装配置跟着串口一起坏——这份坏了大不了丢记忆,不该连累工具链配置。
7
+ *
8
+ * 记忆的单位是 **USB 身份,不是 COM 号**:同一块板子换个 USB 口,Windows 会新分一个 COM 号
9
+ * (COM5 → COM7),按 COM 号记等于每次都要重设波特率。身份按可靠度分三档:
10
+ * usb:<VID>:<PID>:<序列号> —— 最可靠(每块板子唯一,换口换机器都认得出)
11
+ * usb:<VID>:<PID>@<位置> —— 芯片没烧序列号(CH340 常见),退一步按 USB 端口路径区分
12
+ * com:<COMx> —— 不是 USB(板载 UART / 蓝牙串口),只能按名字记
13
+ * 三档都由 portIdentity() 一处决定,engine 与本文件不各写一套。
14
+ *
15
+ * 环境变量:
16
+ * DSH_STM32_SERIAL_CONFIG 整体改指配置文件(单测与多工程隔离用;相对路径按主目录解析)
17
+ * DSH_STM32_NO_CONFIG=1 让读配置的地方当它不存在(与 config.json 同一套开关语义)
18
+ */
19
+ import { randomBytes } from "node:crypto";
20
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { dirname, isAbsolute } from "node:path";
23
+ export const SERIAL_CONFIG_VERSION = 1;
24
+ /** 最多记多少个端口;超了按最后使用时间淘汰最旧的(USB 口多的机器不至于无限长)。 */
25
+ export const MAX_REMEMBERED_PORTS = 32;
26
+ /** 枚举的运行时形态:工具的 schema enum 与校验都从这里取,避免第二个真相。 */
27
+ export const SERIAL_PARITIES = ["none", "odd", "even", "mark", "space"];
28
+ export const SERIAL_STOP_BITS = ["1", "1.5", "2"];
29
+ export const SERIAL_FLOWS = ["none", "xonxoff", "rtscts"];
30
+ export const SERIAL_ENCODINGS = ["utf8", "ascii", "latin1"];
31
+ export const SERIAL_NEWLINES = ["crlf", "lf", "none"];
32
+ /** 缺省参数:115200 8N1、无流控、DTR/RTS 都不动、UTF-8、发 CRLF。 */
33
+ export function defaultSerialSettings() {
34
+ return {
35
+ baudRate: 115200,
36
+ dataBits: 8,
37
+ stopBits: "1",
38
+ parity: "none",
39
+ flow: "none",
40
+ dtr: false,
41
+ rts: false,
42
+ encoding: "utf8",
43
+ newline: "crlf",
44
+ };
45
+ }
46
+ export const SERIAL_BAUD_MIN = 50;
47
+ export const SERIAL_BAUD_MAX = 4_000_000;
48
+ export const SERIAL_DATA_BITS_MIN = 5;
49
+ export const SERIAL_DATA_BITS_MAX = 8;
50
+ function asString(value) {
51
+ return typeof value === "string" ? value.trim() : "";
52
+ }
53
+ /**
54
+ * DTR/RTS 只认真正的布尔值,外加 "true"/"false"/"1"/"0" 这些常见字符串写法。
55
+ * 认不出来返回 null(由调用方记一条错误)——悄悄回落到缺省值会让"我明明设了 rts"变成静默无效。
56
+ */
57
+ function asOptionalBoolean(value) {
58
+ if (typeof value === "boolean")
59
+ return value;
60
+ if (typeof value === "string") {
61
+ const text = value.trim().toLowerCase();
62
+ if (text === "true" || text === "1")
63
+ return true;
64
+ if (text === "false" || text === "0")
65
+ return false;
66
+ }
67
+ return null;
68
+ }
69
+ function asInteger(value) {
70
+ if (typeof value === "number" && Number.isInteger(value))
71
+ return value;
72
+ if (typeof value === "string" && /^\d+$/u.test(value.trim()))
73
+ return Number.parseInt(value.trim(), 10);
74
+ return null;
75
+ }
76
+ function oneOf(value, allowed) {
77
+ const text = asString(value).toLowerCase();
78
+ if (text === "")
79
+ return null;
80
+ return allowed.includes(text) ? text : null;
81
+ }
82
+ /**
83
+ * 把任意 JSON / 工具参数归一成合法参数:非法的字段按缺省值处理并记一条 errors。
84
+ * 不抛异常——参数写错要能变成 settings-invalid 的一次报告,而不是把调用方打崩。
85
+ */
86
+ export function normalizeSerialSettings(raw, errors, base = defaultSerialSettings()) {
87
+ const out = { ...base };
88
+ if (raw === null || raw === undefined)
89
+ return out;
90
+ if (typeof raw !== "object") {
91
+ errors.push("串口参数不是对象,已按缺省值处理");
92
+ return out;
93
+ }
94
+ const record = raw;
95
+ const baud = asInteger(record["baudRate"]);
96
+ if (baud !== null) {
97
+ if (baud < SERIAL_BAUD_MIN || baud > SERIAL_BAUD_MAX) {
98
+ errors.push("baudRate 超出范围(" + String(SERIAL_BAUD_MIN) + "…" + String(SERIAL_BAUD_MAX) + "):" + String(baud));
99
+ }
100
+ else {
101
+ out.baudRate = baud;
102
+ }
103
+ }
104
+ else if (record["baudRate"] !== undefined) {
105
+ errors.push("baudRate 不是整数");
106
+ }
107
+ const bits = asInteger(record["dataBits"]);
108
+ if (bits !== null) {
109
+ if (bits < SERIAL_DATA_BITS_MIN || bits > SERIAL_DATA_BITS_MAX) {
110
+ errors.push("dataBits 只能是 5…8:" + String(bits));
111
+ }
112
+ else {
113
+ out.dataBits = bits;
114
+ }
115
+ }
116
+ else if (record["dataBits"] !== undefined) {
117
+ errors.push("dataBits 不是整数");
118
+ }
119
+ const stop = oneOf(record["stopBits"], SERIAL_STOP_BITS);
120
+ if (stop !== null)
121
+ out.stopBits = stop;
122
+ else if (record["stopBits"] !== undefined && asString(record["stopBits"]) !== "")
123
+ errors.push("stopBits 只能是 1 / 1.5 / 2");
124
+ const parity = oneOf(record["parity"], SERIAL_PARITIES);
125
+ if (parity !== null)
126
+ out.parity = parity;
127
+ else if (record["parity"] !== undefined && asString(record["parity"]) !== "")
128
+ errors.push("parity 只能是 none / odd / even / mark / space");
129
+ const flow = oneOf(record["flow"], SERIAL_FLOWS);
130
+ if (flow !== null)
131
+ out.flow = flow;
132
+ else if (record["flow"] !== undefined && asString(record["flow"]) !== "")
133
+ errors.push("flow 只能是 none / xonxoff / rtscts");
134
+ const encoding = oneOf(record["encoding"], SERIAL_ENCODINGS);
135
+ if (encoding !== null)
136
+ out.encoding = encoding;
137
+ else if (record["encoding"] !== undefined && asString(record["encoding"]) !== "")
138
+ errors.push("encoding 只能是 utf8 / ascii / latin1");
139
+ const newline = oneOf(record["newline"], SERIAL_NEWLINES);
140
+ if (newline !== null)
141
+ out.newline = newline;
142
+ else if (record["newline"] !== undefined && asString(record["newline"]) !== "")
143
+ errors.push("newline 只能是 crlf / lf / none");
144
+ const dtr = asOptionalBoolean(record["dtr"]);
145
+ if (dtr !== null)
146
+ out.dtr = dtr;
147
+ else if (record["dtr"] !== undefined)
148
+ errors.push("dtr 只能是 true / false");
149
+ const rts = asOptionalBoolean(record["rts"]);
150
+ if (rts !== null)
151
+ out.rts = rts;
152
+ else if (record["rts"] !== undefined)
153
+ errors.push("rts 只能是 true / false");
154
+ return out;
155
+ }
156
+ /** 参数是否与缺省值一致(报告里用来提示「这次哪些参数是默认的」)。 */
157
+ export function settingsAreDefault(settings) {
158
+ const base = defaultSerialSettings();
159
+ return Object.keys(base).every((key) => settings[key] === base[key]);
160
+ }
161
+ function text(value) {
162
+ return typeof value === "string" ? value.trim() : "";
163
+ }
164
+ /** Windows 用总线路径当序列号时的形状:5&2c1a4b3&0&1;这种值换个口就变,不能当身份。 */
165
+ function isBusPathId(value) {
166
+ return /^\d+&/u.test(value);
167
+ }
168
+ /**
169
+ * 端口身份:三档按可靠度选第一档可用的。
170
+ * 纯函数(只依赖 facts),engine 与配置层共用同一份判断,别各写一套。
171
+ */
172
+ export function portIdentity(facts) {
173
+ // 字段声明成 string,但调用方可能是「手工改过的 serial.json / 老版本记录」,
174
+ // 缺字段时按空串处理,别让一个半截配置把整条打开流程打崩。
175
+ const vid = text(facts.vid).toUpperCase();
176
+ const pid = text(facts.pid).toUpperCase();
177
+ const serial = text(facts.serialNumber);
178
+ const location = text(facts.location);
179
+ if (vid !== "" && pid !== "") {
180
+ if (serial !== "" && !isBusPathId(serial))
181
+ return "usb:" + vid + ":" + pid + ":" + serial;
182
+ if (location !== "")
183
+ return "usb:" + vid + ":" + pid + "@" + location;
184
+ if (serial !== "")
185
+ return "usb:" + vid + ":" + pid + "@" + serial;
186
+ return "usb:" + vid + ":" + pid;
187
+ }
188
+ return "com:" + text(facts.port).toUpperCase();
189
+ }
190
+ /** 身份的可读形态(报告里给人看:usb:0483:5740@1-3.4 这种比一段 JSON 好认)。 */
191
+ export function describeIdentity(identity) {
192
+ if (identity.startsWith("usb:"))
193
+ return "USB " + identity.slice(4);
194
+ if (identity.startsWith("com:"))
195
+ return "端口名 " + identity.slice(4);
196
+ return identity;
197
+ }
198
+ let cache = null;
199
+ function envValue(env, key) {
200
+ const value = env[key];
201
+ return value === undefined ? "" : value.trim();
202
+ }
203
+ function homeDir(env) {
204
+ const userProfile = envValue(env, "USERPROFILE");
205
+ if (userProfile !== "")
206
+ return userProfile;
207
+ const home = envValue(env, "HOME");
208
+ if (home !== "")
209
+ return home;
210
+ return homedir();
211
+ }
212
+ function toPosix(value) {
213
+ return value.replace(/\\/gu, "/").replace(/\/+$/u, "");
214
+ }
215
+ /** 配置文件路径:DSH_STM32_SERIAL_CONFIG 优先(相对路径按主目录解析)。 */
216
+ export function serialConfigPath(env = process.env) {
217
+ const override = envValue(env, "DSH_STM32_SERIAL_CONFIG");
218
+ if (override !== "")
219
+ return isAbsolute(override) ? toPosix(override) : toPosix(homeDir(env) + "/" + override);
220
+ return toPosix(homeDir(env)) + "/.dsh-stm32/serial.json";
221
+ }
222
+ /** 与 config.json 共用的总开关:关掉时所有读都当「没有配置」。 */
223
+ export function serialConfigReadingDisabled(env = process.env) {
224
+ const flag = envValue(env, "DSH_STM32_NO_CONFIG");
225
+ return flag === "1" || flag === "true";
226
+ }
227
+ export function defaultSerialConfig() {
228
+ return { version: SERIAL_CONFIG_VERSION, ports: [], updatedAt: "" };
229
+ }
230
+ function normalizeMemory(raw, errors, index) {
231
+ if (raw === null || typeof raw !== "object") {
232
+ errors.push("第 " + String(index + 1) + " 条端口记忆不是对象,已丢弃");
233
+ return null;
234
+ }
235
+ const record = raw;
236
+ const identity = asString(record["identity"]);
237
+ if (identity === "") {
238
+ errors.push("第 " + String(index + 1) + " 条端口记忆没有 identity,已丢弃");
239
+ return null;
240
+ }
241
+ return {
242
+ identity,
243
+ comPort: asString(record["comPort"]).toUpperCase(),
244
+ description: asString(record["description"]),
245
+ vid: asString(record["vid"]).toUpperCase(),
246
+ pid: asString(record["pid"]).toUpperCase(),
247
+ serialNumber: asString(record["serialNumber"]),
248
+ location: asString(record["location"]),
249
+ settings: normalizeSerialSettings(record["settings"], errors),
250
+ lastUsedAt: asString(record["lastUsedAt"]),
251
+ lastOkAt: asString(record["lastOkAt"]),
252
+ openCount: Math.max(0, asInteger(record["openCount"]) ?? 0),
253
+ };
254
+ }
255
+ /** 把任意 JSON 归一成配置:坏条目丢一条记一条,绝不让整个文件失效。 */
256
+ export function normalizeSerialConfig(raw, errors) {
257
+ if (raw === null || typeof raw !== "object") {
258
+ errors.push("配置内容不是对象,已按空配置处理");
259
+ return defaultSerialConfig();
260
+ }
261
+ const record = raw;
262
+ const list = Array.isArray(record["ports"]) ? record["ports"] : [];
263
+ if (record["ports"] !== undefined && !Array.isArray(record["ports"])) {
264
+ errors.push("ports 不是数组,已按空列表处理");
265
+ }
266
+ const ports = [];
267
+ const seen = new Set();
268
+ for (let i = 0; i < list.length; i += 1) {
269
+ const memory = normalizeMemory(list[i], errors, i);
270
+ if (memory === null)
271
+ continue;
272
+ if (seen.has(memory.identity))
273
+ continue;
274
+ seen.add(memory.identity);
275
+ ports.push(memory);
276
+ }
277
+ return {
278
+ version: typeof record["version"] === "number" ? record["version"] : SERIAL_CONFIG_VERSION,
279
+ ports,
280
+ updatedAt: asString(record["updatedAt"]),
281
+ };
282
+ }
283
+ export function readSerialConfig(env = process.env) {
284
+ const path = serialConfigPath(env);
285
+ if (serialConfigReadingDisabled(env))
286
+ return { path, exists: false, config: null, errors: [], mtimeMs: 0 };
287
+ let mtimeMs = 0;
288
+ let size = -1;
289
+ try {
290
+ const stat = statSync(path);
291
+ mtimeMs = stat.mtimeMs;
292
+ size = stat.size;
293
+ }
294
+ catch {
295
+ cache = null;
296
+ return { path, exists: false, config: null, errors: [], mtimeMs: 0 };
297
+ }
298
+ if (cache !== null && cache.path === path && cache.mtimeMs === mtimeMs && cache.size === size)
299
+ return cache.read;
300
+ let text = "";
301
+ try {
302
+ text = readFileSync(path, "utf8");
303
+ }
304
+ catch (error) {
305
+ const read = {
306
+ path,
307
+ exists: true,
308
+ config: null,
309
+ errors: ["串口配置文件读不了:" + describeError(error)],
310
+ mtimeMs,
311
+ };
312
+ cache = { path, mtimeMs, size, read };
313
+ return read;
314
+ }
315
+ const errors = [];
316
+ let parsed = null;
317
+ try {
318
+ parsed = text.trim() === "" ? null : JSON.parse(text);
319
+ }
320
+ catch (error) {
321
+ const read = {
322
+ path,
323
+ exists: true,
324
+ config: null,
325
+ errors: ["串口配置文件不是合法 JSON:" + describeError(error) + ";已按无记忆处理(重新写入会覆盖它)"],
326
+ mtimeMs,
327
+ };
328
+ cache = { path, mtimeMs, size, read };
329
+ return read;
330
+ }
331
+ const config = parsed === null ? defaultSerialConfig() : normalizeSerialConfig(parsed, errors);
332
+ const read = { path, exists: true, config, errors, mtimeMs };
333
+ cache = { path, mtimeMs, size, read };
334
+ return read;
335
+ }
336
+ function describeError(error) {
337
+ return error instanceof Error ? error.message : String(error);
338
+ }
339
+ /** 原子写:同目录 tmp + rename。半截 JSON 比没有记忆更糟(下次直接整份失效)。 */
340
+ export function writeSerialConfig(config, env = process.env) {
341
+ const path = serialConfigPath(env);
342
+ const normalized = {
343
+ version: SERIAL_CONFIG_VERSION,
344
+ ports: config.ports.slice(0, MAX_REMEMBERED_PORTS),
345
+ updatedAt: new Date().toISOString(),
346
+ };
347
+ const body = JSON.stringify(normalized, null, 2) + "\n";
348
+ const tmpPath = path + ".tmp-" + String(process.pid) + "-" + randomBytes(4).toString("hex");
349
+ try {
350
+ mkdirSync(dirname(path), { recursive: true });
351
+ writeFileSync(tmpPath, body, "utf8");
352
+ renameSync(tmpPath, path);
353
+ }
354
+ catch (error) {
355
+ try {
356
+ if (existsSync(tmpPath))
357
+ unlinkSync(tmpPath);
358
+ }
359
+ catch {
360
+ // 清理失败不影响主错误
361
+ }
362
+ cache = null;
363
+ return { ok: false, path, error: "写串口配置失败:" + describeError(error) };
364
+ }
365
+ cache = null;
366
+ return { ok: true, path, error: "" };
367
+ }
368
+ /** 按身份找记忆;不是 USB 设备时退化成按 COM 号找。 */
369
+ export function findPortMemory(config, facts) {
370
+ if (config === null)
371
+ return null;
372
+ const identity = portIdentity(facts);
373
+ return config.ports.find((memory) => memory.identity === identity) ?? null;
374
+ }
375
+ /**
376
+ * 取这块板子的历史参数。
377
+ * 记忆只是「基准」:调用方显式给的参数永远覆盖它,缺省的字段才落到历史值上。
378
+ */
379
+ export function recallPortSettings(facts, env = process.env) {
380
+ const read = readSerialConfig(env);
381
+ const memory = findPortMemory(read.config, facts);
382
+ if (memory === null) {
383
+ return { remembered: false, settings: defaultSerialSettings(), comPort: "", lastUsedAt: "", openCount: 0 };
384
+ }
385
+ return {
386
+ remembered: true,
387
+ // 老版本 / 手改过的记录里 settings 可能是半截的,这里再归一一次:
388
+ // 记忆只负责「值是多少」,合法性永远由 normalizeSerialSettings 说了算。
389
+ settings: normalizeSerialSettings(memory.settings, [], defaultSerialSettings()),
390
+ comPort: text(memory.comPort),
391
+ lastUsedAt: text(memory.lastUsedAt),
392
+ openCount: typeof memory.openCount === "number" ? memory.openCount : 0,
393
+ };
394
+ }
395
+ /**
396
+ * 打开成功后记一笔:按身份 upsert,其余条目原样保留(别人的板子不能被我们的打开挤掉)。
397
+ * 只记「这次真的通了」的参数——失败时调用方不该写,否则下次 recover 会复用一个错参数。
398
+ */
399
+ export function rememberPort(facts, settings, env = process.env) {
400
+ const identity = portIdentity(facts);
401
+ if (serialConfigReadingDisabled(env))
402
+ return { ok: false, identity, path: serialConfigPath(env), error: "配置读取被 DSH_STM32_NO_CONFIG 关掉了,没有写入" };
403
+ const read = readSerialConfig(env);
404
+ const base = read.config ?? defaultSerialConfig();
405
+ const now = new Date().toISOString();
406
+ const previous = base.ports.find((memory) => memory.identity === identity) ?? null;
407
+ const entry = {
408
+ identity,
409
+ comPort: facts.port,
410
+ description: facts.description,
411
+ vid: text(facts.vid).toUpperCase(),
412
+ pid: text(facts.pid).toUpperCase(),
413
+ serialNumber: text(facts.serialNumber),
414
+ location: text(facts.location),
415
+ settings: normalizeSerialSettings(settings, []),
416
+ lastUsedAt: now,
417
+ lastOkAt: now,
418
+ openCount: (previous?.openCount ?? 0) + 1,
419
+ };
420
+ const others = base.ports.filter((memory) => memory.identity !== identity);
421
+ const ports = [entry, ...others]
422
+ .sort((left, right) => (right.lastUsedAt > left.lastUsedAt ? 1 : right.lastUsedAt < left.lastUsedAt ? -1 : 0))
423
+ .slice(0, MAX_REMEMBERED_PORTS);
424
+ const written = writeSerialConfig({ version: SERIAL_CONFIG_VERSION, ports, updatedAt: now }, env);
425
+ return { ok: written.ok, identity, path: written.path, error: written.error };
426
+ }
427
+ /** 单测用:清掉 mtime 缓存。 */
428
+ export function resetSerialConfigCache() {
429
+ cache = null;
430
+ }
@@ -7,8 +7,9 @@
7
7
  */
8
8
  import { createConnection } from "node:net";
9
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
10
- import { join, resolve } from "node:path";
10
+ import { dirname, join, resolve } from "node:path";
11
11
  import { deriveChipPinTable, findMcuDbDir } from "../data/chips.js";
12
+ import { familyProfileOf, chooseOpenocdTarget } from "../data/family.js";
12
13
  import { describeSearchScope, discoverInstalls, discoveryDisabled, resolveSearchConfig } from "../data/search-roots.js";
13
14
  import { resolveF1Chip } from "../data/stm32f1.js";
14
15
  import { detectBuildDir, findElf } from "./build.js";
@@ -108,10 +109,15 @@ export function diagnoseUsb(pnputilText) {
108
109
  };
109
110
  }
110
111
  if ((swdProbes.length > 0 || serialBridges.length > 0) && hasDriverProblem) {
112
+ const jlink = swdProbes.some((p) => p.kind === "jlink");
111
113
  return {
112
114
  kind: "driver-error",
113
115
  probes,
114
- detail: "能看到探针/桥设备(" + (list || serialBridges.map((p) => p.label).join("、")) + ")但驱动状态异常(Problem Code 非 0):设备管理器里重装/回退驱动(CMSIS-DAP 与 ST-Link 走 WinUSB/HID 通用驱动即可)。",
116
+ detail: "能看到探针/桥设备(" + (list || serialBridges.map((p) => p.label).join("、")) + ")但驱动状态异常(Problem Code 非 0):" +
117
+ (jlink
118
+ ? "J-Link 必须装 SEGGER 的 USB 驱动(J-Link 安装器里选 USB Driver;现代探针用 WinUSB,老探针要 legacy 驱动),只装 OpenOCD 不够;"
119
+ : "") +
120
+ "设备管理器里重装/回退驱动(CMSIS-DAP 与 ST-Link 走 WinUSB/HID 通用驱动即可)。",
115
121
  };
116
122
  }
117
123
  if (swdProbes.length > 0) {
@@ -189,20 +195,56 @@ export function openocdTransportArgs(interfaceConfig) {
189
195
  export function capabilitiesOf(tools) {
190
196
  const found = new Set(tools.filter((tool) => tool.found).map((tool) => tool.id));
191
197
  const has = (id) => found.has(id);
198
+ const flashOpenocd = has("openocd");
199
+ const flashCubeProgrammer = has("cubeprogrammer");
192
200
  return {
193
201
  build: has("gcc") && has("cmake") && has("ninja"),
194
- flash: has("openocd"),
195
- debug: has("openocd") && has("gdb"),
202
+ flash: flashOpenocd || flashCubeProgrammer,
203
+ debug: flashOpenocd && has("gdb"),
196
204
  generate: has("cubemx") && has("cubemx-java"),
205
+ flashOpenocd,
206
+ flashCubeProgrammer,
207
+ debugOpenocd: flashOpenocd,
197
208
  };
198
209
  }
210
+ /**
211
+ * 检查本机 openocd 安装里有没有这族要用的 target 脚本。
212
+ *
213
+ * 不能只凭「openocd 在 PATH 里」就说能烧:xpack / 精简发行版可能只带 interface、
214
+ * 不带 target;插件内置脚本(C0/U0)也要确认模板文件真的在包里。找不到 scripts
215
+ * 根目录时返回空串(无法判断,不误报)。
216
+ */
217
+ function openocdTargetProblem(openocdPath, choice) {
218
+ if (choice.error !== "")
219
+ return choice.error;
220
+ const target = choice.targetConfig.trim();
221
+ if (target === "")
222
+ return "";
223
+ if (target.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(target)) {
224
+ return existsSync(target) ? "" : "插件内置的 openocd target 脚本不存在:" + target;
225
+ }
226
+ const base = dirname(openocdPath);
227
+ const roots = [
228
+ join(base, "..", "share", "openocd", "scripts"),
229
+ join(base, "..", "..", "share", "openocd", "scripts"),
230
+ join(base, "scripts"),
231
+ ];
232
+ const root = roots.find((candidate) => existsSync(candidate));
233
+ if (root === undefined)
234
+ return "";
235
+ return existsSync(join(root, ...target.split("/"))) ? "" : "本机 openocd 缺少 " + target;
236
+ }
199
237
  export function recommendationsOf(tools, missingRequired, capabilities) {
200
238
  const lines = [];
201
239
  const missing = tools.filter((tool) => tool.required && !tool.found);
202
240
  if (missing.length === 0) {
203
- lines.push("必需组件齐全:" + (capabilities.build ? "可以编译" : "但编译还缺组件") + "、" +
204
- (capabilities.flash ? "可以只烧录" : "烧录还缺 openocd") + "、" +
205
- (capabilities.debug ? "可以烧录并调试" : "调试还缺 gdb") + "。");
241
+ lines.push("必需组件齐全:" + (capabilities.build ? "可以编译" : "但编译还缺组件") + ";" +
242
+ (capabilities.flashOpenocd
243
+ ? "openocd 可以烧录"
244
+ : capabilities.flashCubeProgrammer
245
+ ? "只有 CubeProgrammer 可烧录(仅 ST-LINK,不能调试)"
246
+ : "烧录还缺后端(openocd 或 STM32CubeProgrammer)") + ";" +
247
+ (capabilities.debug ? "可以烧录并调试" : "调试还缺 openocd+gdb") + "。");
206
248
  }
207
249
  else {
208
250
  lines.push("缺 " + missingRequired.join("、") + "。按下面的顺序装,装一项就少一项:");
@@ -212,6 +254,27 @@ export function recommendationsOf(tools, missingRequired, capabilities) {
212
254
  }
213
255
  lines.push("需要我帮你装吗?回一句「装 gcc」「装 openocd」或「把缺的都装上」,我就照上面的命令在这台机器上装,装完再跑一次 stm32_doctor 复测;你也可以自己装完再跑一次。");
214
256
  }
257
+ // gdb/openocd 不再恒为 required(只编译的机器不该被它们拦),但缺了要明确说影响哪条腿。
258
+ const gdb = tools.find((item) => item.id === "gdb");
259
+ if (!capabilities.flashOpenocd) {
260
+ const openocd = tools.find((item) => item.id === "openocd");
261
+ if (!capabilities.flash) {
262
+ lines.push("烧录没有可用后端:openocd 与 CubeProgrammer 都没找到。只编译不受影响;要烧录至少装一个。");
263
+ if (openocd !== undefined)
264
+ lines.push("openocd:" + (openocd.install[0] ?? openocd.hint) + "(自检:" + openocd.verify + ")");
265
+ }
266
+ else {
267
+ lines.push("烧录只能走 CubeProgrammer:它只认 ST-LINK,DAPLink/J-Link 与非 ST 探针仍需 openocd。");
268
+ }
269
+ }
270
+ if (!capabilities.debug) {
271
+ if (!capabilities.flashOpenocd) {
272
+ lines.push("调试用不了:调试服务端只有 openocd,CubeProgrammer 不能替代。");
273
+ }
274
+ else if (gdb !== undefined && !gdb.found) {
275
+ lines.push("调试还缺 GDB(能烧录、不能 F5):" + (gdb.install[0] ?? gdb.hint) + "(自检:" + gdb.verify + ")");
276
+ }
277
+ }
215
278
  const cubeMx = tools.find((item) => item.id === "cubemx");
216
279
  const cubeMxJava = tools.find((item) => item.id === "cubemx-java");
217
280
  if (cubeMx !== undefined && !cubeMx.found) {
@@ -638,7 +701,21 @@ export async function runDoctor(subprocess, request) {
638
701
  notes.push("USB:" + usb.detail);
639
702
  }
640
703
  else if (usb.kind === "ok") {
641
- notes.push("USB:探针在线(CMSIS-DAP 已枚举)。");
704
+ const swd = usb.probes.filter((item) => item.kind === "st-link" || item.kind === "jlink" || item.kind === "cmsis-dap" || item.kind === "daplink");
705
+ notes.push("USB:" + (swd.length > 0 ? "探针在线:" + swd.map((item) => item.label).join("、") : usb.detail));
706
+ }
707
+ const openocdTool = tools.find((tool) => tool.id === "openocd");
708
+ const cubePrgTool = tools.find((tool) => tool.id === "cubeprogrammer");
709
+ if (iocMcu !== null && iocMcu.cpn !== "" && openocdTool !== undefined && openocdTool.found) {
710
+ const targetProblem = openocdTargetProblem(openocdTool.path, chooseOpenocdTarget(familyProfileOf(iocMcu.cpn)));
711
+ if (targetProblem !== "") {
712
+ if (cubePrgTool !== undefined && cubePrgTool.found) {
713
+ notes.push("openocd target 脚本:" + targetProblem + ";ST-LINK 可改用 CubeProgrammer 烧录,调试仍不可用。");
714
+ }
715
+ else {
716
+ blockers.push("openocd target 脚本:" + targetProblem);
717
+ }
718
+ }
642
719
  }
643
720
  if (iocPath === "")
644
721
  notes.push("工程根目录里没有 .ioc:generate/ioc_inspect 用不了");