dsh-stm32 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +567 -516
  2. package/README_EN.md +544 -510
  3. package/client/client.js +7033 -682
  4. package/docs/reading-guide.md +921 -859
  5. package/lib/client.js +7033 -682
  6. package/lib/commands/register.js +2 -0
  7. package/lib/data/firmware-packages.js +35 -0
  8. package/lib/data/firmware-pins.js +7 -0
  9. package/lib/data/install-guides.js +110 -0
  10. package/lib/data/ioc-presets.js +118 -0
  11. package/lib/engine/artifacts.js +123 -0
  12. package/lib/engine/breakpoint-hits.js +73 -0
  13. package/lib/engine/build.js +161 -5
  14. package/lib/engine/channel-tap.js +227 -0
  15. package/lib/engine/channels.js +48 -0
  16. package/lib/engine/clocks.js +192 -0
  17. package/lib/engine/datasheet/auto.js +74 -0
  18. package/lib/engine/datasheet/digest.js +74 -0
  19. package/lib/engine/datasheet/lcsc.js +60 -0
  20. package/lib/engine/datasheet/pinout.js +119 -0
  21. package/lib/engine/datasheet/price.js +152 -0
  22. package/lib/engine/datasheet/search.js +147 -0
  23. package/lib/engine/datasheet/store.js +371 -0
  24. package/lib/engine/debug-session.js +48 -2
  25. package/lib/engine/ecad/autobuild.js +156 -0
  26. package/lib/engine/ecad/bom.js +238 -0
  27. package/lib/engine/ecad/brief.js +205 -0
  28. package/lib/engine/ecad/checks.js +239 -0
  29. package/lib/engine/ecad/design.js +177 -0
  30. package/lib/engine/ecad/dfm.js +314 -0
  31. package/lib/engine/ecad/easyeda.js +454 -0
  32. package/lib/engine/ecad/fabrication.js +104 -0
  33. package/lib/engine/ecad/gen/footprint.js +159 -0
  34. package/lib/engine/ecad/gen/symbol.js +103 -0
  35. package/lib/engine/ecad/import.js +372 -0
  36. package/lib/engine/ecad/jlcpcb.js +141 -0
  37. package/lib/engine/ecad/libs.js +316 -0
  38. package/lib/engine/ecad/models3d.js +89 -0
  39. package/lib/engine/ecad/netgate.js +286 -0
  40. package/lib/engine/ecad/normalize.js +182 -0
  41. package/lib/engine/ecad/package.js +126 -0
  42. package/lib/engine/ecad/padmerge.js +128 -0
  43. package/lib/engine/ecad/padprecheck.js +123 -0
  44. package/lib/engine/ecad/part-import.js +257 -0
  45. package/lib/engine/ecad/pcb/apply.js +53 -0
  46. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  47. package/lib/engine/ecad/pcb/emc.js +275 -0
  48. package/lib/engine/ecad/pcb/geometry.js +63 -0
  49. package/lib/engine/ecad/pcb/gerber.js +499 -0
  50. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  51. package/lib/engine/ecad/pcb/impedance.js +119 -0
  52. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  53. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  54. package/lib/engine/ecad/pcb/ipc.js +129 -0
  55. package/lib/engine/ecad/pcb/krt.js +182 -0
  56. package/lib/engine/ecad/pcb/links.js +393 -0
  57. package/lib/engine/ecad/pcb/mech.js +201 -0
  58. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  59. package/lib/engine/ecad/pcb/netlist.js +146 -0
  60. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  61. package/lib/engine/ecad/pcb/placement.js +140 -0
  62. package/lib/engine/ecad/pcb/power.js +203 -0
  63. package/lib/engine/ecad/pcb/render3d.js +208 -0
  64. package/lib/engine/ecad/pcb/route.js +167 -0
  65. package/lib/engine/ecad/pcb/router.js +469 -0
  66. package/lib/engine/ecad/pcb/rules.js +122 -0
  67. package/lib/engine/ecad/pcb/scene.js +513 -0
  68. package/lib/engine/ecad/pcb/stackup.js +154 -0
  69. package/lib/engine/ecad/pcb/swap.js +222 -0
  70. package/lib/engine/ecad/pcb/tracks.js +70 -0
  71. package/lib/engine/ecad/runtime.js +227 -0
  72. package/lib/engine/ecad/toolchain.js +146 -0
  73. package/lib/engine/ecad/tsci.js +362 -0
  74. package/lib/engine/ecad/zip.js +98 -0
  75. package/lib/engine/event-bus.js +158 -0
  76. package/lib/engine/event-log.js +335 -0
  77. package/lib/engine/fault-hints.js +146 -0
  78. package/lib/engine/generate-script.js +4 -1
  79. package/lib/engine/generate.js +145 -5
  80. package/lib/engine/interrupts.js +247 -0
  81. package/lib/engine/ioc-diff.js +369 -0
  82. package/lib/engine/ioc-plan.js +12 -2
  83. package/lib/engine/ioc-sync.js +58 -0
  84. package/lib/engine/mcu-info.js +134 -0
  85. package/lib/engine/msys2-install.js +31 -6
  86. package/lib/engine/panel-actions.js +103 -0
  87. package/lib/engine/pdf/curve.js +321 -0
  88. package/lib/engine/pdf/png.js +83 -0
  89. package/lib/engine/pdf/reader.js +336 -0
  90. package/lib/engine/pdf/schematic.js +93 -0
  91. package/lib/engine/pdf/tables.js +249 -0
  92. package/lib/engine/pdf/toolchain.js +50 -0
  93. package/lib/engine/pinout.js +140 -0
  94. package/lib/engine/probe-info.js +95 -0
  95. package/lib/engine/probe.js +45 -0
  96. package/lib/engine/progress.js +99 -0
  97. package/lib/engine/project-conf.js +254 -0
  98. package/lib/engine/project-layout.js +198 -0
  99. package/lib/engine/project-repair.js +205 -0
  100. package/lib/engine/schematic/checks.js +153 -0
  101. package/lib/engine/schematic/draw.js +390 -0
  102. package/lib/engine/schematic/edit.js +229 -0
  103. package/lib/engine/schematic/kicad-sch.js +225 -0
  104. package/lib/engine/schematic/model.js +442 -0
  105. package/lib/engine/schematic/nets.js +219 -0
  106. package/lib/engine/schematic/pcb.js +144 -0
  107. package/lib/engine/schematic/review.js +134 -0
  108. package/lib/engine/schematic/sexpr.js +134 -0
  109. package/lib/engine/schematic/to-ioc.js +197 -0
  110. package/lib/engine/schematic/transform.js +25 -0
  111. package/lib/engine/session-context.js +106 -0
  112. package/lib/engine/source-slice.js +59 -0
  113. package/lib/engine/tool-events.js +119 -0
  114. package/lib/engine/toolchain-gate.js +8 -0
  115. package/lib/engine/watch-admin.js +101 -0
  116. package/lib/engine/watch-record.js +39 -0
  117. package/lib/engine/watch-recorder.js +116 -0
  118. package/lib/engine/web-api.js +1123 -4
  119. package/lib/engine/web-routes.js +18 -1
  120. package/lib/engine/workspace-memo.js +41 -0
  121. package/lib/index.js +118 -24
  122. package/lib/skill/stm32-workflow.js +1 -1
  123. package/lib/tools/build.js +10 -2
  124. package/lib/tools/code-patch.js +2 -2
  125. package/lib/tools/datasheet.js +447 -0
  126. package/lib/tools/debug-session.js +9 -4
  127. package/lib/tools/debug.js +2 -2
  128. package/lib/tools/doctor.js +2 -2
  129. package/lib/tools/ecad.js +903 -0
  130. package/lib/tools/flash.js +2 -2
  131. package/lib/tools/gen.js +166 -0
  132. package/lib/tools/generate.js +7 -5
  133. package/lib/tools/import-circuit.js +146 -0
  134. package/lib/tools/ioc-apply.js +11 -2
  135. package/lib/tools/ioc-inspect.js +2 -2
  136. package/lib/tools/ioc-plan.js +2 -2
  137. package/lib/tools/ioc-verify.js +2 -2
  138. package/lib/tools/layout.js +92 -0
  139. package/lib/tools/mcu-info.js +163 -0
  140. package/lib/tools/part-import.js +182 -0
  141. package/lib/tools/pcb.js +2316 -0
  142. package/lib/tools/pdf.js +423 -0
  143. package/lib/tools/project-create.js +28 -0
  144. package/lib/tools/project-dir.js +25 -1
  145. package/lib/tools/regs.js +2 -2
  146. package/lib/tools/route-plan.js +2 -2
  147. package/lib/tools/rtt.js +10 -2
  148. package/lib/tools/sch-draw.js +433 -0
  149. package/lib/tools/sch-edit.js +145 -0
  150. package/lib/tools/schematic.js +817 -0
  151. package/lib/tools/serial.js +22 -0
  152. package/lib/tools/watch.js +24 -2
  153. package/package.json +1 -1
