dsh-stm32 0.1.2 → 0.1.3

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 (44) hide show
  1. package/README.md +59 -21
  2. package/README_EN.md +59 -21
  3. package/docs/development-notes.md +374 -3
  4. package/docs/reading-guide.md +87 -66
  5. package/lib/data/chips.js +38 -51
  6. package/lib/data/cmsis-sources.js +27 -1
  7. package/lib/data/device-facts.js +201 -0
  8. package/lib/data/stm32f1.js +94 -150
  9. package/lib/data/svd.js +627 -0
  10. package/lib/engine/assets.js +924 -0
  11. package/lib/engine/breakpoints.js +242 -0
  12. package/lib/engine/debug-session.js +153 -5
  13. package/lib/engine/debug.js +75 -41
  14. package/lib/engine/doctor.js +2 -2
  15. package/lib/engine/flash.js +31 -59
  16. package/lib/engine/ioc-plan.js +5 -5
  17. package/lib/engine/probe-error.js +212 -0
  18. package/lib/engine/probe-session.js +311 -0
  19. package/lib/engine/register-template.js +32 -8
  20. package/lib/engine/regs.js +2 -0
  21. package/lib/engine/rtt.js +600 -0
  22. package/lib/index.js +8 -0
  23. package/lib/tools/assets.js +341 -0
  24. package/lib/tools/cache.js +8 -0
  25. package/lib/tools/debug-session.js +40 -5
  26. package/lib/tools/debug.js +41 -11
  27. package/lib/tools/doctor.js +11 -0
  28. package/lib/tools/flash.js +15 -6
  29. package/lib/tools/generate.js +3 -0
  30. package/lib/tools/ioc-apply.js +2 -0
  31. package/lib/tools/ioc-inspect.js +2 -0
  32. package/lib/tools/ioc-plan.js +3 -0
  33. package/lib/tools/project-create.js +24 -0
  34. package/lib/tools/regs.js +453 -61
  35. package/lib/tools/route-plan.js +3 -0
  36. package/lib/tools/rtt.js +347 -0
  37. package/package.json +1 -1
  38. package/templates/register/CMakeLists.txt +7 -1
  39. package/templates/register/Core/Inc/rtt.h +103 -0
  40. package/templates/register/Core/Src/main.c +25 -0
  41. package/templates/register/Core/Src/rtt.c +297 -0
  42. package/templates/scaffold/RTT.md +86 -0
  43. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  44. package/lib/data/f1-ram.generated.js +0 -34
