@turingcode/cli 0.3.15 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. package/dist/features/contract/command.js +64 -64
  2. package/dist/features/probe/program_project.js +3 -3
  3. package/dist/features/project/analysis_static.js +2 -2
  4. package/dist/features/project/project_sync_to_server.js +5 -5
  5. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +48 -48
  6. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +13 -10
  7. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_Driver.hpp +97 -0
  8. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_I2C.hpp +83 -0
  9. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_SPI.hpp +69 -0
  10. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/COM_USART.hpp +58 -0
  11. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver.md +22 -13
  12. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_ic.md +40 -42
  13. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_protocol.md +6 -106
  14. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_rtos.md +1 -2
  15. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_test.md +4 -1
  16. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -57
  17. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +70 -70
  18. package/package.json +2 -2
@@ -4,70 +4,70 @@ import { describeContract } from "./describe.js";
4
4
  export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
5
5
  export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
6
6
  /** The contract format in brief, for `contract --help`. Only tables, and each table's and column's name, are required. */
7
- const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
- field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
- {
10
- "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
11
- "format": "markdown", // (default), or "format": "csv": one <table>.csv per table. The tables
12
- // given with --tables / --dep must be in their own contract's format
13
- "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
- // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
- // but an empty cell forbidden is "required": true plus
16
- // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
- "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
- "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
- // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
- "tables": [{
21
- "name": "Orders",
22
- "required": true, // (default) the table must be in the document
23
- "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
- "ordered": false, // (default) true: columns must be in the declared order
25
- "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
- "columns": [{
27
- "name": "Total",
28
- "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
- "required": false, // (default) true: every cell must be filled (an empty cell fails
30
- // MISSING_VALUE); the column itself must always be in the header
31
- "separator": ",", // (default) list item separator
32
- "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
- // empty cells are skipped: use "required" to forbid them
34
- }],
35
- "rules": [{ // exactly one of require, count
36
- "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
- "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
- "on": "Table", // or "alias:Table"; default: the table the rule is in
39
- "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
- "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
- "count": { "$gte": 1 } // or: condition on how many there are
42
- }]
43
- }]
44
- }
45
- Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
- (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
- and {"$ne": "x"} means "no item is x"). Operators:
48
- $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
- $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
- $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
- $every {...} every list item meets the condition
52
- $length {...} length (chars, or list items) meets the condition
53
- $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
- $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
- document outside the value's own table (prose and other tables both count)
56
- $calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
57
- Codes: each failing operator reports its own: $eq $in → BAD_VALUE, $regex → PATTERN, $gt.. → OUT_OF_RANGE,
58
- $length → BAD_LENGTH, $ref → UNKNOWN_REF, $unique → DUPLICATE_KEY, $mentioned → NOT_MENTIONED,
59
- {"$ne": null} in a rule → REQUIRED_IF, a wrong type → BAD_TYPE, a rule's other queries → MATCH.
60
- A value failing every branch of an $or reports the branches' code when they agree, else NONE_OF
61
- (each branch's code in the message, and in --json "alternatives").
62
- Examples:
63
- "match": { "$regex": "^O-[0-9]+$" }
64
- "match": { "$in": ["open", "paid", "shipped"] }
65
- "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
- "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
- "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
- { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
- { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
- { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
7
+ const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
8
+ field is optional. "(default)" marks the value used when a field is left out; other values are examples.
9
+ {
10
+ "name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
11
+ "format": "markdown", // (default), or "format": "csv": one <table>.csv per table. The tables
12
+ // given with --tables / --dep must be in their own contract's format
13
+ "missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
14
+ // Keep a marker like "-" out of it when "-" is a real value: "-" allowed
15
+ // but an empty cell forbidden is "required": true plus
16
+ // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
17
+ "allow_extra_tables": false, // (default) true: tables not declared here are allowed
18
+ "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
19
+ // its tables passed with --dep customers=<file>, referenced as "customers:Table.Column"
20
+ "tables": [{
21
+ "name": "Orders",
22
+ "required": true, // (default) the table must be in the document
23
+ "primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
24
+ "ordered": false, // (default) true: columns must be in the declared order
25
+ "allow_extra_columns": false, // (default) true: columns not declared here are allowed
26
+ "columns": [{
27
+ "name": "Total",
28
+ "type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
29
+ "required": false, // (default) true: every cell must be filled (an empty cell fails
30
+ // MISSING_VALUE); the column itself must always be in the header
31
+ "separator": ",", // (default) list item separator
32
+ "match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
33
+ // empty cells are skipped: use "required" to forbid them
34
+ }],
35
+ "rules": [{ // exactly one of require, count
36
+ "id": "...", "description": "...", // shown in findings; description replaces the "expected" text
37
+ "severity": "error", // (default) or "warning": reported as WARN, does not fail the check
38
+ "on": "Table", // or "alias:Table"; default: the table the rule is in
39
+ "when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
40
+ "require": { "Tracking": { "$ne": null } }, // row query each of them matches
41
+ "count": { "$gte": 1 } // or: condition on how many there are
42
+ }]
43
+ }]
44
+ }
45
+ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
46
+ (split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
47
+ and {"$ne": "x"} means "no item is x"). Operators:
48
+ $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
49
+ $gt $gte $lt $lte exact number comparison, or date comparison with a "YYYY-MM-DD" bound
50
+ $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
51
+ $every {...} every list item meets the condition
52
+ $length {...} length (chars, or list items) meets the condition
53
+ $unique true no two rows share the value; in a row query ["A", "B"]: the combination
54
+ $mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
55
+ document outside the value's own table (prose and other tables both count)
56
+ $calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
57
+ Codes: each failing operator reports its own: $eq $in → BAD_VALUE, $regex → PATTERN, $gt.. → OUT_OF_RANGE,
58
+ $length → BAD_LENGTH, $ref → UNKNOWN_REF, $unique → DUPLICATE_KEY, $mentioned → NOT_MENTIONED,
59
+ {"$ne": null} in a rule → REQUIRED_IF, a wrong type → BAD_TYPE, a rule's other queries → MATCH.
60
+ A value failing every branch of an $or reports the branches' code when they agree, else NONE_OF
61
+ (each branch's code in the message, and in --json "alternatives").
62
+ Examples:
63
+ "match": { "$regex": "^O-[0-9]+$" }
64
+ "match": { "$in": ["open", "paid", "shipped"] }
65
+ "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
66
+ "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
67
+ "match": { "$ref": "customers:Customers.ID" } // a column of the dependency "customers"
68
+ { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
69
+ { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
70
+ { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
71
71
  { "severity": "warning", "require": { "ID": { "$mentioned": "*" } } }`;
72
72
  const check = {
73
73
  command: "check",
@@ -7,7 +7,7 @@ import { SWD_SPEED_PROP } from '../../stm32/actions/DebugAction.js';
7
7
  /** Flashes the newest ELF in the project's build/ folder. */
8
8
  export default _defineTool({
9
9
  name: 'program_project',
10
- description: "Flash the newest .elf in the project's build/ folder \
10
+ description: "Flash the newest .elf in the project's build/ folder \
11
11
  (downloaded by `turingcode project sync -b`) to the board over SWD, verify it and reset the target.",
12
12
  properties: { speed: SWD_SPEED_PROP },
13
13
  needsProbe: true,
@@ -22,8 +22,8 @@ export default _defineTool({
22
22
  chip,
23
23
  speed: args.speed,
24
24
  }).catch((e) => {
25
- throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
26
- (USB sleep, DEV_USB_COMM_ERR, probe not found), \
25
+ throw new Error(`${e?.message ?? e}\n\nIf the probe does not answer \
26
+ (USB sleep, DEV_USB_COMM_ERR, probe not found), \
27
27
  run \`turingcode probe reset-usb\` and try again once.`);
28
28
  });
29
29
  return `Programmed ${elf.path} (${chip})\n\n${program_result}`;
@@ -5,8 +5,8 @@ import { DIR_PROP, requireStm32Project } from '../../stm32/utils/project_utils.j
5
5
  /** Static analysis of the server copy of the project's own sources (never Drivers/). */
6
6
  export default _defineTool({
7
7
  name: 'analysis_static',
8
- description: 'Static analysis of your stm32 project on the TuringCode server (its own sources, never Drivers/HAL/CMSIS; \
9
- run `turingcode project sync` first to include local changes). Profiles: quick (cppcheck), full (cppcheck + clang-tidy) \
8
+ description: 'Static analysis of your stm32 project on the TuringCode server (its own sources, never Drivers/HAL/CMSIS; \
9
+ run `turingcode project sync` first to include local changes). Profiles: quick (cppcheck), full (cppcheck + clang-tidy) \
10
10
  or misra (cppcheck MISRA C:2012). Returns `file:line:col: severity: message [check id]` lines. The project is the working directory or --dir; it must hold the .ioc.',
11
11
  properties: {
12
12
  dir: DIR_PROP,
@@ -8,11 +8,11 @@ import { DIR_PROP, resolveProjectDir } from '../../stm32/utils/project_utils.js'
8
8
  export default _defineTool({
9
9
  name: 'project_sync_to_server',
10
10
  description: "Sync a local folder's files (except build/ and git-ignored files; Drivers/ and Middlewares/ are always sent) " +
11
- 'to the TuringCode server; only files the server lacks or has a different version of are uploaded. \
12
- To restore deleted Drivers/ files use `turingcode project drivers`. \
13
- Stops before uploading when a USER CODE BEGIN/END marker is unmatched, and warns about code outside USER CODE sections that `project regen` would remove. \
14
- The folder is the working directory or --dir, never one above or below it. A folder holding a .ioc or .mxproject file keeps its name on the server; \
15
- any other folder is synced as <name>-<hash of its path>, and only --syntax works with it. \
11
+ 'to the TuringCode server; only files the server lacks or has a different version of are uploaded. \
12
+ To restore deleted Drivers/ files use `turingcode project drivers`. \
13
+ Stops before uploading when a USER CODE BEGIN/END marker is unmatched, and warns about code outside USER CODE sections that `project regen` would remove. \
14
+ The folder is the working directory or --dir, never one above or below it. A folder holding a .ioc or .mxproject file keeps its name on the server; \
15
+ any other folder is synced as <name>-<hash of its path>, and only --syntax works with it. \
16
16
  With paths, only those .c/.h/.cpp/.hpp files (and the headers next to each) are copied into .turingcode/temp/ of the project folder and synced as a temp project with no .ioc or CMakeLists, for `--syntax`.',
17
17
  properties: {
18
18
  dir: DIR_PROP,
@@ -1,49 +1,49 @@
1
- ---
2
- name: turingcode-cli
3
- description: use for creating, build, debug, program, flash or analyze any STM32 project
4
- ---
5
-
6
- # turingcode CLI for STM32
7
-
8
- `turingcode` handles the whole STM32 workflow: project setup, building, configuration, flashing and debugging. Use it instead of calling probe-rs or STM32_Programmer_CLI directly.
9
-
10
- ## Start here
11
-
12
- - Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
13
-
14
- ## Commands
15
-
16
- Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
-
18
- - `turingcode project --help`: sync, build, pull, regen and static analysis.
19
- - `turingcode syntax-check --help`: clang syntax check of the project, or of loose files, folders or globs.
20
- - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
21
- - `turingcode debug --help`: breakpoints, stepping, stack, variables.
22
-
23
- ## Server tools
24
-
25
- Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
26
-
27
- - `turingcode tool list` shows the available tools.
28
- - `turingcode tool call <name> --args '<json>' > result.md` runs one.
29
- - On Windows PowerShell or cmd, inline JSON loses its quotes: write the JSON to a `.json` file and pass `--args args.json`.
30
-
31
-
32
- ## New project
33
-
34
- Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
35
-
36
- ## Typical loop
37
-
38
- 1. Edit the code, run `turingcode project sync -b` and fix the reported errors.
39
- - Before finishing a change, run `turingcode project sync -b -a` for static analysis.
40
- 2. Flash with `turingcode probe program`.
41
- 3. Verify it runs without looking at the board: read a register the program changes a few times with `turingcode probe read` and check that it changes as expected.
42
- 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
43
-
44
- ## CRITICAL Safety rules
45
-
46
- - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu.
47
- - Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
48
- - NEVER touch RDP without asking first.
1
+ ---
2
+ name: turingcode-cli
3
+ description: use for creating, build, debug, program, flash or analyze any STM32 project
4
+ ---
5
+
6
+ # turingcode CLI for STM32
7
+
8
+ `turingcode` handles the whole STM32 workflow: project setup, building, configuration, flashing and debugging. Use it instead of calling probe-rs or STM32_Programmer_CLI directly.
9
+
10
+ ## Start here
11
+
12
+ - Run `turingcode status` first. It shows the project, token, last build, debug session and installed probe tools.
13
+
14
+ ## Commands
15
+
16
+ Each command group has its own `--help` with flags and examples. Read it before using commands in that area.
17
+
18
+ - `turingcode project --help`: sync, build, pull, regen and static analysis.
19
+ - `turingcode syntax-check --help`: clang syntax check of the project, or of loose files, folders or globs.
20
+ - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
21
+ - `turingcode debug --help`: breakpoints, stepping, stack, variables.
22
+
23
+ ## Server tools
24
+
25
+ Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
26
+
27
+ - `turingcode tool list` shows the available tools.
28
+ - `turingcode tool call <name> --args '<json>' > result.md` runs one.
29
+ - On Windows PowerShell or cmd, inline JSON loses its quotes: write the JSON to a `.json` file and pass `--args args.json`.
30
+
31
+
32
+ ## New project
33
+
34
+ Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
35
+
36
+ ## Typical loop
37
+
38
+ 1. Edit the code, run `turingcode project sync -b` and fix the reported errors.
39
+ - Before finishing a change, run `turingcode project sync -b -a` for static analysis.
40
+ 2. Flash with `turingcode probe program`.
41
+ 3. Verify it runs without looking at the board: read a register the program changes a few times with `turingcode probe read` and check that it changes as expected.
42
+ 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
43
+
44
+ ## CRITICAL Safety rules
45
+
46
+ - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu.
47
+ - Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
48
+ - NEVER touch RDP without asking first.
49
49
  - Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
@@ -1,13 +1,7 @@
1
1
  # M_Status
2
2
 
3
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
- - Values are ordered best to worst so `|=` keeps the worst result:
8
- M_OK = 0, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE,
9
- M_DISABLED, M_NOT_SUPPORTED,M_NOT_FOUND, M_ERROR
10
-
4
+
11
5
  ## Usage
12
6
 
13
7
  ```cpp
@@ -25,10 +19,19 @@ return status; // the worst result win
25
19
  #pragma once
26
20
  /**
27
21
  * Status type shared by all drivers
28
- * Ordered best to worst `|=` keeps the worst result.
22
+ * Values are ordered best to worst so `|=` keeps the worst result.
29
23
  */
30
- enum M_StatusEnum { M_OK = 0, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE,
31
- M_DISABLED, M_NOT_SUPPORTED,M_NOT_FOUND, M_ERROR };
24
+ enum M_StatusEnum {
25
+ M_OK = 0,
26
+ M_BUSY,
27
+ M_TIMEOUT,
28
+ M_OUT_OF_RANGE,
29
+ M_DISABLED,
30
+ M_NOT_SUPPORTED,
31
+ M_NOT_FOUND,
32
+ M_MISMATCH,
33
+ M_ERROR
34
+ };
32
35
 
33
36
  class M_Status {
34
37
  public:
@@ -0,0 +1,97 @@
1
+ #pragma once
2
+
3
+ // ... includes ... //
4
+
5
+ class COM_Driver {
6
+ public:
7
+ // must be implemented in the subclass
8
+ virtual M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) = 0;
9
+ virtual M_Status write(uint8_t reg, const uint8_t* data, size_t len) = 0;
10
+
11
+ // read, modify, write
12
+ M_Status write_bit(uint8_t reg, uint8_t bit, uint8_t value);
13
+
14
+ /**
15
+ * @brief write a register and verify it; retry if it fails
16
+ * @returns
17
+ * M_OK: written and verified,
18
+ * M_MISMATCH: written but read back differently.
19
+ * ...other possible errors...
20
+ */
21
+ M_Status write_verify(uint8_t reg, uint8_t value, size_t tries, uint8_t mask = 0xFF);
22
+
23
+ // keep retrying until (reg & mask) == expected
24
+ M_Status wait_for_register(uint8_t reg, uint8_t expected, size_t tries, uint8_t mask = 0xFF);
25
+
26
+ /**
27
+ * @brief set the read/write address mask for the device;
28
+ *
29
+ * sent address = (reg & ~clear) | set = (reg & ~clear) | set
30
+ */
31
+ void set_address_mask(uint8_t read_set, uint8_t read_clear,
32
+ uint8_t write_set, uint8_t write_clear);
33
+
34
+
35
+ // ---- Busy check ---- //
36
+ /**
37
+ * when are not using RTOS mutexes to protect the bus,
38
+ * we need a busy flag to avoid trying to send/recv data
39
+ * while busy for calls that dont block during the transfer (DMA, Interrupt, ...)
40
+ *
41
+ * for full duplex bus lines we can use 2 independent flags
42
+ */
43
+ public:
44
+ /**
45
+ * @brief take the bus; false when another transfer already owns it.
46
+ *
47
+ * avoid pattenrs like:
48
+ * if (!isBusy()) { ... setBusy(); ... }
49
+ * because another thread could set it between the check and the set.
50
+ */
51
+ bool trySetBusy() { return !this->flag_busy_.exchange(true, std::memory_order_acquire); }
52
+ bool isBusy() const { return flag_busy_.load(std::memory_order_acquire); }
53
+ void setBusy() { flag_busy_.store(true, std::memory_order_release); }
54
+ void clearBusy() { flag_busy_.store(false, std::memory_order_release); }
55
+ /**
56
+ * std::atomic is the more MISRA-friendly choice than __atomic_*
57
+ * if <atomic> is not supported then we can use:
58
+ */
59
+ //// bool isBusy() const { return __atomic_load_n(&flag_busy_, __ATOMIC_ACQUIRE) != 0; }
60
+ //// void setBusy() { __atomic_store_n(&flag_busy_, 1, __ATOMIC_RELEASE); }
61
+ //// void clearBusy() { __atomic_store_n(&flag_busy_, 0, __ATOMIC_RELEASE); }
62
+ protected:
63
+ volatile bool flag_busy=false;
64
+
65
+ // ---- Handle ---- //
66
+ public:
67
+ /**
68
+ * @brief Stores the bus and DMA handles and device address (if needed)
69
+ */
70
+ void bind_com(void* handle,
71
+ uint16_t dev_addr,
72
+ DMA_HandleTypeDef* rx_dma=nullptr,
73
+ DMA_HandleTypeDef* tx_dma=nullptr);
74
+ /**
75
+ * @brief isHandle and handle are non-virtual.
76
+ * Subclasses add a *typed version that hides them.
77
+ */
78
+ bool isHandle(void *check)const;
79
+ void* handle() const;
80
+ protected:
81
+ void* _handle=nullptr;
82
+ DMA_HandleTypeDef* _tx_dma=nullptr;
83
+ DMA_HandleTypeDef* _rx_dma=nullptr;
84
+
85
+ public:
86
+ /**
87
+ * @brief level of the device's interrupt pin; false when the bus driver has no pin
88
+ */
89
+ virtual bool is_interrupt_pin_set() const { return false; }
90
+
91
+ private:
92
+ uint16_t _dev_addr;
93
+ uint16_t _mask_read_set;
94
+ uint16_t _mask_read_clear;
95
+ uint16_t _mask_write_set;
96
+ uint16_t _mask_write_clear;
97
+ };
@@ -0,0 +1,83 @@
1
+ #pragma once
2
+
3
+ // ... includes ... //
4
+
5
+ /**
6
+ * @brief I2C bus driver
7
+ *
8
+ * - `read`/`write` map to `HAL_I2C_Mem_Read`/`HAL_I2C_Mem_Write` with `reg` as the memory address.
9
+ * - `init()` is for I2C with a `TIMINGR` register (G4, L4, H7, F7). On F1/F4 the speed is `Init.ClockSpeed` instead.
10
+ * - The bitrate uses worst-case spec edge times, so it is slower than the real bus; that is the safe side for a timeout.
11
+ * - A slave can stretch SCL, so give `I2C_TIMEOUT_MARGIN_MS` room for the slowest device on the bus.
12
+ */
13
+ class COM_I2C : public COM_Driver {
14
+ public:
15
+ /**
16
+ * @param dev_addr 7-bit device address; HAL wants it shifted left by 1
17
+ */
18
+ COM_I2C(I2C_HandleTypeDef* hi2c, uint16_t dev_addr);
19
+ M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override;
20
+ M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
21
+
22
+ /**
23
+ * @brief call after HAL_I2C_Init and the filter config; reads the live CR1
24
+ */
25
+ void init() {
26
+ I2C_TypeDef* i2c = this->handle()->Instance;
27
+ // kernel clock actually selected in RCC
28
+ uint32_t clk = 0;
29
+ if (i2c == I2C1) clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_I2C1);
30
+ else if (i2c == I2C2) clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_I2C2);
31
+ #ifdef I2C3
32
+ else if (i2c == I2C3) clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_I2C3);
33
+ #endif
34
+ #ifdef I2C4
35
+ else if (i2c == I2C4) clk = HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_I2C4);
36
+ #endif
37
+ if (clk == 0) return;
38
+
39
+ // t_SCL = t_SYNC1 + t_SYNC2 + (SCLL+1 + SCLH+1) * (PRESC+1) * t_I2CCLK
40
+ uint32_t t = this->handle()->Init.Timing;
41
+ uint32_t presc = ((t & I2C_TIMINGR_PRESC) >> I2C_TIMINGR_PRESC_Pos) + 1u;
42
+ uint32_t scll = ((t & I2C_TIMINGR_SCLL) >> I2C_TIMINGR_SCLL_Pos) + 1u;
43
+ uint32_t sclh = ((t & I2C_TIMINGR_SCLH) >> I2C_TIMINGR_SCLH_Pos) + 1u;
44
+ uint32_t cycles = presc * (scll + sclh);
45
+
46
+ // worst-case rise + fall from the I2C spec, picked by the nominal speed
47
+ uint32_t nominal = clk / cycles;
48
+ uint32_t edge_ns = (nominal <= 150000u) ? (1000u + 300u) // standard mode
49
+ : (nominal <= 600000u) ? (300u + 300u) // fast mode
50
+ : (120u + 120u); // fast mode plus
51
+ uint32_t cr1 = i2c->CR1;
52
+ // analog filter max delay, once per edge; check the datasheet value for the part
53
+ if ((cr1 & I2C_CR1_ANFOFF) == 0) edge_ns += 2u * 260u;
54
+ uint32_t dnf = (cr1 & I2C_CR1_DNF) >> I2C_CR1_DNF_Pos;
55
+
56
+ // sync delays: digital filter + ~3 clocks resync per edge, plus the edge times
57
+ cycles += 2u * (dnf + 3u);
58
+ cycles += (uint32_t)(((uint64_t)edge_ns * clk + 999999999u) / 1000000000u);
59
+ this->__bitrate = clk / cycles;
60
+ }
61
+
62
+ /**
63
+ * @brief get maximum allowed timeout for a packet
64
+ * @param len transfered data length in bytes
65
+ */
66
+ uint32_t __packet_timeout_ms(size_t len) const {
67
+ if (this->__bitrate == 0) return I2C_TIMEOUT_MARGIN_MS;
68
+ // 9 bits per byte (8 data + ACK); +3 bytes for address, register, repeated-start address
69
+ uint32_t bits = ((uint32_t)len + 3u) * 9u;
70
+ uint32_t frame_ms = (bits * 1000u + this->__bitrate - 1u) / this->__bitrate;
71
+ return frame_ms + I2C_TIMEOUT_MARGIN_MS;
72
+ }
73
+
74
+ bool isHandle(I2C_HandleTypeDef *check) const {
75
+ return this->handle() == check;
76
+ }
77
+ I2C_HandleTypeDef* handle() const {
78
+ return (I2C_HandleTypeDef*)_handle;
79
+ }
80
+
81
+ private:
82
+ uint32_t __bitrate = 0;
83
+ };
@@ -0,0 +1,69 @@
1
+ #pragma once
2
+
3
+ // ... includes ... //
4
+
5
+ /**
6
+ * @brief SPI bus driver
7
+ *
8
+ * - `init()` is for SPI with `CR2 DS` (G4, L4, F7). On F1/F4 the frame size is `SPI_CR1_DFF` (set = 16 bits), and H7 uses `CFG1` for both the prescaler and the frame size.
9
+ * - `SPI_FRAME_GAP_US` is the CPU time per frame in polling/IT mode; a few µs is typical, measure it on the board if the timeout is tight.
10
+ */
11
+ class COM_SPI : public COM_Driver {
12
+ public:
13
+ COM_SPI(SPI_HandleTypeDef* hspi, GPIO_TypeDef* cs_port, uint16_t cs_pin);
14
+ M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override;
15
+ M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
16
+
17
+ /**
18
+ * @brief call after the clocks and HAL_SPI_Init
19
+ */
20
+ void init() {
21
+ SPI_TypeDef* spi = this->handle()->Instance;
22
+ // SPI1 and SPI4 are on APB2, the rest on APB1; check the reference manual for the part
23
+ bool apb2 = (spi == SPI1);
24
+ #ifdef SPI4
25
+ apb2 = apb2 || (spi == SPI4);
26
+ #endif
27
+ uint32_t pclk = apb2 ? HAL_RCC_GetPCLK2Freq() : HAL_RCC_GetPCLK1Freq();
28
+ // SPI_BAUDRATEPRESCALER_x stores BR bits; divider = 2^(BR+1)
29
+ this->__bitrate = pclk / (2u << (this->handle()->Init.BaudRatePrescaler >> SPI_CR1_BR_Pos));
30
+ // SPI_DATASIZE_xBIT stores (x - 1) in CR2 DS
31
+ this->__frame_bits = (this->handle()->Init.DataSize >> SPI_CR2_DS_Pos) + 1u;
32
+ }
33
+
34
+ /**
35
+ * @brief get maximum allowed timeout for a packet
36
+ *
37
+ * calculate separate timeouts for each transfer type
38
+ * (Transmit, Receive) and never merge both budgets into one timeout.
39
+ *
40
+ * @param len transfered data length in bytes
41
+ */
42
+ uint32_t __packet_timeout_ms(size_t len) const {
43
+ if (this->__bitrate == 0) return SPI_TIMEOUT_MARGIN_MS;
44
+ // ceil(len * bits * 1000 / bitrate); len <= 65535 and bits <= 16, so it fits in 32 bits
45
+ uint32_t frame_ms = ((uint32_t)len * this->__frame_bits * 1000u + this->__bitrate - 1u) / this->__bitrate;
46
+ // polling/IT mode: CPU handles each frame, so add a gap per frame; DMA has none
47
+ uint32_t gap_us = (this->_tx_dma || this->_rx_dma) ? 0u : SPI_FRAME_GAP_US;
48
+ uint32_t gap_ms = ((uint32_t)len * gap_us + 999u) / 1000u;
49
+ return frame_ms + gap_ms + SPI_TIMEOUT_MARGIN_MS;
50
+ }
51
+
52
+ bool isHandle(SPI_HandleTypeDef *check) const {
53
+ return this->handle() == check;
54
+ }
55
+ SPI_HandleTypeDef* handle() const {
56
+ return (SPI_HandleTypeDef*)_handle;
57
+ }
58
+
59
+ bool is_interrupt_pin_set() const override {
60
+ return this->_int_port != nullptr && HAL_GPIO_ReadPin(this->_int_port, this->_int_pin) == GPIO_PIN_SET;
61
+ }
62
+ bool is_interrupt_pin(uint16_t pin) const { return this->_int_port != nullptr && this->_int_pin == pin; }
63
+
64
+ private:
65
+ GPIO_TypeDef* _cs_port;
66
+ uint16_t _cs_pin;
67
+ uint32_t __bitrate = 0;
68
+ uint32_t __frame_bits = 8;
69
+ };
@@ -0,0 +1,58 @@
1
+ #pragma once
2
+
3
+ // ... includes ... //
4
+
5
+ /**
6
+ * @brief USART bus driver
7
+ *
8
+ * - read/write `reg` is ignored for USART
9
+ * - `COM_USART` has no registers, so `write_bit`, `write_verify` and `wait_for_register` don't apply to it.
10
+ */
11
+ class COM_USART : public COM_Driver {
12
+ public:
13
+ explicit COM_USART(UART_HandleTypeDef* huart);
14
+
15
+ M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override;
16
+ M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
17
+
18
+ /**
19
+ * @brief call after HAL_UART_Init
20
+ */
21
+ void init() {
22
+ const UART_InitTypeDef& in = this->handle()->Init;
23
+ // word length already includes the parity bit on STM32
24
+ uint32_t data = (in.WordLength == UART_WORDLENGTH_9B) ? 9u : 8u;
25
+ #ifdef UART_WORDLENGTH_7B
26
+ if (in.WordLength == UART_WORDLENGTH_7B) data = 7u;
27
+ #endif
28
+ // 0.5 stop bits rounds up to 1, 1.5 to 2
29
+ uint32_t stop = (in.StopBits == UART_STOPBITS_2) ? 2u : 1u;
30
+ #ifdef UART_STOPBITS_1_5
31
+ if (in.StopBits == UART_STOPBITS_1_5) stop = 2u;
32
+ #endif
33
+ this->__frame_bits = 1u + data + stop; // + start bit
34
+ }
35
+
36
+ /**
37
+ * @brief get maximum allowed timeout for a packet
38
+ * @param len length in bytes
39
+ */
40
+ uint32_t __packet_timeout_ms(size_t len) const {
41
+ uint32_t baud = this->handle()->Init.BaudRate;
42
+ if (baud == 0) return USART_TIMEOUT_MARGIN_MS;
43
+ // ceil(len * bits * 1000 / baud);
44
+ uint32_t frame_ms = ((uint32_t)len * this->__frame_bits * 1000u + baud - 1u) / baud;
45
+ return frame_ms + USART_TIMEOUT_MARGIN_MS;
46
+ }
47
+
48
+ bool isHandle(UART_HandleTypeDef *check) const {
49
+ return this->handle() == check;
50
+ }
51
+ UART_HandleTypeDef* handle() const {
52
+ return (UART_HandleTypeDef*)_handle;
53
+ }
54
+
55
+ private:
56
+ // worst case until init() runs
57
+ uint32_t __frame_bits = USART_MAX_BITS_PER_FRAME;
58
+ };
@@ -31,27 +31,35 @@ After correctly determining what drivers are needed we can go onto the next step
31
31
 
32
32
  ### 3 Source of truth - IMPORTANT
33
33
 
34
- - ALWAYS take every register, reset value, timing, encoding and other facts about parts that you write in code take them from datasheet, errata or application notes.
35
- - Turingcode tools have a knowledge base tool that you should use to find these information (see: `turingcode tool list`) when using the knowledge base tool first list file names then search on related files.
34
+ - Turingcode tools have a knowledge base tool that you should use to find these information (see: `turingcode tool list`)
35
+ - when using the knowledge base tool first list file names then search on related files
36
+ - ALWAYS save result of the knowledge base calls into a file the grep it.
37
+
38
+ - ALWAYS take every register, reset value, timing, encoding and other facts about parts that you write in code take them from datasheet, errata or application notes.
36
39
  - For values that you find from references cite them: `// [CITE: ABC]` in the code.
37
40
  - For values that you guessed or did not find from reference files mark them with a `// [GUESS]` in the code and list them in the end.
41
+ - Timeouts and poll counts are not guesses: compute them from the cited timing (transfer length × slowest clock, worst-case reset or conversion time) plus a stated margin, and write the calculation in the comment, e.g. `// [CALC: 7 B at 1 MHz = 56 us; 1 ms tick -> 2 ms]`. Use `[GUESS]` only when there is no timing to compute from.
42
+ - Register writes are not retried: a read-back mismatch is an error (tries = 1) unless the project gives a reason to retry.
38
43
  - timing and margin checks use the datasheet's worst-case (min/max) values, not typical when a setting depends on a margin, cite it.
39
44
 
40
45
  - NEVER skip this step to go faster, the time it takes to debug a faulty register value because you guessed it is much longer than first reading it from the proper source.
41
46
 
42
47
  #### 3.1 Facts to check
43
48
 
44
- Check at least these facts, plus any others that apply to the part, then saved a table of the checked facts into `App/facts.md`, if possible you can delegate the task of fact checking to a subagent then read the facts yourself:
49
+ Check at least these facts, plus any others that apply to the part and project,
50
+ - save a table of the checked facts into `App/facts.md`
51
+ - if possible you can delegate the task of fact checking to a subagent then read the facts yourself:
45
52
 
46
- - chip ID
47
- - bus mode and maximum clock, checked against the definition
48
- - start-up boot and reset timing
49
- - turn-on and settling time after the output is enabled (samples that are not valid yet)
50
- - interrupt latched/pulsed behaviour
51
- - interface bits to set when the chip is used over one bus only, for example turning I2C off on an SPI-only design.
52
- - "Must set to 1" bits such as DEVICE_CONF
53
- - errata of both the part and of the MCU (An item applies only if the driver uses that mode or feature)
54
- - to find every item: search `<MCU> errata` with `names_only` to get the file, then search that file once per peripheral the driver uses, with `names_only` and `top_k` 10, and decide each item by its title
53
+ Facts to check:
54
+ * chip ID
55
+ * bus mode and maximum clock, checked against the definition
56
+ * start-up boot and reset timing
57
+ * turn-on and settling time after the output is enabled (samples that are not valid yet)
58
+ * interrupt latched/pulsed behaviour
59
+ * interface bits to set when the chip is used over one bus only, for example turning I2C off on an SPI-only design.
60
+ * "Must set to 1" bits such as DEVICE_CONF
61
+ * errata of both the part and of the MCU (An item applies only if the driver uses that mode or feature)
62
+ * to find every item: search `<MCU> errata` with `names_only` to get the file, then search that file once per peripheral the driver uses, with `names_only` and `top_k` 10, and decide each item by its title
55
63
 
56
64
 
57
65
  ### 4 Writing Drivers
@@ -65,7 +73,8 @@ Only Communication protocol drivers call HAL; IC drivers and the base classes do
65
73
  ### 5 Testing drivers
66
74
 
67
75
  - After drivers are written we must also test them, a syntax-only compile does not count as tested, read `references/driver/driver_test.md`
68
-
76
+ - Before finishing, list every line of the definition that touches a driver (bus mode, pin edge, rates, ranges, what stays powered off). Check that the code and a test cover each one.
77
+
69
78
  ### 6 Final Deliverable
70
79
 
71
80
  - if your task was only to make drivers: dont get confused by the project definition given to you, it might say things like "I want a stm32 project that does XYZ" there is no need to create a stm32 project, the final deliverable of the task are the driver files only.
@@ -1,14 +1,16 @@
1
- # IC and sensor driver
1
+ # IC and Sensor driver
2
2
 
3
3
  - Use this when creating or editing a driver for an external IC, sensor or component.
4
4
  - Name of classes and variables here is a suggestion, use the existing naming convention of the project or instructions if they are given.
5
5
 
6
- - IC drivers live in `Drivers/<IC>/` and talk to the chip only through a `COM_Driver*` (`driver_protocol.md`).
7
-
6
+ ## Generic IC Drivers Rules
7
+
8
+ - IC drivers live in `Drivers/<IC>/`, IC_Driver are generic and dont depend on the bus protocol. they talk to the chip only through a `COM_Driver*`.
9
+ - any driver method call (read, write, verify_id, ...) before a successful init() should return an error.
10
+
8
11
  ## Register header
9
12
 
10
- - before the driver Write the register map first. Check the knowledge base server for the part's register table before writing it.
11
- - `<ic>_regs.h`:
13
+ - Check thee part's register table and make a `<ic>_regs.h`:
12
14
  ```h
13
15
  #define ABC123_WHO_AM_I 0x0F
14
16
  #define ABC123_ID 0x6B
@@ -30,7 +32,7 @@ class IC_Driver {
30
32
  explicit IC_Driver(COM_Driver* com) : _com(com) {}
31
33
  virtual M_Status init() = 0;
32
34
  virtual M_Status reset() = 0;
33
- virtual M_Status read(uint8_t* buf, size_t* index) = 0;
35
+ virtual M_Status read(uint8_t* buf, size_t capacity, size_t* index) = 0;
34
36
 
35
37
  bool is_interrupt_pin_set() const { return this->com()->is_interrupt_pin_set(); }
36
38
  protected:
@@ -42,18 +44,31 @@ class IC_Driver {
42
44
 
43
45
  ## Sensor driver
44
46
 
45
- - A sensor driver never creates its COM driver, The owner wires the sensor and com driver together:
46
- - The driver is generic; the project's choices (range, ODR, filters, FIFO watermark, interrupt routing, oversampling, ...) belong to the app, not the driver.
47
+ - A sensor driver never creates its COM driver, The owner wires the sensor and com driver together.
48
+ - Sensor Driver is generic; the project's choices (range, ODR, filters, FIFO watermark, interrupt routing, oversampling, ...) belong to the app, not the driver.
47
49
  - Values that depend on the config (sensitivity per LSB, sample period, settling time) are computed from `_cfg`, never fixed constants.
48
50
 
49
-
51
+ - ICs of one family can share a templated base for compile-time sample sizes (eg: `template <size_t AXES, size_t BYTES_PER_AXIS> class IC_Sensor : public IC_Driver`).
52
+
50
53
  ```cpp
51
54
  class Sensor_ABC123 : public IC_Driver {
52
55
  public:
53
56
  using IC_Driver::IC_Driver;
57
+ M_Status reset() override;
54
58
  M_Status init() override;
55
- M_Status reset() override;
56
- M_Status read(uint8_t* buf, size_t* index) override;
59
+ /**
60
+ *
61
+ * Read one sample in one burst
62
+ * (if available: auto-increment, BDU block data update to prevent tearing while reading).
63
+ *
64
+ * Return only fresh data: check data-ready if polling (status bit)
65
+ * for DRDY interrupt based reads, data should be fresh
66
+ * so no need for checking again.
67
+ *
68
+ * change the caller's buffer and `*index` on successful reads only.
69
+ */
70
+ M_Status read(uint8_t* buf, size_t capacity, size_t* index) override;
71
+
57
72
  M_Status verify_id();
58
73
 
59
74
  bool is_interrupt_pin_set() const;
@@ -65,7 +80,10 @@ class Sensor_ABC123 : public IC_Driver {
65
80
  CFG_ODR odr = CFG_ODR::HZ_104;
66
81
  CFG_RANGE range = CFG_RANGE::G2;
67
82
  };
68
- M_Status set_config(const Config& cfg);
83
+ /**
84
+ * store the config, then init(); also used to reconfigure at runtime
85
+ */
86
+ M_Status init(const Config& cfg) { this->_cfg = cfg; return this->init(); }
69
87
  private:
70
88
  Config _cfg;
71
89
  };
@@ -74,12 +92,9 @@ class Sensor_ABC123 : public IC_Driver {
74
92
  ```cpp
75
93
  COM_SPI spi_imu(&hspi1, IMU_CS_GPIO_Port, IMU_CS_Pin);
76
94
  Sensor_ABC123 imu(&spi_imu);
77
- imu.set_config(...);//with required config in the app
78
- imu.init();
95
+ imu.init({ .odr = Sensor_ABC123::CFG_ODR::HZ_416 }); // or imu.init() for the defaults
79
96
  ```
80
97
 
81
- - ICs of one family can share a templated base for compile-time sample sizes (eg: `template <size_t AXES, size_t BYTES_PER_AXIS> class IC_Sensor : public IC_Driver`).
82
-
83
98
  ### init() order
84
99
 
85
100
  1. Set bus address masks before the first access
@@ -89,37 +104,20 @@ imu.init();
89
104
  4. set range, filters and options, then enable the output rate, unless the datasheet gives another order.
90
105
  - never hand settling samples as valid data: wait out the settling time before starting the FIFO or interrupt.
91
106
 
92
-
93
107
  - use `write_verify` to check the bits that are written to be set.
108
+ - stop at the first failed write: never enable the output rate after a failed configuration write.
94
109
 
95
110
  ```cpp
96
- M_Status Sensor_ABC123::init() {
97
- // set bus address masks before the first access
98
- this->com()->set_address_mask(ABC123_SPI_READ, 0, 0, 0);
99
-
100
- M_Status status = this->verify_id();
101
- if (status != M_StatusEnum::M_OK) return status;
102
- status |= this->reset();
103
- if (status != M_StatusEnum::M_OK) return status;
104
-
105
- // range, filters and other configs are set before setting the ODR
106
- status |= this->com()->write_verify(ABC123_CTRL2, (uint8_t)this->_cfg.range << ABC123_FS_POS, 3);
107
-
108
- // set ODR last as it usually powers up and starts the board
109
- status |= this->com()->write_verify(ABC123_CTRL1, (uint8_t)this->_cfg.odr << ABC123_ODR_POS, 3, ABC123_CTRL1_RW_MASK);
110
- return status;
111
- }
111
+ M_Status Sensor_ABC123::init()
112
112
  ```
113
113
 
114
- ### read()
115
-
116
- - Read one sample in one burst (auto-increment, block data update if available), so all axes come from the same sample.
117
- - Return only fresh data: check data-ready if polling (status bit) and return `M_BUSY` when there is none, for DRDY interrupt based reads data should be fresh so no need for checking again.
118
- - change the caller's buffer and `*index` on successful reads only.
119
114
 
120
115
  ### Interrupt pin
121
116
 
122
- - Set the chip's interrupt output to latched or level where the chip supports it, so a high pin means unread data.
123
- - missed edge recovery (watchdogs, re-arming) should be handled in the app task not in the drivers, when working on projects that go beyond making drivers only, see `references/tasks-and-interrupts.md` also.
124
-
125
-
117
+ - Pick the interrupt mode from how the MCU takes the pin:
118
+ - Edge-triggered external interrupt: use pulsed, so every sample gives a new edge even after a missed read.
119
+ - Level-checked or polled pin: use latched, so a high pin means unread data.
120
+ - If the chip only latches and the MCU uses edges, the app must also check the pin level.
121
+
122
+ - missed edge recovery (watchdogs, re-arming) should be handled in the app task not in the drivers;
123
+ - when working on projects that go beyond making drivers only, see `references/tasks-and-interrupts.md` also.
@@ -5,112 +5,12 @@
5
5
 
6
6
  ## COM_Driver
7
7
  - `COM_Driver` is the base class; subclasses (`COM_SPI`, `COM_I2C`, `COM_USART`) implement read and write with HAL or LL.
8
-
9
-
10
- ```cpp
11
- class COM_Driver {
12
- public:
13
- // must be implemented in the subclass
14
- virtual M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) = 0;
15
- virtual M_Status write(uint8_t reg, const uint8_t* data, size_t len) = 0;
16
-
17
- // read, modify, write
18
- M_Status write_bit(uint8_t reg, uint8_t bit, uint8_t value);
19
- // write, read, compare under mask
20
- M_Status write_verify(uint8_t reg, uint8_t value, size_t tries, uint8_t mask = 0xFF);
21
-
22
- // keep retrying until (reg & mask) == expected
23
- M_Status wait_for_register(uint8_t reg, uint8_t expected, size_t tries, uint8_t mask = 0xFF);
24
-
25
- /**
26
- * @brief address on the wire = (reg & ~clear) | set
27
- */
28
- void set_address_mask(uint8_t read_set, uint8_t read_clear,
29
- uint8_t write_set, uint8_t write_clear);
30
-
31
- /**
32
- * @brief Stores the bus and DMA handles and device address (if needed)
33
- */
34
- void bind_com(void* handle,
35
- uint16_t dev_addr,
36
- DMA_HandleTypeDef* rx_dma=nullptr,
37
- DMA_HandleTypeDef* tx_dma=nullptr);
38
-
39
- public:
40
- bool isBusy() const;
41
- void clearBusy();
42
- /**
43
- * @brief isHandle and handle are non-virtual.
44
- * Subclasses add a *typed version that hides them.
45
- */
46
- bool isHandle(void *check)const;
47
- void* handle() const;
48
-
49
- /**
50
- * @brief level of the device's interrupt pin; false when the bus driver has no pin
51
- */
52
- virtual bool is_interrupt_pin_set() const { return false; }
53
-
54
- private:
55
- uint16_t _dev_addr;
56
- uint16_t _mask_read_set;
57
- uint16_t _mask_read_clear;
58
- uint16_t _mask_write_set;
59
- uint16_t _mask_write_clear;
60
-
61
- protected:
62
- void* _handle=nullptr;
63
- volatile bool flag_busy=false;
64
- DMA_HandleTypeDef* _tx_dma=nullptr;
65
- DMA_HandleTypeDef* _rx_dma=nullptr;
66
- };
67
- ```
68
-
8
+ - Read `references/code/COM_Driver.hpp`
9
+
69
10
  ## Protocol driver
70
11
 
71
12
  - Owns the HAL handle and chip select; the IC driver never sees them.
72
-
73
- ### Example 1:
74
- ```cpp
75
- class COM_SPI : public COM_Driver {
76
- public:
77
- COM_SPI(SPI_HandleTypeDef* hspi, GPIO_TypeDef* cs_port, uint16_t cs_pin);
78
- M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override;
79
- M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
80
-
81
- bool isHandle(SPI_HandleTypeDef *check) const {
82
- return this->handle() == check;
83
- }
84
- SPI_HandleTypeDef* handle() const {
85
- return (SPI_HandleTypeDef*)_handle;
86
- }
87
-
88
- bool is_interrupt_pin_set() const override {
89
- return this->_int_port != nullptr && HAL_GPIO_ReadPin(this->_int_port, this->_int_pin) == GPIO_PIN_SET;
90
- }
91
- bool is_interrupt_pin(uint16_t pin) const { return this->_int_port != nullptr && this->_int_pin == pin; }
92
-
93
- private:
94
- GPIO_TypeDef* _cs_port;
95
- uint16_t _cs_pin;
96
- };
97
- ```
98
-
99
- ### Example 2:
100
- ```cpp
101
- class COM_USART : public COM_Driver {
102
- public:
103
- explicit COM_USART(UART_HandleTypeDef* huart);
104
-
105
- M_Status read(uint8_t reg, uint8_t* data, size_t len = 1) override;
106
- M_Status write(uint8_t reg, const uint8_t* data, size_t len) override;
107
- bool isHandle(UART_HandleTypeDef *check) const {
108
- return this->handle() == check;
109
- }
110
- UART_HandleTypeDef* handle() const {
111
- return (UART_HandleTypeDef*)_handle;
112
- }
113
- };
114
- ```
115
- - read/write `reg` is ignored for USART
116
- - `COM_USART` has no registers, so `write_bit`, `write_verify` and `wait_for_register` don't apply to it.
13
+ - Read the example for the bus you are writing:
14
+ - SPI: `references/code/COM_SPI.hpp`
15
+ - I2C: `references/code/COM_I2C.hpp`
16
+ - USART: `references/code/COM_USART.hpp`
@@ -1,13 +1,12 @@
1
1
  # RTOS support for drivers
2
2
 
3
3
  - Use this when the project runs an RTOS (eg: FreeRTOS) so its drivers can be called from more than one task.
4
-
4
+ - when using freeRTOS, use osDelay instead of HAL_Delay
5
5
 
6
6
  ## Util_MutexManager
7
7
 
8
8
  - `COM_Driver` inherits `Util_MutexManager` under `#ifdef INC_FREERTOS_H`.
9
9
 
10
-
11
10
  - A base class that gives each COM driver a FreeRTOS mutex and a binary semaphore, so tasks sharing a bus take turns and a DMA transfer keeps the bus busy until its ISR finishes.
12
11
  - **Mutex**: guards a blocking transfer. use from task context only, never from an ISR.
13
12
  - **Binary semaphore**: marks a DMA/IT transfer in flight. The starting task releases it if the start fails; otherwise the complete/error ISR releases it.
@@ -11,4 +11,7 @@ Cases it must cover:
11
11
  * each read-back mismatch;
12
12
  * no new data returns M_BUSY and leaves the output untouched;
13
13
  * decoding with values whose high and low bytes differ, plus negative and extreme values.
14
- * Work out the expected bytes from the datasheet, not from the driver's own constants.
14
+ * Work out the expected bytes from the datasheet, not from the driver's own constants.
15
+
16
+ ### Prove the tests can fail
17
+ - In a throwaway copy, break one thing per area (an init value or its order, an error path, the decoding) and check that the matching test fails. If it still passes, strengthen the test.
@@ -1,57 +1,57 @@
1
- # Storage
2
-
3
- - Use this when saving settings, calibration or other data to flash or EEPROM.
4
-
5
- ## Register array
6
-
7
- - Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
8
- - Derive each offset from the previous one with `sizeof`:
9
- ```cpp
10
- #define REG_CTRL 0 // uint8
11
- #define REG_CALIB_ACC 1 // 3 × float
12
- #define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
13
- ```
14
- - Save only settings, never live status or measurements.
15
- - Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
16
- - Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
17
- - Bound every setter over the whole write:
18
- ```cpp
19
- if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
20
- ```
21
-
22
- ## Settings page
23
-
24
- - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
25
- ```ld
26
- FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
27
- ```
28
- - Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
29
- - Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
30
- - Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
31
-
32
- ## Header
33
-
34
- - Start the page with one 16-byte header for the whole array, then the registers:
35
- ```
36
- [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
- 0 4 6 10 16
38
- ```
39
- - `magic`: a fixed constant; blank or foreign flash won't match.
40
- - `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
41
- - `crc`: over the registers; catches a cut-off save or a flipped bit.
42
- - On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
43
-
44
- ## Writing
45
-
46
- - Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
47
- - Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
48
- ```cpp
49
- M_Status status = this->flash_unlock();
50
- if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
51
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
52
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
53
- status |= this->flash_lock();
54
- if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
55
- ```
56
- - Give your own busy-bit polling a timeout; the HAL calls already have one.
57
- - Save from a task or the main loop, never from an ISR.
1
+ # Storage
2
+
3
+ - Use this when saving settings, calibration or other data to flash or EEPROM.
4
+
5
+ ## Register array
6
+
7
+ - Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
8
+ - Derive each offset from the previous one with `sizeof`:
9
+ ```cpp
10
+ #define REG_CTRL 0 // uint8
11
+ #define REG_CALIB_ACC 1 // 3 × float
12
+ #define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
13
+ ```
14
+ - Save only settings, never live status or measurements.
15
+ - Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
16
+ - Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
17
+ - Bound every setter over the whole write:
18
+ ```cpp
19
+ if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
20
+ ```
21
+
22
+ ## Settings page
23
+
24
+ - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
25
+ ```ld
26
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
27
+ ```
28
+ - Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
29
+ - Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
30
+ - Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
31
+
32
+ ## Header
33
+
34
+ - Start the page with one 16-byte header for the whole array, then the registers:
35
+ ```
36
+ [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
+ 0 4 6 10 16
38
+ ```
39
+ - `magic`: a fixed constant; blank or foreign flash won't match.
40
+ - `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
41
+ - `crc`: over the registers; catches a cut-off save or a flipped bit.
42
+ - On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
43
+
44
+ ## Writing
45
+
46
+ - Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
47
+ - Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
48
+ ```cpp
49
+ M_Status status = this->flash_unlock();
50
+ if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
51
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
52
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
53
+ status |= this->flash_lock();
54
+ if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
55
+ ```
56
+ - Give your own busy-bit polling a timeout; the HAL calls already have one.
57
+ - Save from a task or the main loop, never from an ISR.
@@ -1,70 +1,70 @@
1
- # Tasks and interrupts
2
-
3
- - Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
4
-
5
- ## ISRs
6
-
7
- - Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
8
- - Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
9
- - Use one event bit per source.
10
- - Count events that must not be lost; bits merge when an event repeats before it's handled:
11
- ```cpp
12
- while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
13
- ```
14
- - Null-check globals in callbacks; they can fire before the object exists.
15
-
16
- ## Without an RTOS
17
-
18
- - Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
19
- ```cpp
20
- __disable_irq();
21
- uint32_t events = g_events;
22
- g_events = 0;
23
- __enable_irq();
24
- if (events & EVT_IMU_READY) imu->read_into_memory();
25
- ```
26
-
27
- ## With FreeRTOS
28
-
29
- - Notify the worker task from the ISR with `...FromISR` APIs, then yield:
30
- ```cpp
31
- BaseType_t woken = pdFALSE;
32
- xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
33
- portYIELD_FROM_ISR(woken);
34
- ```
35
- - When an interrupt marks new data (UART RX event, data-ready pin, DMA complete), notify the task from it; don't make the task poll with `osDelay`. Poll only when no interrupt source exists, and say so in a comment.
36
- - One notification can stand for several events: on each wake, handle everything pending (loop until no complete item is left).
37
- - Set the task handle before enabling the IRQ, and reset it to `nullptr` if task creation fails.
38
- - Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
39
- - Wait with a timeout as a safety net; on timeout poll the source, so a missed edge (or data a parse step left behind) can't stall the task:
40
- ```cpp
41
- if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
42
- && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
43
- ```
44
-
45
- ## Shared data
46
-
47
- - ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
48
- ```cpp
49
- taskENTER_CRITICAL();
50
- size_t n = rx_len;
51
- memcpy(local, rx_buf, n);
52
- rx_len = 0;
53
- taskEXIT_CRITICAL();
54
- parse(local, n); // never parse rx_buf in place
55
- ```
56
- - Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
57
-
58
- ## DMA
59
-
60
- - Use static or member buffers, never locals; DMA keeps running after the call returns.
61
- - Check the length against the buffer size before copying in.
62
- - Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
63
- ```cpp
64
- if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
65
- this->_tx_busy = false; // or this->_tx_sem.release()
66
- return M_StatusEnum::M_ERROR;
67
- }
68
- ```
69
- - Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
70
- - Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
1
+ # Tasks and interrupts
2
+
3
+ - Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
4
+
5
+ ## ISRs
6
+
7
+ - Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
8
+ - Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
9
+ - Use one event bit per source.
10
+ - Count events that must not be lost; bits merge when an event repeats before it's handled:
11
+ ```cpp
12
+ while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
13
+ ```
14
+ - Null-check globals in callbacks; they can fire before the object exists.
15
+
16
+ ## Without an RTOS
17
+
18
+ - Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
19
+ ```cpp
20
+ __disable_irq();
21
+ uint32_t events = g_events;
22
+ g_events = 0;
23
+ __enable_irq();
24
+ if (events & EVT_IMU_READY) imu->read_into_memory();
25
+ ```
26
+
27
+ ## With FreeRTOS
28
+
29
+ - Notify the worker task from the ISR with `...FromISR` APIs, then yield:
30
+ ```cpp
31
+ BaseType_t woken = pdFALSE;
32
+ xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
33
+ portYIELD_FROM_ISR(woken);
34
+ ```
35
+ - When an interrupt marks new data (UART RX event, data-ready pin, DMA complete), notify the task from it; don't make the task poll with `osDelay`. Poll only when no interrupt source exists, and say so in a comment.
36
+ - One notification can stand for several events: on each wake, handle everything pending (loop until no complete item is left).
37
+ - Set the task handle before enabling the IRQ, and reset it to `nullptr` if task creation fails.
38
+ - Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
39
+ - Wait with a timeout as a safety net; on timeout poll the source, so a missed edge (or data a parse step left behind) can't stall the task:
40
+ ```cpp
41
+ if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
42
+ && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
43
+ ```
44
+
45
+ ## Shared data
46
+
47
+ - ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
48
+ ```cpp
49
+ taskENTER_CRITICAL();
50
+ size_t n = rx_len;
51
+ memcpy(local, rx_buf, n);
52
+ rx_len = 0;
53
+ taskEXIT_CRITICAL();
54
+ parse(local, n); // never parse rx_buf in place
55
+ ```
56
+ - Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
57
+
58
+ ## DMA
59
+
60
+ - Use static or member buffers, never locals; DMA keeps running after the call returns.
61
+ - Check the length against the buffer size before copying in.
62
+ - Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
63
+ ```cpp
64
+ if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
65
+ this->_tx_busy = false; // or this->_tx_sem.release()
66
+ return M_StatusEnum::M_ERROR;
67
+ }
68
+ ```
69
+ - Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
70
+ - Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.3.15",
3
+ "version": "0.3.16",
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": {
@@ -42,4 +42,4 @@
42
42
  "@types/yargs": "17.0.35",
43
43
  "typescript": "7.0.2"
44
44
  }
45
- }
45
+ }