@@ -5,9 +5,11 @@
5
5
  * CMakeCache 里已经记住了生成器与编译器路径,`cmake --build` 最不容易跑偏。
6
6
  * 产物路径与 CMakePresets.json 的 binaryDir 一致,这样 VS Code 的 F5 与插件看到同一个 .elf。
7
7
  */
8
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
8
+ import { existsSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
9
9
  import { join, resolve } from "node:path";
10
+ import { findChipFact } from "../data/device-facts.js";
10
11
  import { resolveSearchConfig } from "../data/search-roots.js";
12
+ import { readIocCpn } from "./breakpoints.js";
11
13
  import { runCapture, runStreaming } from "./subprocess-runner.js";
12
14
  import { resolveToolIn } from "./probe.js";
13
15
  import { envWithBinDirs } from "./tool-env.js";
@@ -35,6 +37,64 @@ export function parseMemoryUsage(text) {
35
37
  }
36
38
  return usages;
37
39
  }
40
+ /**
41
+ * `arm-none-eabi-size` 的 berkeley 行:`text data bss dec hex filename`(S80)。
42
+ * 用于增量构建没链接、链接器没打印占用时,直接量一次已存在的 elf。
43
+ */
44
+ export function parseBerkeleySize(text) {
45
+ for (const line of text.split(/\r?\n/u)) {
46
+ const parts = line.trim().split(/\s+/u);
47
+ if (parts.length < 5)
48
+ continue;
49
+ const [textBytes, dataBytes, bssBytes] = parts.slice(0, 3).map((item) => Number.parseInt(item, 10));
50
+ if (!Number.isFinite(textBytes) || !Number.isFinite(dataBytes) || !Number.isFinite(bssBytes))
51
+ continue;
52
+ return { text: textBytes, data: dataBytes, bss: bssBytes };
53
+ }
54
+ return null;
55
+ }
56
+ /**
57
+ * 增量构建的占用兜底(S80):没有链接输出时,用同一套工具链的 size 量 elf。
58
+ *
59
+ * 只在「构建成功 + 有 elf + 日志里没有占用」时才跑;总量来自器件事实(同样只在有 .ioc 时才有)。
60
+ */
61
+ async function measureElfUsage(subprocess, elfPath, binDirs, projectDir, signal) {
62
+ try {
63
+ const size = await resolveToolIn(subprocess, ["arm-none-eabi-size"], [...binDirs], signal);
64
+ if (size === null)
65
+ return [];
66
+ const captured = await runCapture(subprocess, {
67
+ argv: [size, elfPath],
68
+ cwd: projectDir,
69
+ env: envWithBinDirs([...binDirs]),
70
+ ...(signal === undefined ? {} : { signal }),
71
+ });
72
+ if (captured.exitCode !== 0)
73
+ return [];
74
+ const parsed = parseBerkeleySize(captured.stdout);
75
+ if (parsed === null)
76
+ return [];
77
+ const chip = findChipFact(readIocCpn(projectDir));
78
+ const out = [];
79
+ const add = (region, usedBytes, totalBytes) => {
80
+ if (totalBytes === null || totalBytes <= 0)
81
+ return;
82
+ out.push({
83
+ region,
84
+ usedBytes,
85
+ totalBytes,
86
+ percent: Math.round((usedBytes / totalBytes) * 1000) / 10,
87
+ raw: region + ": " + String(usedBytes) + " B / " + String(totalBytes) + " B",
88
+ });
89
+ };
90
+ add("FLASH", parsed.text + parsed.data, chip?.flashBytes ?? null);
91
+ add("RAM", parsed.data + parsed.bss, chip?.ramBytes ?? null);
92
+ return out;
93
+ }
94
+ catch {
95
+ return [];
96
+ }
97
+ }
38
98
  /** 从编译器/链接器输出里挑出错误行;重复行去重(同一头文件可能被多个 translation unit 报一次)。 */