@@ -0,0 +1,347 @@
1
+ /**
2
+ * stm32_rtt:RTT 的入口工具。四个动作对应一条最短路径:
3
+ *
4
+ * start —— 确认目标里有控制块 → openocd rtt setup/start → 开通道 TCP 端口
5
+ * dump —— 连上通道读一段时间的记录(可按级别过滤、按条数截断)
6
+ * stop —— 断通道,让 openocd 收掉 rtt server
7
+ * status —— 只读快照
8
+ *
9
+ * 设计取舍:
10
+ * - 没有活跃调试会话时,start 自己起一个(ensureSession),用户不用记着先开会话;
11
+ * - dump/stop/status 不再跑工具链 gate:RTT 都跑起来了说明 openocd 在,再检查一遍只会碍事;
12
+ * - 失败也返回完整形状的 report(字段全是默认值 + probeError),免得宿主序列化时炸。
13
+ */
14
+ import { DEFAULT_DUMP_SECONDS, DEFAULT_MAX_RECORDS, DEFAULT_RTT_PORT, DEFAULT_RTT_SIZE, RTT_LEVEL_NAMES, dumpRtt, rttStatus, startRtt, stopRtt, } from "../engine/rtt.js";
15
+ import { PROBE_ERROR_SCHEMA } from "../engine/probe-error.js";
16
+ import { ensureSession, sessionInfo } from "../engine/probe-session.js";
17
+ import { ensureToolchain, gateReportNotes } from "../engine/toolchain-gate.js";
18
+ import { resolveProjectDir, validateToolArgs } from "./project-dir.js";
19
+ export const RTT_TOOL = "stm32_rtt";
20
+ const ENV_CHECK_SCHEMA = {
21
+ type: "string",
22
+ enum: ["block", "warn", "off"],
23
+ description: "工具链检查:block 缺件就拒绝(默认)、warn 只警告、off 不检查",
24
+ };
25
+ const RECORD_SCHEMA = {
26
+ type: "object",
27
+ additionalProperties: false,
28
+ properties: {
29
+ t: { type: "number", description: "模板写进来的毫秒时间戳(通常就是 HAL_GetTick)" },
30
+ level: { type: "number", description: "级别:1=error 2=warn 3=info 4=debug" },
31
+ text: { type: "string", description: "记录正文" },
32
+ },
33
+ required: ["t", "level", "text"],
34
+ };
35
+ const SESSION_SCHEMA = {
36
+ type: "object",
37
+ additionalProperties: false,
38
+ properties: {
39
+ port: { type: "number", description: "gdb 端口(0 表示当时没有会话)" },
40
+ tclPort: { type: "number", description: "openocd 的 Tcl RPC 端口(0 表示没有)" },
41
+ },
42
+ required: ["port", "tclPort"],
43
+ };
44
+ export const outputSchema = {
45
+ type: "object",
46
+ additionalProperties: false,
47
+ properties: {
48
+ ok: { type: "boolean", description: "这次动作成功没有" },
49
+ action: { type: "string", description: "start / dump / stop / status" },
50
+ projectDir: { type: "string", description: "工程目录" },
51
+ addr: { type: "string", description: "RTT 控制块地址(十六进制)" },
52
+ size: { type: "number", description: "控制块预留字节数" },
53
+ banner: { type: "string", description: "控制块标识(rtt setup 的第三个参数)" },
54
+ port: { type: "number", description: "RTT 通道的 TCP 端口" },
55
+ running: { type: "boolean", description: "RTT 当前是否在跑" },
56
+ startedAt: { type: "number", description: "start 的 Unix 毫秒时间戳;没跑时为 0" },
57
+ runningMs: { type: "number", description: "已经跑了多少毫秒;没跑时为 0" },
58
+ durationMs: { type: "number", description: "这次动作花了多少毫秒" },
59
+ records: { type: "array", description: "dump 到的记录(按时间顺序)", items: RECORD_SCHEMA },
60
+ dropped: { type: "number", description: "按 level 过滤掉的条数" },
61
+ bytes: { type: "number", description: "从通道读到的字节数" },
62
+ truncated: { type: "boolean", description: "是否因为 maxRecords 提前收尾" },
63
+ stopped: { type: "boolean", description: "通道是否在窗口内被关掉(目标复位或 stop)" },
64
+ session: SESSION_SCHEMA,
65
+ errors: { type: "array", description: "失败原因(一条一行)", items: { type: "string" } },
66
+ message: { type: "string", description: "一句话结论" },
67
+ notes: { type: "array", description: "补充说明", items: { type: "string" } },
68
+ probeError: PROBE_ERROR_SCHEMA,
69
+ },
70
+ required: [
71
+ "ok",
72
+ "action",
73
+ "projectDir",
74
+ "addr",
75
+ "size",
76
+ "banner",
77
+ "port",
78
+ "running",
79
+ "startedAt",
80
+ "runningMs",
81
+ "durationMs",
82
+ "records",
83
+ "dropped",
84
+ "bytes",
85
+ "truncated",
86
+ "stopped",
87
+ "session",
88
+ "errors",
89
+ "message",
90
+ "notes",
91
+ ],
92
+ };
93
+ const ACTIONS = ["start", "dump", "stop", "status"];
94
+ function sessionWire() {
95
+ const session = sessionInfo();
96
+ if (session === null)
97
+ return { port: 0, tclPort: 0 };
98
+ return { port: session.port, tclPort: session.tclPort };
99
+ }
100
+ /** 报告先按默认值填满,再逐项覆盖:任何一条失败路径都不会漏字段。 */
101
+ function baseReport(action, projectDir) {
102
+ const snapshot = rttStatus();
103
+ return {
104
+ ok: false,
105
+ action,
106
+ projectDir,
107
+ addr: snapshot.addr,
108
+ size: snapshot.size,
109
+ banner: snapshot.banner,
110
+ port: snapshot.port,
111
+ running: snapshot.running,
112
+ startedAt: snapshot.startedAt,
113
+ runningMs: snapshot.runningMs,
114
+ durationMs: 0,
115
+ records: [],
116
+ dropped: 0,
117
+ bytes: 0,
118
+ truncated: false,
119
+ stopped: false,
120
+ session: sessionWire(),
121
+ errors: [],
122
+ message: "",
123
+ notes: [],
124
+ };
125
+ }
126
+ function failure(action, projectDir, message, notes = [], probeError = null) {
127
+ const report = baseReport(action, projectDir);
128
+ report.message = message;
129
+ report.errors = [message];
130
+ report.notes = notes;
131
+ if (probeError !== null)
132
+ report.probeError = probeError;
133
+ return { message, report };
134
+ }
135
+ function formatReport(report) {
136
+ const lines = [];
137
+ lines.push((report.ok ? "完成" : "失败") + "(" + report.action + "):" + report.message);
138
+ if (report.running) {
139
+ lines.push("RTT 在跑:控制块 " + report.addr + "(" + String(report.size) + " 字节),通道端口 " + String(report.port) +
140
+ (report.banner === "" ? "" : ",banner " + report.banner) + ",已跑 " + String(report.runningMs) + " ms");
141
+ }
142
+ const shown = report.records.slice(0, 80);
143
+ for (const record of shown) {
144
+ const name = RTT_LEVEL_NAMES[record.level] ?? String(record.level);
145
+ lines.push(" [" + String(record.t) + " ms][" + name + "] " + record.text);
146
+ }
147
+ if (report.records.length > shown.length)
148
+ lines.push(" … 还有 " + String(report.records.length - shown.length) + " 条(调大 maxRecords 或分批 dump)");
149
+ if (report.truncated)
150
+ lines.push("· 达到 maxRecords 上限,提前收尾");
151
+ if (report.stopped)
152
+ lines.push("· RTT 通道已停(目标复位或 rtt stop)");
153
+ lines.push("· 这次读 " + String(report.bytes) + " 字节" + (report.dropped > 0 ? ",按级别过滤掉 " + String(report.dropped) + " 条" : ""));
154
+ for (const note of report.notes)
155
+ lines.push("· " + note);
156
+ for (const error of report.errors.slice(0, 6))
157
+ lines.push("! " + error);
158
+ return lines;
159
+ }
160
+ function readNumber(value) {
161
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
162
+ }
163
+ function readString(value) {
164
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
165
+ }
166
+ function snapshotInto(report, snapshot) {
167
+ report.addr = snapshot.addr;
168
+ report.size = snapshot.size;
169
+ report.banner = snapshot.banner;
170
+ report.port = snapshot.port;
171
+ report.running = snapshot.running;
172
+ report.startedAt = snapshot.startedAt;
173
+ report.runningMs = snapshot.runningMs;
174
+ report.session = sessionWire();
175
+ }
176
+ export function registerRtt(ctx) {
177
+ ctx.tools.register({
178
+ name: RTT_TOOL,
179
+ description: "RTT(Real Time Transfer):start 起 openocd 的 rtt 通道并给出 TCP 端口,dump 读一段时间的记录(级别过滤/条数截断),stop 收掉,status 看状态。",
180
+ parameters: {
181
+ type: "object",
182
+ additionalProperties: false,
183
+ properties: {
184
+ action: { type: "string", enum: [...ACTIONS], description: "start(起 RTT)/ dump(读记录)/ stop(停)/ status(看状态)" },
185
+ projectDir: { type: "string", description: "工程目录;缺省取会话工作目录" },
186
+ addr: { type: "string", description: "RTT 控制块起始地址(十六进制,例如 0x20000000);action=start 必填" },
187
+ size: { type: "number", description: "控制块预留字节数,默认 " + String(DEFAULT_RTT_SIZE) },
188
+ banner: { type: "string", description: "控制块标识(openocd rtt setup 的第三个参数);一般不用填" },
189
+ rttPort: { type: "number", description: "RTT 通道的 TCP 端口,默认 " + String(DEFAULT_RTT_PORT) },
190
+ seconds: { type: "number", description: "dump 的采集窗口(秒),默认 " + String(DEFAULT_DUMP_SECONDS) + ",范围 0.2..60" },
191
+ level: { type: "number", description: "dump 保留到哪一级:1=error 2=warn 3=info 4=debug(默认 4,全要)" },
192
+ maxRecords: { type: "number", description: "dump 最多返回多少条,默认 " + String(DEFAULT_MAX_RECORDS) },
193
+ timeoutMs: { type: "number", description: "Tcl 往返 / 连通道的超时毫秒数" },
194
+ binDirs: { type: "array", description: "工具链目录候选(覆盖默认搜索路径)", items: { type: "string" } },
195
+ envCheck: ENV_CHECK_SCHEMA,
196
+ },
197
+ required: ["action"],
198
+ },
199
+ timeoutMs: 120_000,
200
+ isConcurrencySafe: () => false,
201
+ output: {
202
+ schema: outputSchema,
203
+ render: (_args, value) => [{ type: "text", text: formatReport(value.report).join("\n") }],
204
+ },
205
+ async execute(rawArgs, exec) {
206
+ const args = (rawArgs ?? {});
207
+ const action = typeof args.action === "string" ? args.action.trim() : "";
208
+ const resolution = await resolveProjectDir(ctx, readString(args.projectDir), exec);
209
+ const projectDir = resolution.projectDir;
210
+ const notes = resolution.note === null ? [] : [resolution.note];
211
+ if (!ACTIONS.includes(action)) {
212
+ return failure(action === "" ? "(缺 action)" : action, projectDir, "action 必须是 start / dump / stop / status(收到:" + JSON.stringify(args.action ?? null) + ")", notes);
213
+ }
214
+ // 这些参数都是可选的(addr 只在 start 时必填),所以只校验"用户真的传了的"那几个:
215
+ // validateToolArgs 会把没传的一律算缺参,直接拿全表调用会误伤 dump/stop/status。
216
+ const passed = [
217
+ { name: "addr", kind: "string" },
218
+ { name: "banner", kind: "string" },
219
+ { name: "projectDir", kind: "string" },
220
+ { name: "binDirs", kind: "string[]" },
221
+ ].filter((spec) => args[spec.name] !== undefined);
222
+ const invalid = passed.length === 0 ? null : validateToolArgs(RTT_TOOL, args, passed);
223
+ if (invalid !== null)
224
+ return failure(action, projectDir, invalid, notes);
225
+ const binDirs = Array.isArray(args.binDirs) ? args.binDirs : undefined;
226
+ if (action === "start") {
227
+ const addr = readString(args.addr);
228
+ if (addr === undefined)
229
+ return failure(action, projectDir, "start 需要 addr:控制块起始地址(十六进制,例如 0x20000000)", notes);
230
+ const gate = await ensureToolchain(ctx, {
231
+ capability: "debug",
232
+ ...(binDirs === undefined ? {} : { binDirs }),
233
+ envCheck: args.envCheck,
234
+ signal: exec.signal,
235
+ });
236
+ if (!gate.ok && gate.mode === "block") {
237
+ return failure(action, projectDir, gate.message, [...notes, ...gateReportNotes(gate)]);
238
+ }
239
+ const gateNotes = gateReportNotes(gate);
240
+ let session = sessionInfo();
241
+ if (session === null) {
242
+ const subprocess = ctx.get("subprocess");
243
+ if (subprocess === undefined) {
244
+ return failure(action, projectDir, "宿主没有 subprocess 服务,起不了 openocd 会话", [...notes, ...gateNotes]);
245
+ }
246
+ const ensured = await ensureSession(projectDir, {
247
+ subprocess,
248
+ ...(binDirs === undefined ? {} : { binDirs }),
249
+ ...(exec.agent?.id === undefined ? {} : { owner: exec.agent.id }),
250
+ });
251
+ if (!ensured.ok || ensured.session === null) {
252
+ const probeError = ensured.probeError;
253
+ const report = baseReport(action, projectDir);
254
+ report.message = ensured.message;
255
+ report.errors = [ensured.message];
256
+ report.notes = [...notes, ...gateNotes];
257
+ if (probeError !== null)
258
+ report.probeError = probeError;
259
+ return { message: ensured.message, report };
260
+ }
261
+ session = ensured.session;
262
+ notes.push("没有活跃会话,先起了一个调试会话(gdb 端口 " + String(session.port) + ",tcl 端口 " + String(session.tclPort) + ")");
263
+ }
264
+ else {
265
+ notes.push("复用已有调试会话(tcl 端口 " + String(session.tclPort) + ")");
266
+ }
267
+ const started = await startRtt({
268
+ addr,
269
+ ...(readNumber(args.size) === undefined ? {} : { size: readNumber(args.size) ?? DEFAULT_RTT_SIZE }),
270
+ ...(readString(args.banner) === undefined ? {} : { banner: readString(args.banner) ?? "" }),
271
+ ...(readNumber(args.rttPort) === undefined ? {} : { port: readNumber(args.rttPort) ?? DEFAULT_RTT_PORT }),
272
+ ...(readNumber(args.timeoutMs) === undefined ? {} : { timeoutMs: readNumber(args.timeoutMs) ?? 5_000 }),
273
+ signal: exec.signal,
274
+ });
275
+ const report = baseReport(action, projectDir);
276
+ report.ok = started.ok;
277
+ report.addr = started.addr;
278
+ report.size = started.size;
279
+ report.banner = started.banner;
280
+ report.port = started.port;
281
+ report.durationMs = started.durationMs;
282
+ report.message = started.message;
283
+ report.notes = [...notes, ...gateNotes, ...started.notes];
284
+ report.errors = started.ok ? [] : [started.message];
285
+ snapshotInto(report, rttStatus());
286
+ if (started.probeError !== null)
287
+ report.probeError = started.probeError;
288
+ return { message: started.message, report };
289
+ }
290
+ if (action === "dump") {
291
+ const dumped = await dumpRtt({
292
+ ...(readNumber(args.seconds) === undefined ? {} : { seconds: readNumber(args.seconds) ?? DEFAULT_DUMP_SECONDS }),
293
+ ...(readNumber(args.level) === undefined ? {} : { level: readNumber(args.level) ?? 4 }),
294
+ ...(readNumber(args.maxRecords) === undefined ? {} : { maxRecords: readNumber(args.maxRecords) ?? DEFAULT_MAX_RECORDS }),
295
+ ...(readNumber(args.timeoutMs) === undefined ? {} : { timeoutMs: readNumber(args.timeoutMs) ?? 3_000 }),
296
+ signal: exec.signal,
297
+ });
298
+ const report = baseReport(action, projectDir);
299
+ report.ok = dumped.ok;
300
+ report.durationMs = dumped.durationMs;
301
+ report.records = dumped.records;
302
+ report.dropped = dumped.dropped;
303
+ report.bytes = dumped.bytes;
304
+ report.truncated = dumped.truncated;
305
+ report.stopped = dumped.stopped;
306
+ report.message = dumped.message;
307
+ report.notes = [...notes, ...dumped.notes];
308
+ report.errors = dumped.ok ? [] : [dumped.message];
309
+ snapshotInto(report, rttStatus());
310
+ report.port = dumped.port;
311
+ report.addr = dumped.addr === "" ? report.addr : dumped.addr;
312
+ if (dumped.probeError !== null)
313
+ report.probeError = dumped.probeError;
314
+ return { message: dumped.message, report };
315
+ }
316
+ if (action === "stop") {
317
+ const stopped = await stopRtt();
318
+ const report = baseReport(action, projectDir);
319
+ report.ok = stopped.ok;
320
+ report.durationMs = stopped.durationMs;
321
+ report.stopped = stopped.stopped;
322
+ report.port = stopped.port;
323
+ report.dropped = stopped.dropped;
324
+ report.bytes = stopped.bytes;
325
+ report.message = stopped.message;
326
+ report.notes = [...notes, ...stopped.notes];
327
+ report.errors = stopped.ok ? [] : [stopped.message];
328
+ snapshotInto(report, rttStatus());
329
+ if (stopped.probeError !== null)
330
+ report.probeError = stopped.probeError;
331
+ return { message: stopped.message, report };
332
+ }
333
+ const snapshot = rttStatus();
334
+ const report = baseReport(action, projectDir);
335
+ report.ok = true;
336
+ report.notes = notes;
337
+ snapshotInto(report, snapshot);
338
+ report.dropped = snapshot.dropped;
339
+ report.bytes = snapshot.bytes;
340
+ report.message = snapshot.running
341
+ ? "RTT 在跑:控制块 " + snapshot.addr + ",通道端口 " + String(snapshot.port) + ",已收 " + String(snapshot.records) + " 条 / " + String(snapshot.bytes) + " 字节" +
342
+ (snapshot.lastError === null ? "" : ";上次出错:" + snapshot.lastError)
343
+ : "RTT 没在跑" + (snapshot.lastError === null ? "" : ";上次出错:" + snapshot.lastError);
344
+ return { message: report.message, report };
345
+ },
346
+ });
347
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-stm32",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "DSH 插件:STM32(F103C8T6)全流程工具层 —— 环境探测、.ioc 事务、生成工程、编译、只烧录、按需调试",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -32,10 +32,16 @@ message("Linker script: " ${DSH_LINKER_SCRIPT})
32
32
  enable_language(C ASM)
33
33
 
34
34
  # ---------------- 可执行文件 ----------------
35
- # 只编译三个源:用户 main.c、CMSIS 的 system_stm32f1xx.c、启动文件。
35
+ # 编译四个源:用户 main.c、可选的 RTT(Core/Src/rtt.c)、CMSIS 的 system_stm32f1xx.c、启动文件。
36
36
  # 设备头与内核头通过下面两个 include 目录提供,全部来自下载缓存。
37
+ #
38
+ # RTT 是"编进来但不默认启用":模板的 main.c 里 rtt_init() 是注释掉的,工具链又开了
39
+ # --gc-sections,所以没调用时 rtt.c 的代码和 3 KB 控制块缓冲会被链接器丢掉,不占
40
+ # RAM/Flash。要用就把 main.c 里 USER CODE BEGIN 2 的两行注释取消(RTT 不想要的话,
41
+ # 也可以把下面这一行删掉,main.c 里对应的 #include "rtt.h" 一起删)。
37
42
  add_executable(${CMAKE_PROJECT_NAME}
38
43
  Core/Src/main.c
44
+ Core/Src/rtt.c
39
45
  Drivers/CMSIS/Device/ST/__FAMILY_DIR__/Source/Templates/system_stm32f1xx.c
40
46
  Drivers/CMSIS/Device/ST/__FAMILY_DIR__/Source/Templates/gcc/__STARTUP_FILE__
41
47
  )
@@ -0,0 +1,103 @@
1
+ /*
2
+ * 极简 RTT(Real Time Transfer)——寄存器版模板自带
3
+ *
4
+ * 它做三件事:
5
+ * 1) 在 RAM 里放一块**与 SEGGER RTT 兼容**的控制块(首 10 字节是 "SEGGER RTT"、
6
+ * 3 个上行通道、每个通道一个环形缓冲),这样 openocd 原生的 rtt 命令
7
+ * (rtt setup / rtt start / rtt server start)能直接认它;
8
+ * 2) 提供 rtt_printf()/rtt_write() 把一条记录写进通道 0;
9
+ * 3) 给出控制块地址,供 dsh-stm32 的 stm32_rtt action=start addr=... 使用。
10
+ *
11
+ * 记录格式是 dsh-stm32 自己的约定(不抄 SEGGER,SEGGER 没有级别和时间戳):
12
+ * [4B 长度 LE][1B 级别][8B 时间戳 ms LE][payload UTF-8]
13
+ * 长度字段 = 9 + payload 字节数(不含这 4 字节本身),级别 1..4 = error/warn/info/debug。
14
+ * src/engine/rtt.ts 里的 parseRttFrames() 就是按这个顺序解的。
15
+ *
16
+ * RAM 成本:RTT_UP_CHANNELS × RTT_BUF_SIZE = 3 × 1 KB = 3 KB(.bss)。
17
+ * C8T6 只有 20 KB,RAM 紧就把 RTT_UP_CHANNELS 改成 1,或把 RTT_BUF_SIZE 改成 256。
18
+ * 注意:模板默认**不调用** rtt_init(),工具链开了 --gc-sections,所以未启用时
19
+ * 这块内存与 rtt.c 的代码都会被链接器丢掉,不占 RAM/Flash;取消了 main.c 里
20
+ * USER CODE BEGIN 2 的注释才会真正进来。
21
+ *
22
+ * 地址怎么拿(start 时 addr 填它):
23
+ * arm-none-eabi-nm build/<preset>/<工程名>.elf | findstr _SEGGER_RTT
24
+ * 或 gdb 里:p &_SEGGER_RTT
25
+ * 也可以在运行时把 rtt_control_block_addr() 打出来看,但别把地址写死到别的工程里。
26
+ */
27
+
28
+ #ifndef DSH_STM32_RTT_H
29
+ #define DSH_STM32_RTT_H
30
+
31
+ #include <stdint.h>
32
+
33
+ #ifdef __cplusplus
34
+ extern "C" {
35
+ #endif
36
+
37
+ /* 级别:与 stm32_rtt 的 dump level 过滤一致(dump 的 level 是"保留到哪一级"的上限) */
38
+ #define RTT_LEVEL_ERROR 1u
39
+ #define RTT_LEVEL_WARN 2u
40
+ #define RTT_LEVEL_INFO 3u
41
+ #define RTT_LEVEL_DEBUG 4u
42
+
43
+ /* 上行通道数:通道 0 是 stm32_rtt 读的那一条("Terminal"),1/2 留给应用自己分用途。 */
44
+ #ifndef RTT_UP_CHANNELS
45
+ #define RTT_UP_CHANNELS 3u
46
+ #endif
47
+
48
+ /* 每个上行通道的环形缓冲字节数(3 × 1024 = 3 KB .bss)。 */
49
+ #ifndef RTT_BUF_SIZE
50
+ #define RTT_BUF_SIZE 1024u
51
+ #endif
52
+
53
+ /* 单条记录的 payload 上限(字节,不含结尾 0);超长截断,不会写半条帧。 */
54
+ #ifndef RTT_MSG_MAX
55
+ #define RTT_MSG_MAX 120u
56
+ #endif
57
+
58
+ /* 控制块起始地址:stm32_rtt action=start addr=<这个值>。 */
59
+ uint32_t rtt_control_block_addr(void);
60
+
61
+ /* 控制块占的字节数:给 rtt setup <addr> <size> 的 size 用(传大一点也无害)。 */
62
+ uint32_t rtt_control_block_size(void);
63
+
64
+ /*
65
+ * 初始化控制块:清空环、填好 3 个通道描述符,最后才写 ID 魔数
66
+ * (这样 openocd/stm32_rtt 看到魔数时描述符一定已经就绪)。
67
+ * 可重复调用。会打开 DWT 周期计数器给时间戳用,所以要在时钟初始化之后调用。
68
+ */
69
+ void rtt_init(void);
70
+
71
+ /*
72
+ * 写一条记录到通道 0。level 取 RTT_LEVEL_*(越界会被夹到 1..4)。
73
+ * text 是已经格式化好的字符串(结尾 0 会被 strlen 截掉,不写进环)。
74
+ * 返回写进去的 payload 字节数;环满/放不下完整一条时返回 0(整条丢,不写半条)。
75
+ * 可以从主循环和中断里调用;但它不加锁,多个上下文同时写会互相踩(要并发就在外面关中断)。
76
+ */
77
+ uint32_t rtt_write(uint32_t level, const char *text);
78
+
79
+ /*
80
+ * printf 风格:先 vsnprintf 到内部缓冲(最多 RTT_MSG_MAX 字节),再走 rtt_write。
81
+ *
82
+ * 链接提示:vsnprintf 会牵进 newlib 的 _sbrk(堆延伸)。寄存器版模板没有 syscalls.c,
83
+ * 所以 rtt.c 里给了一份**弱符号** _sbrk 兜底(直接失败,等于没有堆),保证只加
84
+ * rtt_init() + rtt_printf() 就能链接过。你自己有 syscalls.c 时那份强符号会自动覆盖它。
85
+ * 完全不想碰 newlib 就用 rtt_write(level, "已经格式化好的字符串")。
86
+ */
87
+ uint32_t rtt_printf(uint32_t level, const char *fmt, ...);
88
+
89
+ /*
90
+ * 时间戳(毫秒)。默认实现用 DWT 周期计数器按 SystemCoreClock 换算;
91
+ * 应用可以覆盖它(弱符号)来用 HAL_GetTick / 自己的 RTC:
92
+ * uint64_t rtt_time_ms(void) { return HAL_GetTick(); }
93
+ */
94
+ uint64_t rtt_time_ms(void);
95
+
96
+ /* 因为环满而整条丢掉的记录数(只在本地可见,dump 的 dropped 只统计按级别过滤掉的)。 */
97
+ uint32_t rtt_dropped_count(void);
98
+
99
+ #ifdef __cplusplus
100
+ }
101
+ #endif
102
+
103
+ #endif /* DSH_STM32_RTT_H */
@@ -13,6 +13,7 @@
13
13
  #include <stdint.h>
14
14
 
15
15
  #include "stm32f1xx.h"
16
+ #include "rtt.h" /* 模板自带的极简 RTT;不用就把这行和下面 USER CODE BEGIN 2 的示例一起删掉 */
16
17
 
17
18
  /* 换板子改这两行 */
18
19
  #define LED_PORT GPIOC
@@ -64,6 +65,30 @@ int main(void)
64
65
  clock_init(); /* 先把频率提到芯片能跑的上限,再配外设 */
65
66
  led_init();
66
67
 
68
+ /* USER CODE BEGIN 2 */
69
+ /*
70
+ * RTT 调试输出(可选,默认没开):模板里 rtt.c/rtt.h 已经就位,但 rtt_init()
71
+ * 不强制调用——工具链开了 --gc-sections,没调用时 rtt.c 的代码和 3 KB 控制块
72
+ * 缓冲会被整个丢掉,不占 RAM/Flash。要用就取消下面两行的注释:
73
+ *
74
+ * rtt_init(); // 必须在 clock_init() 之后(时间戳要用 DWT 周期计数器)
75
+ * rtt_printf(RTT_LEVEL_INFO, "boot: sysclk=%lu Hz", (unsigned long)SystemCoreClock);
76
+ *
77
+ * 之后在宿主侧这样读(openocd 的 rtt 命令 + TCP 端口,插件已经封装好):
78
+ * arm-none-eabi-nm build/<preset>/<工程名>.elf | findstr _SEGGER_RTT // 拿控制块地址
79
+ * stm32_rtt action=start addr=0x2000xxxx // 地址就是 nm 出来的那个,size 用默认 0x400
80
+ * stm32_rtt action=dump // 打印 {t, level, text} 记录
81
+ * stm32_rtt action=stop
82
+ *
83
+ * 代价与限制:
84
+ * - 3 个上行通道 × 1 KB = 3 KB RAM(C8T6 只有 20 KB)。嫌多就改 rtt.h 里的
85
+ * RTT_UP_CHANNELS=1、RTT_BUF_SIZE=256;
86
+ * - 控制块是普通 .bss 变量,地址随重链接漂移,所以别把地址写死,每次 nm 一遍;
87
+ * - 环满时整条记录丢弃(不阻塞、不覆盖未读数据),rtt_dropped_count() 能看丢了几条;
88
+ * - 主循环和中断都能写,但它没加锁:多个上下文并发写要自己关中断。
89
+ */
90
+ /* USER CODE END 2 */
91
+
67
92
  while (1) {
68
93
  led_toggle();
69
94
  g_led_blink_count++;