@turingcode/cli 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/create-cli.js +6 -4
- package/dist/cli/index.js +1 -1
- package/dist/core/exact/fraction.js +2 -0
- package/dist/core/files.js +2 -2
- package/dist/core/json-shape.js +1 -0
- package/dist/core/query.js +2 -2
- package/dist/core/tables/csv.d.ts +13 -2
- package/dist/core/tables/csv.js +54 -25
- package/dist/core/tables/markdown.js +8 -2
- package/dist/features/contract/diagnostics.d.ts +3 -0
- package/dist/features/contract/diagnostics.js +7 -4
- package/dist/features/contract/load.js +4 -4
- package/dist/features/contract/rules.d.ts +12 -0
- package/dist/features/contract/rules.js +31 -4
- package/dist/features/debug/clear_breakpoint.d.ts +1 -0
- package/dist/features/debug/clear_breakpoint.js +1 -1
- package/dist/features/debug/command.js +2 -2
- package/dist/features/debug/continue.d.ts +1 -0
- package/dist/features/debug/continue.js +2 -2
- package/dist/features/debug/debug_start.d.ts +1 -0
- package/dist/features/debug/debug_start.js +2 -2
- package/dist/features/debug/debug_stop.d.ts +1 -0
- package/dist/features/debug/debug_stop.js +1 -1
- package/dist/features/debug/evaluate.d.ts +1 -0
- package/dist/features/debug/evaluate.js +5 -5
- package/dist/features/debug/get_stack.d.ts +1 -0
- package/dist/features/debug/get_stack.js +1 -1
- package/dist/features/debug/get_variables.d.ts +1 -0
- package/dist/features/debug/get_variables.js +2 -2
- package/dist/features/debug/halt.d.ts +1 -0
- package/dist/features/debug/halt.js +1 -1
- package/dist/features/debug/set_breakpoint.d.ts +1 -0
- package/dist/features/debug/set_breakpoint.js +1 -1
- package/dist/features/debug/step.d.ts +1 -0
- package/dist/features/debug/step.js +2 -2
- package/dist/features/install-mods/install.js +4 -3
- package/dist/features/install-skills/install.d.ts +1 -0
- package/dist/features/install-skills/install.js +1 -1
- package/dist/features/probe/command.d.ts +1 -1
- package/dist/features/probe/command.js +103 -35
- package/dist/features/probe/kill_all_debuggers.d.ts +1 -0
- package/dist/features/probe/kill_all_debuggers.js +5 -5
- package/dist/features/probe/list_probes.d.ts +1 -0
- package/dist/features/probe/list_probes.js +1 -1
- package/dist/features/probe/program_project.d.ts +1 -0
- package/dist/features/probe/program_project.js +3 -3
- package/dist/features/probe/read_fault_status.d.ts +1 -0
- package/dist/features/probe/read_fault_status.js +1 -1
- package/dist/features/probe/read_memory.d.ts +1 -0
- package/dist/features/probe/read_memory.js +2 -2
- package/dist/features/probe/read_peripheral.d.ts +1 -0
- package/dist/features/probe/read_peripheral.js +7 -5
- package/dist/features/probe/reset_probe_usb.d.ts +1 -0
- package/dist/features/probe/reset_probe_usb.js +1 -1
- package/dist/features/probe/reset_target.d.ts +1 -0
- package/dist/features/probe/reset_target.js +1 -1
- package/dist/features/probe/target_info.d.ts +1 -0
- package/dist/features/probe/target_info.js +1 -1
- package/dist/features/project/analysis_static.d.ts +1 -0
- package/dist/features/project/analysis_static.js +1 -1
- package/dist/features/project/analysis_syntax_check.d.ts +1 -0
- package/dist/features/project/analysis_syntax_check.js +1 -1
- package/dist/features/project/command.js +3 -8
- package/dist/features/project/project_download_template.d.ts +1 -0
- package/dist/features/project/project_download_template.js +4 -4
- package/dist/features/project/project_sync_to_server.js +2 -2
- package/dist/features/project/stm32_cubetools_download_drivers.d.ts +1 -0
- package/dist/features/project/stm32_cubetools_download_drivers.js +2 -2
- package/dist/features/status/get_status.d.ts +1 -0
- package/dist/features/status/get_status.js +1 -1
- package/dist/features/table/check.js +5 -5
- package/dist/features/table/read.js +9 -9
- package/dist/features/tool/command.d.ts +2 -2
- package/dist/features/tool/command.js +95 -66
- package/dist/lib.d.ts +4 -0
- package/dist/lib.js +4 -2
- package/dist/stm32/actions/DebugAction.d.ts +4 -2
- package/dist/stm32/actions/DebugAction.js +6 -5
- package/dist/stm32/actions/DebugActionInfo.d.ts +4 -0
- package/dist/stm32/actions/DebugActionInfo.js +4 -2
- package/dist/stm32/actions/DebugActionListProbes.d.ts +1 -0
- package/dist/stm32/actions/DebugActionListProbes.js +1 -1
- package/dist/stm32/actions/DebugActionProgram.d.ts +8 -2
- package/dist/stm32/actions/DebugActionProgram.js +9 -7
- package/dist/stm32/actions/DebugActionRead.d.ts +8 -7
- package/dist/stm32/actions/DebugActionRead.js +5 -3
- package/dist/stm32/actions/DebugActionReset.d.ts +2 -1
- package/dist/stm32/actions/DebugActionReset.js +1 -1
- package/dist/stm32/actions/DebugActionServer.d.ts +4 -0
- package/dist/stm32/actions/DebugActionServer.js +4 -2
- package/dist/stm32/analysis.d.ts +1 -0
- package/dist/stm32/build.d.ts +4 -4
- package/dist/stm32/build.js +1 -1
- package/dist/stm32/context.js +2 -2
- package/dist/stm32/daemon.d.ts +8 -6
- package/dist/stm32/daemon.js +25 -18
- package/dist/stm32/regen.js +14 -8
- package/dist/stm32/session.d.ts +9 -6
- package/dist/stm32/session.js +11 -10
- package/dist/stm32/sync.d.ts +1 -0
- package/dist/stm32/sync.js +5 -3
- package/dist/stm32/tool.d.ts +5 -3
- package/dist/stm32/toolCommand.d.ts +4 -4
- package/dist/stm32/toolCommand.js +1 -3
- package/dist/stm32/utils/discover_tools.d.ts +2 -1
- package/dist/stm32/utils/discover_tools.js +1 -1
- package/dist/stm32/utils/downloadzip_utils.js +4 -4
- package/dist/stm32/utils/faultUtils.d.ts +2 -1
- package/dist/stm32/utils/faultUtils.js +2 -2
- package/dist/stm32/utils/findElf.d.ts +1 -1
- package/dist/stm32/utils/findElf.js +1 -1
- package/dist/stm32/utils/listSyncFiles.js +12 -10
- package/dist/stm32/utils/mcu_utils.d.ts +5 -6
- package/dist/stm32/utils/mcu_utils.js +10 -9
- package/dist/stm32/utils/project_utils.d.ts +1 -1
- package/dist/stm32/utils/project_utils.js +5 -3
- package/dist/stm32/utils/usb_utils.js +2 -2
- package/dist/stm32/utils/user_code.d.ts +4 -1
- package/dist/stm32/utils/user_code.js +5 -3
- package/dist/stm32/utils/utils_mutex.js +34 -14
- package/dist/stm32/validate.d.ts +1 -0
- package/dist/stm32/validate.js +1 -1
- package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +19 -23
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +71 -23
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +33 -0
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/app-startup.md +49 -0
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +103 -0
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/host-protocol.md +48 -0
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +24 -23
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +140 -0
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +66 -0
- package/package.json +4 -1
- package/dist/features/project/project_build.d.ts +0 -2
- package/dist/features/project/project_build.js +0 -22
- package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +0 -22
- package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +0 -19
- package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +0 -9
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +0 -42
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +0 -35
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +0 -34
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { readFile, readdir } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Server reply formats that name the resolved CubeMX MCU
|
|
5
|
+
* Error replies are left out.
|
|
6
|
+
*/
|
|
5
7
|
const MCU_PATTERNS = [
|
|
6
|
-
/^Barebone project template for (STM32\w+) \(/m,
|
|
7
|
-
/^Created project '[^']*' \((STM32\w+), /m,
|
|
8
|
+
/^Barebone project template for (STM32\w+) \(/m, /** PROJECT_TEMPLATE_READY */
|
|
9
|
+
/^Created project '[^']*' \((STM32\w+), /m, /** PROJECT_CREATED */
|
|
8
10
|
];
|
|
9
11
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* @
|
|
13
|
-
* @returns
|
|
12
|
+
* Returns the CubeMX MCU name (e.g. STM32G474RETx) from a project_template or project_create reply.
|
|
13
|
+
* @param text the server reply
|
|
14
|
+
* @returns the MCU name, or undefined when the reply names none
|
|
14
15
|
*/
|
|
15
16
|
export function getMcuFromText(text) {
|
|
16
17
|
for (const re of MCU_PATTERNS) {
|
|
@@ -68,7 +69,7 @@ export function parseTargetInfo(text) {
|
|
|
68
69
|
voltage: get('Voltage'),
|
|
69
70
|
};
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
+
/** The flash size letter of a CubeMX MCU name (the 11th character, e.g. STM32F303C[C]Tx) by size in KB */
|
|
72
73
|
const FLASH_CODES = { 16: '4', 32: '6', 64: '8', 128: 'B', 192: 'Z', 256: 'C', 384: 'D', 512: 'E', 768: 'F', 1024: 'G', 1536: 'H', 2048: 'I' };
|
|
73
74
|
/**
|
|
74
75
|
* The product lines of a device name, e.g. `STM32F302xB-xC/STM32F303xB-xC/F358xx` -> F302, F303, F358.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export interface ProjectSettings {
|
|
2
|
-
included_files: string[];
|
|
2
|
+
included_files: string[]; /** posix paths relative to the project root; files or folders synced even when otherwise excluded */
|
|
3
3
|
}
|
|
4
4
|
/**
|
|
5
5
|
* Loads <root>/.turingcode/settings.json, filling missing keys with defaults.
|
|
@@ -54,7 +54,7 @@ export async function findProject(start = process.cwd()) {
|
|
|
54
54
|
break;
|
|
55
55
|
}
|
|
56
56
|
const holds = async (dir, test) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).some((e) => test(e.name, e.isDirectory()));
|
|
57
|
-
|
|
57
|
+
/** the home folder's .turingcode/ holds user settings, not a project, so it never marks one */
|
|
58
58
|
const home = resolve(homedir());
|
|
59
59
|
for (const dir of ancestors) {
|
|
60
60
|
const marked = await holds(dir, (n, isDir) => isDir ? n === ".turingcode" && dir !== home && dirname(dir) !== dir : /^(\.mxproject|.+\.ioc)$/.test(n));
|
|
@@ -86,8 +86,10 @@ export async function findStm32ProjectIn(root) {
|
|
|
86
86
|
throw new Error(`Several STM32 projects found in ${root}:\n${roots.join("\n")}`);
|
|
87
87
|
return { root: roots[0], name: basename(roots[0]) };
|
|
88
88
|
}
|
|
89
|
-
|
|
90
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Folders never searched for a .ioc: generated or vendored trees that can hold many files, and dot folders
|
|
91
|
+
* (.git, and .turingcode whose regen baseline holds a copy of the .ioc).
|
|
92
|
+
*/
|
|
91
93
|
const SKIPPED_DIRS = /^(Drivers|build|node_modules|\..*)$/;
|
|
92
94
|
/**
|
|
93
95
|
* Lists dir and every folder below it that holds a .ioc or .mxproject file, without walking SKIPPED_DIRS.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
const run = promisify(execFile);
|
|
4
|
-
|
|
4
|
+
/** ST-LINK hardware IDs: V2, V2-1, V3 (three USB configurations), V3SET. */
|
|
5
5
|
const STLINK_IDS = ['3748', '374B', '374E', '374F', '3753', '3754'].map((pid) => `USB\\VID_0483&PID_${pid}`);
|
|
6
6
|
/**
|
|
7
7
|
* Restarts every connected ST-LINK USB device, waking one stuck in USB sleep.
|
|
@@ -12,7 +12,7 @@ export async function resetStlinkUsb() {
|
|
|
12
12
|
throw new Error('USB reset is only supported on Windows (pnputil)');
|
|
13
13
|
const restarted = [];
|
|
14
14
|
for (const hwid of STLINK_IDS) {
|
|
15
|
-
|
|
15
|
+
/** pnputil exits non-zero when no device matches. */
|
|
16
16
|
const { stdout } = await run('pnputil', ['/enum-devices', '/connected', '/deviceid', hwid], { windowsHide: true }).catch(() => ({ stdout: '' }));
|
|
17
17
|
for (const [, id] of stdout.matchAll(/^Instance ID:\s+(.+)$/gm)) {
|
|
18
18
|
await run('pnputil', ['/restart-device', id.trim()], { windowsHide: true });
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CubeMX keeps only the code between the USER CODE BEGIN and USER CODE END markers when it regenerates a file.
|
|
3
|
+
*/
|
|
1
4
|
export interface UserSection {
|
|
2
5
|
name: string;
|
|
3
|
-
start: number;
|
|
6
|
+
start: number; /** body is text.slice(start, end): the lines between the two markers */
|
|
4
7
|
end: number;
|
|
5
8
|
}
|
|
6
9
|
/**
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* CubeMX keeps only the code between the USER CODE BEGIN and USER CODE END markers when it regenerates a file.
|
|
3
|
+
*/
|
|
2
4
|
const MARKER = /\/\*\s*USER CODE (BEGIN|END)\s+(.+?)\s*\*\//g;
|
|
3
5
|
/**
|
|
4
6
|
* Scans a source file for CubeMX user code sections, collecting every marker mismatch instead of stopping at the first.
|
|
@@ -19,7 +21,7 @@ export function scanUserSections(text) {
|
|
|
19
21
|
errors.push(`line ${open.line}: USER CODE BEGIN ${open.name} has no matching END`);
|
|
20
22
|
if (sections.some((s) => s.name === name))
|
|
21
23
|
errors.push(`line ${line}: USER CODE section "${name}" appears twice`);
|
|
22
|
-
|
|
24
|
+
/** Body starts on the line after the marker when nothing else follows it on its line. */
|
|
23
25
|
const after = at + marker.length;
|
|
24
26
|
const eol = /^[ \t]*\r?\n/.exec(text.slice(after));
|
|
25
27
|
open = { name, start: after + (eol ? eol[0].length : 0), line };
|
|
@@ -28,7 +30,7 @@ export function scanUserSections(text) {
|
|
|
28
30
|
errors.push(`line ${line}: USER CODE END ${name} has no matching BEGIN`);
|
|
29
31
|
}
|
|
30
32
|
else {
|
|
31
|
-
|
|
33
|
+
/** Body ends before the END marker's indentation when the marker starts its line. */
|
|
32
34
|
const lineStart = text.lastIndexOf('\n', at - 1) + 1;
|
|
33
35
|
const end = lineStart >= open.start && /^[ \t]*$/.test(text.slice(lineStart, at))
|
|
34
36
|
? lineStart
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Probe lock for the debug actions and the debug session: one probe operation at a time, in this process and,
|
|
3
|
+
* once setProbeLockFile was called, across processes through a lock file that holds the owner's pid.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdirSync, readFileSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
6
|
import { dirname } from 'node:path';
|
|
5
|
-
let owner;
|
|
6
|
-
let lockFile;
|
|
7
|
+
let owner; /** name of the run in this process holding the probe */
|
|
8
|
+
let lockFile; /** set by the CLI to <project>/.turingcode/probe.lock */
|
|
7
9
|
/**
|
|
8
10
|
* Makes claimProbe also take a lock file, so other processes see the probe as busy.
|
|
9
11
|
* @param file lock file path, e.g. <project>/.turingcode/probe.lock; undefined turns the lock file off
|
|
@@ -42,17 +44,33 @@ function claimLockFile(name) {
|
|
|
42
44
|
if (e?.code !== 'EEXIST')
|
|
43
45
|
throw e;
|
|
44
46
|
}
|
|
47
|
+
let text = '';
|
|
45
48
|
let held = {};
|
|
46
49
|
try {
|
|
47
|
-
|
|
50
|
+
text = readFileSync(file, 'utf8');
|
|
51
|
+
held = JSON.parse(text);
|
|
48
52
|
}
|
|
49
53
|
catch {
|
|
50
|
-
|
|
54
|
+
/** unreadable or half written: treated as stale */
|
|
51
55
|
}
|
|
52
|
-
|
|
56
|
+
/** shortcut: a reused pid of a dead owner looks alive, so its lock waits for that process; add a start time if that bites */
|
|
53
57
|
if (held.pid && held.pid !== process.pid && isAlive(held.pid))
|
|
54
58
|
throw new Error(`The probe is busy with another turingcode run (pid ${held.pid}): ${held.name ?? 'unknown'}`);
|
|
55
|
-
|
|
59
|
+
/** stale: its process is gone. Moved away first (atomic), so two processes never both delete it and one a fresh lock. */
|
|
60
|
+
const moved = `${file}.${process.pid}`;
|
|
61
|
+
try {
|
|
62
|
+
renameSync(file, moved);
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
if (e?.code === 'ENOENT')
|
|
66
|
+
continue; /** another process took it over first */
|
|
67
|
+
throw e;
|
|
68
|
+
}
|
|
69
|
+
/** shortcut: if a third process created a lock while a fresh one was moved, putting it back replaces that one; add a takeover lock if that bites */
|
|
70
|
+
if (readFileSync(moved, 'utf8') === text)
|
|
71
|
+
unlinkSync(moved);
|
|
72
|
+
else
|
|
73
|
+
renameSync(moved, file); /** a fresh lock had replaced the stale one: put it back, the next loop reports it busy */
|
|
56
74
|
}
|
|
57
75
|
}
|
|
58
76
|
/**
|
|
@@ -79,15 +97,17 @@ export function releaseProbe() {
|
|
|
79
97
|
unlinkSync(lockFile);
|
|
80
98
|
}
|
|
81
99
|
catch {
|
|
82
|
-
|
|
100
|
+
/** no lock file, or not ours */
|
|
83
101
|
}
|
|
84
102
|
try {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
103
|
+
/**
|
|
104
|
+
* an empty .turingcode/ left outside a project would mark that folder as one.
|
|
105
|
+
* Keep this non-recursive: rmdir removes only an empty folder in one atomic step, so it can never delete
|
|
106
|
+
* project files or another process's lock; a readdir check first would race with that process.
|
|
107
|
+
*/
|
|
88
108
|
rmdirSync(dirname(lockFile));
|
|
89
109
|
}
|
|
90
110
|
catch {
|
|
91
|
-
|
|
111
|
+
/** not empty (other project files, or another process's lock) or already gone */
|
|
92
112
|
}
|
|
93
113
|
}
|
package/dist/stm32/validate.d.ts
CHANGED
package/dist/stm32/validate.js
CHANGED
|
@@ -13,7 +13,7 @@ export function validateArgs(def, args) {
|
|
|
13
13
|
if (!Object.hasOwn(args, key))
|
|
14
14
|
return `Missing argument: ${key}`;
|
|
15
15
|
for (const [key, v] of Object.entries(args)) {
|
|
16
|
-
|
|
16
|
+
/** own keys only: properties.__proto__ or .constructor would otherwise be found on Object.prototype */
|
|
17
17
|
const p = Object.hasOwn(properties, key) ? properties[key] : undefined;
|
|
18
18
|
if (!p)
|
|
19
19
|
return `Unknown argument: ${key}`;
|
|
@@ -5,35 +5,34 @@ description: Use when running the turingcode CLI on an STM32 project - creating
|
|
|
5
5
|
|
|
6
6
|
# turingcode for STM32
|
|
7
7
|
|
|
8
|
-
`turingcode`
|
|
9
|
-
there, and drives the board through the local debug probe. Run any command with `--help` for its
|
|
10
|
-
flags. Start with `turingcode status`: it shows the project, token, last build, debug session and
|
|
11
|
-
the installed probe tools. Server commands need `TURINGCODE_TOKEN`: set it in the environment, or
|
|
12
|
-
put `TURINGCODE_TOKEN=<token>` in a git-ignored `.env` in the folder you run `turingcode` from (a set
|
|
13
|
-
variable wins). Never print the token or commit the `.env`.
|
|
8
|
+
- `turingcode` is a set of tools for working with stm32 projects.
|
|
14
9
|
|
|
15
|
-
##
|
|
10
|
+
## Before you start
|
|
16
11
|
|
|
17
|
-
|
|
12
|
+
- Run `turingcode status` first: it shows the project, token, last build, debug session and the installed probe tools.
|
|
18
13
|
|
|
19
|
-
|
|
20
|
-
|---|---|
|
|
21
|
-
| `references/new-project.md` | creating a project: identifying the chip, picking the CubeMX name, downloading the template |
|
|
22
|
-
| `references/build-and-check.md` | syncing, building, pulling, regenerating from the `.ioc`, restoring drivers, syntax checks, static analysis |
|
|
23
|
-
| `references/board-and-debug.md` | flashing, resetting, reading registers or memory, decoding faults, recovering a probe, breakpoints and stepping |
|
|
14
|
+
## Commands
|
|
24
15
|
|
|
25
|
-
|
|
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).
|
|
26
29
|
|
|
27
|
-
In generated files (main.c, stm32*_it.c, ...) write code only between `/* USER CODE BEGIN <name> */` and
|
|
28
|
-
`/* USER CODE END <name> */`; CubeMX deletes everything else on `project regen`. Never change, move or delete
|
|
29
|
-
the markers, and keep code the section already holds.
|
|
30
|
-
`project sync` stops on unmatched markers and warns about code outside the sections.
|
|
31
30
|
|
|
32
31
|
## Server tools
|
|
33
32
|
|
|
34
33
|
Pins, clocks, .ioc edits, the knowledge base and register lookup are server tools:
|
|
35
34
|
|
|
36
|
-
- `turingcode tool list` to
|
|
35
|
+
- `turingcode tool list` to get a list of available tools.
|
|
37
36
|
- `turingcode tool call <name> --args '<json>' > result.md` to run it.
|
|
38
37
|
|
|
39
38
|
After a tool changes the server copy of the project, run `project pull` (or `project regen`).
|
|
@@ -43,8 +42,5 @@ After a tool changes the server copy of the project, run `project pull` (or `pro
|
|
|
43
42
|
1. Edit the code, then `turingcode project sync -b` and fix the reported errors;
|
|
44
43
|
`turingcode project sync -b -a` before finishing a change.
|
|
45
44
|
2. `turingcode probe program` to flash.
|
|
46
|
-
3. Confirm it runs without looking at the board: read the register the program changes a few times
|
|
47
|
-
with `probe read` and check it changes as expected. E.g. a blinking LED on PB6 of an STM32F3:
|
|
48
|
-
GPIOB ODR is `0x48000414`, and `probe read --address 0x48000414 --length 4` should alternate
|
|
49
|
-
between `00000040` and `00000000` (look up the base address and ODR offset for your chip).
|
|
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.
|
|
50
46
|
4. On a crash, `probe faults`, or `debug start` with breakpoints to find the cause.
|
|
@@ -1,43 +1,91 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: turingcode-firmware-code
|
|
3
|
-
description: Coding rules for embedded C/C++ firmware
|
|
3
|
+
description: Coding rules for embedded C/C++ firmware on STM32 (HAL, FreeRTOS, CMSIS-RTOS2) — file layout under App/, house style, and safety rules. Use whenever writing, editing, reviewing or organizing .c, .cpp, .h or .hpp files for a microcontroller, sensor drivers, ISRs and HAL callbacks, DMA, UART/SPI protocols, RTOS tasks, flash storage, filters, register maps and more.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Embedded C/C++ rules
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report to the user.
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## Read the matching reference first
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
Before writing code in an area, read its reference file:
|
|
13
13
|
|
|
14
14
|
| Read | When the change touches |
|
|
15
15
|
|---|---|
|
|
16
|
-
| `references/
|
|
17
|
-
| `references/
|
|
18
|
-
| `references/
|
|
19
|
-
| `references/
|
|
16
|
+
| `references/driver.md` | creating or modifying a driver for an external IC (sensor, part, ...) or Protocol (i2c, spi, ...) |
|
|
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 |
|
|
19
|
+
| `references/app-startup.md` | `main.c` hook, `extern "C"` entry, initialization order, task creation, re-init, µs time base |
|
|
20
|
+
| `references/storage.md` | saving settings, calibration or other data to flash/EEPROM |
|
|
21
|
+
| `references/host-protocol.md` | parsing host frames, command dispatch, register writes from a host, reply/telemetry packets |
|
|
22
|
+
| `references/M_StatusEnum.md` | the project has no `M_Status.hpp`, or how to return and combine statuses |
|
|
23
|
+
|
|
24
|
+
Names in the reference examples (`crc32`, `read_u32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own helpers and base classes. Use the existing ones. Add a missing helper once, to `Utils/` (CRC, byte packing) or `Platform/` (flash, bus access), never inline in the module that needs it.
|
|
25
|
+
|
|
26
|
+
## Generated and vendor code
|
|
27
|
+
|
|
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
|
+
- Never edit vendor code (HAL, CMSIS).
|
|
30
|
+
- Keep `main.c` thin: it only calls into `App/app.cpp`,
|
|
31
|
+
- when the app is C++ use a thin `extern "C"` interface.
|
|
32
|
+
- All application code lives in `<Project>/App/`.
|
|
33
|
+
|
|
34
|
+
## File layout
|
|
35
|
+
|
|
36
|
+
The architecture plan splits the project into Code Areas, each with a Structural_Role, and lists the ICs used. Map them to files as follows.
|
|
37
|
+
|
|
38
|
+
### Folders
|
|
39
|
+
|
|
40
|
+
Each Code Area gets exactly one folder in `<Project>/App/`:
|
|
41
|
+
|
|
42
|
+
- Code that talks to an external IC (register access, configuration, readout, commands) → `Drivers/<IC>/`. `<IC>` is the part number from the IC list, uppercase, without ordering, package or reel suffixes. All Code Areas of one IC share that folder.
|
|
43
|
+
- Everything else → one top-level category folder. Prefer these names; use another concise PascalCase name only when none fits:
|
|
44
|
+
|
|
45
|
+
| Folder | Typical content |
|
|
46
|
+
|---|---|
|
|
47
|
+
| `Platform/` | Adapters between HAL and App/: shared-bus arbitration, MCU peripheral access |
|
|
48
|
+
| `Algorithms/` | Data transformation: conversion, calibration, filtering, estimation, fusion |
|
|
49
|
+
| `Control/` | Regulation that commands actuators |
|
|
50
|
+
| `Comms/` | Protocols with external hosts/devices: framing, parsing, telemetry |
|
|
51
|
+
| `Storage/` | Persistent data: logs, saved settings |
|
|
52
|
+
| `UI/` | Local user interaction: screens, menus, buttons, status LEDs |
|
|
53
|
+
| `System/` | Orchestration: startup order, main cycle or tasks, modes, fault supervision |
|
|
54
|
+
| `Update/` | Firmware update |
|
|
55
|
+
| `Math/` | Shared numeric types and linear algebra |
|
|
56
|
+
| `Utils/` | Generic, domain-free helpers used by two or more Code Areas |
|
|
57
|
+
|
|
58
|
+
Create a folder only when something goes in it. No subfolders other than `Drivers/<IC>/`.
|
|
59
|
+
|
|
60
|
+
### Files
|
|
61
|
+
|
|
62
|
+
Each Code Area is one module: a source file and a header with the same base name (`.c`/`.h` for C, `.cpp`/`.hpp` for C++).
|
|
63
|
+
|
|
64
|
+
- **Driver modules**: the base name is the IC part number in lowercase (`test_ic_1.c` / `test_ic_1.h`), however the Code Area is worded. Add `<ic>_regs.h` when it does register access. A second Code Area for the same IC gets its own base name in the same folder.
|
|
65
|
+
- **Other modules**: the base name is the snake_case of the Code Area's purpose, without the category word (`attitude_estimation`, `output_protocol`).
|
|
66
|
+
- Header only, with no source file, when the module holds just constants, macros or inline/template helpers.
|
|
67
|
+
- Base names are unique across `App/`; on a collision, prefix the lowercase category name.
|
|
68
|
+
- Create no other files: no tests, docs, build files, README, configuration headers or placeholders.
|
|
20
69
|
|
|
21
70
|
## House style
|
|
22
71
|
|
|
23
|
-
Match
|
|
72
|
+
Match the existing style; don't "modernize" it.
|
|
24
73
|
|
|
25
|
-
- **Classes**: PascalCase joined
|
|
26
|
-
- **Members**: private fields start with `_
|
|
27
|
-
- **Methods**: snake_case
|
|
28
|
-
- **Errors**: return
|
|
29
|
-
- **Comments**: `/* ---- Title ---- */` section banners
|
|
30
|
-
- **
|
|
31
|
-
- **Layering**:
|
|
32
|
-
- Never edit vendor code (HAL, CMSIS, generated code outside `USER CODE` blocks).
|
|
74
|
+
- **Classes**: PascalCase words joined by underscores, prefixed by layer or role: `Sensor_Driver`, `Util_Mutex`, `Filter_MovingAvg`.
|
|
75
|
+
- **Members**: private fields start with `_`, internal helpers with `__`. Always access members through `this->`.
|
|
76
|
+
- **Methods**: snake_case in new code. Leave existing names in other cases as they are.
|
|
77
|
+
- **Errors**: return the project's `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints. Accumulate with `status |= ...` so the worst result wins.
|
|
78
|
+
- **Comments**: `/* ---- Title ---- */` for section banners; `/** */` blocks explain why, physics and units, and cite the datasheet; `////` marks code disabled temporarily.
|
|
79
|
+
- **Variants**: templates and `if constexpr` for compile-time sizes and variants; runtime feature switches as register or config bits. Use concrete class names directly (`Sensor_ICM42688 imu;`), with no typedef selection layer.
|
|
80
|
+
- **Layering**: all code lives in `App/`. Generic, reusable code goes in `Utils/` or `Math/`; chip- or product-specific code stays in its own module.
|
|
33
81
|
|
|
34
|
-
##
|
|
82
|
+
## Safety rules
|
|
35
83
|
|
|
36
|
-
1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return (`xTaskCreate`, semaphore acquire, queue send).
|
|
37
|
-
2. **Every wait has a timeout and an error path.** No
|
|
38
|
-
3. **
|
|
39
|
-
4. **
|
|
84
|
+
1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return (`xTaskCreate`, semaphore acquire, queue send). Never return a hard-coded `M_StatusEnum::M_OK` after fallible steps. If ignoring one is genuinely safe, say why in a comment.
|
|
85
|
+
2. **Every wait has a timeout and an error path.** No unbounded loops on hardware (ID checks, status bits, ready flags), and no retry count where 0 means "forever". Return an error so a missing peripheral fails visibly instead of hanging boot.
|
|
86
|
+
3. **Budget memory.** No `new`/`delete` in periodic or per-transaction paths; preallocate buffers and matrices as members or statics. Keep KB-sized objects (filter windows, matrices, arrays) off task stacks, and size each stack for what it holds.
|
|
87
|
+
4. **Test speed tweaks.** Before committing a performance change to a read or parse path, test it on hardware and confirm the success branch still runs on success.
|
|
40
88
|
|
|
41
89
|
## Before you finish
|
|
42
90
|
|
|
43
|
-
Re-read the diff against
|
|
91
|
+
Re-read the diff against these rules and against the checklist at the end of each reference file you loaded.
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# M_Status
|
|
2
|
+
|
|
3
|
+
- Use this when the project has no `M_Status.hpp` yet, or when unsure how to return or combine statuses.
|
|
4
|
+
|
|
5
|
+
## Values
|
|
6
|
+
|
|
7
|
+
- Only these, ordered best to worst: `M_OK`, `M_ERROR`, `M_BUSY`, `M_TIMEOUT`, `M_OUT_OF_RANGE`, `M_DISABLED`, `M_NOT_SUPPORTED`. Never add one without asking.
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
```cpp
|
|
12
|
+
M_Status status = M_StatusEnum::M_OK;
|
|
13
|
+
status |= this->com()->write(REG, &val, 1);
|
|
14
|
+
status |= HAL_SPI_Transmit(this->_hspi, buf, len, 10); // HAL statuses too
|
|
15
|
+
return status; // the worst result wins
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## If the project has none
|
|
19
|
+
|
|
20
|
+
- Add `Utils/M_Status.hpp`. Include the family HAL header (`stm32g4xx_hal.h`, `stm32f3xx_hal.h`, ...) for `HAL_StatusTypeDef`.
|
|
21
|
+
|
|
22
|
+
```cpp
|
|
23
|
+
enum M_StatusEnum { M_OK = 0, M_ERROR, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE, M_DISABLED, M_NOT_SUPPORTED };
|
|
24
|
+
|
|
25
|
+
class M_Status {
|
|
26
|
+
public:
|
|
27
|
+
M_StatusEnum value;
|
|
28
|
+
M_Status(M_StatusEnum v = M_OK) : value(v) {}
|
|
29
|
+
M_Status(HAL_StatusTypeDef h); // HAL_OK→M_OK, HAL_ERROR→M_ERROR, HAL_BUSY→M_BUSY, HAL_TIMEOUT→M_TIMEOUT
|
|
30
|
+
M_Status& operator|=(M_Status o) { if (o.value > this->value) this->value = o.value; return *this; }
|
|
31
|
+
operator M_StatusEnum() const { return this->value; }
|
|
32
|
+
};
|
|
33
|
+
```
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/app-startup.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# App startup
|
|
2
|
+
|
|
3
|
+
- Use this when writing the `main.c` hook, the app entry, initialization order, task creation, re-init of drivers, or a µs time base.
|
|
4
|
+
|
|
5
|
+
## Entry from main.c
|
|
6
|
+
|
|
7
|
+
- `main.c` passes the HAL handles in one C struct to one `extern "C"` function. The rest of the app is invisible to C.
|
|
8
|
+
- Declare every C-callable function in a header. Without one, C compiles an implicit declaration and passes garbage arguments.
|
|
9
|
+
|
|
10
|
+
```c
|
|
11
|
+
#ifdef __cplusplus
|
|
12
|
+
extern "C" {
|
|
13
|
+
#endif
|
|
14
|
+
typedef struct {
|
|
15
|
+
SPI_HandleTypeDef* spi_1;
|
|
16
|
+
TIM_HandleTypeDef* tim_micros;
|
|
17
|
+
} App_Config;
|
|
18
|
+
|
|
19
|
+
void app_init(App_Config cfg);
|
|
20
|
+
#ifdef __cplusplus
|
|
21
|
+
}
|
|
22
|
+
#endif
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Initialization
|
|
26
|
+
|
|
27
|
+
- The order lives in one function, written out step by step. Don't spread it over constructors or static initializers.
|
|
28
|
+
- Construct before `init()`, and `init()` before first use. Nothing reads a store before it's loaded.
|
|
29
|
+
- If `init()` needs the scheduler (RTOS delays, mutexes), run it in a task, and make the tasks that depend on it wait for it.
|
|
30
|
+
- Check every `xTaskCreate`, `osThreadNew`, queue and event-group creation.
|
|
31
|
+
|
|
32
|
+
## Re-init
|
|
33
|
+
|
|
34
|
+
- One owner handles re-init requests.
|
|
35
|
+
- Clear the module's ready flag first; its users skip their work while it's clear.
|
|
36
|
+
- Set it again only when `init()` returns `M_StatusEnum::M_OK`.
|
|
37
|
+
|
|
38
|
+
## Time base
|
|
39
|
+
|
|
40
|
+
- A 32-bit µs counter wraps after about 71.6 min. Extend it with an overflow count, and test the wrap.
|
|
41
|
+
- A shared timer callback checks `htim` against the timer it owns before acting.
|
|
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
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Writing and Editing an IC driver
|
|
2
|
+
|
|
3
|
+
- Use this when you want to create or edit driver for ICs or Protocols.
|
|
4
|
+
- If the project already has a COM driver or an IC base with similar names, inherit from it. Don't write a second one.
|
|
5
|
+
|
|
6
|
+
## Layers
|
|
7
|
+
|
|
8
|
+
- `COM_Driver` is the base for protocol drivers (`COM_SPI`, `COM_I2C`). Only these call HAL.
|
|
9
|
+
- `IC_Driver` is the base for IC drivers in `Drivers/<IC>/`. It talks to the chip only through a `COM_Driver*`.
|
|
10
|
+
|
|
11
|
+
## COM driver
|
|
12
|
+
|
|
13
|
+
- Used as a base class for communication protocols (I2C, SPI, ...)
|
|
14
|
+
- Subclasses implement transfers (read and write) using HAL or LL methods.
|
|
15
|
+
|
|
16
|
+
```cpp
|
|
17
|
+
class COM_Driver {
|
|
18
|
+
public:
|
|
19
|
+
virtual M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) = 0;
|
|
20
|
+
virtual M_Status write(uint8_t reg, const uint8_t* data, size_t len) = 0;
|
|
21
|
+
|
|
22
|
+
M_Status write_bit(uint8_t reg, uint8_t bit, uint8_t value); // read-modify-write
|
|
23
|
+
M_Status write_verify(uint8_t reg, uint8_t value, size_t tries); // write, read back, compare
|
|
24
|
+
M_Status wait_for_register(uint8_t reg, uint8_t expected, size_t tries);
|
|
25
|
+
void set_address_mask(uint8_t write_or, uint8_t read_or); // e.g. SPI read bit 0x80
|
|
26
|
+
};
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Protocol driver
|
|
30
|
+
|
|
31
|
+
- Owns the HAL handle and chip select; the IC driver never sees them.
|
|
32
|
+
- Holds the bus mutex for the whole transfer, chip select included, so ICs sharing the bus don't interleave.
|
|
33
|
+
|
|
34
|
+
```cpp
|
|
35
|
+
class COM_SPI : public COM_Driver {
|
|
36
|
+
public:
|
|
37
|
+
COM_SPI(SPI_HandleTypeDef* hspi, GPIO_TypeDef* cs_port, uint16_t cs_pin);
|
|
38
|
+
M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override; // CS low, TX reg|read mask, RX data, CS high
|
|
39
|
+
M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
|
|
40
|
+
private:
|
|
41
|
+
SPI_HandleTypeDef* _hspi;
|
|
42
|
+
GPIO_TypeDef* _cs_port;
|
|
43
|
+
uint16_t _cs_pin;
|
|
44
|
+
};
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## IC_Driver Class
|
|
48
|
+
|
|
49
|
+
- Base class used for all ICs
|
|
50
|
+
- Subclasses implement the virtual methods.
|
|
51
|
+
- A feature the IC lacks (eg: write into a temperature sensor) returns `M_StatusEnum::M_NOT_SUPPORTED`, never `M_StatusEnum::M_OK`.
|
|
52
|
+
- ICs of one family can share a templated base between the two for compile-time sample sizes, (eg: `template <size_t AXES, size_t BYTES_PER_AXIS> class IC_Sensor : public IC_Driver`).
|
|
53
|
+
|
|
54
|
+
```cpp
|
|
55
|
+
class IC_Driver {
|
|
56
|
+
public:
|
|
57
|
+
explicit IC_Driver(COM_Driver* com) : _com(com) {}
|
|
58
|
+
virtual M_Status init() = 0;
|
|
59
|
+
virtual M_Status reset() = 0;
|
|
60
|
+
virtual M_Status read(uint8_t* buf, size_t* index) = 0; // appends at buf[*index]
|
|
61
|
+
protected:
|
|
62
|
+
COM_Driver* com() { return this->_com; }
|
|
63
|
+
private:
|
|
64
|
+
COM_Driver* _com;
|
|
65
|
+
};
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### IC Sensor Driver
|
|
69
|
+
|
|
70
|
+
```cpp
|
|
71
|
+
class Sensor_ABC123 : public IC_Driver {
|
|
72
|
+
public:
|
|
73
|
+
using IC_Driver::IC_Driver;
|
|
74
|
+
M_Status init() override;
|
|
75
|
+
M_Status reset() override;
|
|
76
|
+
M_Status read(uint8_t* buf, size_t* index) override;
|
|
77
|
+
M_Status verify_id() { return this->com()->wait_for_register(ABC123_WHO_AM_I, ABC123_ID, 5); }
|
|
78
|
+
};
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- It never calls HAL and never creates its COM driver. The owner wires the two together:
|
|
82
|
+
```cpp
|
|
83
|
+
COM_SPI spi_imu(&hspi1, IMU_CS_GPIO_Port, IMU_CS_Pin);
|
|
84
|
+
Sensor_ABC123 imu(&spi_imu);
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Register header
|
|
88
|
+
|
|
89
|
+
`abc123_regs.h`, plain C, in datasheet order:
|
|
90
|
+
```c
|
|
91
|
+
#define ABC123_WHO_AM_I 0x0F
|
|
92
|
+
#define ABC123_ID 0x6B
|
|
93
|
+
#define ABC123_CTRL1 0x10
|
|
94
|
+
#define ABC123_ODR_POS 4
|
|
95
|
+
#define ABC123_ODR_MASK (0x0F << ABC123_ODR_POS)
|
|
96
|
+
#define ABC123_SPI_READ 0x80
|
|
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`
|