39
99
  export function parseBuildErrors(text) {
40
100
  const errors = [];
@@ -139,6 +199,63 @@ export function pickConfigurePreset(projectDir) {
139
199
  });
140
200
  return sorted[0] ?? null;
141
201
  }
202
+ function normalizeDir(path) {
203
+ return path.replace(/\\/gu, "/").replace(/\/+$/u, "").toLowerCase();
204
+ }
205
+ /**
206
+ * 判断 CMakeCache 是不是「这个工程、这台机器」产出的。
207
+ *
208
+ * 复制或改名工程目录后,缓存里的绝对路径还指着旧位置;换工具链后编译器路径也可能失效。
209
+ * 这两种情况 cmake 有时只打一行 CMake Error、退出码却仍是 0(旧 ninja 报 no work to do),
210
+ * 所以要在编译前与失败后都看一眼缓存,而不是让人去试 clean。
211
+ */
212
+ export function inspectCmakeCache(buildDir, projectDir, options = {}) {
213
+ const cacheFile = join(buildDir, "CMakeCache.txt");
214
+ const readText = options.readText ?? ((file) => readFileSync(file, "utf8"));
215
+ const fileExists = options.fileExists ?? ((file) => existsSync(file));
216
+ if (!fileExists(cacheFile))
217
+ return { present: false, issues: [] };
218
+ let text = "";
219
+ try {
220
+ text = readText(cacheFile);
221
+ }
222
+ catch {
223
+ return { present: true, issues: ["CMakeCache.txt 读不出来(权限或编码问题)"] };
224
+ }
225
+ const values = new Map();
226
+ for (const line of text.split(/\r?\n/u)) {
227
+ const match = /^([A-Za-z0-9_]+)(?::[A-Za-z0-9_]+)?=(.*)$/u.exec(line);
228
+ if (match === null)
229
+ continue;
230
+ values.set(match[1], match[2]);
231
+ }
232
+ const issues = [];
233
+ const home = values.get("CMAKE_HOME_DIRECTORY") ?? "";
234
+ if (home !== "" && normalizeDir(home) !== normalizeDir(projectDir)) {
235
+ issues.push("缓存记录的源码目录是 " + home + ",当前工程是 " + projectDir + "(工程被复制或改名过)");
236
+ }
237
+ for (const key of ["CMAKE_C_COMPILER", "CMAKE_MAKE_PROGRAM"]) {
238
+ const tool = values.get(key) ?? "";
239
+ if (tool === "" || tool.endsWith("-NOTFOUND"))
240
+ continue;
241
+ if (!fileExists(tool)) {
242
+ issues.push("缓存记录的" + (key === "CMAKE_C_COMPILER" ? "编译器" : "构建器") + "不存在:" + tool);
243
+ }
244
+ }
245
+ return { present: true, issues: issues.slice(0, 5) };
246
+ }
247
+ /** 删掉 CMakeCache.txt 与 CMakeFiles,让下一次 cmake 重新配置(reconfigure 用)。 */
248
+ export function clearCmakeCache(buildDir) {
249
+ const removed = [];
250
+ for (const name of ["CMakeCache.txt", "CMakeFiles"]) {
251
+ const target = join(buildDir, name);
252
+ if (!existsSync(target))
253
+ continue;
254
+ rmSync(target, { recursive: true, force: true });
255
+ removed.push(name);
256
+ }
257
+ return removed;
258
+ }
142
259
  /** CMakeCache 里记的工程名(CMAKE_PROJECT_NAME:<TYPE>=<名字>);读不到返回空串。 */
