@turingcode/cli 0.3.13 → 0.3.14

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.
@@ -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}`;
@@ -14,7 +14,7 @@ const ALWAYS_SKIPPED = /\.(zip|gz|gzip|rar)$/i; /** archives, even when listed i
14
14
  * @returns true if the path passes the rules
15
15
  */
16
16
  function isSyncablePre(rel) {
17
- return (!rel.startsWith("build/") &&
17
+ return (!/(^|\/)build\//.test(rel) && /** build output at any depth, as the server skips it */
18
18
  !/(^|\/)\.[^/]*\//.test(rel) && /** dot folders at any depth: .git, .turingcode, .codex, .vscode, ... */
19
19
  !/(^|\/)\.env(\.[^/]*)?$/.test(rel) && /** .env, .env.local, ... */
20
20
  !/\.csv$/i.test(rel) && /** data dumps */
@@ -1,48 +1,48 @@
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, syntax check and static analysis.
19
- - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
- - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
-
22
- ## Server tools
23
-
24
- Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
25
-
26
- - `turingcode tool list` shows the available tools.
27
- - `turingcode tool call <name> --args '<json>' > result.md` runs one.
28
- - On Windows PowerShell or cmd, inline JSON loses its quotes: write the JSON to a `.json` file and pass `--args args.json`.
29
-
30
-
31
- ## New project
32
-
33
- Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
34
-
35
- ## Typical loop
36
-
37
- 1. Edit the code, run `turingcode project sync -b` and fix the reported errors.
38
- - Before finishing a change, run `turingcode project sync -b -a` for static analysis.
39
- 2. Flash with `turingcode probe program`.
40
- 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.
41
- 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
42
-
43
- ## CRITICAL Safety rules
44
-
45
- - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu.
46
- - Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
47
- - 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, syntax check and static analysis.
19
+ - `turingcode probe --help`: flash, reset, read memory or registers, decode faults, recover a stuck probe.
20
+ - `turingcode debug --help`: breakpoints, stepping, stack, variables.
21
+
22
+ ## Server tools
23
+
24
+ Pins, clocks, `.ioc` edits, register lookup and the datasheet knowledge base (MCUs and components) run as server tools:
25
+
26
+ - `turingcode tool list` shows the available tools.
27
+ - `turingcode tool call <name> --args '<json>' > result.md` runs one.
28
+ - On Windows PowerShell or cmd, inline JSON loses its quotes: write the JSON to a `.json` file and pass `--args args.json`.
29
+
30
+
31
+ ## New project
32
+
33
+ Only when the user asks for a new project: follow [references/newproject.md](references/newproject.md).
34
+
35
+ ## Typical loop
36
+
37
+ 1. Edit the code, run `turingcode project sync -b` and fix the reported errors.
38
+ - Before finishing a change, run `turingcode project sync -b -a` for static analysis.
39
+ 2. Flash with `turingcode probe program`.
40
+ 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.
41
+ 4. On a crash, run `turingcode probe faults`, or `turingcode debug start` with breakpoints to find the cause.
42
+
43
+ ## CRITICAL Safety rules
44
+
45
+ - Don't ever write debug registers by hand (DHCSR, DEMCR, DCRSR, DCRDR, FPB). doing so may brick the mcu.
46
+ - Halt, step and breakpoints go through `turingcode debug`, which releases the debug state on exit.
47
+ - NEVER touch RDP without asking first.
48
48
  - Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
@@ -15,7 +15,7 @@ A project's `AGENTS.md` overrides this skill wherever it is more specific (layou
15
15
  |---|---|
16
16
  | `references/driver.md` | a driver for an external IC or bus protocol |
17
17
  | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions |
18
- | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, shared data |
18
+ | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks and their wakeups, DMA, shared data |
19
19
  | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, init order, tasks, µs time base |
20
20
  | `references/storage.md` | saving settings, calibration or data to flash/EEPROM |
21
21
  | `references/host-protocol.md` | host frames, command dispatch, register writes, replies/telemetry |
@@ -1,57 +1,57 @@
1
- # Storage
2
-
3
- - Use this when saving settings, calibration or other data to flash or EEPROM.
4
-
5
- ## Register array
6
-
7
- - Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
8
- - Derive each offset from the previous one with `sizeof`:
9
- ```cpp
10
- #define REG_CTRL 0 // uint8
11
- #define REG_CALIB_ACC 1 // 3 × float
12
- #define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
13
- ```
14
- - Save only settings, never live status or measurements.
15
- - Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
16
- - Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
17
- - Bound every setter over the whole write:
18
- ```cpp
19
- if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
20
- ```
21
-
22
- ## Settings page
23
-
24
- - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
25
- ```ld
26
- FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
27
- ```
28
- - Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
29
- - Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
30
- - Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
31
-
32
- ## Header
33
-
34
- - Start the page with one 16-byte header for the whole array, then the registers:
35
- ```
36
- [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
- 0 4 6 10 16
38
- ```
39
- - `magic`: a fixed constant; blank or foreign flash won't match.
40
- - `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
41
- - `crc`: over the registers; catches a cut-off save or a flipped bit.
42
- - On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
43
-
44
- ## Writing
45
-
46
- - Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
47
- - Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
48
- ```cpp
49
- M_Status status = this->flash_unlock();
50
- if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
51
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
52
- if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
53
- status |= this->flash_lock();
54
- if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
55
- ```
56
- - Give your own busy-bit polling a timeout; the HAL calls already have one.
57
- - Save from a task or the main loop, never from an ISR.
1
+ # Storage
2
+
3
+ - Use this when saving settings, calibration or other data to flash or EEPROM.
4
+
5
+ ## Register array
6
+
7
+ - Keep all settings in one byte array addressed by offset. RAM is the working copy; save and load it as a whole.
8
+ - Derive each offset from the previous one with `sizeof`:
9
+ ```cpp
10
+ #define REG_CTRL 0 // uint8
11
+ #define REG_CALIB_ACC 1 // 3 × float
12
+ #define REG_COUNT (REG_CALIB_ACC + 3 * sizeof(float))
13
+ ```
14
+ - Save only settings, never live status or measurements.
15
+ - Copy multi-byte values with `memcpy`, never through a cast pointer; offsets are unaligned and an unaligned `float` access faults.
16
+ - Keep defaults in one `static constexpr uint8_t REG_DEFAULTS[REG_COUNT]` table; `load_defaults()` copies it in.
17
+ - Bound every setter over the whole write:
18
+ ```cpp
19
+ if (reg >= REG_COUNT || len > REG_COUNT - reg) return M_StatusEnum::M_OUT_OF_RANGE;
20
+ ```
21
+
22
+ ## Settings page
23
+
24
+ - Use the last flash page, and shrink `FLASH` in the linker script by it so code can't land there:
25
+ ```ld
26
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K - 2K /* last 2 KB page: settings */
27
+ ```
28
+ - Take the page size, program type and erase fields from the HAL, not from memory: `FLASH_PAGE_SIZE`, `FLASH_TYPEPROGRAM_*`, and `Page` or `PageAddress` in `FLASH_EraseInitTypeDef`.
29
+ - Derive the write unit from the program type (`sizeof(uint64_t)` for `DOUBLEWORD`). Align every block to it and pad with `0xFF`.
30
+ - Check every HAL flash return, and `PageError == 0xFFFFFFFF` after erase.
31
+
32
+ ## Header
33
+
34
+ - Start the page with one 16-byte header for the whole array, then the registers:
35
+ ```
36
+ [ magic u32 | version u16 | crc u32 | pad ][ registers ... ]
37
+ 0 4 6 10 16
38
+ ```
39
+ - `magic`: a fixed constant; blank or foreign flash won't match.
40
+ - `version`: bump it when an offset moves, a register is added or removed, or a new default must replace saved values.
41
+ - `crc`: over the registers; catches a cut-off save or a flipped bit.
42
+ - On load, if the read fails or any field mismatches, load the defaults and return `M_ERROR`. The caller logs it and keeps running; it's expected on first boot.
43
+
44
+ ## Writing
45
+
46
+ - Write in this order: build the header with the new CRC, unlock, erase, program the header, program the registers, lock, then read back and compare header and registers.
47
+ - Erase or program only after a successful unlock, and stop at the first failure. Always lock, even after a failure:
48
+ ```cpp
49
+ M_Status status = this->flash_unlock();
50
+ if (status == M_StatusEnum::M_OK) status |= this->flash_erase_page(SETTINGS_PAGE);
51
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(0, hdr, HDR_LEN);
52
+ if (status == M_StatusEnum::M_OK) status |= this->flash_program(HDR_LEN, this->_regs, REG_COUNT);
53
+ status |= this->flash_lock();
54
+ if (status == M_StatusEnum::M_OK) status = this->verify(hdr);
55
+ ```
56
+ - Give your own busy-bit polling a timeout; the HAL calls already have one.
57
+ - Save from a task or the main loop, never from an ISR.
@@ -1,67 +1,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
- - Give ISRs that call FreeRTOS an NVIC priority ≥ `configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY` (numerically).
36
- - Wait with a timeout; on timeout poll the source, so a missed edge can't stall the task:
37
- ```cpp
38
- if (xTaskNotifyWait(0, UINT32_MAX, &bits, pdMS_TO_TICKS(50)) != pdTRUE
39
- && HAL_GPIO_ReadPin(IMU_DRDY_GPIO_Port, IMU_DRDY_Pin)) bits |= EVT_IMU_READY;
40
- ```
41
-
42
- ## Shared data
43
-
44
- - ISR ↔ loop or task: copy and clear under a critical section, then work on the copy. Use `taskENTER_CRITICAL()` with FreeRTOS, `__disable_irq()` without:
45
- ```cpp
46
- taskENTER_CRITICAL();
47
- size_t n = rx_len;
48
- memcpy(local, rx_buf, n);
49
- rx_len = 0;
50
- taskEXIT_CRITICAL();
51
- parse(local, n); // never parse rx_buf in place
52
- ```
53
- - Task ↔ task: take a mutex with a timeout, never `portMAX_DELAY`. On timeout, skip this cycle.
54
-
55
- ## DMA
56
-
57
- - Use static or member buffers, never locals; DMA keeps running after the call returns.
58
- - Check the length against the buffer size before copying in.
59
- - Take a semaphore (RTOS) or test-and-set a busy flag with interrupts off (bare-metal) before writing the buffer. Release it in the complete callback, and yourself if the start fails:
60
- ```cpp
61
- if (HAL_UART_Transmit_DMA(this->_huart, this->_tx_buf, len) != HAL_OK) {
62
- this->_tx_busy = false; // or this->_tx_sem.release()
63
- return M_StatusEnum::M_ERROR;
64
- }
65
- ```
66
- - Enable both the DMA and the peripheral interrupt in the `.ioc`; UART TX completion comes from the USART IRQ.
67
- - Check the generated `*_IRQHandler` calls `HAL_DMA_IRQHandler` / `HAL_UART_IRQHandler`. If empty, add it in USER CODE; otherwise the IRQ re-enters forever.
1
+ # Tasks and interrupts
2
+
3
+ - Use this when writing ISRs, HAL callbacks, the main loop, RTOS tasks, DMA, or data shared between them.
4
+
5
+ ## ISRs
6
+
7
+ - Only signal from an ISR: set an event bit, notify a task, or bump a counter. Do bus transfers, parsing and math in the loop or a task; in an ISR they block every lower-priority interrupt.
8
+ - Never call blocking HAL (`HAL_SPI_Transmit`, `HAL_Delay`, ...) or `printf` in an ISR.
9
+ - Use one event bit per source.
10
+ - Count events that must not be lost; bits merge when an event repeats before it's handled:
11
+ ```cpp
12
+ while (this->_done != g_isr_count) { handle_event(); this->_done++; } // g_isr_count: volatile, ++ in the ISR
13
+ ```
14
+ - Null-check globals in callbacks; they can fire before the object exists.
15
+
16
+ ## Without an RTOS
17
+
18
+ - Set bits in a `volatile` event word in the ISR. In the loop, take and clear it with interrupts off, then work with them on:
19
+ ```cpp
20
+ __disable_irq();
21
+ uint32_t events = g_events;
22
+ g_events = 0;
23
+ __enable_irq();
24
+ if (events & EVT_IMU_READY) imu->read_into_memory();
25
+ ```
26
+
27
+ ## With FreeRTOS
28
+
29
+ - Notify the worker task from the ISR with `...FromISR` APIs, then yield:
30
+ ```cpp
31
+ BaseType_t woken = pdFALSE;
32
+ xTaskNotifyFromISR(reader_task, EVT_IMU_READY, eSetBits, &woken);
33
+ portYIELD_FROM_ISR(woken);
34
+ ```
35
+ - 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.13",
3
+ "version": "0.3.14",
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
+ }