@turingcode/cli 0.3.7 → 0.3.8
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.
- package/dist/features/debug/debug_start.js +6 -2
- package/dist/features/probe/program_project.js +10 -6
- package/dist/features/probe/read_fault_status.js +4 -2
- package/dist/features/probe/read_memory.js +3 -1
- package/dist/features/probe/read_peripheral.js +3 -2
- package/dist/features/probe/reset_target.js +4 -2
- package/dist/features/probe/target_info.js +4 -2
- package/dist/features/project/project_sync_to_server.js +16 -6
- package/dist/stm32/actions/DebugAction.d.ts +5 -0
- package/dist/stm32/actions/DebugAction.js +11 -1
- package/dist/stm32/actions/DebugActionInfo.js +1 -1
- package/dist/stm32/actions/DebugActionProgram.d.ts +12 -2
- package/dist/stm32/actions/DebugActionProgram.js +39 -4
- package/dist/stm32/actions/DebugActionRead.d.ts +2 -0
- package/dist/stm32/actions/DebugActionRead.js +3 -0
- package/dist/stm32/actions/DebugActionReset.d.ts +1 -0
- package/dist/stm32/actions/DebugActionReset.js +2 -2
- package/dist/stm32/context.d.ts +5 -2
- package/dist/stm32/context.js +2 -2
- package/dist/stm32/session.d.ts +1 -0
- package/dist/stm32/session.js +2 -0
- package/dist/stm32/tool.d.ts +1 -0
- package/dist/stm32/toolCommand.js +10 -2
- package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +49 -46
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -57
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +67 -67
- package/package.json +1 -1
|
@@ -3,11 +3,15 @@ import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
|
3
3
|
import { startSession } from '../../stm32/session.js';
|
|
4
4
|
import { findElf } from '../../stm32/utils/findElf.js';
|
|
5
5
|
import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
|
|
6
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
6
7
|
/** Starts a probe-rs debug session on the project's board. */
|
|
7
8
|
export default _defineTool({
|
|
8
9
|
name: 'debug_start',
|
|
9
10
|
description: "Start a probe-rs debug session on the project's board using the newest .elf in build/. By default it attaches to the running firmware (which must match that .elf); with flash=true it flashes the .elf first and halts after reset, so breakpoints can be set before continue. Takes ownership of the probe until `turingcode debug stop`.",
|
|
10
|
-
properties: {
|
|
11
|
+
properties: {
|
|
12
|
+
flash: { type: 'boolean', description: 'Flash the .elf and halt after reset (default false: attach)' },
|
|
13
|
+
speed: SWD_SPEED_PROP,
|
|
14
|
+
},
|
|
11
15
|
needsProbe: true,
|
|
12
16
|
run: async (args, ctx) => {
|
|
13
17
|
const project = await findStm32Project();
|
|
@@ -16,7 +20,7 @@ export default _defineTool({
|
|
|
16
20
|
throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
|
|
17
21
|
const chip = await getMcuFromIoc(project.root);
|
|
18
22
|
const flash = args.flash === true;
|
|
19
|
-
const s = await startSession({ root: project.root, chip, elf: elf.path, flash });
|
|
23
|
+
const s = await startSession({ root: project.root, chip, elf: elf.path, flash, speed: args.speed });
|
|
20
24
|
return `Debug session started (${flash ? 'flashed' : 'attached'}, ${chip}, ${elf.path})\n${await s.location()}`;
|
|
21
25
|
},
|
|
22
26
|
});
|
|
@@ -3,14 +3,17 @@ import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
|
3
3
|
import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
|
|
4
4
|
import { findElf } from '../../stm32/utils/findElf.js';
|
|
5
5
|
import { DebugActionProgram } from '../../stm32/actions/DebugActionProgram.js';
|
|
6
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
6
7
|
/** Flashes the newest ELF in the project's build/ folder. */
|
|
7
8
|
export default _defineTool({
|
|
8
9
|
name: 'program_project',
|
|
9
|
-
description: "Flash the newest .elf in the project's build/ folder \
|
|
10
|
-
(downloaded by `turingcode project sync -b`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
|
|
11
|
-
verify it and reset the target.
|
|
10
|
+
description: "Flash the newest .elf in the project's build/ folder \
|
|
11
|
+
(downloaded by `turingcode project sync -b`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
|
|
12
|
+
verify it and reset the target. If probe-rs fails and STM32_Programmer_CLI is installed, retries once with it \
|
|
13
|
+
(hot-plug: attaches and halts the running core without a reset).",
|
|
14
|
+
properties: { speed: SWD_SPEED_PROP },
|
|
12
15
|
needsProbe: true,
|
|
13
|
-
run: async (
|
|
16
|
+
run: async (args, ctx) => {
|
|
14
17
|
const project = await findStm32Project();
|
|
15
18
|
const elf = await findElf(project.root);
|
|
16
19
|
if (!elf)
|
|
@@ -19,9 +22,10 @@ export default _defineTool({
|
|
|
19
22
|
const program_result = await DebugActionProgram.run_action_get_tail({
|
|
20
23
|
elf: elf.path,
|
|
21
24
|
chip,
|
|
25
|
+
speed: args.speed,
|
|
22
26
|
}).catch((e) => {
|
|
23
|
-
throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
|
|
24
|
-
(USB sleep, DEV_USB_COMM_ERR, probe not found), \
|
|
27
|
+
throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
|
|
28
|
+
(USB sleep, DEV_USB_COMM_ERR, probe not found), \
|
|
25
29
|
run \`turingcode probe reset-usb\` and try again once.`);
|
|
26
30
|
});
|
|
27
31
|
return `Programmed ${elf.path} (${chip})\n\n${program_result}`;
|
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import { _defineTool } from '../../stm32/tool.js';
|
|
2
2
|
import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
3
3
|
import { DebugActionRead } from '../../stm32/actions/DebugActionRead.js';
|
|
4
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
4
5
|
import { FAULT_REGS_ADDRESS, decodeFaultStatus } from '../../stm32/utils/faultUtils.js';
|
|
5
6
|
import { getMcuFromIoc, isArmv6m } from '../../stm32/utils/mcu_utils.js';
|
|
6
7
|
/** Reads and decodes the SCB fault status registers. */
|
|
7
8
|
export default _defineTool({
|
|
8
9
|
name: 'read_fault_status',
|
|
9
10
|
description: 'Read and decode the Cortex-M fault status registers (CFSR, HFSR, DFSR, MMFAR, BFAR, AFSR) over SWD (probe-rs or STM32_Programmer_CLI), without halting the core. Use it after the board hangs in HardFault_Handler.',
|
|
11
|
+
properties: { speed: SWD_SPEED_PROP },
|
|
10
12
|
needsProbe: true,
|
|
11
|
-
run: async (
|
|
13
|
+
run: async (args, ctx) => {
|
|
12
14
|
const project = await findStm32Project();
|
|
13
15
|
const chip = await getMcuFromIoc(project.root);
|
|
14
16
|
if (isArmv6m(chip))
|
|
15
17
|
return `${chip} has a Cortex-M0/M0+ core, which has no fault status registers: every fault is a plain HardFault.`;
|
|
16
|
-
const { words: regs } = await DebugActionRead.run_action({ chip, address: FAULT_REGS_ADDRESS, width: 32, count: 6 });
|
|
18
|
+
const { words: regs } = await DebugActionRead.run_action({ chip, address: FAULT_REGS_ADDRESS, width: 32, count: 6, speed: args.speed });
|
|
17
19
|
return `Fault status of ${chip}\n\n${decodeFaultStatus(regs)}`;
|
|
18
20
|
},
|
|
19
21
|
});
|
|
@@ -3,6 +3,7 @@ import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
|
3
3
|
import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
|
|
4
4
|
import { hex } from '../../stm32/utils/faultUtils.js';
|
|
5
5
|
import { DebugActionRead } from '../../stm32/actions/DebugActionRead.js';
|
|
6
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
6
7
|
/** Reads target memory while the core keeps running. */
|
|
7
8
|
export default _defineTool({
|
|
8
9
|
name: 'read_memory',
|
|
@@ -11,6 +12,7 @@ export default _defineTool({
|
|
|
11
12
|
address: { type: 'string', pattern: '^0x[0-9A-Fa-f]{1,8}$' },
|
|
12
13
|
length: { type: 'integer', minimum: 1, maximum: 4096, description: 'Bytes to read' },
|
|
13
14
|
width: { type: 'string', enum: ['8', '16', '32'], description: 'Access width in bits' },
|
|
15
|
+
speed: SWD_SPEED_PROP,
|
|
14
16
|
},
|
|
15
17
|
required: ['address', 'length'],
|
|
16
18
|
needsProbe: true,
|
|
@@ -23,7 +25,7 @@ export default _defineTool({
|
|
|
23
25
|
throw new Error(`address and length must be multiples of ${width / 8} bytes for ${width}-bit reads`);
|
|
24
26
|
const project = await findStm32Project();
|
|
25
27
|
const chip = await getMcuFromIoc(project.root);
|
|
26
|
-
const { words } = await DebugActionRead.run_action({ chip, address, width, count: length / (width / 8) });
|
|
28
|
+
const { words } = await DebugActionRead.run_action({ chip, address, width, count: length / (width / 8), speed: args.speed });
|
|
27
29
|
/** 16 bytes per line, each line prefixed with its address */
|
|
28
30
|
const perLine = 128 / width;
|
|
29
31
|
const lines = [];
|
|
@@ -2,6 +2,7 @@ import { callServer } from '../../stm32/context.js';
|
|
|
2
2
|
import { _defineTool } from '../../stm32/tool.js';
|
|
3
3
|
import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
4
4
|
import { DebugActionRead } from '../../stm32/actions/DebugActionRead.js';
|
|
5
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
5
6
|
import { hex } from '../../stm32/utils/faultUtils.js';
|
|
6
7
|
import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
|
|
7
8
|
import { loadPeripheral } from '../../stm32/utils/svdUtils.js';
|
|
@@ -9,7 +10,7 @@ import { loadPeripheral } from '../../stm32/utils/svdUtils.js';
|
|
|
9
10
|
export default _defineTool({
|
|
10
11
|
name: 'read_peripheral',
|
|
11
12
|
description: "Read and decode a peripheral's registers (e.g. GPIOA, USART2, TIM1, RCC) over SWD (probe-rs or STM32_Programmer_CLI), using the MCU's SVD data from the TuringCode server (needs TURINGCODE_TOKEN the first time per peripheral, then cached in .turingcode/svd/ and works offline). Does not halt the core. Data/FIFO registers whose read has side effects are skipped. Lists non-zero fields only.",
|
|
12
|
-
properties: { name: { type: 'string', pattern: '^[A-Za-z0-9_]{1,32}$' } },
|
|
13
|
+
properties: { name: { type: 'string', pattern: '^[A-Za-z0-9_]{1,32}$' }, speed: SWD_SPEED_PROP },
|
|
13
14
|
required: ['name'],
|
|
14
15
|
needsProbe: true,
|
|
15
16
|
run: async (args) => {
|
|
@@ -41,7 +42,7 @@ export default _defineTool({
|
|
|
41
42
|
for (const run of runs) {
|
|
42
43
|
/** Read whole words; a 16-bit register at offset 2 is the upper half of its word */
|
|
43
44
|
const start = run[0].addressOffsetInt & ~3;
|
|
44
|
-
const { words } = await DebugActionRead.run_action({ chip, address: p.baseAddressInt + start, width: 32, count: ((run[run.length - 1].addressOffsetInt - start) >> 2) + 1 });
|
|
45
|
+
const { words } = await DebugActionRead.run_action({ chip, address: p.baseAddressInt + start, width: 32, count: ((run[run.length - 1].addressOffsetInt - start) >> 2) + 1, speed: args.speed });
|
|
45
46
|
for (const r of run)
|
|
46
47
|
values.set(r, words[(r.addressOffsetInt - start) >> 2] >>> ((r.addressOffsetInt & 3) * 8));
|
|
47
48
|
}
|
|
@@ -2,15 +2,17 @@ import { _defineTool } from '../../stm32/tool.js';
|
|
|
2
2
|
import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
3
3
|
import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
|
|
4
4
|
import { DebugActionReset } from '../../stm32/actions/DebugActionReset.js';
|
|
5
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
5
6
|
/** Resets the board over SWD; the chip comes from the project's .ioc. */
|
|
6
7
|
export default _defineTool({
|
|
7
8
|
name: 'reset_target',
|
|
8
9
|
description: "Hardware reset of the project's target board over SWD (probe-rs or STM32_Programmer_CLI).",
|
|
10
|
+
properties: { speed: SWD_SPEED_PROP },
|
|
9
11
|
needsProbe: true,
|
|
10
|
-
run: async (
|
|
12
|
+
run: async (args, ctx) => {
|
|
11
13
|
const project = await findStm32Project();
|
|
12
14
|
const chip = await getMcuFromIoc(project.root);
|
|
13
|
-
const reset_result = await DebugActionReset.run_action_get_tail({ chip });
|
|
15
|
+
const reset_result = await DebugActionReset.run_action_get_tail({ chip, speed: args.speed });
|
|
14
16
|
return `Reset ${chip}\n\n${reset_result}`;
|
|
15
17
|
},
|
|
16
18
|
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DebugActionInfo } from '../../stm32/actions/DebugActionInfo.js';
|
|
2
|
+
import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
|
|
2
3
|
import { callServer } from '../../stm32/context.js';
|
|
3
4
|
import { _defineTool } from '../../stm32/tool.js';
|
|
4
5
|
import { deviceLines, lineFamily, matchMcuNames, parseTargetInfo } from '../../stm32/utils/mcu_utils.js';
|
|
@@ -7,9 +8,10 @@ export default _defineTool({
|
|
|
7
8
|
name: 'target_info',
|
|
8
9
|
description: 'Identify the chip connected to the debug probe (STM32_Programmer_CLI, without resetting it): device ID, name, flash size, core and voltage, ' +
|
|
9
10
|
'and the CubeMX MCU names that match it for `turingcode project template --mcu` (needs TURINGCODE_TOKEN; the package and pin count cannot be read over SWD). Needs no project.',
|
|
11
|
+
properties: { speed: SWD_SPEED_PROP },
|
|
10
12
|
needsProbe: true,
|
|
11
|
-
run: async () => {
|
|
12
|
-
const out = await DebugActionInfo.run_action({});
|
|
13
|
+
run: async (args) => {
|
|
14
|
+
const out = await DebugActionInfo.run_action({ speed: args.speed });
|
|
13
15
|
const info = parseTargetInfo(out.stdout + out.stderr);
|
|
14
16
|
if (!info.name)
|
|
15
17
|
throw new Error(`No target found: ${DebugActionInfo.tail(out)}`);
|
|
@@ -41,11 +41,21 @@ export default _defineTool({
|
|
|
41
41
|
const outside = findings.length
|
|
42
42
|
? `\n\nWarning: code outside USER CODE sections differs from what CubeMX generated; \`project regen\` would stop on it. Move it into a USER CODE section:\n\n${findings.join('\n\n')}`
|
|
43
43
|
: '';
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
44
|
+
if (args.build === undefined && args.analyse === undefined)
|
|
45
|
+
return synced + outside;
|
|
46
|
+
const parts = [];
|
|
47
|
+
/** the CLI prints each part as soon as it is done, so a long build does not look stuck */
|
|
48
|
+
const emit = (part) => (ctx.print ? ctx.print(part) : parts.push(part));
|
|
49
|
+
emit(`# Sync\n${synced}${outside}`);
|
|
50
|
+
let built = true;
|
|
51
|
+
if (args.build !== undefined) {
|
|
52
|
+
const build = await runBuild(project, args.build || 'Debug', !!args.verbose);
|
|
53
|
+
built = build.ok;
|
|
54
|
+
emit(`# Build\n${build.text}`);
|
|
55
|
+
}
|
|
56
|
+
if (args.analyse !== undefined) {
|
|
57
|
+
emit(`# Static analysis\n${built ? await analysisStatic.run({ profile: args.analyse || 'quick' }, ctx) : 'Skipped: the build failed.'}`);
|
|
58
|
+
}
|
|
59
|
+
return parts.join('\n');
|
|
50
60
|
},
|
|
51
61
|
});
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { DiscoveredSystemTool, SystemToolId } from '../utils/discover_tools.js';
|
|
2
|
+
import { Prop } from '../tool.js';
|
|
3
|
+
/** SWD clock in kHz when a command sets none: slow enough for long wires and clone probes, still flashes in seconds */
|
|
4
|
+
export declare const DEFAULT_SWD_SPEED_KHZ = 1000;
|
|
5
|
+
/** The `speed` argument of the commands that open the probe; fills {speed} in the command lines */
|
|
6
|
+
export declare const SWD_SPEED_PROP: Prop;
|
|
2
7
|
/** Values for the {placeholders}; booleans switch optional argument groups on and off */
|
|
3
8
|
export type ActionParams = Record<string, string | number | boolean>;
|
|
4
9
|
/** A command line argument with {name} placeholders, or a group of them used only when the boolean param `if` is true */
|
|
@@ -6,6 +6,15 @@ import { promisify } from 'node:util';
|
|
|
6
6
|
import { discover_system_tools, toolHint, } from '../utils/discover_tools.js';
|
|
7
7
|
import { claimProbe, releaseProbe } from '../utils/utils_mutex.js';
|
|
8
8
|
const run = promisify(execFile);
|
|
9
|
+
/** SWD clock in kHz when a command sets none: slow enough for long wires and clone probes, still flashes in seconds */
|
|
10
|
+
export const DEFAULT_SWD_SPEED_KHZ = 1000;
|
|
11
|
+
/** The `speed` argument of the commands that open the probe; fills {speed} in the command lines */
|
|
12
|
+
export const SWD_SPEED_PROP = {
|
|
13
|
+
type: 'integer',
|
|
14
|
+
minimum: 5,
|
|
15
|
+
maximum: 24000,
|
|
16
|
+
description: `SWD clock in kHz (default ${DEFAULT_SWD_SPEED_KHZ}); the probe rounds it to a clock it supports`,
|
|
17
|
+
};
|
|
9
18
|
/**
|
|
10
19
|
* A debug operation (program, read memory, reset, ...) and the command line of each tool that can do it.
|
|
11
20
|
* The first installed tool in `commands` order runs it, with the placeholders filled from the action params.
|
|
@@ -51,7 +60,8 @@ export class DebugAction {
|
|
|
51
60
|
const template = this.commands[tool.id];
|
|
52
61
|
if (!template)
|
|
53
62
|
throw new Error(`${this.title} is not supported by ${tool.id}`);
|
|
54
|
-
const values = this.values(params);
|
|
63
|
+
const values = { ...this.values(params) };
|
|
64
|
+
values.speed ??= DEFAULT_SWD_SPEED_KHZ;
|
|
55
65
|
const fill = (arg) => arg.replace(/\{(\w+)\}/g, (_all, name) => {
|
|
56
66
|
if (!(name in values))
|
|
57
67
|
throw new Error(`${this.title}: no value for {${name}} in the ${tool.id} command`);
|
|
@@ -6,6 +6,6 @@ import { DebugAction } from './DebugAction.js';
|
|
|
6
6
|
export class DebugActionInfo extends DebugAction {
|
|
7
7
|
static title = 'Identifying the target';
|
|
8
8
|
static commands = {
|
|
9
|
-
STM32_Programmer_CLI: ['-c', 'port=SWD', 'mode=HOTPLUG'],
|
|
9
|
+
STM32_Programmer_CLI: ['-c', 'port=SWD', 'mode=HOTPLUG', 'freq={speed}'],
|
|
10
10
|
};
|
|
11
11
|
}
|
|
@@ -3,6 +3,7 @@ import { DiscoveredSystemTool } from '../utils/discover_tools.js';
|
|
|
3
3
|
export type ProgramParams = {
|
|
4
4
|
chip: string; /** probe-rs target name (e.g. STM32G474RETx) */
|
|
5
5
|
elf: string; /** path of the ELF to flash */
|
|
6
|
+
speed?: number; /** SWD clock in kHz, default DEFAULT_SWD_SPEED_KHZ */
|
|
6
7
|
};
|
|
7
8
|
/**
|
|
8
9
|
* Writes an ELF over SWD, verifies it and resets the target.
|
|
@@ -18,6 +19,7 @@ export declare class DebugActionProgram extends DebugAction {
|
|
|
18
19
|
if: string;
|
|
19
20
|
args: string[];
|
|
20
21
|
})[];
|
|
22
|
+
/** HOTPLUG attaches and halts the running core without a reset, so it works where probe-rs's reset-and-halt times out */
|
|
21
23
|
STM32_Programmer_CLI: (string | {
|
|
22
24
|
if: string;
|
|
23
25
|
args: string[];
|
|
@@ -26,9 +28,17 @@ export declare class DebugActionProgram extends DebugAction {
|
|
|
26
28
|
/**
|
|
27
29
|
* Programs the ELF. If probe-rs fails on a dual-bank G47x/G48x part it has no algorithm for, retries once
|
|
28
30
|
* with the whole chip erased first, which also clears data kept in flash.
|
|
29
|
-
*
|
|
31
|
+
* If probe-rs still fails and STM32_Programmer_CLI is installed, retries once with it.
|
|
32
|
+
* @param p chip, ELF and SWD clock
|
|
30
33
|
* @param tool tool to use, default the one pickSystemTool returns
|
|
31
|
-
* @returns the tool output, with a note at the end when the whole chip was erased
|
|
34
|
+
* @returns the tool output, with a note at the end when the whole chip was erased or the fallback tool ran
|
|
32
35
|
*/
|
|
33
36
|
static run_action(p: ProgramParams, tool?: DiscoveredSystemTool): Promise<ToolOutput>;
|
|
37
|
+
/**
|
|
38
|
+
* Programs the ELF with one tool; on probe-rs and a dual-bank G47x/G48x part, retries once with the whole chip erased.
|
|
39
|
+
* @param p chip, ELF and SWD clock
|
|
40
|
+
* @param tool tool to use
|
|
41
|
+
* @returns the tool output, with a note at the end when the whole chip was erased
|
|
42
|
+
*/
|
|
43
|
+
private static run_with_dual_bank_retry;
|
|
34
44
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { DebugAction } from './DebugAction.js';
|
|
2
2
|
import { DebugActionRead } from './DebugActionRead.js';
|
|
3
|
+
import { discover_system_tools } from '../utils/discover_tools.js';
|
|
3
4
|
import { hasSingleBankFlashAlgo } from '../utils/mcu_utils.js';
|
|
4
5
|
/** STM32G4 FLASH_OPTR and its DBANK bit (dual-bank mode, 2 KB pages, bank 2 at 0x08040000). */
|
|
5
6
|
const G4_FLASH_OPTR = 0x40022020;
|
|
@@ -8,9 +9,10 @@ const G4_OPTR_DBANK = 1 << 22;
|
|
|
8
9
|
* Tells whether the target runs in a flash mode that probe-rs's per-sector erase gets wrong:
|
|
9
10
|
* a 128/256 KB STM32G47x/G48x with DBANK set, where probe-rs assumes the single-bank page layout.
|
|
10
11
|
* @param chip probe-rs target name (e.g. STM32G474CCTx)
|
|
12
|
+
* @param speed SWD clock in kHz
|
|
11
13
|
* @returns true when the whole chip must be erased before programming
|
|
12
14
|
*/
|
|
13
|
-
async function needsChipErase(chip) {
|
|
15
|
+
async function needsChipErase(chip, speed) {
|
|
14
16
|
if (!hasSingleBankFlashAlgo(chip))
|
|
15
17
|
return false;
|
|
16
18
|
const { words: [optr], } = await DebugActionRead.run_action({
|
|
@@ -18,6 +20,7 @@ async function needsChipErase(chip) {
|
|
|
18
20
|
address: G4_FLASH_OPTR,
|
|
19
21
|
width: 32,
|
|
20
22
|
count: 1,
|
|
23
|
+
speed,
|
|
21
24
|
});
|
|
22
25
|
return (optr & G4_OPTR_DBANK) !== 0;
|
|
23
26
|
}
|
|
@@ -37,6 +40,8 @@ export class DebugActionProgram extends DebugAction {
|
|
|
37
40
|
'{chip}',
|
|
38
41
|
'--protocol',
|
|
39
42
|
'swd',
|
|
43
|
+
'--speed',
|
|
44
|
+
'{speed}',
|
|
40
45
|
'--non-interactive',
|
|
41
46
|
'--disable-progressbars',
|
|
42
47
|
{ if: 'chipErase', args: ['--chip-erase'] },
|
|
@@ -44,9 +49,12 @@ export class DebugActionProgram extends DebugAction {
|
|
|
44
49
|
'--reset',
|
|
45
50
|
'{elf}',
|
|
46
51
|
],
|
|
52
|
+
/** HOTPLUG attaches and halts the running core without a reset, so it works where probe-rs's reset-and-halt times out */
|
|
47
53
|
STM32_Programmer_CLI: [
|
|
48
54
|
'-c',
|
|
49
55
|
'port=SWD',
|
|
56
|
+
'mode=HOTPLUG',
|
|
57
|
+
'freq={speed}',
|
|
50
58
|
{ if: 'chipErase', args: ['-e', 'all'] },
|
|
51
59
|
'-w',
|
|
52
60
|
'{elf}',
|
|
@@ -57,18 +65,45 @@ export class DebugActionProgram extends DebugAction {
|
|
|
57
65
|
/**
|
|
58
66
|
* Programs the ELF. If probe-rs fails on a dual-bank G47x/G48x part it has no algorithm for, retries once
|
|
59
67
|
* with the whole chip erased first, which also clears data kept in flash.
|
|
60
|
-
*
|
|
68
|
+
* If probe-rs still fails and STM32_Programmer_CLI is installed, retries once with it.
|
|
69
|
+
* @param p chip, ELF and SWD clock
|
|
61
70
|
* @param tool tool to use, default the one pickSystemTool returns
|
|
62
|
-
* @returns the tool output, with a note at the end when the whole chip was erased
|
|
71
|
+
* @returns the tool output, with a note at the end when the whole chip was erased or the fallback tool ran
|
|
63
72
|
*/
|
|
64
73
|
static async run_action(p, tool) {
|
|
65
74
|
tool ??= await this.pickSystemTool();
|
|
75
|
+
try {
|
|
76
|
+
return await this.run_with_dual_bank_retry(p, tool);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
if (tool.id !== 'probe-rs')
|
|
80
|
+
throw e;
|
|
81
|
+
const cube = (await discover_system_tools()).find((t) => t.id === 'STM32_Programmer_CLI');
|
|
82
|
+
if (!cube)
|
|
83
|
+
throw e;
|
|
84
|
+
const out = await super.run_action({ ...p, chipErase: false }, cube).catch((e2) => {
|
|
85
|
+
throw new Error(`${e.message}\n\nRetried with STM32_Programmer_CLI, which also failed:\n${e2.message}`);
|
|
86
|
+
});
|
|
87
|
+
/** appended to stderr so tail() keeps it */
|
|
88
|
+
return {
|
|
89
|
+
...out,
|
|
90
|
+
stderr: `${out.stderr}\nprobe-rs failed, programmed with STM32_Programmer_CLI instead. probe-rs error:\n${e.message.slice(-500)}`,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Programs the ELF with one tool; on probe-rs and a dual-bank G47x/G48x part, retries once with the whole chip erased.
|
|
96
|
+
* @param p chip, ELF and SWD clock
|
|
97
|
+
* @param tool tool to use
|
|
98
|
+
* @returns the tool output, with a note at the end when the whole chip was erased
|
|
99
|
+
*/
|
|
100
|
+
static async run_with_dual_bank_retry(p, tool) {
|
|
66
101
|
try {
|
|
67
102
|
return await super.run_action({ ...p, chipErase: false }, tool);
|
|
68
103
|
}
|
|
69
104
|
catch (e) {
|
|
70
105
|
/** A failed OPTR read (e.g. probe unplugged) means no retry, and the programming error is the one to report */
|
|
71
|
-
if (tool.id !== 'probe-rs' || !(await needsChipErase(p.chip).catch(() => false)))
|
|
106
|
+
if (tool.id !== 'probe-rs' || !(await needsChipErase(p.chip, p.speed).catch(() => false)))
|
|
72
107
|
throw e;
|
|
73
108
|
const out = await super.run_action({ ...p, chipErase: true }, tool);
|
|
74
109
|
/** appended to stderr so tail() keeps it */
|
|
@@ -5,6 +5,7 @@ export type ReadParams = {
|
|
|
5
5
|
address: number; /** start address, aligned to the word width */
|
|
6
6
|
width: 8 | 16 | 32; /** word width in bits */
|
|
7
7
|
count: number; /** number of words to read */
|
|
8
|
+
speed?: number; /** SWD clock in kHz, default DEFAULT_SWD_SPEED_KHZ */
|
|
8
9
|
};
|
|
9
10
|
/** Reads target memory without halting the core. Never writes to the target. */
|
|
10
11
|
export declare class DebugActionRead extends DebugAction {
|
|
@@ -17,6 +18,7 @@ export declare class DebugActionRead extends DebugAction {
|
|
|
17
18
|
chip: string; /** probe-rs target name (e.g. STM32G474RETx) */
|
|
18
19
|
width: 8 | 16 | 32; /** word width in bits */
|
|
19
20
|
count: number; /** number of words to read */
|
|
21
|
+
speed?: number; /** SWD clock in kHz, default DEFAULT_SWD_SPEED_KHZ */
|
|
20
22
|
address: string;
|
|
21
23
|
bytes: number;
|
|
22
24
|
};
|
|
@@ -9,6 +9,8 @@ export class DebugActionRead extends DebugAction {
|
|
|
9
9
|
'{chip}',
|
|
10
10
|
'--protocol',
|
|
11
11
|
'swd',
|
|
12
|
+
'--speed',
|
|
13
|
+
'{speed}',
|
|
12
14
|
'--non-interactive',
|
|
13
15
|
'b{width}',
|
|
14
16
|
'0x{address}',
|
|
@@ -18,6 +20,7 @@ export class DebugActionRead extends DebugAction {
|
|
|
18
20
|
'-c',
|
|
19
21
|
'port=SWD',
|
|
20
22
|
'mode=HOTPLUG',
|
|
23
|
+
'freq={speed}',
|
|
21
24
|
'-r{width}',
|
|
22
25
|
'0x{address}',
|
|
23
26
|
'{bytes}',
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DebugAction } from './DebugAction.js';
|
|
2
2
|
export type ResetParams = {
|
|
3
3
|
chip: string; /** probe-rs target name (e.g. STM32G474RETx) */
|
|
4
|
+
speed?: number; /** SWD clock in kHz, default DEFAULT_SWD_SPEED_KHZ */
|
|
4
5
|
};
|
|
5
6
|
/** Resets the target through the only connected probe. */
|
|
6
7
|
export declare class DebugActionReset extends DebugAction {
|
|
@@ -3,7 +3,7 @@ import { DebugAction } from './DebugAction.js';
|
|
|
3
3
|
export class DebugActionReset extends DebugAction {
|
|
4
4
|
static title = 'Reset';
|
|
5
5
|
static commands = {
|
|
6
|
-
'probe-rs': ['reset', '--chip', '{chip}', '--protocol', 'swd', '--non-interactive'],
|
|
7
|
-
STM32_Programmer_CLI: ['-c', 'port=SWD', 'mode=HOTPLUG', '-rst'],
|
|
6
|
+
'probe-rs': ['reset', '--chip', '{chip}', '--protocol', 'swd', '--speed', '{speed}', '--non-interactive'],
|
|
7
|
+
STM32_Programmer_CLI: ['-c', 'port=SWD', 'mode=HOTPLUG', 'freq={speed}', '-rst'],
|
|
8
8
|
};
|
|
9
9
|
}
|
package/dist/stm32/context.d.ts
CHANGED
|
@@ -18,6 +18,9 @@ export declare function callServer(name: string, args: object, timeoutMs?: numbe
|
|
|
18
18
|
* @param project project root and name
|
|
19
19
|
* @param preset CMake preset
|
|
20
20
|
* @param verbose keep the full reply of a successful build, not the short one
|
|
21
|
-
* @returns the build reply, followed by where the ELF went or why it was not downloaded
|
|
21
|
+
* @returns the build reply, followed by where the ELF went or why it was not downloaded, and whether the build succeeded
|
|
22
22
|
*/
|
|
23
|
-
export declare function runBuild(project: Project, preset: string, verbose?: boolean): Promise<
|
|
23
|
+
export declare function runBuild(project: Project, preset: string, verbose?: boolean): Promise<{
|
|
24
|
+
text: string;
|
|
25
|
+
ok: boolean;
|
|
26
|
+
}>;
|
package/dist/stm32/context.js
CHANGED
|
@@ -32,11 +32,11 @@ export function callServer(name, args, timeoutMs) {
|
|
|
32
32
|
* @param project project root and name
|
|
33
33
|
* @param preset CMake preset
|
|
34
34
|
* @param verbose keep the full reply of a successful build, not the short one
|
|
35
|
-
* @returns the build reply, followed by where the ELF went or why it was not downloaded
|
|
35
|
+
* @returns the build reply, followed by where the ELF went or why it was not downloaded, and whether the build succeeded
|
|
36
36
|
*/
|
|
37
37
|
export async function runBuild(project, preset, verbose = false) {
|
|
38
38
|
const r = await buildProject(callServer, project, preset);
|
|
39
39
|
/** a failed build keeps the full reply, so no error is hidden */
|
|
40
40
|
const text = r.ok && !verbose ? compactBuildReply(r.text) : r.text;
|
|
41
|
-
return r.note ? `${text}\n\n${r.note}` : text;
|
|
41
|
+
return { text: r.note ? `${text}\n\n${r.note}` : text, ok: r.ok };
|
|
42
42
|
}
|
package/dist/stm32/session.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export interface StartOptions {
|
|
|
11
11
|
chip: string; /** probe-rs target name */
|
|
12
12
|
elf: string; /** ELF with the debug info of the running firmware */
|
|
13
13
|
flash: boolean; /** flash the ELF and halt after reset, instead of attaching */
|
|
14
|
+
speed?: number; /** SWD clock in kHz, default DEFAULT_SWD_SPEED_KHZ */
|
|
14
15
|
}
|
|
15
16
|
export declare class DebugSession {
|
|
16
17
|
readonly opts: StartOptions;
|
package/dist/stm32/session.js
CHANGED
|
@@ -7,6 +7,7 @@ import { readFile } from 'node:fs/promises';
|
|
|
7
7
|
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
8
8
|
import { claimProbe, releaseProbe } from './utils/utils_mutex.js';
|
|
9
9
|
import { DebugActionServer } from './actions/DebugActionServer.js';
|
|
10
|
+
import { DEFAULT_SWD_SPEED_KHZ } from './actions/DebugAction.js';
|
|
10
11
|
export class DebugSession {
|
|
11
12
|
opts;
|
|
12
13
|
proc;
|
|
@@ -294,6 +295,7 @@ export async function startSession(opts) {
|
|
|
294
295
|
chip: opts.chip,
|
|
295
296
|
cwd: opts.root,
|
|
296
297
|
wireProtocol: 'Swd',
|
|
298
|
+
speed: opts.speed ?? DEFAULT_SWD_SPEED_KHZ,
|
|
297
299
|
connectUnderReset: false,
|
|
298
300
|
consoleLogLevel: 'Console',
|
|
299
301
|
...(opts.flash && {
|
package/dist/stm32/tool.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export interface ToolContext {
|
|
|
17
17
|
cwd: string; /** caller's working directory */
|
|
18
18
|
socketPath: string; /** debug daemon socket of the project */
|
|
19
19
|
debugActive(): boolean;
|
|
20
|
+
print?(part: string): void; /** CLI only: prints a finished part of the reply now; without it the tool returns every part */
|
|
20
21
|
}
|
|
21
22
|
export interface ToolDef {
|
|
22
23
|
name: string;
|
|
@@ -57,7 +57,12 @@ export async function runToolCommand(tool, args, mode) {
|
|
|
57
57
|
const refused = safetyCheck(tool, session);
|
|
58
58
|
if (refused)
|
|
59
59
|
throw new Error(refused);
|
|
60
|
-
return tool.run(args, {
|
|
60
|
+
return tool.run(args, {
|
|
61
|
+
cwd,
|
|
62
|
+
socketPath: paths.socket,
|
|
63
|
+
debugActive: () => session,
|
|
64
|
+
print: part => process.stdout.write(part.trimEnd() + "\n"),
|
|
65
|
+
});
|
|
61
66
|
}
|
|
62
67
|
/**
|
|
63
68
|
* Builds the yargs subcommand of one tool: a flag per argument, the tool's description as help, and its examples.
|
|
@@ -94,7 +99,10 @@ export function toolCommand(spec) {
|
|
|
94
99
|
if (invalid) {
|
|
95
100
|
throw Object.assign(new Error(invalid.replace(/^(Missing argument|Unknown argument): (\w+)/, (_m, what, name) => `${what}: --${flagName(name)}`)), { exitCode: BAD_ARGUMENTS });
|
|
96
101
|
}
|
|
97
|
-
|
|
102
|
+
const text = (await runToolCommand(spec.tool, args, spec.mode)).trimEnd();
|
|
103
|
+
/** empty when the tool already printed every part */
|
|
104
|
+
if (text)
|
|
105
|
+
process.stdout.write(text + "\n");
|
|
98
106
|
},
|
|
99
107
|
};
|
|
100
108
|
}
|
|
@@ -1,46 +1,49 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: turingcode-cli
|
|
3
|
-
description: Use
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# turingcode for STM32
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
##
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
## Commands
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
- `turingcode project --help`: sync (
|
|
19
|
-
- `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
|
|
20
|
-
- `turingcode debug --help`: breakpoints, stepping, stack, variables.
|
|
21
|
-
|
|
22
|
-
##
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
##
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
1
|
+
---
|
|
2
|
+
name: turingcode-cli
|
|
3
|
+
description: Use the turingcode CLI for any STM32 project work - create, sync, build or analyze a project; regenerate from the .ioc; change pins, clocks or peripherals; flash, read registers or debug the board; look up MCU and component datasheets.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# turingcode CLI for STM32
|
|
7
|
+
|
|
8
|
+
`turingcode` handles the whole STM32 workflow: project setup, building, configuration, flashing and debugging. Use it instead of calling probe-rs or STM32_Programmer_CLI directly.
|
|
9
|
+
|
|
10
|
+
## Start here
|
|
11
|
+
|
|
12
|
+
Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
|
|
13
|
+
|
|
14
|
+
## Commands
|
|
15
|
+
|
|
16
|
+
Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
|
|
17
|
+
|
|
18
|
+
- `turingcode project --help`: sync (`-b` to also build), pull, regen, drivers, syntax check, static analysis.
|
|
19
|
+
- `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
|
|
20
|
+
- `turingcode debug --help`: breakpoints, stepping, stack, variables.
|
|
21
|
+
|
|
22
|
+
## Server tools
|
|
23
|
+
|
|
24
|
+
Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
|
|
25
|
+
|
|
26
|
+
- `turingcode tool list` shows the available tools.
|
|
27
|
+
- `turingcode tool call <name> --args '<json>' > result.md` runs one.
|
|
28
|
+
|
|
29
|
+
After a tool changes the server copy of the project, run `turingcode project pull` (or `project regen`) to bring the changes local.
|
|
30
|
+
|
|
31
|
+
## New project
|
|
32
|
+
|
|
33
|
+
Only when the user asks for one.
|
|
34
|
+
|
|
35
|
+
1. Run `turingcode probe info` to identify the connected chip and list its matching CubeMX names.
|
|
36
|
+
2. Pick one name. The package (pin count) can't be read over SWD, so ask the user or pick a package with the pins they need. Names that differ only in package build the same code for their shared pins.
|
|
37
|
+
3. Run `turingcode project template --mcu <name>` to download it into `./<name>/`, then `cd` into that folder. All project commands run from the project folder; copy your `.env` there if you use one.
|
|
38
|
+
|
|
39
|
+
## Typical loop
|
|
40
|
+
|
|
41
|
+
1. Edit the code, run `turingcode project sync -b` and fix the reported errors. Before finishing a change, run `turingcode project sync -b -a` to add static analysis.
|
|
42
|
+
2. Flash with `turingcode probe program`.
|
|
43
|
+
3. Verify it runs without looking at the board: read a register the program changes a few times with `turingcode probe read` and check that it changes as expected.
|
|
44
|
+
4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
|
|
45
|
+
|
|
46
|
+
## CRITICAL Safety rules
|
|
47
|
+
|
|
48
|
+
- Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu. Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
|
|
49
|
+
- Don't touch RDP without a reason. Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
|
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
# Storage
|
|
2
|
-
|
|
3
|
-
- Use this when saving settings, calibration or other data to flash or EEPROM.
|
|
4
|
-
|
|
5
|
-
## Register array
|
|
6
|
-
|
|
7
|
-
- Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
|
|
8
|
-
- Derive each offset from the previous one with `sizeof`:
|
|
9
|
-
```cpp
|
|
10
|
-
#define REG_CTRL 0 // uint8
|
|
11
|
-
#define REG_CALIB_ACC 1 // 3 × float
|
|
12
|
-
#define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
|
|
13
|
-
```
|
|
14
|
-
- Save only settings, never live status or measurements.
|
|
15
|
-
- Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
|
|
16
|
-
- Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
|
|
17
|
-
- Bound every setter over the whole write:
|
|
18
|
-
```cpp
|
|
19
|
-
if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
|
|
20
|
-
```
|
|
21
|
-
|
|
22
|
-
## Settings page
|
|
23
|
-
|
|
24
|
-
- Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
|
|
25
|
-
```ld
|
|
26
|
-
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
|
|
27
|
-
```
|
|
28
|
-
- Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
|
|
29
|
-
- Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
|
|
30
|
-
- Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
|
|
31
|
-
|
|
32
|
-
## Header
|
|
33
|
-
|
|
34
|
-
- Start the page with one 16-byte header for the whole array, then the registers:
|
|
35
|
-
```
|
|
36
|
-
[ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
|
|
37
|
-
0 4 6 10 16
|
|
38
|
-
```
|
|
39
|
-
- `magic`: a fixed constant; blank or foreign flash won't match.
|
|
40
|
-
- `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
|
|
41
|
-
- `crc`: over the registers; catches a cut-off save or a flipped bit.
|
|
42
|
-
- On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
|
|
43
|
-
|
|
44
|
-
## Writing
|
|
45
|
-
|
|
46
|
-
- Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
|
|
47
|
-
- Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
|
|
48
|
-
```cpp
|
|
49
|
-
M_Status status = this->flash_unlock();
|
|
50
|
-
if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
|
|
51
|
-
if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
|
|
52
|
-
if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
|
|
53
|
-
status |= this->flash_lock();
|
|
54
|
-
if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
|
|
55
|
-
```
|
|
56
|
-
- Give your own busy-bit polling a timeout; the HAL calls already have one.
|
|
57
|
-
- Save from a task or the main loop, never from an ISR.
|
|
1
|
+
# Storage
|
|
2
|
+
|
|
3
|
+
- Use this when saving settings, calibration or other data to flash or EEPROM.
|
|
4
|
+
|
|
5
|
+
## Register array
|
|
6
|
+
|
|
7
|
+
- Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
|
|
8
|
+
- Derive each offset from the previous one with `sizeof`:
|
|
9
|
+
```cpp
|
|
10
|
+
#define REG_CTRL 0 // uint8
|
|
11
|
+
#define REG_CALIB_ACC 1 // 3 × float
|
|
12
|
+
#define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
|
|
13
|
+
```
|
|
14
|
+
- Save only settings, never live status or measurements.
|
|
15
|
+
- Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
|
|
16
|
+
- Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
|
|
17
|
+
- Bound every setter over the whole write:
|
|
18
|
+
```cpp
|
|
19
|
+
if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Settings page
|
|
23
|
+
|
|
24
|
+
- Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
|
|
25
|
+
```ld
|
|
26
|
+
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
|
|
27
|
+
```
|
|
28
|
+
- Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
|
|
29
|
+
- Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
|
|
30
|
+
- Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
|
|
31
|
+
|
|
32
|
+
## Header
|
|
33
|
+
|
|
34
|
+
- Start the page with one 16-byte header for the whole array, then the registers:
|
|
35
|
+
```
|
|
36
|
+
[ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
|
|
37
|
+
0 4 6 10 16
|
|
38
|
+
```
|
|
39
|
+
- `magic`: a fixed constant; blank or foreign flash won't match.
|
|
40
|
+
- `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
|
|
41
|
+
- `crc`: over the registers; catches a cut-off save or a flipped bit.
|
|
42
|
+
- On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
|
|
43
|
+
|
|
44
|
+
## Writing
|
|
45
|
+
|
|
46
|
+
- Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
|
|
47
|
+
- Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
|
|
48
|
+
```cpp
|
|
49
|
+
M_Status status = this->flash_unlock();
|
|
50
|
+
if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
|
|
51
|
+
if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
|
|
52
|
+
if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
|
|
53
|
+
status |= this->flash_lock();
|
|
54
|
+
if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
|
|
55
|
+
```
|
|
56
|
+
- Give your own busy-bit polling a timeout; the HAL calls already have one.
|
|
57
|
+
- Save from a task or the main loop, never from an ISR.
|
|
@@ -1,67 +1,67 @@
|
|
|
1
|
-
# Tasks and interrupts
|
|
2
|
-
|
|
3
|
-
- Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
|
|
4
|
-
|
|
5
|
-
## ISRs
|
|
6
|
-
|
|
7
|
-
- Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
|
|
8
|
-
- Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
|
|
9
|
-
- Use one event bit per source.
|
|
10
|
-
- Count events that must not be lost; bits merge when an event repeats before it's handled:
|
|
11
|
-
```cpp
|
|
12
|
-
while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
|
|
13
|
-
```
|
|
14
|
-
- Null-check globals in callbacks; they can fire before the object exists.
|
|
15
|
-
|
|
16
|
-
## Without an RTOS
|
|
17
|
-
|
|
18
|
-
- Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
|
|
19
|
-
```cpp
|
|
20
|
-
__disable_irq();
|
|
21
|
-
uint32_t events = g_events;
|
|
22
|
-
g_events = 0;
|
|
23
|
-
__enable_irq();
|
|
24
|
-
if (events & EVT_IMU_READY) imu->read_into_memory();
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
## With FreeRTOS
|
|
28
|
-
|
|
29
|
-
- Notify the worker task from the ISR with `...FromISR` APIs, then yield:
|
|
30
|
-
```cpp
|
|
31
|
-
BaseType_t woken = pdFALSE;
|
|
32
|
-
xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
|
|
33
|
-
portYIELD_FROM_ISR(woken);
|
|
34
|
-
```
|
|
35
|
-
- Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
|
|
36
|
-
- Wait with a timeout; on timeout poll the source, so a missed edge can't stall the task:
|
|
37
|
-
```cpp
|
|
38
|
-
if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
|
|
39
|
-
&& HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
## Shared data
|
|
43
|
-
|
|
44
|
-
- ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
|
|
45
|
-
```cpp
|
|
46
|
-
taskENTER_CRITICAL();
|
|
47
|
-
size_t n = rx_len;
|
|
48
|
-
memcpy(local, rx_buf, n);
|
|
49
|
-
rx_len = 0;
|
|
50
|
-
taskEXIT_CRITICAL();
|
|
51
|
-
parse(local, n); // never parse rx_buf in place
|
|
52
|
-
```
|
|
53
|
-
- Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
|
|
54
|
-
|
|
55
|
-
## DMA
|
|
56
|
-
|
|
57
|
-
- Use static or member buffers, never locals; DMA keeps running after the call returns.
|
|
58
|
-
- Check the length against the buffer size before copying in.
|
|
59
|
-
- Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
|
|
60
|
-
```cpp
|
|
61
|
-
if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
|
|
62
|
-
this->_tx_busy = false; // or this->_tx_sem.release()
|
|
63
|
-
return M_StatusEnum::M_ERROR;
|
|
64
|
-
}
|
|
65
|
-
```
|
|
66
|
-
- Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
|
|
67
|
-
- Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
|
|
1
|
+
# Tasks and interrupts
|
|
2
|
+
|
|
3
|
+
- Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
|
|
4
|
+
|
|
5
|
+
## ISRs
|
|
6
|
+
|
|
7
|
+
- Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
|
|
8
|
+
- Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
|
|
9
|
+
- Use one event bit per source.
|
|
10
|
+
- Count events that must not be lost; bits merge when an event repeats before it's handled:
|
|
11
|
+
```cpp
|
|
12
|
+
while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
|
|
13
|
+
```
|
|
14
|
+
- Null-check globals in callbacks; they can fire before the object exists.
|
|
15
|
+
|
|
16
|
+
## Without an RTOS
|
|
17
|
+
|
|
18
|
+
- Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
|
|
19
|
+
```cpp
|
|
20
|
+
__disable_irq();
|
|
21
|
+
uint32_t events = g_events;
|
|
22
|
+
g_events = 0;
|
|
23
|
+
__enable_irq();
|
|
24
|
+
if (events & EVT_IMU_READY) imu->read_into_memory();
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## With FreeRTOS
|
|
28
|
+
|
|
29
|
+
- Notify the worker task from the ISR with `...FromISR` APIs, then yield:
|
|
30
|
+
```cpp
|
|
31
|
+
BaseType_t woken = pdFALSE;
|
|
32
|
+
xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
|
|
33
|
+
portYIELD_FROM_ISR(woken);
|
|
34
|
+
```
|
|
35
|
+
- Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
|
|
36
|
+
- Wait with a timeout; on timeout poll the source, so a missed edge can't stall the task:
|
|
37
|
+
```cpp
|
|
38
|
+
if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
|
|
39
|
+
&& HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Shared data
|
|
43
|
+
|
|
44
|
+
- ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
|
|
45
|
+
```cpp
|
|
46
|
+
taskENTER_CRITICAL();
|
|
47
|
+
size_t n = rx_len;
|
|
48
|
+
memcpy(local, rx_buf, n);
|
|
49
|
+
rx_len = 0;
|
|
50
|
+
taskEXIT_CRITICAL();
|
|
51
|
+
parse(local, n); // never parse rx_buf in place
|
|
52
|
+
```
|
|
53
|
+
- Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
|
|
54
|
+
|
|
55
|
+
## DMA
|
|
56
|
+
|
|
57
|
+
- Use static or member buffers, never locals; DMA keeps running after the call returns.
|
|
58
|
+
- Check the length against the buffer size before copying in.
|
|
59
|
+
- Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
|
|
60
|
+
```cpp
|
|
61
|
+
if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
|
|
62
|
+
this->_tx_busy = false; // or this->_tx_sem.release()
|
|
63
|
+
return M_StatusEnum::M_ERROR;
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
- Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
|
|
67
|
+
- Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
|
package/package.json
CHANGED