dsh-embedded-workbench 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/lib/index.js +197 -197
- package/lib/types/index.d.ts +43 -43
- package/package.json +5 -3
- package/skills/c-cpp-dev/SKILL.md +121 -121
- package/skills/debug-methodology/SKILL.md +83 -83
- package/skills/debug-methodology/references/iterative-debug-case-study.md +103 -103
- package/skills/embedded-firmware-dev/SKILL.md +133 -133
- package/skills/embedded-firmware-dev/references/architecture-principles.md +204 -204
- package/skills/embedded-firmware-dev/references/embedded-patterns.md +95 -95
- package/skills/embedded-firmware-dev/references/lvgl-pitfalls.md +68 -68
- package/skills/embedded-workbench/SKILL.md +242 -242
- package/skills/embedded-workbench/references/final-qc.md +40 -40
- package/skills/embedded-workbench/references/platform-tool-mapping.md +88 -88
- package/skills/fact-check/SKILL.md +57 -57
- package/skills/hardfault-triage/SKILL.md +237 -237
- package/skills/keil-mdk-build/SKILL.md +237 -237
- package/skills/state-machine-design/SKILL.md +190 -190
- package/src/index.ts +209 -209
|
@@ -1,204 +1,204 @@
|
|
|
1
|
-
# Embedded Architecture Principles
|
|
2
|
-
|
|
3
|
-
Design principles extracted from real embedded firmware architecture. Framework-agnostic, applicable across projects.
|
|
4
|
-
|
|
5
|
-
## 1. Three-Layer Ownership
|
|
6
|
-
|
|
7
|
-
```text
|
|
8
|
-
BSP (drivers) → Components (business logic) → GUI (presentation)
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
Dependencies flow downward. Lower layers never call upward.
|
|
12
|
-
|
|
13
|
-
| Layer | Owns | Never Owns |
|
|
14
|
-
| ------- | ------ | ------------ |
|
|
15
|
-
| BSP | Hardware registers, timing, raw sensor data | Business decisions, display logic |
|
|
16
|
-
| Components | State machines, policy decisions, data transformation | Pixel rendering, layout |
|
|
17
|
-
| GUI | Widget lifecycle, screen layout, user interaction | Hardware control, policy logic |
|
|
18
|
-
|
|
19
|
-
**Violation symptoms**: A GUI page directly setting PWM duty. A sensor driver computing display-ready values. A backlight module checking DND state.
|
|
20
|
-
|
|
21
|
-
**Fix**: Move the decision to the layer that owns the truth. Pass decisions downward as commands, upward as events.
|
|
22
|
-
|
|
23
|
-
## 2. Single Source of Truth
|
|
24
|
-
|
|
25
|
-
Every piece of runtime state has **exactly one** owning module.
|
|
26
|
-
|
|
27
|
-
```text
|
|
28
|
-
Source of Truth → Derived State → Cached State
|
|
29
|
-
(primary, canonical) (computed from truth) (snapshot for performance)
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
- **Source of truth**: The module that produces or receives the value first. Only this module writes it.
|
|
33
|
-
- **Derived state**: Computed from source of truth. Recalculated when source changes, not cached indefinitely.
|
|
34
|
-
- **Cached state**: Snapshot of derived state for performance. Must be invalidated when source changes.
|
|
35
|
-
|
|
36
|
-
**Rule**: If two modules both "own" a value, the architecture is wrong. Pick one owner. Other modules read or subscribe.
|
|
37
|
-
|
|
38
|
-
## 3. Pull Over Push
|
|
39
|
-
|
|
40
|
-
Prefer **pull mode** (sync on read) over **push mode** (periodic background write).
|
|
41
|
-
|
|
42
|
-
```text
|
|
43
|
-
Push (fragile): Background task → write cache → consumer reads cache
|
|
44
|
-
Pull (robust): Consumer reads → check source freshness → sync if stale → return
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
**Why**: In embedded systems, "sensor has data" and "cache is refreshed" are concurrent events. A push-based cache updater may not fire before the first consumer reads, producing stale or zero values.
|
|
48
|
-
|
|
49
|
-
**When push is OK**: High-frequency data where read-time sync is too expensive. But always pair with a freshness timestamp and stale-data fallback.
|
|
50
|
-
|
|
51
|
-
## 4. Atomic Event Consumption
|
|
52
|
-
|
|
53
|
-
For transient hardware events that multiple consumers need, use **check-and-clear**:
|
|
54
|
-
|
|
55
|
-
```c
|
|
56
|
-
bool consume_event() {
|
|
57
|
-
bool occurred = event_latch;
|
|
58
|
-
event_latch = false; // Atomic clear
|
|
59
|
-
return occurred;
|
|
60
|
-
}
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
Multiple consumers each call `consume_event()`. Each event is delivered to every interested consumer exactly once per occurrence.
|
|
64
|
-
|
|
65
|
-
**Anti-pattern**: A shared `bool event_happened` flag that Consumer A clears before Consumer B reads it. Or Consumer B reads a flag already set again by the next cycle.
|
|
66
|
-
|
|
67
|
-
## 5. Bidirectional State Transitions
|
|
68
|
-
|
|
69
|
-
Every state that has a forward path **must** have a reverse guard:
|
|
70
|
-
|
|
71
|
-
```text
|
|
72
|
-
Forward: Idle → Active (when start condition met)
|
|
73
|
-
Reverse: Active → Idle (when start condition lost)
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
**Rule**: If a target state's preconditions can become false while already in that state, define a reverse transition. One-way latches will eventually leak incorrect state.
|
|
77
|
-
|
|
78
|
-
**Check**: For every state variable, ask: "What makes it go back?" If there's no answer, you have a latent bug.
|
|
79
|
-
|
|
80
|
-
## 6. Lifecycle Completeness
|
|
81
|
-
|
|
82
|
-
Every async flag (pending, in-progress, busy, data-ready) must be cleared in **every** lifecycle path:
|
|
83
|
-
|
|
84
|
-
```text
|
|
85
|
-
init() → stop() → reset() → recover() → power_off()
|
|
86
|
-
✓ ✓ ✓ ✓ ✓
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
Missing one path = stale flag = next operation silently blocked with no error.
|
|
90
|
-
|
|
91
|
-
**Rule**: Cleanup must happen **before** any new operation starts, not after. Otherwise a brief window exists where the old flag aborts the new attempt.
|
|
92
|
-
|
|
93
|
-
## 7. Grace Windows for Transients
|
|
94
|
-
|
|
95
|
-
Mode switches, direction reversals, and re-initialization produce transient sensor perturbations. These are **not** genuine errors.
|
|
96
|
-
|
|
97
|
-
**Pattern**: Allow a bounded tolerance window (1-2 samples) after any mode transition before applying strict error thresholds.
|
|
98
|
-
|
|
99
|
-
**Without grace window**: First post-switch sample exceeds threshold → false error accumulation → unnecessary fault escalation.
|
|
100
|
-
|
|
101
|
-
**With grace window**: First 1-2 samples after transition are compared with relaxed thresholds. Steady-state samples use normal thresholds.
|
|
102
|
-
|
|
103
|
-
## 8. Single Computation Point for Display Strategies
|
|
104
|
-
|
|
105
|
-
When multiple UI pages need to decide "show value vs. show loading vs. show error":
|
|
106
|
-
|
|
107
|
-
```text
|
|
108
|
-
Anti-pattern: Fixed:
|
|
109
|
-
Page A: if (x && !y) compute_strategy(state, fault) → strategy
|
|
110
|
-
Page B: if (!y && x) Page A: render(strategy)
|
|
111
|
-
Page C: if (x || z) Page B: render(strategy)
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
One function owns the decision. Pages only render the result. This prevents:
|
|
115
|
-
|
|
116
|
-
- Subtle inconsistencies between pages
|
|
117
|
-
- New conditions added to some pages but not others
|
|
118
|
-
- Impossible-to-test combinatorial behavior
|
|
119
|
-
|
|
120
|
-
## 9. Minimal Root-Cause Fix
|
|
121
|
-
|
|
122
|
-
When you find the root cause, the fix is usually **1-2 lines at the data source**.
|
|
123
|
-
|
|
124
|
-
**Self-check**: If you're changing 5+ call sites to handle a problem, the fix is in the wrong place. Ask: what single state change would make all those call sites correct without modification?
|
|
125
|
-
|
|
126
|
-
**Example**: A cached value goes stale. Fix: invalidate the cache at the source when the primary value changes (1 line). Anti-pattern: add freshness checks at every consumer (5+ sites).
|
|
127
|
-
|
|
128
|
-
## 10. Module Boundary Respect
|
|
129
|
-
|
|
130
|
-
When debugging — before touching any code, map the ownership:
|
|
131
|
-
|
|
132
|
-
1. Which module owns the truth?
|
|
133
|
-
2. Which module derives policy from it?
|
|
134
|
-
3. Which modules only consume?
|
|
135
|
-
|
|
136
|
-
**Rule**: Fix the module that owns the truth. Don't patch consumers.
|
|
137
|
-
|
|
138
|
-
**Example**: A display page showing stale sensor data. The sensor component owns the measurement truth. The display strategy computation owns the loading/error/ready decision. Fix: recompute display strategy when sensor state changes. Don't add per-page staleness checks.
|
|
139
|
-
|
|
140
|
-
## 11. Layout and Logic Separation
|
|
141
|
-
|
|
142
|
-
GUI pages must separate **what to show** from **how to show it**.
|
|
143
|
-
|
|
144
|
-
```c
|
|
145
|
-
// Anti-pattern (mixed):
|
|
146
|
-
page_poll() {
|
|
147
|
-
value = sensor_read();
|
|
148
|
-
if (value > threshold) {
|
|
149
|
-
lv_label_set_text(label, "High");
|
|
150
|
-
lv_obj_set_style_bg_color(screen, red, 0);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// Fixed (separated):
|
|
155
|
-
display_model_t model = compute_display_model(sensor_read());
|
|
156
|
-
page_render(model); // Only sets widgets, no logic
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
**Rules**:
|
|
160
|
-
|
|
161
|
-
- Widget creation and styling (`Setup()`) lives in one function. Business logic lives in another.
|
|
162
|
-
- State polling and decision-making return a **display model** struct. The render function consumes it mechanically.
|
|
163
|
-
- No `if (business_condition)` inside a `lv_obj_set_*()` call. Conditions are resolved before rendering.
|
|
164
|
-
- A render function should be callable with any valid display model and produce correct output without knowing how the model was computed.
|
|
165
|
-
|
|
166
|
-
**Why**: Mixed layout and logic means changing a widget position risks breaking business rules, and changing a threshold risks breaking layout. Separation makes each side testable independently.
|
|
167
|
-
|
|
168
|
-
## 12. UI Decoupling from Lower Layers
|
|
169
|
-
|
|
170
|
-
GUI pages must not directly call component or BSP APIs. All data flows through a **presentation interface**.
|
|
171
|
-
|
|
172
|
-
```c
|
|
173
|
-
// Anti-pattern (coupled) — Page_Sensor.c:
|
|
174
|
-
raw = bsp_i2c_read(0x52, 0x00); // GUI calling BSP directly
|
|
175
|
-
co2 = raw * 0.01; // GUI doing data transformation
|
|
176
|
-
if (co2 > 2000) { ... } // GUI owning business thresholds
|
|
177
|
-
|
|
178
|
-
// Fixed (decoupled) — Page_Sensor.c:
|
|
179
|
-
data = env_monitor_get_display_data(SENSOR_CO2);
|
|
180
|
-
render_display_model(data);
|
|
181
|
-
```
|
|
182
|
-
|
|
183
|
-
**Presentation interface design**:
|
|
184
|
-
|
|
185
|
-
- Returns pre-processed, display-ready values (no raw ADC counts, no protocol-level flags)
|
|
186
|
-
- Hides whether the data source is local (I2C sensor) or remote (inter-processor protocol from another device)
|
|
187
|
-
- Provides a **display strategy** enum (Ready / Loading / Error / NotApplicable) — the page consumes the strategy, doesn't compute it
|
|
188
|
-
- Single entry point per data domain: `xxx_get_display_data()` rather than 5 different getters
|
|
189
|
-
|
|
190
|
-
**Benefits**:
|
|
191
|
-
|
|
192
|
-
- Sensor protocol changes don't touch GUI code
|
|
193
|
-
- Pages work identically whether data comes from local sensor or remote device
|
|
194
|
-
- Pages can be tested with mock display data without hardware
|
|
195
|
-
- New pages for the same data domain reuse the same presentation interface
|
|
196
|
-
|
|
197
|
-
**Migration path** (when inheriting a coupled codebase):
|
|
198
|
-
|
|
199
|
-
1. Identify all component/BSP calls in GUI files
|
|
200
|
-
2. Group them by data domain (sensor, motor, fault, etc.)
|
|
201
|
-
3. For each domain, create a thin `xxx_get_display_data()` wrapper
|
|
202
|
-
4. Move data transformation logic from GUI into the wrapper
|
|
203
|
-
5. Replace direct calls in pages with the wrapper
|
|
204
|
-
6. Once all pages use the wrapper, refactor the wrapper's internals freely
|
|
1
|
+
# Embedded Architecture Principles
|
|
2
|
+
|
|
3
|
+
Design principles extracted from real embedded firmware architecture. Framework-agnostic, applicable across projects.
|
|
4
|
+
|
|
5
|
+
## 1. Three-Layer Ownership
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
BSP (drivers) → Components (business logic) → GUI (presentation)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Dependencies flow downward. Lower layers never call upward.
|
|
12
|
+
|
|
13
|
+
| Layer | Owns | Never Owns |
|
|
14
|
+
| ------- | ------ | ------------ |
|
|
15
|
+
| BSP | Hardware registers, timing, raw sensor data | Business decisions, display logic |
|
|
16
|
+
| Components | State machines, policy decisions, data transformation | Pixel rendering, layout |
|
|
17
|
+
| GUI | Widget lifecycle, screen layout, user interaction | Hardware control, policy logic |
|
|
18
|
+
|
|
19
|
+
**Violation symptoms**: A GUI page directly setting PWM duty. A sensor driver computing display-ready values. A backlight module checking DND state.
|
|
20
|
+
|
|
21
|
+
**Fix**: Move the decision to the layer that owns the truth. Pass decisions downward as commands, upward as events.
|
|
22
|
+
|
|
23
|
+
## 2. Single Source of Truth
|
|
24
|
+
|
|
25
|
+
Every piece of runtime state has **exactly one** owning module.
|
|
26
|
+
|
|
27
|
+
```text
|
|
28
|
+
Source of Truth → Derived State → Cached State
|
|
29
|
+
(primary, canonical) (computed from truth) (snapshot for performance)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- **Source of truth**: The module that produces or receives the value first. Only this module writes it.
|
|
33
|
+
- **Derived state**: Computed from source of truth. Recalculated when source changes, not cached indefinitely.
|
|
34
|
+
- **Cached state**: Snapshot of derived state for performance. Must be invalidated when source changes.
|
|
35
|
+
|
|
36
|
+
**Rule**: If two modules both "own" a value, the architecture is wrong. Pick one owner. Other modules read or subscribe.
|
|
37
|
+
|
|
38
|
+
## 3. Pull Over Push
|
|
39
|
+
|
|
40
|
+
Prefer **pull mode** (sync on read) over **push mode** (periodic background write).
|
|
41
|
+
|
|
42
|
+
```text
|
|
43
|
+
Push (fragile): Background task → write cache → consumer reads cache
|
|
44
|
+
Pull (robust): Consumer reads → check source freshness → sync if stale → return
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Why**: In embedded systems, "sensor has data" and "cache is refreshed" are concurrent events. A push-based cache updater may not fire before the first consumer reads, producing stale or zero values.
|
|
48
|
+
|
|
49
|
+
**When push is OK**: High-frequency data where read-time sync is too expensive. But always pair with a freshness timestamp and stale-data fallback.
|
|
50
|
+
|
|
51
|
+
## 4. Atomic Event Consumption
|
|
52
|
+
|
|
53
|
+
For transient hardware events that multiple consumers need, use **check-and-clear**:
|
|
54
|
+
|
|
55
|
+
```c
|
|
56
|
+
bool consume_event() {
|
|
57
|
+
bool occurred = event_latch;
|
|
58
|
+
event_latch = false; // Atomic clear
|
|
59
|
+
return occurred;
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Multiple consumers each call `consume_event()`. Each event is delivered to every interested consumer exactly once per occurrence.
|
|
64
|
+
|
|
65
|
+
**Anti-pattern**: A shared `bool event_happened` flag that Consumer A clears before Consumer B reads it. Or Consumer B reads a flag already set again by the next cycle.
|
|
66
|
+
|
|
67
|
+
## 5. Bidirectional State Transitions
|
|
68
|
+
|
|
69
|
+
Every state that has a forward path **must** have a reverse guard:
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
Forward: Idle → Active (when start condition met)
|
|
73
|
+
Reverse: Active → Idle (when start condition lost)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
**Rule**: If a target state's preconditions can become false while already in that state, define a reverse transition. One-way latches will eventually leak incorrect state.
|
|
77
|
+
|
|
78
|
+
**Check**: For every state variable, ask: "What makes it go back?" If there's no answer, you have a latent bug.
|
|
79
|
+
|
|
80
|
+
## 6. Lifecycle Completeness
|
|
81
|
+
|
|
82
|
+
Every async flag (pending, in-progress, busy, data-ready) must be cleared in **every** lifecycle path:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
init() → stop() → reset() → recover() → power_off()
|
|
86
|
+
✓ ✓ ✓ ✓ ✓
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Missing one path = stale flag = next operation silently blocked with no error.
|
|
90
|
+
|
|
91
|
+
**Rule**: Cleanup must happen **before** any new operation starts, not after. Otherwise a brief window exists where the old flag aborts the new attempt.
|
|
92
|
+
|
|
93
|
+
## 7. Grace Windows for Transients
|
|
94
|
+
|
|
95
|
+
Mode switches, direction reversals, and re-initialization produce transient sensor perturbations. These are **not** genuine errors.
|
|
96
|
+
|
|
97
|
+
**Pattern**: Allow a bounded tolerance window (1-2 samples) after any mode transition before applying strict error thresholds.
|
|
98
|
+
|
|
99
|
+
**Without grace window**: First post-switch sample exceeds threshold → false error accumulation → unnecessary fault escalation.
|
|
100
|
+
|
|
101
|
+
**With grace window**: First 1-2 samples after transition are compared with relaxed thresholds. Steady-state samples use normal thresholds.
|
|
102
|
+
|
|
103
|
+
## 8. Single Computation Point for Display Strategies
|
|
104
|
+
|
|
105
|
+
When multiple UI pages need to decide "show value vs. show loading vs. show error":
|
|
106
|
+
|
|
107
|
+
```text
|
|
108
|
+
Anti-pattern: Fixed:
|
|
109
|
+
Page A: if (x && !y) compute_strategy(state, fault) → strategy
|
|
110
|
+
Page B: if (!y && x) Page A: render(strategy)
|
|
111
|
+
Page C: if (x || z) Page B: render(strategy)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
One function owns the decision. Pages only render the result. This prevents:
|
|
115
|
+
|
|
116
|
+
- Subtle inconsistencies between pages
|
|
117
|
+
- New conditions added to some pages but not others
|
|
118
|
+
- Impossible-to-test combinatorial behavior
|
|
119
|
+
|
|
120
|
+
## 9. Minimal Root-Cause Fix
|
|
121
|
+
|
|
122
|
+
When you find the root cause, the fix is usually **1-2 lines at the data source**.
|
|
123
|
+
|
|
124
|
+
**Self-check**: If you're changing 5+ call sites to handle a problem, the fix is in the wrong place. Ask: what single state change would make all those call sites correct without modification?
|
|
125
|
+
|
|
126
|
+
**Example**: A cached value goes stale. Fix: invalidate the cache at the source when the primary value changes (1 line). Anti-pattern: add freshness checks at every consumer (5+ sites).
|
|
127
|
+
|
|
128
|
+
## 10. Module Boundary Respect
|
|
129
|
+
|
|
130
|
+
When debugging — before touching any code, map the ownership:
|
|
131
|
+
|
|
132
|
+
1. Which module owns the truth?
|
|
133
|
+
2. Which module derives policy from it?
|
|
134
|
+
3. Which modules only consume?
|
|
135
|
+
|
|
136
|
+
**Rule**: Fix the module that owns the truth. Don't patch consumers.
|
|
137
|
+
|
|
138
|
+
**Example**: A display page showing stale sensor data. The sensor component owns the measurement truth. The display strategy computation owns the loading/error/ready decision. Fix: recompute display strategy when sensor state changes. Don't add per-page staleness checks.
|
|
139
|
+
|
|
140
|
+
## 11. Layout and Logic Separation
|
|
141
|
+
|
|
142
|
+
GUI pages must separate **what to show** from **how to show it**.
|
|
143
|
+
|
|
144
|
+
```c
|
|
145
|
+
// Anti-pattern (mixed):
|
|
146
|
+
page_poll() {
|
|
147
|
+
value = sensor_read();
|
|
148
|
+
if (value > threshold) {
|
|
149
|
+
lv_label_set_text(label, "High");
|
|
150
|
+
lv_obj_set_style_bg_color(screen, red, 0);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Fixed (separated):
|
|
155
|
+
display_model_t model = compute_display_model(sensor_read());
|
|
156
|
+
page_render(model); // Only sets widgets, no logic
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**Rules**:
|
|
160
|
+
|
|
161
|
+
- Widget creation and styling (`Setup()`) lives in one function. Business logic lives in another.
|
|
162
|
+
- State polling and decision-making return a **display model** struct. The render function consumes it mechanically.
|
|
163
|
+
- No `if (business_condition)` inside a `lv_obj_set_*()` call. Conditions are resolved before rendering.
|
|
164
|
+
- A render function should be callable with any valid display model and produce correct output without knowing how the model was computed.
|
|
165
|
+
|
|
166
|
+
**Why**: Mixed layout and logic means changing a widget position risks breaking business rules, and changing a threshold risks breaking layout. Separation makes each side testable independently.
|
|
167
|
+
|
|
168
|
+
## 12. UI Decoupling from Lower Layers
|
|
169
|
+
|
|
170
|
+
GUI pages must not directly call component or BSP APIs. All data flows through a **presentation interface**.
|
|
171
|
+
|
|
172
|
+
```c
|
|
173
|
+
// Anti-pattern (coupled) — Page_Sensor.c:
|
|
174
|
+
raw = bsp_i2c_read(0x52, 0x00); // GUI calling BSP directly
|
|
175
|
+
co2 = raw * 0.01; // GUI doing data transformation
|
|
176
|
+
if (co2 > 2000) { ... } // GUI owning business thresholds
|
|
177
|
+
|
|
178
|
+
// Fixed (decoupled) — Page_Sensor.c:
|
|
179
|
+
data = env_monitor_get_display_data(SENSOR_CO2);
|
|
180
|
+
render_display_model(data);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
**Presentation interface design**:
|
|
184
|
+
|
|
185
|
+
- Returns pre-processed, display-ready values (no raw ADC counts, no protocol-level flags)
|
|
186
|
+
- Hides whether the data source is local (I2C sensor) or remote (inter-processor protocol from another device)
|
|
187
|
+
- Provides a **display strategy** enum (Ready / Loading / Error / NotApplicable) — the page consumes the strategy, doesn't compute it
|
|
188
|
+
- Single entry point per data domain: `xxx_get_display_data()` rather than 5 different getters
|
|
189
|
+
|
|
190
|
+
**Benefits**:
|
|
191
|
+
|
|
192
|
+
- Sensor protocol changes don't touch GUI code
|
|
193
|
+
- Pages work identically whether data comes from local sensor or remote device
|
|
194
|
+
- Pages can be tested with mock display data without hardware
|
|
195
|
+
- New pages for the same data domain reuse the same presentation interface
|
|
196
|
+
|
|
197
|
+
**Migration path** (when inheriting a coupled codebase):
|
|
198
|
+
|
|
199
|
+
1. Identify all component/BSP calls in GUI files
|
|
200
|
+
2. Group them by data domain (sensor, motor, fault, etc.)
|
|
201
|
+
3. For each domain, create a thin `xxx_get_display_data()` wrapper
|
|
202
|
+
4. Move data transformation logic from GUI into the wrapper
|
|
203
|
+
5. Replace direct calls in pages with the wrapper
|
|
204
|
+
6. Once all pages use the wrapper, refactor the wrapper's internals freely
|
|
@@ -1,95 +1,95 @@
|
|
|
1
|
-
# Embedded Engineering Patterns
|
|
2
|
-
|
|
3
|
-
Recurring patterns from real firmware debugging sessions. Generic and reusable across projects.
|
|
4
|
-
|
|
5
|
-
## GIF / Animation Timer Lifecycle Safety
|
|
6
|
-
|
|
7
|
-
Animated UI elements (GIFs, sprite sheets, frame animations) use hardware timers with callbacks. Improper lifecycle management causes HardFault (INVSTATE, corrupted callback pointers).
|
|
8
|
-
|
|
9
|
-
### Pattern: Generation Counter Guard
|
|
10
|
-
|
|
11
|
-
**Problem**: A timer callback fires after the animated object has been deleted. The callback's user_data pointer references freed memory.
|
|
12
|
-
|
|
13
|
-
**Fix**: Maintain a module-level `generation` counter. Increment on each `Create`/`Delete` cycle. The timer callback captures the generation at creation time and compares it to the current value before accessing any object.
|
|
14
|
-
|
|
15
|
-
```c
|
|
16
|
-
timer_cb:
|
|
17
|
-
if (captured_generation != global_generation) {
|
|
18
|
-
// Object was deleted and recreated; safely delete this stale timer
|
|
19
|
-
lv_timer_del(timer);
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
// Safe to use objects
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
### Pattern: Cleanup Ordering
|
|
26
|
-
|
|
27
|
-
**Problem**: Calling `lv_obj_clean()` before deleting the animation timer allows the timer to fire on already-cleaned children.
|
|
28
|
-
|
|
29
|
-
**Fix**: Always delete the animation timer **first**, then clean the parent object. In page exit functions:
|
|
30
|
-
|
|
31
|
-
```c
|
|
32
|
-
void page_exit() {
|
|
33
|
-
anim_timer_del(); // 1. Kill the timer
|
|
34
|
-
lv_obj_clean(page); // 2. Then clean objects
|
|
35
|
-
}
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
### Pattern: Null-After-Free for Static Pointers
|
|
39
|
-
|
|
40
|
-
**Problem**: A static LVGL object pointer (e.g., `static lv_obj_t *icon`) retains its value after `lv_obj_clean()` frees the underlying object. On re-entry, `lv_img_set_src(icon, ...)` dereferences freed memory.
|
|
41
|
-
|
|
42
|
-
**Fix**: Set static LVGL pointers to NULL immediately after `lv_obj_clean()` or `lv_obj_del()`. In `Setup()`, guard against NULL before using any cached pointer.
|
|
43
|
-
|
|
44
|
-
## One-Directional State Latch Anti-Pattern
|
|
45
|
-
|
|
46
|
-
### Problem
|
|
47
|
-
|
|
48
|
-
A state variable transitions `A → B` when condition X becomes true, but never transitions back to `A` even when X becomes false again. The one-way latch silently leaks incorrect state to downstream consumers.
|
|
49
|
-
|
|
50
|
-
### Detection
|
|
51
|
-
|
|
52
|
-
- State is set in one code path but never reset in any other path
|
|
53
|
-
- The state transition lacks a reverse guard condition
|
|
54
|
-
- A `step()` or `update()` function advances state without checking whether preconditions still hold
|
|
55
|
-
|
|
56
|
-
### Fix: Bidirectional Guard
|
|
57
|
-
|
|
58
|
-
Add a reverse check at the top of the state update function, before the forward transition:
|
|
59
|
-
|
|
60
|
-
```c
|
|
61
|
-
void state_update() {
|
|
62
|
-
// Reverse guard: if preconditions are lost, go back
|
|
63
|
-
if (state == Ready && error_is_active()) {
|
|
64
|
-
state = Recovering;
|
|
65
|
-
}
|
|
66
|
-
// Forward transition
|
|
67
|
-
if (state == Recovering && init_complete()) {
|
|
68
|
-
state = Ready;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
Key principle: **If a target state's preconditions can become false while already in that state, define a reverse transition.**
|
|
74
|
-
|
|
75
|
-
## Async Flag Lifecycle Audit Checklist
|
|
76
|
-
|
|
77
|
-
When adding a new async operation (pending, in-progress, busy, data-ready flag):
|
|
78
|
-
|
|
79
|
-
- [ ] `init()` — Reset flag to known-safe
|
|
80
|
-
- [ ] `start()` — Set flag before triggering async work
|
|
81
|
-
- [ ] `stop()` — Reset flag
|
|
82
|
-
- [ ] `reset()` — Reset flag
|
|
83
|
-
- [ ] `recover()` — Reset flag
|
|
84
|
-
- [ ] `power_off()` — Reset flag
|
|
85
|
-
- [ ] Callback/timeout handler — Reset flag on completion
|
|
86
|
-
|
|
87
|
-
**Rule**: The cleanup must happen **before** any new operation is attempted, not after. Otherwise a stale flag can abort the new attempt in a brief race window.
|
|
88
|
-
|
|
89
|
-
## Derived State Invariant
|
|
90
|
-
|
|
91
|
-
**Pattern**: When resetting a primary state, also reset all derived/cached values that were computed from it. Otherwise cached values from the old state can satisfy preconditions for a transition that should be blocked.
|
|
92
|
-
|
|
93
|
-
**Example**: Resetting `display_state` to `WarmingUp` but leaving `cached_value = 42.0` (a valid measurement from the previous Ready state). A downstream check `if (cached_value > 0) → Ready` fires before the warmup timer starts, causing a one-frame Ready leak.
|
|
94
|
-
|
|
95
|
-
**Fix**: In every reset function, clear derived values alongside the primary state. Use a single reset entry point that handles both.
|
|
1
|
+
# Embedded Engineering Patterns
|
|
2
|
+
|
|
3
|
+
Recurring patterns from real firmware debugging sessions. Generic and reusable across projects.
|
|
4
|
+
|
|
5
|
+
## GIF / Animation Timer Lifecycle Safety
|
|
6
|
+
|
|
7
|
+
Animated UI elements (GIFs, sprite sheets, frame animations) use hardware timers with callbacks. Improper lifecycle management causes HardFault (INVSTATE, corrupted callback pointers).
|
|
8
|
+
|
|
9
|
+
### Pattern: Generation Counter Guard
|
|
10
|
+
|
|
11
|
+
**Problem**: A timer callback fires after the animated object has been deleted. The callback's user_data pointer references freed memory.
|
|
12
|
+
|
|
13
|
+
**Fix**: Maintain a module-level `generation` counter. Increment on each `Create`/`Delete` cycle. The timer callback captures the generation at creation time and compares it to the current value before accessing any object.
|
|
14
|
+
|
|
15
|
+
```c
|
|
16
|
+
timer_cb:
|
|
17
|
+
if (captured_generation != global_generation) {
|
|
18
|
+
// Object was deleted and recreated; safely delete this stale timer
|
|
19
|
+
lv_timer_del(timer);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
// Safe to use objects
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Pattern: Cleanup Ordering
|
|
26
|
+
|
|
27
|
+
**Problem**: Calling `lv_obj_clean()` before deleting the animation timer allows the timer to fire on already-cleaned children.
|
|
28
|
+
|
|
29
|
+
**Fix**: Always delete the animation timer **first**, then clean the parent object. In page exit functions:
|
|
30
|
+
|
|
31
|
+
```c
|
|
32
|
+
void page_exit() {
|
|
33
|
+
anim_timer_del(); // 1. Kill the timer
|
|
34
|
+
lv_obj_clean(page); // 2. Then clean objects
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Pattern: Null-After-Free for Static Pointers
|
|
39
|
+
|
|
40
|
+
**Problem**: A static LVGL object pointer (e.g., `static lv_obj_t *icon`) retains its value after `lv_obj_clean()` frees the underlying object. On re-entry, `lv_img_set_src(icon, ...)` dereferences freed memory.
|
|
41
|
+
|
|
42
|
+
**Fix**: Set static LVGL pointers to NULL immediately after `lv_obj_clean()` or `lv_obj_del()`. In `Setup()`, guard against NULL before using any cached pointer.
|
|
43
|
+
|
|
44
|
+
## One-Directional State Latch Anti-Pattern
|
|
45
|
+
|
|
46
|
+
### Problem
|
|
47
|
+
|
|
48
|
+
A state variable transitions `A → B` when condition X becomes true, but never transitions back to `A` even when X becomes false again. The one-way latch silently leaks incorrect state to downstream consumers.
|
|
49
|
+
|
|
50
|
+
### Detection
|
|
51
|
+
|
|
52
|
+
- State is set in one code path but never reset in any other path
|
|
53
|
+
- The state transition lacks a reverse guard condition
|
|
54
|
+
- A `step()` or `update()` function advances state without checking whether preconditions still hold
|
|
55
|
+
|
|
56
|
+
### Fix: Bidirectional Guard
|
|
57
|
+
|
|
58
|
+
Add a reverse check at the top of the state update function, before the forward transition:
|
|
59
|
+
|
|
60
|
+
```c
|
|
61
|
+
void state_update() {
|
|
62
|
+
// Reverse guard: if preconditions are lost, go back
|
|
63
|
+
if (state == Ready && error_is_active()) {
|
|
64
|
+
state = Recovering;
|
|
65
|
+
}
|
|
66
|
+
// Forward transition
|
|
67
|
+
if (state == Recovering && init_complete()) {
|
|
68
|
+
state = Ready;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Key principle: **If a target state's preconditions can become false while already in that state, define a reverse transition.**
|
|
74
|
+
|
|
75
|
+
## Async Flag Lifecycle Audit Checklist
|
|
76
|
+
|
|
77
|
+
When adding a new async operation (pending, in-progress, busy, data-ready flag):
|
|
78
|
+
|
|
79
|
+
- [ ] `init()` — Reset flag to known-safe
|
|
80
|
+
- [ ] `start()` — Set flag before triggering async work
|
|
81
|
+
- [ ] `stop()` — Reset flag
|
|
82
|
+
- [ ] `reset()` — Reset flag
|
|
83
|
+
- [ ] `recover()` — Reset flag
|
|
84
|
+
- [ ] `power_off()` — Reset flag
|
|
85
|
+
- [ ] Callback/timeout handler — Reset flag on completion
|
|
86
|
+
|
|
87
|
+
**Rule**: The cleanup must happen **before** any new operation is attempted, not after. Otherwise a stale flag can abort the new attempt in a brief race window.
|
|
88
|
+
|
|
89
|
+
## Derived State Invariant
|
|
90
|
+
|
|
91
|
+
**Pattern**: When resetting a primary state, also reset all derived/cached values that were computed from it. Otherwise cached values from the old state can satisfy preconditions for a transition that should be blocked.
|
|
92
|
+
|
|
93
|
+
**Example**: Resetting `display_state` to `WarmingUp` but leaving `cached_value = 42.0` (a valid measurement from the previous Ready state). A downstream check `if (cached_value > 0) → Ready` fires before the warmup timer starts, causing a one-frame Ready leak.
|
|
94
|
+
|
|
95
|
+
**Fix**: In every reset function, clear derived values alongside the primary state. Use a single reset entry point that handles both.
|