@turingcode/cli 0.3.6 → 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.
Files changed (33) hide show
  1. package/dist/features/debug/debug_start.js +6 -2
  2. package/dist/features/probe/program_project.js +10 -6
  3. package/dist/features/probe/read_fault_status.js +4 -2
  4. package/dist/features/probe/read_memory.js +3 -1
  5. package/dist/features/probe/read_peripheral.js +3 -2
  6. package/dist/features/probe/reset_target.js +4 -2
  7. package/dist/features/probe/target_info.js +4 -2
  8. package/dist/features/project/project_sync_to_server.js +16 -6
  9. package/dist/stm32/actions/DebugAction.d.ts +5 -0
  10. package/dist/stm32/actions/DebugAction.js +11 -1
  11. package/dist/stm32/actions/DebugActionInfo.js +1 -1
  12. package/dist/stm32/actions/DebugActionProgram.d.ts +12 -2
  13. package/dist/stm32/actions/DebugActionProgram.js +39 -4
  14. package/dist/stm32/actions/DebugActionRead.d.ts +2 -0
  15. package/dist/stm32/actions/DebugActionRead.js +3 -0
  16. package/dist/stm32/actions/DebugActionReset.d.ts +1 -0
  17. package/dist/stm32/actions/DebugActionReset.js +2 -2
  18. package/dist/stm32/context.d.ts +5 -2
  19. package/dist/stm32/context.js +2 -2
  20. package/dist/stm32/session.d.ts +1 -0
  21. package/dist/stm32/session.js +2 -0
  22. package/dist/stm32/tool.d.ts +1 -0
  23. package/dist/stm32/toolCommand.js +10 -2
  24. package/mods/claude/turingcode-skills/skills/AGENTS.md +8 -0
  25. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +49 -46
  26. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +3 -2
  27. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/app-startup.md +0 -7
  28. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +0 -6
  29. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/host-protocol.md +0 -7
  30. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +0 -6
  31. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -140
  32. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +67 -66
  33. 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: { flash: { type: 'boolean', description: 'Flash the .elf and halt after reset (default false: attach)' } },
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 (_args, ctx) => {
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 (_args, ctx) => {
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 (_args, ctx) => {
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
- const parts = [`# Sync\n${synced}${outside}`];
45
- if (args.build !== undefined)
46
- parts.push(`# Build\n${await runBuild(project, args.build || 'Debug', !!args.verbose)}`);
47
- if (args.analyse !== undefined)
48
- parts.push(`# Static analysis\n${await analysisStatic.run({ profile: args.analyse || 'quick' }, ctx)}`);
49
- return parts.length > 1 ? parts.join('\n') : synced + outside;
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
- * @param p chip and ELF
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
- * @param p chip and ELF
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
  }
@@ -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<string>;
23
+ export declare function runBuild(project: Project, preset: string, verbose?: boolean): Promise<{
24
+ text: string;
25
+ ok: boolean;
26
+ }>;
@@ -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
  }
@@ -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;
@@ -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 && {
@@ -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, { cwd, socketPath: paths.socket, debugActive: () => session });
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
- process.stdout.write((await runToolCommand(spec.tool, args, spec.mode)).trimEnd() + "\n");
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
  }