143
260
  function readCmakeProjectName(buildDir) {
144
261
  try {
@@ -315,6 +432,23 @@ export async function runBuild(subprocess, request) {
315
432
  }
316
433
  preNotes.push("首次构建:自动执行了 cmake --preset " + preset.name + "(" + configureSeconds + " s,省掉手动配置)");
317
434
  }
435
+ // S191:缓存可能是从别处复制来的,或者工具链路径已经失效。先看一眼,别等编译完才猜。
436
+ const cacheCheck = inspectCmakeCache(buildDir, projectDir);
437
+ const cacheStale = cacheCheck.present && cacheCheck.issues.length > 0;
438
+ const cacheIssues = cacheCheck.issues;
439
+ if (cacheStale && request.reconfigure === true) {
440
+ const removed = clearCmakeCache(buildDir);
441
+ const retry = await runBuild(subprocess, { ...request, buildDir: undefined, reconfigure: false });
442
+ return {
443
+ ...retry,
444
+ cacheStale: false,
445
+ cacheIssues,
446
+ notes: [
447
+ "构建缓存与当前工程不匹配(" + cacheIssues[0] + "),已清掉 " + (removed.length === 0 ? "缓存(本来就没有可删的)" : removed.join("、")) + " 后重新配置",
448
+ ...retry.notes,
449
+ ],
450
+ };
451
+ }
318
452
  const argv = [cmake, "--build", buildDir];
319
453
  if (request.target !== undefined)
320
454
  argv.push("--target", request.target);
@@ -342,8 +476,13 @@ export async function runBuild(subprocess, request) {
342
476
  const durationMs = Date.now() - startedAt;
343
477
  const log = outcome.stdout + "\n" + outcome.stderr;
344
478
  const errors = parseBuildErrors(log);
345
- const memoryUsage = parseMemoryUsage(log);
479
+ const logMemory = parseMemoryUsage(log);
346
480
  const elf = findElf(buildDir);
481
+ /* 增量构建不重新链接,链接器不会打印占用;用 size 现量一次(S80)。 */
482
+ const memoryUsage = logMemory.length === 0 && elf !== null && outcome.exitCode === 0
483
+ ? await measureElfUsage(subprocess, elf.path, config.binDirs, projectDir, request.signal)
484
+ : logMemory;
485
+ const measured = logMemory.length === 0 && memoryUsage.length > 0;
347
486
  const base = {
348
487
  projectDir,
349
488
  buildDir,
@@ -357,16 +496,24 @@ export async function runBuild(subprocess, request) {
357
496
  logTail: tail(log, 30),
358
497
  };
359
498
  const notes = [...preNotes];
499
+ if (cacheStale) {
500
+ notes.push("构建缓存与当前工程可能不匹配:" + cacheIssues.slice(0, 2).join(";") + ";reconfigure:true 会清掉缓存重配,clean:true 只清产物");
501
+ }
360
502
  if (elf !== null) {
361
503
  notes.push("产物:" + elf.path + "(" + String(elf.size) + " B)");
362
504
  const selectionNote = elfSelectionNote(buildDir);
363
505
  if (selectionNote !== "")
364
506
  notes.push(selectionNote);
365
507
  }
366
- if (memoryUsage.length > 0)
508
+ if (memoryUsage.length > 0) {
367
509
  notes.push("占用:" + memoryUsage.map((item) => item.region + " " + String(item.percent) + "%").join(","));
368
- else if (elf !== null)
510
+ // 占用不是链接器给的,就得说明来源,否则读者会以为这次真的链接了(S80)。
511
+ if (measured)
512
+ notes.push("本次没有重新链接;占用由 arm-none-eabi-size 直接量 elf 得到");
513
+ }
514
+ else if (elf !== null) {
369
515
  notes.push("本次是增量构建,没有重新链接,因此没有内存占用数据(需要时用 clean 构建)");
516
+ }
370
517
  if (outcome.spawnError !== null) {
371
518
  return fail(request, "cmake 启动失败:" + outcome.spawnError, { ...base, errors: [outcome.spawnError] });
372
519
  }
@@ -376,7 +523,15 @@ export async function runBuild(subprocess, request) {
376
523
  return fail(request, "编译超时(" + String(request.timeoutMs ?? DEFAULT_TIMEOUT_MS) + " ms)", base);
377
524
  if (outcome.exitCode !== 0) {
378
525
  const first = errors.length > 0 ? errors[0] : "exit code " + String(outcome.exitCode);
379
- return fail(request, "编译失败:" + first, { ...base, notes });
526
+ const staleNotes = cacheStale
527
+ ? ["构建缓存与当前工程不匹配:" + cacheIssues.slice(0, 2).join(";") + "。先 clean:true 重试,或 reconfigure:true 清掉缓存重配,或直接删掉 " + base.buildDir]
528
+ : [];
529
+ const staleSuffix = cacheStale ? "(疑因构建缓存不匹配:先 clean 或 reconfigure)" : "";
530
+ return fail(request, "编译失败:" + first + staleSuffix, {
531
+ ...base,
532
+ notes: [...notes, ...staleNotes],
533
+ ...(cacheStale ? { cacheStale: true, cacheIssues } : {}),
534
+ });
380
535
  }
381
536
  // 实测:把整个工程(含 build/)复制/改名后,cmake 会先打印
382
537
  // "CMake Error: The current CMakeCache.txt directory ... is different than ...",
@@ -420,6 +575,7 @@ export async function runBuild(subprocess, request) {
420
575
  ok: true,
421
576
  ...base,
422
577
  ...(converted.length === 0 ? {} : { converted }),
578
+ ...(cacheStale ? { cacheStale: true, cacheIssues } : {}),
423
579
  notes,
424
580
  message: "编译成功(" + (durationMs / 1000).toFixed(1) + " s," + String(errors.length) + " 个错误、" + String(base.warningCount) + " 个警告)",
425
581
  };
@@ -0,0 +1,227 @@
1
+ /**
2
+ * 常驻通道:把串口与 RTT 的输出持续灌进事件流,而不是只在工具调用时取一段。
3
+ *
4
+ * 为什么放在服务端而不是面板轮询工具:面板一刷新就该有历史,且「一轮联调里
5
+ * 串口一直在冒字」不该依赖某个前台工具被调用。这里只做两件事:定时取增量、
6
+ * 通过 `emitChannel` 归成事件;解析与过滤全复用 serial / rtt 已有的实现。
7
+ *
8
+ * 串口 tap 自己维护文件偏移,不碰 `readSerial` 的读路径:rx.ndjson 是只追加的,
9
+ * 两边各读各的,互不抢游标。
10
+ */
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { emitChannel } from "./channels.js";
14
+ import { currentSerialSession } from "./serial.js";
15
+ import { dumpRtt, rttStatus } from "./rtt.js";
16
+ /** 轮询间隔:串口 700 ms、RTT 2 s(每次 dump 都建一次 TCP 连接,不能太密)。 */
17
+ const SERIAL_POLL_MS = 700;
18
+ const RTT_POLL_MS = 2_000;
19
+ /** 单批上限:一次塞太多会把面板尾部挤满,剩下的下一拍再发。 */
20
+ const SERIAL_BATCH_LINES = 200;
21
+ /** 尾部指纹长度:桥重写文件时长度往往不变,只靠偏移判断会漏读或错读。 */
22
+ const SERIAL_TAIL_BYTES = 32;
23
+ const RTT_BATCH_RECORDS = 200;
24
+ function blank(name) {
25
+ return { active: false, lines: 0, lastAt: "", lastError: "", timer: null, offset: 0, carry: "", sourceId: "", tail: "", lineCarry: "" };
26
+ }
27
+ const taps = { serial: blank("serial"), rtt: blank("rtt") };
28
+ function stamp() {
29
+ return new Date().toISOString();
30
+ }
31
+ /** 读 rx.ndjson 里偏移之后的新增完整行;半行留到下一拍。 */
32
+ function readSerialIncrement(ipcDir) {
33
+ const file = join(ipcDir, "rx.ndjson");
34
+ if (!existsSync(file))
35
+ return { lines: [], reset: false };
36
+ const runtime = taps.serial;
37
+ const buffer = readFileSync(file);
38
+ let start = runtime.offset;
39
+ let reset = start > buffer.length;
40
+ // 偏移落在旧文件里但也可能「越界到别的字段」:用尾部指纹确认上一批还在原处。
41
+ // 桥在 open 之后重写 rx.ndjson,长度可能不变,只看长度会静默错位。
42
+ if (!reset && start > 0 && runtime.tail !== "") {
43
+ const from = Math.max(0, start - runtime.tail.length);
44
+ if (buffer.subarray(from, start).toString("utf8") !== runtime.tail)
45
+ reset = true;
46
+ }
47
+ if (reset)
48
+ start = 0;
49
+ const chunk = buffer.subarray(start);
50
+ const text = runtime.carry + chunk.toString("utf8");
51
+ const parts = text.split("\n");
52
+ runtime.carry = parts.pop() ?? "";
53
+ runtime.offset = buffer.length - Buffer.byteLength(runtime.carry, "utf8");
54
+ runtime.tail = buffer.subarray(Math.max(0, buffer.length - SERIAL_TAIL_BYTES)).toString("utf8");
55
+ const lines = [];
56
+ for (const part of parts) {
57
+ const raw = part.trim();
58
+ if (raw === "")
59
+ continue;
60
+ try {
61
+ const parsed = JSON.parse(raw);
62
+ const data = typeof parsed.d === "string" ? parsed.d : "";
63
+ if (data === "")
64
+ continue;
65
+ if (parsed.p === true) {
66
+ runtime.lineCarry += data;
67
+ continue;
68
+ }
69
+ lines.push(runtime.lineCarry + data);
70
+ runtime.lineCarry = "";
71
+ }
72
+ catch {
73
+ // 半行或被桥截断的行:跳过,等下一批。
74
+ }
75
+ }
76
+ return { lines, reset };
77
+ }
78
+ /**
79
+ * 取一次串口增量并写事件流,返回本次发出的行数。
80
+ *
81
+ * 单独导出是为了单测能喂一个临时 ipc 目录,不必真的开串口。
82
+ */
83
+ export function tapSerialOnce(ipcDir, sessionId, meta = {}) {
84
+ const runtime = taps.serial;
85
+ // 会话换了:偏移与残留都归零。
86
+ if (runtime.sourceId !== sessionId) {
87
+ runtime.sourceId = sessionId;
88
+ runtime.offset = 0;
89
+ runtime.carry = "";
90
+ runtime.tail = "";
91
+ runtime.lineCarry = "";
92
+ }
93
+ try {
94
+ const { lines, reset } = readSerialIncrement(ipcDir);
95
+ if (reset)
96
+ runtime.lastError = "串口输出文件被重写,从头读";
97
+ if (lines.length === 0)
98
+ return 0;
99
+ const batch = lines.slice(0, SERIAL_BATCH_LINES);
100
+ emitChannel({
101
+ channel: "serial",
102
+ lines: batch,
103
+ meta: { action: "stream", sessionId, ...meta },
104
+ source: "system",
105
+ });
106
+ runtime.lines += batch.length;
107
+ runtime.lastAt = stamp();
108
+ runtime.lastError = "";
109
+ return batch.length;
110
+ }
111
+ catch (error) {
112
+ runtime.lastError = error instanceof Error ? error.message : String(error);
113
+ return 0;
114
+ }
115
+ }
116
+ function pollSerial() {
117
+ const runtime = taps.serial;
118
+ const session = currentSerialSession();
119
+ if (session === null) {
120
+ if (runtime.lastError !== "没有串口会话")
121
+ runtime.lastError = "没有串口会话";
122
+ return;
123
+ }
124
+ tapSerialOnce(session.ipcDir, session.sessionId, { port: session.port });
125
+ }
126
+ async function pollRtt() {
127
+ const runtime = taps.rtt;
128
+ const snapshot = rttStatus();
129
+ if (!snapshot.running) {
130
+ if (runtime.lastError !== "RTT 没在跑")
131
+ runtime.lastError = "RTT 没在跑";
132
+ return;
133
+ }
134
+ try {
135
+ const dumped = await dumpRtt({ seconds: 0.5, maxRecords: RTT_BATCH_RECORDS });
136
+ if (!dumped.ok) {
137
+ runtime.lastError = dumped.message;
138
+ return;
139
+ }
140
+ const records = dumped.records;
141
+ if (records.length === 0)
142
+ return;
143
+ emitChannel({
144
+ channel: "rtt",
145
+ lines: records.map((record) => "[" + record.level + "] " + record.text),
146
+ meta: { action: "stream", port: snapshot.port, addr: snapshot.addr },
147
+ source: "system",
148
+ });
149
+ runtime.lines += records.length;
150
+ runtime.lastAt = stamp();
151
+ runtime.lastError = "";
152
+ }
153
+ catch (error) {
154
+ runtime.lastError = error instanceof Error ? error.message : String(error);
155
+ }
156
+ }
157
+ function startOne(name) {
158
+ const runtime = taps[name];
159
+ if (runtime.active)
160
+ return;
161
+ runtime.active = true;
162
+ runtime.lastError = "";
163
+ if (name === "serial") {
164
+ runtime.timer = setInterval(pollSerial, SERIAL_POLL_MS);
165
+ }
166
+ else {
167
+ let busy = false;
168
+ runtime.timer = setInterval(() => {
169
+ // dump 是 async 且要等窗口,重叠调用只会把 openocd 压满。
170
+ if (busy)
171
+ return;
172
+ busy = true;
173
+ void pollRtt().finally(() => {
174
+ busy = false;
175
+ });
176
+ }, RTT_POLL_MS);
177
+ }
178
+ const timer = runtime.timer;
179
+ if (timer !== null && typeof timer.unref === "function")
180
+ timer.unref();
181
+ }
182
+ function stopOne(name) {
183
+ const runtime = taps[name];
184
+ if (!runtime.active)
185
+ return;
186
+ runtime.active = false;
187
+ if (runtime.timer !== null)
188
+ clearInterval(runtime.timer);
189
+ runtime.timer = null;
190
+ }
191
+ /** 开/关常驻通道;返回操作后的状态。 */
192
+ export function setChannelTaps(request = {}) {
193
+ if (request.serial !== undefined) {
194
+ if (request.serial)
195
+ startOne("serial");
196
+ else
197
+ stopOne("serial");
198
+ }
199
+ if (request.rtt !== undefined) {
200
+ if (request.rtt)
201
+ startOne("rtt");
202
+ else
203
+ stopOne("rtt");
204
+ }
205
+ return channelTapStatus();
206
+ }
207
+ /** 当前状态(面板据此画开关)。 */
208
+ export function channelTapStatus() {
209
+ return ["serial", "rtt"].map((name) => ({
210
+ name,
211
+ active: taps[name].active,
212
+ lines: taps[name].lines,
213
+ lastAt: taps[name].lastAt,
214
+ lastError: taps[name].lastError,
215
+ }));
216
+ }
217
+ /** 停掉所有常驻通道;插件 dispose 与单测都用它。 */
218
+ export function stopChannelTaps() {
219
+ stopOne("serial");
220
+ stopOne("rtt");
221
+ }
222
+ /** 单测用:停掉并清空计数与偏移。 */
223
+ export function resetChannelTaps() {
224
+ stopChannelTaps();
225
+ taps.serial = blank("serial");
226
+ taps.rtt = blank("rtt");
227
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 实时通道事件:串口、RTT、变量监视的输出走同一条总线。
3
+ *
4
+ * 为什么不另开一条 SSE:面板已经按 seq 续播,把通道输出也编进同一序号,
5
+ * 时间线、详情、证据目录就能共用一套断线与回放逻辑;代价是通道行不是独立流,
6
+ * 面板按 kind=channel:<名字> 过滤即可。
7
+ *
8
+ * 一次工具调用产生一条通道事件,最多 400 行、单行 400 字符:面板只需要看尾部,
9
+ * 完整原文仍在工具返回值与 rx.ndjson / RTT 记录里。
10
+ */
11
+ import { emitEvent } from "./event-bus.js";
12
+ /** 中文标签写进摘要,面板与证据目录直接可读。 */
13
+ const CHANNEL_LABEL = {
14
+ serial: "串口",
15
+ rtt: "RTT",
16
+ watch: "监视",
17
+ };
18
+ export const CHANNEL_LINE_LIMIT = 400;
19
+ const CHANNEL_CHAR_LIMIT = 400;
20
+ function normalizeLines(lines) {
21
+ const nonEmpty = lines.map((line) => String(line)).filter((line) => line !== "");
22
+ const shown = [];
23
+ for (const text of nonEmpty) {
24
+ shown.push(text.length > CHANNEL_CHAR_LIMIT ? text.slice(0, CHANNEL_CHAR_LIMIT) + "…" : text);
25
+ if (shown.length >= CHANNEL_LINE_LIMIT)
26
+ break;
27
+ }
28
+ return { total: nonEmpty.length, shown };
29
+ }
30
+ /** 追加一段通道输出;返回 null 表示没有内容可发。 */
31
+ export function emitChannel(chunk) {
32
+ const { total, shown } = normalizeLines(chunk.lines);
33
+ if (total === 0)
34
+ return null;
35
+ const label = CHANNEL_LABEL[chunk.channel];
36
+ const payload = { channel: chunk.channel, lines: shown };
37
+ if (chunk.meta !== undefined)
38
+ payload.meta = chunk.meta;
39
+ if (total > shown.length)
40
+ payload.omitted = total - shown.length;
41
+ return emitEvent({
42
+ source: chunk.source ?? "model",
43
+ kind: "channel:" + chunk.channel,
44
+ status: "info",
45
+ summary: label + " " + String(total) + " 行" + (total > shown.length ? "(面板保留前 " + String(shown.length) + " 行)" : ""),
46
+ payload,
47
+ });
48
+ }