@turingcode/cli 0.3.5 → 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 +1 -1
- package/dist/features/debug/command.js +1 -1
- package/dist/features/debug/debug_start.js +1 -1
- package/dist/features/probe/program_project.js +2 -2
- package/dist/features/project/command.js +3 -8
- package/dist/features/project/project_sync_to_server.js +1 -1
- package/dist/stm32/build.js +1 -1
- package/dist/stm32/utils/findElf.d.ts +1 -1
- package/dist/stm32/utils/findElf.js +1 -1
- package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +5 -3
- package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +69 -25
- 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 -3
- package/dist/features/project/project_build.js +0 -22
- 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 -21
package/dist/cli/create-cli.js
CHANGED
|
@@ -36,7 +36,7 @@ export function createCli(args) {
|
|
|
36
36
|
"- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
|
|
37
37
|
" MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
|
|
38
38
|
" Contract format: $0 contract --help.",
|
|
39
|
-
"- STM32 projects: `project sync
|
|
39
|
+
"- STM32 projects: `project sync -b` to build on the server, `probe program` to flash the board,",
|
|
40
40
|
" `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug",
|
|
41
41
|
" session; `status` shows the project and the installed debug tools.",
|
|
42
42
|
"- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);",
|
|
@@ -58,7 +58,7 @@ const command = {
|
|
|
58
58
|
"`debug start` launches a background daemon for the project that holds the probe-rs session; the other",
|
|
59
59
|
"debug commands talk to it, so the session lives across runs until `debug stop` (the daemon then exits).",
|
|
60
60
|
"Its files are in .turingcode/ (daemon.token, daemon.log, probe.lock). Needs probe-rs and a .elf in build/",
|
|
61
|
-
"(`project
|
|
61
|
+
"(`project sync -b`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
|
|
62
62
|
PROJECT_HELP,
|
|
63
63
|
].join("\n")),
|
|
64
64
|
handler: () => { },
|
|
@@ -13,7 +13,7 @@ export default _defineTool({
|
|
|
13
13
|
const project = await findStm32Project();
|
|
14
14
|
const elf = await findElf(project.root);
|
|
15
15
|
if (!elf)
|
|
16
|
-
throw new Error("No .elf in the project's build/ folder: run `turingcode project
|
|
16
|
+
throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
|
|
17
17
|
const chip = await getMcuFromIoc(project.root);
|
|
18
18
|
const flash = args.flash === true;
|
|
19
19
|
const s = await startSession({ root: project.root, chip, elf: elf.path, flash });
|
|
@@ -7,14 +7,14 @@ import { DebugActionProgram } from '../../stm32/actions/DebugActionProgram.js';
|
|
|
7
7
|
export default _defineTool({
|
|
8
8
|
name: 'program_project',
|
|
9
9
|
description: "Flash the newest .elf in the project's build/ folder \
|
|
10
|
-
(downloaded by `turingcode project
|
|
10
|
+
(downloaded by `turingcode project sync -b`) to the board over SWD with the installed programmer (probe-rs or STM32_Programmer_CLI), \
|
|
11
11
|
verify it and reset the target.",
|
|
12
12
|
needsProbe: true,
|
|
13
13
|
run: async (_args, ctx) => {
|
|
14
14
|
const project = await findStm32Project();
|
|
15
15
|
const elf = await findElf(project.root);
|
|
16
16
|
if (!elf)
|
|
17
|
-
throw new Error("No .elf in the project's build/ folder: run `turingcode project
|
|
17
|
+
throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
|
|
18
18
|
const chip = await getMcuFromIoc(project.root);
|
|
19
19
|
const program_result = await DebugActionProgram.run_action_get_tail({
|
|
20
20
|
elf: elf.path,
|
|
@@ -2,7 +2,6 @@ import { TOKEN_HELP } from "../../core/mcp.js";
|
|
|
2
2
|
import { toolCommand } from "../../stm32/toolCommand.js";
|
|
3
3
|
import analysisStatic from "./analysis_static.js";
|
|
4
4
|
import analysisSyntaxCheck from "./analysis_syntax_check.js";
|
|
5
|
-
import projectBuild from "./project_build.js";
|
|
6
5
|
import projectDownloadTemplate from "./project_download_template.js";
|
|
7
6
|
import projectRegenerate from "./project_regenerate.js";
|
|
8
7
|
import projectSyncFromServer from "./project_sync_from_server.js";
|
|
@@ -23,10 +22,6 @@ const subcommands = [
|
|
|
23
22
|
toolCommand({ command: "pull", tool: projectSyncFromServer, mode: "local", server: true, examples: [
|
|
24
23
|
["$0 project pull", "download the files that changed on the server, overwriting local copies"],
|
|
25
24
|
] }),
|
|
26
|
-
toolCommand({ command: "build", tool: projectBuild, mode: "local", server: true, examples: [
|
|
27
|
-
["$0 project build", "build the Debug preset and download the .elf into build/Debug/"],
|
|
28
|
-
["$0 project build --preset Release", "build another preset"],
|
|
29
|
-
] }),
|
|
30
25
|
toolCommand({ command: "check", tool: analysisSyntaxCheck, mode: "local", server: true, examples: [
|
|
31
26
|
["$0 project check", "syntax-check Core/ and App/ of the synced project"],
|
|
32
27
|
["$0 project check --files Core/Src/main.c", "one file"],
|
|
@@ -50,10 +45,10 @@ const command = {
|
|
|
50
45
|
command: "project",
|
|
51
46
|
describe: "Sync, build and edit the local STM32 project with the Turing Code server",
|
|
52
47
|
builder: cli => subcommands.reduce((c, s) => c.command(s), cli)
|
|
53
|
-
.demandCommand(1, "project needs a subcommand: sync, pull,
|
|
48
|
+
.demandCommand(1, "project needs a subcommand: sync, pull, check, analyze, regen, template or drivers")
|
|
54
49
|
.epilogue([
|
|
55
|
-
"Typical use: edit files, `project sync` (
|
|
56
|
-
"
|
|
50
|
+
"Typical use: edit files, `project sync -b` (add `-a` to also analyse), then `probe program`.",
|
|
51
|
+
"`project check` (syntax) and `project analyze` (cppcheck, clang-tidy, MISRA) check the synced code.",
|
|
57
52
|
"Other server tools (pins, clocks, .ioc edits) go through `tool call`; after one that",
|
|
58
53
|
"changes the server copy, `project pull` brings the changes back, and `project regen` regenerates the code.",
|
|
59
54
|
PROJECT_HELP,
|
|
@@ -19,7 +19,7 @@ export default _defineTool({
|
|
|
19
19
|
build: {
|
|
20
20
|
type: 'string',
|
|
21
21
|
enum: ['', 'Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
|
|
22
|
-
description: 'After a successful sync, build with this preset
|
|
22
|
+
description: 'After a successful sync, build with this preset; empty = Debug',
|
|
23
23
|
},
|
|
24
24
|
analyse: {
|
|
25
25
|
type: 'string',
|
package/dist/stm32/build.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** Server build of the STM32 project and download of its ELF. Used by
|
|
1
|
+
/** Server build of the STM32 project and download of its ELF. Used by `project sync -b` and the VS Code extension. */
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { replyBody } from '../core/mcp.js';
|
|
4
4
|
import { downloadFile } from './utils/downloadzip_utils.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Finds the most recently built .elf under the project's build/ folder (
|
|
2
|
+
* Finds the most recently built .elf under the project's build/ folder (project sync -b downloads it to build/<preset>/).
|
|
3
3
|
* @param root project root folder
|
|
4
4
|
* @returns the .elf path and its modification time, or undefined when there is none
|
|
5
5
|
*/
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readdir, stat } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
/**
|
|
4
|
-
* Finds the most recently built .elf under the project's build/ folder (
|
|
4
|
+
* Finds the most recently built .elf under the project's build/ folder (project sync -b downloads it to build/<preset>/).
|
|
5
5
|
* @param root project root folder
|
|
6
6
|
* @returns the .elf path and its modification time, or undefined when there is none
|
|
7
7
|
*/
|
|
@@ -6,14 +6,16 @@ description: Use when running the turingcode CLI on an STM32 project - creating
|
|
|
6
6
|
# turingcode for STM32
|
|
7
7
|
|
|
8
8
|
- `turingcode` is a set of tools for working with stm32 projects.
|
|
9
|
-
|
|
10
|
-
|
|
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.
|
|
11
13
|
|
|
12
14
|
## Commands
|
|
13
15
|
|
|
14
16
|
Read the help before you run commands in an area; every subcommand has its own `--help` with flags and examples.
|
|
15
17
|
|
|
16
|
-
- `turingcode project --help`: sync
|
|
18
|
+
- `turingcode project --help`: sync (with `-b` to build), pull, regen, drivers, syntax check, static analysis.
|
|
17
19
|
- `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
|
|
18
20
|
- `turingcode debug --help`: breakpoints, stepping, stack, variables.
|
|
19
21
|
|
|
@@ -1,47 +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 |
|
|
20
23
|
|
|
21
|
-
|
|
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.
|
|
22
25
|
|
|
23
|
-
|
|
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.
|
|
24
69
|
|
|
25
70
|
## House style
|
|
26
71
|
|
|
27
|
-
Match
|
|
72
|
+
Match the existing style; don't "modernize" it.
|
|
28
73
|
|
|
29
|
-
- **Classes**: PascalCase joined
|
|
30
|
-
- **Members**: private fields start with `_
|
|
31
|
-
- **Methods**: snake_case
|
|
32
|
-
- **Errors**: return
|
|
33
|
-
- **Comments**: `/* ---- Title ---- */` section banners
|
|
34
|
-
- **
|
|
35
|
-
- **Layering**:
|
|
36
|
-
- 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.
|
|
37
81
|
|
|
38
|
-
##
|
|
82
|
+
## Safety rules
|
|
39
83
|
|
|
40
|
-
1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return (`xTaskCreate`, semaphore acquire, queue send).
|
|
41
|
-
2. **Every wait has a timeout and an error path.** No
|
|
42
|
-
3. **
|
|
43
|
-
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.
|
|
44
88
|
|
|
45
89
|
## Before you finish
|
|
46
90
|
|
|
47
|
-
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`
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/host-protocol.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Host protocol
|
|
2
|
+
|
|
3
|
+
- Use this when parsing frames from a host (UART, USB, SPI slave, CAN), dispatching commands, or building reply and telemetry packets.
|
|
4
|
+
- Every received byte is untrusted: one bad length can make the host write anywhere in memory.
|
|
5
|
+
|
|
6
|
+
## Frame sizes
|
|
7
|
+
|
|
8
|
+
- Every size and offset of the frame is a `constexpr` derived from the others. No length is written as a literal in the parser.
|
|
9
|
+
- Use a template for compile-time size variants, per the house style.
|
|
10
|
+
|
|
11
|
+
## Receiving
|
|
12
|
+
|
|
13
|
+
- Find the start of a frame, and drop the bytes before it. If the frame isn't complete yet, wait for more bytes.
|
|
14
|
+
- Remove the frame from the buffer whether or not it parsed, so a bad frame can't block the queue.
|
|
15
|
+
- Bound every search and copy by the bytes actually received, not by the maximum frame size.
|
|
16
|
+
|
|
17
|
+
## Parse checks, in order
|
|
18
|
+
|
|
19
|
+
1. The received length covers the header before any header byte is read.
|
|
20
|
+
2. The length field matches the bytes received and is at most the maximum.
|
|
21
|
+
3. Unsigned subtraction is guarded:
|
|
22
|
+
```cpp
|
|
23
|
+
if (len < OVERHEAD) return M_StatusEnum::M_OUT_OF_RANGE;
|
|
24
|
+
size_t data_len = len - OVERHEAD;
|
|
25
|
+
```
|
|
26
|
+
4. The checksum or CRC matches before anything acts on the frame.
|
|
27
|
+
|
|
28
|
+
## Dispatch
|
|
29
|
+
|
|
30
|
+
- A write to an indexed range checks the whole range, without overflow:
|
|
31
|
+
```cpp
|
|
32
|
+
if (start >= COUNT || len > COUNT - start) return M_StatusEnum::M_OUT_OF_RANGE;
|
|
33
|
+
```
|
|
34
|
+
- Writes to read-only data are rejected.
|
|
35
|
+
- Reply with the result, so the host sees a rejection.
|
|
36
|
+
- Keep these checks compiled in; never put them behind a debug-only macro.
|
|
37
|
+
|
|
38
|
+
## Outgoing packets
|
|
39
|
+
|
|
40
|
+
- Build into a static buffer, and check the room left before each append.
|
|
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
|
|
@@ -1,35 +1,36 @@
|
|
|
1
|
-
# Registers
|
|
1
|
+
# Registers and units
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
- Use this when turning datasheet registers into code, or writing bit fields, units, conversions, constants or macros.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
- Read two's-complement registers (trim values, temperature) into signed types (`int8_t`), as the datasheet says.
|
|
7
|
-
- Keep the datasheet formula and section in a `/** */` comment next to the code that uses it.
|
|
5
|
+
## Datasheet registers
|
|
8
6
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
- Copy bit positions, widths and reset values from the datasheet, and cite it: `/** DS §8.3, table 21 */`.
|
|
8
|
+
- Read two's-complement registers into signed types. Sign-extend non-native widths explicitly:
|
|
9
|
+
```cpp
|
|
10
|
+
int32_t v = ((int32_t)b[0] << 16) | (b[1] << 8) | b[2];
|
|
11
|
+
if (v & 0x800000) v -= 0x1000000; // 24-bit two's complement
|
|
12
|
+
```
|
|
13
|
+
- Read multi-byte values out of byte buffers with `memcpy` or byte shifts, never through a cast pointer (`*(float*)&buf[i]`): the offset may be unaligned.
|
|
14
|
+
- Clear a field before setting it:
|
|
12
15
|
```cpp
|
|
13
|
-
reg = (reg & ~ODR_MASK) | (odr << ODR_POS);
|
|
16
|
+
reg = (reg & ~ODR_MASK) | ((odr << ODR_POS) & ODR_MASK);
|
|
14
17
|
```
|
|
15
|
-
Don't just OR a new value into a register that already holds the old one.
|
|
16
18
|
|
|
17
|
-
## Units
|
|
19
|
+
## Units
|
|
18
20
|
|
|
19
|
-
- Put the unit in
|
|
20
|
-
-
|
|
21
|
-
-
|
|
21
|
+
- Put the unit in every name, or in a comment beside it: `dt_us`, `ref_uT`, `scale_mg_per_lsb`.
|
|
22
|
+
- Convert between units with a named conversion (`us_to_ns()`), never a cast.
|
|
23
|
+
- Write constants in the sensor's output unit.
|
|
24
|
+
- Name noise as `_std` or `_var`; the two differ by a square.
|
|
22
25
|
|
|
23
|
-
##
|
|
26
|
+
## Constants and macros
|
|
24
27
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
```
|
|
29
|
-
Prefer `constexpr` constants and `inline` functions over macros when no token pasting is needed. Derive layout constants (group lengths, offsets) from one source, so nothing is counted twice.
|
|
28
|
+
- Prefer `constexpr` and `inline` over macros unless you need token pasting.
|
|
29
|
+
- Fully parenthesize macro bodies and arguments: `#define CLIP_U16(x) ((x) > 0xFFFF ? 0xFFFF : (x))`.
|
|
30
|
+
- Derive sizes and offsets from one source.
|
|
30
31
|
|
|
31
32
|
## Checklist
|
|
32
|
-
- [ ] Bit positions and signedness match the datasheet
|
|
33
|
+
- [ ] Bit positions and signedness match the datasheet, with a citation
|
|
33
34
|
- [ ] Field writes clear the old value first
|
|
34
|
-
- [ ] Every
|
|
35
|
-
- [ ]
|
|
35
|
+
- [ ] Every value states its unit; conversions are named
|
|
36
|
+
- [ ] Macros are parenthesized; sizes come from one source
|
|
@@ -0,0 +1,140 @@
|
|
|
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
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turingcode/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
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": {
|
|
@@ -23,7 +23,10 @@
|
|
|
23
23
|
"build": "node scripts/build.cjs",
|
|
24
24
|
"typecheck": "tsc --noEmit && tsc --project tsconfig.test.json --noEmit",
|
|
25
25
|
"test": "node scripts/test.cjs",
|
|
26
|
+
"install-skills": "node scripts/build.cjs && node dist/cli/index.js install-skills",
|
|
27
|
+
"install-mods": "node scripts/build.cjs && node dist/cli/index.js install-mods",
|
|
26
28
|
"default_publish": "npm publish --access public --tag latest",
|
|
29
|
+
"after_publish": "npm i -g @azrico/azcli",
|
|
27
30
|
"prepublishOnly": "npm test && npm run build"
|
|
28
31
|
},
|
|
29
32
|
"publishConfig": {
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { runBuild } from '../../stm32/context.js';
|
|
2
|
-
import { _defineTool } from '../../stm32/tool.js';
|
|
3
|
-
import { findStm32Project } from '../../stm32/utils/project_utils.js';
|
|
4
|
-
/** Builds the server copy and downloads the resulting ELF into the local build/<preset>/ folder. */
|
|
5
|
-
export default _defineTool({
|
|
6
|
-
name: 'project_build',
|
|
7
|
-
description: 'Build the project on the TuringCode server \
|
|
8
|
-
(run `turingcode project sync` first to include local changes), then download the .elf ' +
|
|
9
|
-
'into the local build/<preset>/ folder for `turingcode probe program`. \
|
|
10
|
-
Prints the result, warnings in the project code, sizes and the clock audit summary (`--verbose` for the full reply).',
|
|
11
|
-
properties: {
|
|
12
|
-
preset: {
|
|
13
|
-
type: 'string',
|
|
14
|
-
enum: ['Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
|
|
15
|
-
},
|
|
16
|
-
verbose: {
|
|
17
|
-
type: 'boolean',
|
|
18
|
-
description: 'Print the full build reply (compiler, Drivers/ warnings, map file, stack usage, build log, clock tables); a failed build always prints it',
|
|
19
|
-
},
|
|
20
|
-
},
|
|
21
|
-
run: async (args) => runBuild(await findStm32Project(), args.preset ?? 'Debug', !!args.verbose),
|
|
22
|
-
});
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
# Concurrency: ISRs, DMA, tasks
|
|
2
|
-
|
|
3
|
-
## Release on every path
|
|
4
|
-
|
|
5
|
-
If a function takes a semaphore or mutex and then starts a transfer, release it when the start fails too. Otherwise the next wait blocks forever:
|
|
6
|
-
```cpp
|
|
7
|
-
if (HAL_UART_Transmit_DMA(...) != HAL_OK) {
|
|
8
|
-
this->_tx_sem.release();
|
|
9
|
-
return Status::ERROR;
|
|
10
|
-
}
|
|
11
|
-
```
|
|
12
|
-
Error callbacks only release what belongs to that error. An RX overrun must not release the TX semaphore while TX DMA is still running.
|
|
13
|
-
|
|
14
|
-
## DMA buffers outlive the transfer
|
|
15
|
-
|
|
16
|
-
- A buffer handed to DMA is static, a class member, or from a pool, never a local array. The stack frame is gone while DMA is still reading it.
|
|
17
|
-
- Check the length against the DMA buffer size before copying into it.
|
|
18
|
-
- Outgoing bytes (command, address) go in the TX buffer, not the RX one.
|
|
19
|
-
|
|
20
|
-
## Shared data has one owner and one protection
|
|
21
|
-
|
|
22
|
-
For every buffer touched by an ISR and a task, or by two tasks, write a comment saying who writes it, who reads it and what protects it. Then pick one of these:
|
|
23
|
-
|
|
24
|
-
- **ISR-filled queue:** the task wraps compaction and clearing in a critical section (or disables that IRQ), or the queue is a lock-free single-producer/single-consumer ring.
|
|
25
|
-
- **Sample written by one task while another parses it:** read into a temp buffer, then copy or swap under the lock. Never write straight into the buffer being parsed, or you get torn samples.
|
|
26
|
-
- **Driver used by a running task:** don't re-init or calibrate it while that task is still using it (see `init-and-timing.md`).
|
|
27
|
-
|
|
28
|
-
## Read-and-clear flags are consumed once
|
|
29
|
-
|
|
30
|
-
A "consume" call returns a flag and clears it. Call it once per flag per cycle and keep the result:
|
|
31
|
-
```cpp
|
|
32
|
-
const bool acc_changed = this->acc->consume_changed();
|
|
33
|
-
const bool gyro_changed = this->gyro->consume_changed(); // its own flag
|
|
34
|
-
```
|
|
35
|
-
A second call on the same flag always returns false.
|
|
36
|
-
|
|
37
|
-
## Checklist
|
|
38
|
-
- [ ] Every acquire has a release on the failure path
|
|
39
|
-
- [ ] Error callbacks only release their own resources
|
|
40
|
-
- [ ] No DMA buffer on the stack; lengths checked against the DMA buffer
|
|
41
|
-
- [ ] Every shared buffer has a documented owner and lock
|
|
42
|
-
- [ ] Each read-and-clear flag is consumed exactly once per cycle
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
# Initialization and timing
|
|
2
|
-
|
|
3
|
-
## Order is explicit
|
|
4
|
-
|
|
5
|
-
- Nothing reads a store before it's initialized: init the flash driver before loading config from it. If the load fails, use defaults, not whatever `new` left in memory (it isn't zeroed).
|
|
6
|
-
- Erased flash reads 0xFF, and that isn't a valid config: every bit on, every scale at its maximum. Detect it with a magic number, version or CRC, and fall back to safe defaults.
|
|
7
|
-
- Leave the flash locked after init. Unlock only around an erase or program.
|
|
8
|
-
|
|
9
|
-
## Callbacks may fire before your objects exist
|
|
10
|
-
|
|
11
|
-
HAL and ISR callbacks (EXTI, UART error, timer) can run before the task that creates the global object, for example when the interrupt is enabled in generated init code. Null-check every global pointer they use:
|
|
12
|
-
```cpp
|
|
13
|
-
if (driver == nullptr) return;
|
|
14
|
-
```
|
|
15
|
-
|
|
16
|
-
## Re-init
|
|
17
|
-
|
|
18
|
-
Before re-initializing or calibrating a driver:
|
|
19
|
-
1. Stop or pause the tasks that use it.
|
|
20
|
-
2. Clear its ready flag first.
|
|
21
|
-
3. Set the flag again only when init succeeds.
|
|
22
|
-
|
|
23
|
-
## Timers
|
|
24
|
-
|
|
25
|
-
- Pass the correct handle to every timer helper. Helpers that compare handles return early on a mismatch, and the event is lost.
|
|
26
|
-
- Declare every C-callable function in its header. Otherwise C compiles an implicit declaration, and the function gets garbage arguments without any error.
|
|
27
|
-
- A 32-bit µs counter wraps after about 71.6 min. Extend it with overflow counting, and test the wrap.
|
|
28
|
-
- Names match types: `delay_us(time_us_t us)`. Don't cast ns into a µs type without converting.
|
|
29
|
-
|
|
30
|
-
## Checklist
|
|
31
|
-
- [ ] Stores are initialized before they're read; failed loads fall back to defaults
|
|
32
|
-
- [ ] Blank flash is detected
|
|
33
|
-
- [ ] Callbacks null-check globals
|
|
34
|
-
- [ ] Re-init stops users and clears the ready flag first
|
|
35
|
-
- [ ] Timer callbacks pass the right handle; C interfaces are declared in headers
|
package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
# Input and bounds
|
|
2
|
-
|
|
3
|
-
Bytes from UART, SPI, flash or a host are untrusted. One bad length byte can let the host write anywhere in memory.
|
|
4
|
-
|
|
5
|
-
## Check before you use
|
|
6
|
-
|
|
7
|
-
Before using a received value as a length, index or offset:
|
|
8
|
-
|
|
9
|
-
- Check it against the **real** buffer size, not a "max expected" constant. A `memcpy` or search over the max length reads past a shorter buffer.
|
|
10
|
-
- Guard unsigned subtraction:
|
|
11
|
-
```cpp
|
|
12
|
-
if (recv_len < HEADER_LEN) return Status::OUT_OF_RANGE;
|
|
13
|
-
size_t data_len = recv_len - HEADER_LEN;
|
|
14
|
-
```
|
|
15
|
-
- Bound every write into a table (registers, config) against its count, for every element (`start + i < count`), not only the first.
|
|
16
|
-
- Keep these checks compiled in. Don't put them behind a debug-only macro.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
## Checklist
|
|
20
|
-
- [ ] Every external length, index and offset is checked against the real size
|
|
21
|
-
- [ ] No unsigned subtraction without a guard
|