@turingcode/cli 0.3.14 → 0.3.15

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 (46) hide show
  1. package/dist/cli/create-cli.js +46 -31
  2. package/dist/core/mcp.d.ts +0 -10
  3. package/dist/core/mcp.js +0 -18
  4. package/dist/features/contract/command.js +64 -64
  5. package/dist/features/probe/program_project.js +3 -3
  6. package/dist/features/project/analysis_static.js +7 -6
  7. package/dist/features/project/command.d.ts +3 -1
  8. package/dist/features/project/command.js +15 -11
  9. package/dist/features/project/project_regenerate.js +4 -3
  10. package/dist/features/project/project_sync_from_server.js +4 -3
  11. package/dist/features/project/project_sync_to_server.js +36 -11
  12. package/dist/features/project/stm32_cubetools_download_drivers.js +5 -4
  13. package/dist/features/status/get_status.js +6 -3
  14. package/dist/features/syntax-check/command.d.ts +2 -0
  15. package/dist/features/syntax-check/command.js +8 -0
  16. package/dist/features/syntax-check/syntax_check.d.ts +3 -0
  17. package/dist/features/syntax-check/syntax_check.js +27 -0
  18. package/dist/features/tool/command.d.ts +2 -0
  19. package/dist/features/tool/command.js +58 -7
  20. package/dist/lib.d.ts +1 -1
  21. package/dist/lib.js +1 -1
  22. package/dist/stm32/analysis.d.ts +40 -4
  23. package/dist/stm32/analysis.js +61 -5
  24. package/dist/stm32/toolCommand.d.ts +1 -0
  25. package/dist/stm32/toolCommand.js +7 -2
  26. package/dist/stm32/utils/makeTempProject.d.ts +16 -0
  27. package/dist/stm32/utils/makeTempProject.js +79 -0
  28. package/dist/stm32/utils/project_utils.d.ts +36 -1
  29. package/dist/stm32/utils/project_utils.js +48 -2
  30. package/mods/claude/turingcode-skills/skills/AGENTS.md +0 -5
  31. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +48 -47
  32. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +50 -42
  33. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +24 -6
  34. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/BusMutexRegistry.hpp +138 -0
  35. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/code/Util_MutexManager.hpp +212 -0
  36. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver.md +72 -0
  37. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_ic.md +125 -0
  38. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_protocol.md +116 -0
  39. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_rtos.md +130 -0
  40. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver/driver_test.md +14 -0
  41. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +57 -57
  42. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +70 -70
  43. package/package.json +2 -2
  44. package/dist/features/project/analysis_syntax_check.d.ts +0 -3
  45. package/dist/features/project/analysis_syntax_check.js +0 -21
  46. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +0 -97
@@ -1,48 +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, 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 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.
48
49
  - Level 1 → 0 mass-erases the flash, and Level 2 is permanent.
@@ -5,15 +5,17 @@ description: Coding rules for embedded C/C++ firmware on STM32. Use whenever wri
5
5
 
6
6
  # Embedded C/C++ rules
7
7
 
8
- These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report it.
8
+ - These rules outrank speed: when a rule conflicts with a faster solution, follow the rule and report it.
9
+ - A project's `AGENTS.md` overrides this skill wherever it is more specific (layout, shared helpers, generator markers, tests).
9
10
 