@@ -0,0 +1,8 @@
1
+ # Writing these skills
2
+
3
+ - Generic only: rules and house style that hold in any project. Never copy one project's architecture (boot order, register layout, frame format) into a skill.
4
+ - Save context: `SKILL.md` holds short rules and a reference table; details go in `references/*.md`, read only when needed.
5
+ - Short bullets, no prose. Small code examples that show the structure, not full implementations.
6
+ - Examples use the house names: `M_Status` / `M_StatusEnum::M_OK`, `this->`, `_member`, snake_case methods.
7
+ - Don't repeat what a tool already reports (e.g. `turingcode status` reports a missing token).
8
+ - Test a change with a subagent that follows only the skill, on real hardware when possible.
@@ -1,46 +1,49 @@
1
- ---
2
- name: turingcode-cli
3
- description: Use when running the turingcode CLI on an STM32 project - creating a project, syncing, building, syntax checks or static analysis, regenerating from the `.ioc`, changing pins, clocks or peripherals through server tools, flashing, reading the board's registers, or debugging with breakpoints. Not for how to write the C/C++ code itself.
4
- ---
5
-
6
- # turingcode for STM32
7
-
8
- - `turingcode` is a set of tools for working with stm32 projects.
9
-
10
- ## Before you start
11
-
12
- - Run `turingcode status` first: it shows the project, token, last build, debug session and the installed probe tools.
13
-
14
- ## Commands
15
-
16
- Read the help before you run commands in an area; every subcommand has its own `--help` with flags and examples.
17
-
18
- - `turingcode project --help`: sync (with `-b` to 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
- ## New project
23
-
24
- Only when the user asks for one.
25
-
26
- 1. `turingcode probe info` identifies the connected chip and lists the matching CubeMX names. Don't call probe-rs or STM32_Programmer_CLI yourself.
27
- 2. Pick one name. The package (pin count) can't be read over SWD: ask the user, or pick one that has the pins they need. Names differing only in package build the same code for pins they share.
28
- 3. `turingcode project template --mcu <name>` downloads it into `./<name>/`; `cd` into it, every project command runs from the project folder (copy the `.env` there too if you use one).
29
-
30
-
31
- ## Server tools
32
-
33
- Pins, clocks, .ioc edits, the knowledge base and register lookup are server tools:
34
-
35
- - `turingcode tool list` to get a list of available tools.
36
- - `turingcode tool call <name> --args '<json>' > result.md` to run it.
37
-
38
- After a tool changes the server copy of the project, run `project pull` (or `project regen`).
39
-
40
- ## Typical loop
41
-
42
- 1. Edit the code, then `turingcode project sync -b` and fix the reported errors;
43
- `turingcode project sync -b -a` before finishing a change.
44
- 2. `turingcode probe program` to flash.
45
- 3. Confirm it runs without looking at the board: read the register the program changes a few times with `probe read` and check it changes as expected.
46
- 4. On a crash, `probe faults`, or `debug start` with breakpoints to find the cause.
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.
@@ -15,7 +15,7 @@ Before writing code in an area, read its reference file:
15
15
  |---|---|
16
16
  | `references/driver.md` | creating or modifying a driver for an external IC (sensor, part, ...) or Protocol (i2c, spi, ...) |
17
17
  | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions, macros |
18
- | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, RTOS tasks, DMA, mutexes/semaphores, data shared between tasks or with an ISR |
18
+ | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, mutexes/semaphores, data shared between tasks or with an ISR |
19
19
  | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, initialization order, task creation, re-init, µs time base |
20
20
  | `references/storage.md` | saving settings, calibration or other data to flash/EEPROM |
21
21
  | `references/host-protocol.md` | parsing host frames, command dispatch, register writes from a host, reply/telemetry packets |
@@ -27,6 +27,7 @@ Names in the reference examples (`crc32`, `read_u32`, `flash_*`, `COM_Driver`, .
27
27
 
28
28
  - CubeMX regenerates generated files (`main.c`, `stm32*_it.c`, …) and deletes everything outside `/* USER CODE BEGIN <name> */` … `/* USER CODE END <name> */`. Write only inside these blocks, keep what they already hold, and never change, move or delete the markers.
29
29
  - Never edit vendor code (HAL, CMSIS).
30
+ - If the generated code already defines a HAL callback (e.g. `HAL_TIM_PeriodElapsedCallback` for the HAL time base), don't define it again. Call your handler from its USER CODE block.
30
31
  - Keep `main.c` thin: it only calls into `App/app.cpp`,
31
32
  - when the app is C++ use a thin `extern "C"` interface.
32
33
  - All application code lives in `<Project>/App/`.
@@ -88,4 +89,4 @@ Match the existing style; don't "modernize" it.
88
89
 
89
90
  ## Before you finish
90
91
 
91
- Re-read the diff against these rules and against the checklist at the end of each reference file you loaded.
92
+ Re-read the diff against these rules and the reference files you loaded.
@@ -40,10 +40,3 @@ void app_init(App_Config cfg);
40
40
  - A 32-bit µs counter wraps after about 71.6 min. Extend it with an overflow count, and test the wrap.
41
41
  - A shared timer callback checks `htim` against the timer it owns before acting.
42
42
  - Names match types (`delay_us(time_us_t us)`), and units are converted, not cast.
43
-
44
- ## Checklist
45
- - [ ] `main.c` calls one `extern "C"` entry; every C-callable function is declared in a header
46
- - [ ] Init order is explicit in one place; nothing is used before its `init()`
47
- - [ ] Every task and RTOS object creation is checked
48
- - [ ] Re-init clears the ready flag first and sets it only on success
49
- - [ ] µs counters handle wrap
@@ -95,9 +95,3 @@ Sensor_ABC123 imu(&spi_imu);
95
95
  #define ABC123_ODR_MASK (0x0F << ABC123_ODR_POS)
96
96
  #define ABC123_SPI_READ 0x80
97
97
  ```
98
-
99
- ## Checklist
100
- - [ ] Existing COM driver and IC base are reused
101
- - [ ] IC driver inherits the base, gets its COM driver from the constructor, and makes no HAL calls
102
- - [ ] Every retry and wait is bounded and returns `M_StatusEnum::M_TIMEOUT`
103
- - [ ] Every status is accumulated; no hard-coded `M_StatusEnum::M_OK`
@@ -39,10 +39,3 @@ if (start >= COUNT || len > COUNT - start) return M_StatusEnum::M_OUT_OF_RANGE;
39
39
 
40
40
  - Build into a static buffer, and check the room left before each append.
41
41
  - Clip values to their field width (`CLIP_U16(dt_us)`), and state the unit.
42
-
43
- ## Checklist
44
- - [ ] Frame sizes are `constexpr` and derive from one source
45
- - [ ] Searches and copies are bounded by the received length
46
- - [ ] Unsigned subtraction is guarded; the checksum is checked before acting
47
- - [ ] Range writes check `start + len` without overflow
48
- - [ ] Bad frames are consumed and answered with an error
@@ -28,9 +28,3 @@ reg = (reg & ~ODR_MASK) | ((odr << ODR_POS) & ODR_MASK);
28
28
  - Prefer `constexpr` and `inline` over macros unless you need token pasting.
29
29
  - Fully parenthesize macro bodies and arguments: `#define CLIP_U16(x) ((x) > 0xFFFF ? 0xFFFF : (x))`.
30
30
  - Derive sizes and offsets from one source.
31
-
32
- ## Checklist
33
- - [ ] Bit positions and signedness match the datasheet, with a citation
34
- - [ ] Field writes clear the old value first
35
- - [ ] Every value states its unit; conversions are named
36
- - [ ] Macros are parenthesized; sizes come from one source
@@ -1,140 +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
- - All settings live in one byte array, addressed by offset. RAM is the working copy; flash is the saved copy, saved and loaded as a whole.
8
- - Each offset derives from the previous one and from `sizeof`, so nothing overlaps or is counted twice:
9
-
10
- ```cpp
11
- #define REG_CTRL 0
12
- #define REG_BOOT_COUNT 1 // uint8
13
- #define REG_CALIB_ACC 2 // 3 × float
14
- #define REG_CALIB_MAG (REG_CALIB_ACC + 3 * sizeof(float)) // 3 × float
15
- #define REG_COUNT (REG_CALIB_MAG + 3 * sizeof(float))
16
- ```
17
- - Save only settings. Live status and measurements stay out of the saved array.
18
- - Read and write multi-byte values with `memcpy`, never through a cast pointer. Offsets are not aligned, and an unaligned `float` access faults:
19
- ```cpp
20
- float x;
21
- memcpy(&x, &this->_regs[REG_CALIB_ACC], sizeof(x)); // not *(float*)&this->_regs[...]
22
- ```
23
- - Defaults are one table in code. `load_defaults()` copies it into the array:
24
- ```cpp
25
- static constexpr uint8_t REG_DEFAULTS[REG_COUNT] = {
26
- 0x01, // REG_CTRL
27
- 0, // REG_BOOT_COUNT
28
- // the rest is zero-filled: calibration floats = 0.0f
29
- };
30
- ```
31
-
32
- - Setters reject offsets at or past the count, for every byte of a multi-byte write:
33
-
34
- ```cpp
35
- M_Status Register_Store::set_bytes(size_t reg, const uint8_t* src, size_t len) {
36
- if (reg >= REG_COUNT || len > REG_COUNT - reg)
37
- return M_StatusEnum::M_OUT_OF_RANGE;
38
- memcpy(&this->_regs[reg], src, len);
39
- return M_StatusEnum::M_OK;
40
- }
41
- ```
42
-
43
- ## Settings page
44
-
45
- - Use the last flash page. Take its address and size from the reference manual's flash chapter.
46
- - Shrink the `FLASH` length in the linker script by that page, so code can never be placed on it:
47
- ```ld
48
- /* last 2 KB page reserved for settings */
49
- FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K
50
- ```
51
- - Take page size, write unit and erase style from the HAL flash header and API, not from memory: `FLASH_PAGE_SIZE`, the `FLASH_TYPEPROGRAM_*` types (half-word on F1/F3, double-word on G4/L4, flash-word on H7), and whether `FLASH_EraseInitTypeDef` takes a page number (`Page`, plus `Banks` on dual-bank parts) or an address (`PageAddress`). Every programmed block starts on, and is padded to, that write unit. The HAL has no write-unit constant; derive it from the program type, e.g. `#define FLASH_WRITE_UNIT sizeof(uint64_t)` for `FLASH_TYPEPROGRAM_DOUBLEWORD`.
52
- - Check every HAL flash return, and `PageError` after `HAL_FLASHEx_Erase` (`0xFFFFFFFF` means success).
53
-
54
- ## Header
55
-
56
- - The first 16 bytes of the settings flash page are a header; the register array follows. One header covers the whole array, never one per setting.
57
-
58
- ```
59
- settings page: [ magic | version | crc | pad ][ registers ... ]
60
- 0 4 6 10 16
61
- ```
62
-
63
- - Each field answers one question on load:
64
- - `magic`: does this page hold our settings at all? It's any fixed constant you pick. Blank flash (`0xFFFFFFFF`) or leftover data from other firmware won't match it.
65
- - `version`: was it saved with the current register layout? An old layout would load into the wrong offsets.
66
- - `crc`: are the registers intact? A save cut off by a reset, or a flipped bit, won't match.
67
-
68
- ```cpp
69
- #define FLASH_MAGIC 0x52454753u // "REGS"
70
- #define FLASH_VERSION 3 // bump when an offset moves, a register is added/removed, or a new default must replace saved values
71
- #define HDR_MAGIC 0 // uint32
72
- #define HDR_VERSION 4 // uint16
73
- #define HDR_CRC 6 // uint32, CRC of the registers
74
- #define HDR_LEN 16 // padded to a multiple of the flash write unit
75
- ```
76
-
77
- - On load, a blank flash (0xFF), or a magic, version or CRC mismatch, loads the defaults from code and reports it. The caller logs that `M_ERROR` and keeps running on the defaults; it's expected on first boot, not a fatal error:
78
-
79
- ```cpp
80
- M_Status Register_Store::load() {
81
- uint8_t hdr[HDR_LEN];
82
- M_Status status = this->flash_read(0, hdr, HDR_LEN);
83
- status |= this->flash_read(HDR_LEN, this->_regs, REG_COUNT);
84
- if (status != M_StatusEnum::M_OK
85
- || read_u32(&hdr[HDR_MAGIC]) != FLASH_MAGIC // blank flash reads 0xFFFFFFFF
86
- || read_u16(&hdr[HDR_VERSION]) != FLASH_VERSION
87
- || read_u32(&hdr[HDR_CRC]) != crc32(this->_regs, REG_COUNT)) {
88
- this->load_defaults();
89
- return M_StatusEnum::M_ERROR; // caller reports it
90
- }
91
- return M_StatusEnum::M_OK;
92
- }
93
- ```
94
-
95
- ## Writing
96
-
97
- - Update the CRC, then erase, program, read back and compare.
98
- - Keep the flash locked except around erase and program, on the failure path too.
99
- - Pad with `0xFF`, the erased value, so padding programs nothing.
100
- - HAL erase and program calls time out internally; check their return. Code that polls the flash busy bit itself needs its own timeout.
101
-
102
- ```cpp
103
- M_Status Register_Store::save() {
104
- uint8_t hdr[HDR_LEN];
105
- memset(hdr, 0xFF, HDR_LEN);
106
- write_u32(&hdr[HDR_MAGIC], FLASH_MAGIC);
107
- write_u16(&hdr[HDR_VERSION], FLASH_VERSION);
108
- write_u32(&hdr[HDR_CRC], crc32(this->_regs, REG_COUNT));
109
-
110
- M_Status status = this->flash_unlock();
111
- if (status == M_StatusEnum::M_OK) { // never erase or program a locked flash
112
- status |= this->flash_erase_page(SETTINGS_PAGE); // checks PageError too
113
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
114
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT); // pads the tail with 0xFF
115
- }
116
- status |= this->flash_lock(); // runs even after a failure
117
- if (status != M_StatusEnum::M_OK) return status;
118
- return this->verify(hdr);
119
- }
120
-
121
- M_Status Register_Store::verify(const uint8_t* hdr) { // read back header and registers
122
- uint8_t buf[HDR_LEN + REG_COUNT];
123
- M_Status status = this->flash_read(0, buf, sizeof(buf));
124
- if (status == M_StatusEnum::M_OK
125
- && (memcmp(buf, hdr, HDR_LEN) != 0 || memcmp(&buf[HDR_LEN], this->_regs, REG_COUNT) != 0))
126
- status = M_StatusEnum::M_ERROR;
127
- return status;
128
- }
129
- ```
130
-
131
- ## Checklist
132
- - [ ] Settings page is the last page and is removed from the linker's `FLASH` region
133
- - [ ] Page size, write unit and erase fields come from the HAL; every HAL return and `PageError` is checked
134
- - [ ] Blocks are aligned and `0xFF`-padded to the write unit
135
- - [ ] Multi-byte values are copied with `memcpy`; erase and program run only after a successful unlock
136
- - [ ] One header (magic, version, CRC) covers the whole array
137
- - [ ] Version is bumped on any layout change, or when a new default must replace saved values
138
- - [ ] Blank flash or a bad header falls back to defaults
139
- - [ ] Writes are read back and compared; flash stays locked after
140
- - [ ] Offsets derive from one source; setters are bounded
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,66 +1,67 @@
1
- # Tasks and interrupts
2
-
3
- - Use this when writing ISRs, HAL callbacks, RTOS tasks, DMA transfers, or data shared between them.
4
-
5
- ## ISR → task
6
-
7
- - ISRs and HAL callbacks only signal a task. Bus transfers, parsing and math run in the task.
8
- - One notify bit per source, so one task can serve several.
9
- - Null-check every global the callback uses, because it can fire before the object exists.
10
-
11
- ```cpp
12
- void HAL_GPIO_EXTI_Callback(uint16_t pin) {
13
- if (reader_task == nullptr) return;
14
- uint32_t bits = 0;
15
- if (pin == IMU_DRDY_Pin) bits |= BIT_IMU_READY;
16
- if (pin == MAG_DRDY_Pin) bits |= BIT_MAG_READY;
17
- if (bits == 0) return;
18
- BaseType_t woken = pdFALSE;
19
- xTaskNotifyFromISR(reader_task, bits, eSetBits, &woken);
20
- portYIELD_FROM_ISR(woken);
21
- }
22
- ```
23
-
24
- ## Task loop
25
-
26
- - Waits on hardware events have a timeout. On timeout, poll the source (e.g. the DRDY pin level), so a missed edge doesn't stall it.
27
-
28
- ```cpp
29
- void task_read_sensors(void*) {
30
- for (;;) {
31
- uint32_t bits = 0;
32
- if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
33
- && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= BIT_IMU_READY;
34
- if (bits & BIT_IMU_READY) imu->read_into_memory();
35
- }
36
- }
37
- ```
38
-
39
- ## Shared data
40
-
41
- - Every buffer used by two contexts has one comment: who writes it, who reads it, what protects it.
42
- - Task ↔ task: a mutex taken with a timeout. On timeout, skip this cycle instead of blocking.
43
- - ISR ↔ task: a single-producer/single-consumer ring, or a critical section around the task's compaction and clearing.
44
- - The writer fills a temporary buffer and copies or swaps it in under the lock. Never write into a buffer that is being parsed.
45
- - A read-and-clear flag is consumed once per cycle, and the result is kept in a local.
46
-
47
- ## DMA
48
-
49
- - DMA buffers are static or class members, never locals.
50
- - Check the length against the DMA buffer size before copying into it.
51
- - Wait for the previous transfer (or take the TX semaphore) before reusing the buffer.
52
- - If starting the transfer fails, release what you took:
53
- ```cpp
54
- if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
55
- this->_tx_sem.release();
56
- return M_StatusEnum::M_ERROR;
57
- }
58
- ```
59
- - An error callback releases only the resources of the transfer that failed.
60
-
61
- ## Checklist
62
- - [ ] ISRs only notify; callbacks null-check globals
63
- - [ ] Every wait on hardware has a timeout and a fallback
64
- - [ ] Every shared buffer documents its writer, reader and lock
65
- - [ ] DMA buffers aren't on the stack; every acquire is released on failure
66
- - [ ] Each read-and-clear flag is consumed once per cycle
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "exports": {