10
- A project's `AGENTS.md` overrides this skill wherever it is more specific (layout, shared helpers, generator markers, tests). Read it first.
11
+ - some names in the references (`crc32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own functions and helpers. Use the existing ones.
12
+ - add a missing helper once to the project's shared helper location (or `Utils/` if it has none), never inline.
11
13
 
12
- ## Read the matching reference first
14
+ ## Read the matching references
13
15
 
14
- | Read | When the change touches |
16
+ | Read | When changing or making |
15
17
  |---|---|
16
- | `references/driver.md` | a driver for an external IC or bus protocol |
18
+ | `references/driver/driver.md` | a driver for an external IC or bus protocol |
17
19
  | `references/registers-and-units.md` | datasheet registers, bit fields, signedness, units, conversions |
18
20
  | `references/tasks-and-interrupts.md` | ISRs, HAL callbacks, the main loop, RTOS tasks and their wakeups, DMA, shared data |
19
21
  | `references/app-startup.md` | `main.c` hook, `extern "C"` entry, init order, tasks, µs time base |
@@ -21,12 +23,7 @@ A project's `AGENTS.md` overrides this skill wherever it is more specific (layou
21
23
  | `references/host-protocol.md` | host frames, command dispatch, register writes, replies/telemetry |
22
24
  | `references/M_StatusEnum.md` | no `M_Status.hpp`, or how to return and combine statuses |
23
25
 
24
- - some names in the references (`crc32`, `flash_*`, `COM_Driver`, ...) are placeholders for the project's own functions and helpers. Use the existing ones.
25
- - add a missing helper once to the project's shared helper location (or `Utils/`/`Platform/` if it has none), never inline.
26
-
27
- ## Generated and vendor code
28
-
29
- ## CubeMX-generated code
26
+ ## Generated code
30
27
 
31
28
  - In generated files (`main.c`, peripheral init, ...), write only inside
32
29
  `/* USER CODE BEGIN/END */` blocks and leave the markers alone. CubeMX
@@ -35,19 +32,25 @@ A project's `AGENTS.md` overrides this skill wherever it is more specific (layou
35
32
  - HAL callbacks can only be defined once. If generated code already defines
36
33
  one (often in `main.c` or `stm32xxxx_it.c`), call your handler from its
37
34
  USER CODE block.
35
+
36
+ ## Application Code Location
37
+
38
38
  - Keep `main.c` thin: it only calls `App/app.h` (`app_init()`, `app_loop()`),
39
- which needs `extern "C"` guards. All application code lives in `<Project>/App/`.
39
+ which needs `extern "C"` guards.
40
+ - All application code lives in `<Project>/App/`, generic code lives in the project's shared helper location (or `App/Utils/`/`App/Math/`).
41
+ - A shared library or SDK inside `App/` is not a Code Area: use it, don't restructure it, ask before changing it.
40
42
 
41
43
  ## File layout
42
44
 
43
- Each Code Area you create gets one folder in `App/`:
45
+ - put source (c,cpp) and header (h,hpp) files in the same folder with the same base name.
46
+ - Include project headers by file name only (`#include "com_spi.hpp"`), never with a folder or `../` path.
47
+
44
48
 
45
- - External IC (registers, config, readout, commands) → `Drivers/<IC>/`, `<IC>` uppercase part number without ordering/package/reel suffixes. All Code Areas of one IC share it.
46
- - Everything else → one category folder:
49
+ - Below is a list of folders for each code area in `App/` folder, these are a guide for you to know where to put things that you must create, not a rule to what to create. only create files and folders that are asked in your task:
47
50
 
48
51
  | Folder | Content |
49
- |---|---|
50
- | `Platform/` | HAL↔App adapters: bus arbitration, peripheral access |
52
+ |---|---|
53
+ | `Drivers/` | IC and Protocol Drivers |
51
54
  | `Algorithms/` | conversion, calibration, filtering, estimation, fusion |
52
55
  | `Control/` | regulation that commands actuators |
53
56
  | `Comms/` | host/device protocols: framing, parsing, telemetry |
@@ -56,39 +59,44 @@ Each Code Area you create gets one folder in `App/`:
56
59
  | `System/` | startup order, main cycle/tasks, modes, faults |
57
60
  | `Update/` | firmware update |
58
61
  | `Math/` | numeric types and linear algebra |
59
- | `Utils/` | domain-free helpers used by 2+ Code Areas |
60
-
61
-
62
-
63
- A shared library or SDK inside `App/` is not a Code Area: use it, don't restructure it, ask before changing it.
64
-
65
- Each Code Area is one module: source + header with the same base name.
66
-
67
- - **Driver**: base name is the lowercase IC part (`test_ic_1.c/.h`); add `<ic>_regs.h` for register access. A second Code Area for the same IC gets its own base name in the same folder.
68
- - **Other**: snake_case purpose without the category word (`attitude_estimation`).
69
- - Header only when the module holds just constants, macros or inline/template helpers.
70
- - Base names are unique across Code Area folders; on collision, prefix the lowercase category.
71
- - Create no other files for a Code Area (tests, docs, build files, README, config headers) unless the project requires them.
62
+ | `Utils/` | domain-free helpers |
72
63
 
73
64
  ## House style
74
65
 
75
- Match the existing style; don't "modernize" it.
66
+ - **Methods**: lowerCamelCase
67
+ - **Members**:
68
+ - Public members: lowerCamelCase
69
+ - Private members: lowerCamelCase with trailing _
70
+ - Internal Helpers: lowerCamelCase with trailing __
71
+ access members via `this->`.
76
72
 
77
73
  - **Classes**: PascalCase joined by underscores, prefixed by layer/role: `Sensor_Driver`, `Util_Mutex`, `Filter_MovingAvg`.
78
- - **Members**: `_` private fields, `__` internal helpers, always via `this->`.
79
- - **Methods**: snake_case in new code; leave existing names.
80
- - **Errors**: return `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints; accumulate with `status |= ...`.
81
- - **Comments**: `/* ---- Title ---- */` banners; `/** */` explains why, physics, units, datasheet; `////` marks disabled code.
74
+
75
+ - **Errors**: prefer `M_Status` (`M_StatusEnum::M_OK`, ...), never `bool` or raw ints; accumulate with `status |= ...`.
76
+
82
77
  - **Variants**: templates/`if constexpr` for compile-time sizes; register/config bits for runtime switches; concrete class names, no typedef selection layer.
83
- - **Layering**: all code in `App/`; generic code in the project's shared helper location (or `Utils/`/`Math/`), chip/product code in its own module.
78
+
79
+ - **Comments**: use structured documentation comments
80
+ - use `/* ---- Title ---- */` banners
81
+ - `////` marks disabled code.
82
+ - for functions write proper comments with `@brief`, `@param`, `@return`, `@throws` and `@note` tags, e.g.:
83
+ ```cpp
84
+ /**
85
+ * @brief …
86
+ *
87
+ * …
88
+ *
89
+ * @tparam …
90
+ * @param A …
91
+ * @param B …
92
+ * @return …
93
+ * @throws …
94
+ * @note …
95
+ */
96
+ ```
84
97
 
85
98
  ## Safety rules
86
99
 
87
- 1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return. Never return `M_OK` after fallible steps; if ignoring one is safe, say why.
100
+ 1. **Never drop a status.** Check or accumulate every status, `HAL_StatusTypeDef` and RTOS return. Never return `M_OK` after fallible steps; if ignoring one is safe, write in comments why.
88
101
  2. **Every wait has a timeout and an error path.** No unbounded hardware loops, no retry count where 0 means "forever"; fail visibly instead of hanging boot.
89
102
  3. **Budget memory.** No `new`/`delete` in periodic/per-transaction paths; preallocate as members or statics; keep KB-sized objects off task stacks and size each stack.
90
- 4. **Test speed tweaks** on hardware before committing, and confirm the success branch still runs.
91
-
92
- ## Before you finish
93
-
94
- Re-read the diff against these rules and the references you loaded.
@@ -1,10 +1,12 @@
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
-
4
+
5
5
  ## Values
6
6
 
7
- - Only these, ordered best to worst: `M_OK`, `M_ERROR`, `M_BUSY`, `M_TIMEOUT`, `M_OUT_OF_RANGE`, `M_DISABLED`, `M_NOT_SUPPORTED`. Never add one without asking.
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
8
10
 
9
11
  ## Usage
10
12
 
@@ -20,14 +22,30 @@ return status; // the worst result win
20
22
  - Add `Utils/M_Status.hpp`. Include the family HAL header (`stm32g4xx_hal.h`, `stm32f3xx_hal.h`, ...) for `HAL_StatusTypeDef`.
21
23
 
22
24
  ```cpp
23
- enum M_StatusEnum { M_OK = 0, M_ERROR, M_BUSY, M_TIMEOUT, M_OUT_OF_RANGE, M_DISABLED, M_NOT_SUPPORTED };
25
+ #pragma once
26
+ /**
27
+ * Status type shared by all drivers
28
+ * Ordered best to worst `|=` keeps the worst result.
29
+ */
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
32
 
25
33
  class M_Status {
26
34
  public:
27
35
  M_StatusEnum value;
28
36
  M_Status(M_StatusEnum v = M_OK) : value(v) {}
29
- M_Status(HAL_StatusTypeDef h); // HAL_OK→M_OK, HAL_ERROR→M_ERROR, HAL_BUSY→M_BUSY, HAL_TIMEOUT→M_TIMEOUT
30
- M_Status& operator|=(M_Status o) { if (o.value > this->value) this->value = o.value; return *this; }
37
+ M_Status(HAL_StatusTypeDef h) {
38
+ switch (h) {
39
+ case HAL_OK: this->value = M_OK; break;
40
+ case HAL_BUSY: this->value = M_BUSY; break;
41
+ case HAL_TIMEOUT: this->value = M_TIMEOUT; break;
42
+ default: this->value = M_ERROR; break;
43
+ }
44
+ }
45
+ M_Status& operator|=(M_Status o) {
46
+ if (o.value > this->value) this->value = o.value;
47
+ return *this;
48
+ }
31
49
  operator M_StatusEnum() const { return this->value; }
32
50
  };
33
- ```
51
+ ```
@@ -0,0 +1,138 @@
1
+ #pragma once
2
+ /**
3
+ * Automatically include FreeRTOS when the project has it.
4
+ */
5
+ #if defined(__has_include)
6
+ #if __has_include("FreeRTOS.h")
7
+ #include "FreeRTOS.h"
8
+ #endif
9
+ #endif
10
+
11
+
12
+ #ifdef INC_FREERTOS_H
13
+ #include <atomic>
14
+ extern "C" {
15
+ #include "cmsis_os.h"
16
+ }
17
+
18
+ /**
19
+ * Shared-bus mutex registry, generic over any HAL handle type
20
+ * (SPI_HandleTypeDef*, UART_HandleTypeDef*, I2C_HandleTypeDef*, ...).
21
+ *
22
+ * Keys by raw pointer identity: two drivers constructed against the SAME
23
+ * physical peripheral handle automatically converge on the same mutex,
24
+ * regardless of what driver class or handle type is asking. Drivers on
25
+ * different peripherals get independent mutexes.
26
+ *
27
+ * Thread-safety: safe to call from several tasks at once, after the
28
+ * scheduler started; the registry guard protects the table.
29
+ */
30
+ class BusMutexRegistry {
31
+ public:
32
+ /**
33
+ * Get-or-create the mutex associated with `handle`. Accepts any
34
+ * pointer type - callers pass e.g. this->handle() directly and it
35
+ * gets reinterpreted to void* for keying purposes only, never
36
+ * dereferenced.
37
+ */
38
+ template <typename HandleT>
39
+ static osMutexId_t acquireBusMutexFor(HandleT* handle) {
40
+ return acquireBusMutexForVoid(static_cast<const void*>(handle));
41
+ }
42
+ template <typename HandleT, typename OwnerT>
43
+ static void setActiveOwner(HandleT* handle, OwnerT* owner) {
44
+ setActiveOwnerVoid(static_cast<const void*>(handle),
45
+ static_cast<void*>(owner));
46
+ }
47
+ template <typename HandleT, typename OwnerT>
48
+ static OwnerT* activeOwner(HandleT* handle) {
49
+ return static_cast<OwnerT*>(activeOwnerVoid(static_cast<const void*>(handle)));
50
+ }
51
+ template <typename HandleT>
52
+ static void clearActiveOwner(HandleT* handle) {
53
+ clearActiveOwnerVoid(static_cast<const void*>(handle));
54
+ }
55
+
56
+ private:
57
+ static constexpr size_t MAX_BUSES = 4; // total across SPI+UART+I2C+... raise if needed
58
+ static inline const void* ownerKeys[MAX_BUSES] = {};
59
+ static inline void* ownerValues[MAX_BUSES] = {};
60
+ static inline size_t ownerCount = 0;
61
+ /**
62
+ * Created on first use, race-free: the firmware builds with
63
+ * -fno-threadsafe-statics, so a plain static initializer could run in
64
+ * two tasks at once. The loser deletes its mutex and uses the winner's.
65
+ */
66
+ static osMutexId_t getRegistryGuard() {
67
+ static std::atomic<osMutexId_t> guard{NULL}; // constant-initialized, no init race
68
+ osMutexId_t current = guard.load(std::memory_order_acquire);
69
+ if (current != NULL) return current;
70
+ osMutexId_t fresh = osMutexNew(NULL);
71
+ if (fresh == NULL) return NULL;
72
+ osMutexId_t expected = NULL;
73
+ if (guard.compare_exchange_strong(expected, fresh, std::memory_order_acq_rel)) return fresh;
74
+ osMutexDelete(fresh);
75
+ return expected;
76
+ }
77
+ static osMutexId_t acquireBusMutexForVoid(const void* key) {
78
+ osMutexId_t registryGuard = getRegistryGuard();
79
+ configASSERT(registryGuard != NULL);
80
+
81
+ osMutexAcquire(registryGuard, osWaitForever);
82
+
83
+ static const void* keys[MAX_BUSES] = {};
84
+ static osMutexId_t values[MAX_BUSES] = {};
85
+ static size_t count = 0;
86
+
87
+ osMutexId_t result = nullptr;
88
+ for (size_t i = 0; i < count; ++i) {
89
+ if (keys[i] == key) { result = values[i]; break; }
90
+ }
91
+ if (result == nullptr) {
92
+ configASSERT(count < MAX_BUSES); // raise MAX_BUSES if this trips
93
+ result = osMutexNew(NULL);
94
+ configASSERT(result != NULL);
95
+ keys[count] = key;
96
+ values[count] = result;
97
+ count++;
98
+ }
99
+
100
+ osMutexRelease(registryGuard);
101
+ return result;
102
+ }
103
+ static void clearActiveOwnerVoid(const void* key) {
104
+ taskENTER_CRITICAL();
105
+ for (size_t i = 0; i < ownerCount; ++i) {
106
+ if (ownerKeys[i] == key) {
107
+ ownerValues[i] = nullptr; // or compact the table if you want
108
+ break;
109
+ }
110
+ }
111
+ taskEXIT_CRITICAL();
112
+ }
113
+ static void setActiveOwnerVoid(const void* key, void* owner) {
114
+ taskENTER_CRITICAL();
115
+ size_t slot = MAX_BUSES;
116
+ for (size_t i = 0; i < ownerCount; ++i) {
117
+ if (ownerKeys[i] == key) { slot = i; break; }
118
+ }
119
+ if (slot == MAX_BUSES) {
120
+ configASSERT(ownerCount < MAX_BUSES); // raise MAX_BUSES if n
121
+ slot = ownerCount++;
122
+ ownerKeys[slot] = key;
123
+ }
124
+ ownerValues[slot] = owner;
125
+ taskEXIT_CRITICAL();
126
+ }
127
+
128
+ static void* activeOwnerVoid(const void* key) {
129
+ void* result = nullptr;
130
+ UBaseType_t saved = taskENTER_CRITICAL_FROM_ISR();
131
+ for (size_t i = 0; i < ownerCount; ++i) {
132
+ if (ownerKeys[i] == key) { result = ownerValues[i]; break; }
133
+ }
134
+ taskEXIT_CRITICAL_FROM_ISR(saved);
135
+ return result;
136
+ }
137
+ };
138
+ #endif
@@ -0,0 +1,212 @@
1
+ #pragma once
2
+
3
+ extern "C" {
4
+ #include "cmsis_os.h"
5
+ }
6
+ #include <atomic>
7
+ #include "FreeRTOS.h"
8
+ #include "semphr.h"
9
+ #include "task.h"
10
+
11
+
12
+ /**
13
+ * Combines two FreeRTOS primitives that serve different roles:
14
+ *
15
+ * - Mutex: mutual exclusion for driver-internal state accessed only
16
+ * from task context. Has priority inheritance. Must be
17
+ * taken/given from a task — NEVER from an ISR.
18
+ *
19
+ * - Binary semaphore: signals "bus/transfer is in use." Can be
20
+ * released from an ISR (e.g. a DMA completion callback), which a
21
+ * mutex cannot. No priority inheritance.
22
+ *
23
+ * Use mutex_lock()/mutex_unlock() to protect short critical sections of
24
+ * your own data structures. Use semaphore_acquire()/semaphore_release()/
25
+ * semaphore_release_from_isr() to track "is a DMA transfer in flight,"
26
+ * released either by the initiating task (on failure to start) or by
27
+ * the completion/error ISR (on finish). Use wait_for_release() to
28
+ * block until the bus is next idle, without touching the semaphore.
29
+ *
30
+ * Each primitive is created on first use, race-free: if two tasks create
31
+ * one at the same time, one handle wins and the other is deleted.
32
+ */
33
+ class Util_MutexManager {
34
+ public:
35
+ Util_MutexManager() {
36
+ this->_owns_mutex = false;
37
+ }
38
+ ~Util_MutexManager() {
39
+ SemaphoreHandle_t mutex = this->_mutex.load(std::memory_order_acquire);
40
+ if (mutex != NULL && this->_owns_mutex) {
41
+ vSemaphoreDelete(mutex);
42
+ }
43
+ SemaphoreHandle_t binSem = this->_binSem.exchange(NULL, std::memory_order_acq_rel);
44
+ if (binSem != NULL) {
45
+ vSemaphoreDelete(binSem);
46
+ }
47
+ }
48
+ /* Copies would share the handles and delete them twice. */
49
+ Util_MutexManager(const Util_MutexManager&) = delete;
50
+ Util_MutexManager& operator=(const Util_MutexManager&) = delete;
51
+
52
+ /**
53
+ * True once the scheduler started. Before that, every call below does
54
+ * nothing: creating or taking a primitive there leaves interrupts masked
55
+ * until the scheduler starts (the HAL tick stops, so HAL_Delay() hangs),
56
+ * and only one context runs anyway, so there is nothing to lock against.
57
+ */
58
+ static bool get_scheduler_is_running() {
59
+ return xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED;
60
+ }
61
+
62
+ /**
63
+ * Create all primitives. Safe to call more than once;
64
+ * each part only gets created if not already present.
65
+ * @param mutex_id adopt this mutex instead of creating one; it is not deleted on destruction.
66
+ * @retval false before the scheduler starts (nothing is created then).
67
+ */
68
+ bool mutex_init(osMutexId_t mutex_id=NULL) {
69
+ if (!get_scheduler_is_running()) return false;
70
+ bool ok = true;
71
+ if(mutex_id != NULL) {
72
+ this->_owns_mutex = false; // adopted - do not delete on destruction
73
+ this->_mutex.store(reinterpret_cast<SemaphoreHandle_t>(mutex_id), std::memory_order_release);
74
+ }else {
75
+ ok = ok && (this->ensure_mutex() != NULL);
76
+ }
77
+ ok = ok && (this->ensure_bin_sem() != NULL);
78
+ this->_mutex_adopted = (mutex_id != NULL) && ok;
79
+ return ok;
80
+ }
81
+
82
+
83
+ bool mutex_lock(TickType_t ticksToWait = portMAX_DELAY) {
84
+ if (!get_scheduler_is_running()) return true;
85
+ SemaphoreHandle_t mutex = this->ensure_mutex();
86
+ if (mutex == NULL) return false;
87
+ return xSemaphoreTake(mutex, ticksToWait) == pdTRUE;
88
+ }
89
+
90
+ bool mutex_unlock() {
91
+ if (!get_scheduler_is_running()) return true;
92
+ SemaphoreHandle_t mutex = this->_mutex.load(std::memory_order_acquire);
93
+ if (mutex == NULL) return false;
94
+ return xSemaphoreGive(mutex) == pdTRUE;
95
+ }
96
+
97
+ /**
98
+ * Who currently holds the mutex (NULL if unheld/uncreated).
99
+ * Task context only — do not call from an ISR.
100
+ */
101
+ TaskHandle_t mutex_holder() {
102
+ SemaphoreHandle_t mutex = this->_mutex.load(std::memory_order_acquire);
103
+ if (mutex == NULL) return NULL;
104
+ return xSemaphoreGetMutexHolder(mutex);
105
+ }
106
+
107
+ /* -------------------------------------------------------------------------- */
108
+ /* Semaphore */
109
+ /* -------------------------------------------------------------------------- */
110
+ bool semaphore_acquire(TickType_t ticksToWait = portMAX_DELAY) {
111
+ if (!get_scheduler_is_running()) return true;
112
+ SemaphoreHandle_t binSem = this->ensure_bin_sem();
113
+ if (binSem == NULL) return false;
114
+ return xSemaphoreTake(binSem, ticksToWait) == pdTRUE;
115
+ }
116
+
117
+ /**
118
+ * Release from task context — e.g. the transfer failed to
119
+ * start, so no completion ISR will ever fire for it.
120
+ */
121
+ bool semaphore_release() {
122
+ if (!get_scheduler_is_running()) return true;
123
+ SemaphoreHandle_t binSem = this->_binSem.load(std::memory_order_acquire);
124
+ if (binSem == NULL) return false;
125
+ return xSemaphoreGive(binSem) == pdTRUE;
126
+ }
127
+
128
+ /**
129
+ * Release from ISR context — e.g. HAL_UART_TxCpltCallback /
130
+ * HAL_UART_ErrorCallback. Yields immediately if a higher
131
+ * priority task was unblocked by the release.
132
+ */
133
+ BaseType_t semaphore_release_from_isr(bool yield=false) {
134
+ if (!get_scheduler_is_running()) return pdFALSE;
135
+ SemaphoreHandle_t binSem = this->_binSem.load(std::memory_order_acquire);
136
+ if (binSem == NULL) return pdFALSE;
137
+ BaseType_t xHigherPriorityTaskWoken = pdFALSE;
138
+ xSemaphoreGiveFromISR(binSem, &xHigherPriorityTaskWoken);
139
+ if(yield){
140
+ portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
141
+ }
142
+ return xHigherPriorityTaskWoken;
143
+ }
144
+
145
+ /**
146
+ * True while the bus is idle (the semaphore's token is available,
147
+ * or no transfer was ever started). Task context only.
148
+ */
149
+ bool get_is_released() {
150
+ SemaphoreHandle_t binSem = this->_binSem.load(std::memory_order_acquire);
151
+ return binSem == NULL || uxSemaphoreGetCount(binSem) == 1;
152
+ }
153
+
154
+ /**
155
+ * Block until the bus is idle, without taking the token, so it
156
+ * never steals it from whoever acquires it next (e.g. write_DMA()).
157
+ * Any number of tasks can wait at once. Polls once per tick, so it
158
+ * returns up to one tick after the release.
159
+ *
160
+ * Reports "idle", not "a transfer finished since I last checked":
161
+ * if nothing acquires the semaphore, it returns true immediately.
162
+ */
163
+ bool wait_for_release(TickType_t ticksToWait = portMAX_DELAY) {
164
+ if (!get_scheduler_is_running()) return true;
165
+ TickType_t start = xTaskGetTickCount();
166
+ while (!this->get_is_released()) {
167
+ if (ticksToWait != portMAX_DELAY && (xTaskGetTickCount() - start) >= ticksToWait) return false;
168
+ vTaskDelay(1);
169
+ }
170
+ return true;
171
+ }
172
+
173
+ protected:
174
+ /**
175
+ * True once mutex_init() adopted an external mutex and created every
176
+ * other primitive. A derived class resets it when that mutex may no
177
+ * longer apply (e.g. a driver rebound to another bus).
178
+ */
179
+ bool _mutex_adopted = false;
180
+
181
+ private:
182
+ std::atomic<SemaphoreHandle_t> _mutex{NULL};
183
+ std::atomic<SemaphoreHandle_t> _binSem{NULL};
184
+ bool _owns_mutex;
185
+
186
+ /** Publish a new handle unless another task got there first; the loser's handle is deleted. */
187
+ static SemaphoreHandle_t publish_once(std::atomic<SemaphoreHandle_t>& slot, SemaphoreHandle_t fresh) {
188
+ SemaphoreHandle_t expected = NULL;
189
+ if (slot.compare_exchange_strong(expected, fresh, std::memory_order_acq_rel)) return fresh;
190
+ vSemaphoreDelete(fresh);
191
+ return expected;
192
+ }
193
+
194
+ SemaphoreHandle_t ensure_mutex() {
195
+ SemaphoreHandle_t mutex = this->_mutex.load(std::memory_order_acquire);
196
+ if (mutex != NULL) return mutex;
197
+ SemaphoreHandle_t fresh = xSemaphoreCreateMutex();
198
+ if (fresh == NULL) return NULL;
199
+ mutex = publish_once(this->_mutex, fresh);
200
+ if (mutex == fresh) this->_owns_mutex = true;
201
+ return mutex;
202
+ }
203
+
204
+ SemaphoreHandle_t ensure_bin_sem() {
205
+ SemaphoreHandle_t binSem = this->_binSem.load(std::memory_order_acquire);
206
+ if (binSem != NULL) return binSem;
207
+ SemaphoreHandle_t fresh = xSemaphoreCreateBinary();
208
+ if (fresh == NULL) return NULL;
209
+ xSemaphoreGive(fresh); // binary semaphores start empty; the bus starts out "free"
210
+ return publish_once(this->_binSem, fresh);
211
+ }
212
+ };