dsh-embedded-workbench 0.7.1
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 -0
- package/README.en-US.md +262 -0
- package/README.md +260 -0
- package/cordis.patch.yml +11 -0
- package/lib/index.js +197 -0
- package/lib/types/index.d.ts +43 -0
- package/package.json +81 -0
- package/skills/c-cpp-dev/SKILL.md +121 -0
- package/skills/debug-methodology/SKILL.md +83 -0
- package/skills/debug-methodology/references/iterative-debug-case-study.md +103 -0
- package/skills/embedded-firmware-dev/SKILL.md +133 -0
- package/skills/embedded-firmware-dev/references/architecture-principles.md +204 -0
- package/skills/embedded-firmware-dev/references/embedded-patterns.md +95 -0
- package/skills/embedded-firmware-dev/references/lvgl-pitfalls.md +68 -0
- package/skills/embedded-workbench/SKILL.md +240 -0
- package/skills/embedded-workbench/references/INDEX.md +88 -0
- package/skills/embedded-workbench/references/audit-ledger.md +38 -0
- package/skills/embedded-workbench/references/contract-matrix.md +31 -0
- package/skills/embedded-workbench/references/decision-log.md +31 -0
- package/skills/embedded-workbench/references/detailed-change-plan.md +76 -0
- package/skills/embedded-workbench/references/durable-requirement-notes.md +27 -0
- package/skills/embedded-workbench/references/final-qc.md +40 -0
- package/skills/embedded-workbench/references/iteration-notes.md +53 -0
- package/skills/embedded-workbench/references/platform-tool-mapping.md +88 -0
- package/skills/embedded-workbench/references/result-note.md +54 -0
- package/skills/embedded-workbench/references/steward-memo.md +54 -0
- package/skills/embedded-workbench/references/task-charter.md +53 -0
- package/skills/hardfault-triage/SKILL.md +237 -0
- package/skills/keil-mdk-build/SKILL.md +237 -0
- package/skills/state-machine-design/SKILL.md +190 -0
- package/src/index.ts +209 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: embedded-firmware-dev
|
|
3
|
+
description: "Use when writing or reviewing embedded C firmware, FreeRTOS tasks, ISR handlers, NVM/flash storage, or sensor driver state machines. NOT for documentation-only RTOS references, conceptual RTOS discussions, or bare-metal projects without an RTOS or sensor subsystem."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
<HARD-GATE>
|
|
7
|
+
This is a domain implementation skill. If you are planning, designing, or entering plan mode — load `Skill("embedded-workbench")` first to activate the workflow gates (Plan Verification Gate, Approval Gate, Closure Gate). Domain skills carry implementation guidance, not workflow enforcement.
|
|
8
|
+
</HARD-GATE>
|
|
9
|
+
|
|
10
|
+
# Embedded Firmware Development
|
|
11
|
+
|
|
12
|
+
## FreeRTOS
|
|
13
|
+
|
|
14
|
+
- Give each task a clear ownership boundary. Shared resources need a deliberate synchronization strategy.
|
|
15
|
+
- Prefer task notifications for one-to-one wakeups, queues for data transfer, event groups for combined state, mutexes for mutual exclusion, semaphores for one-way signaling.
|
|
16
|
+
- Use a mutex (not binary semaphore) when mutual exclusion matters and priority inheritance is needed.
|
|
17
|
+
- Make every blocking wait explicit: use a timeout unless an infinite wait is deliberate.
|
|
18
|
+
- Keep timer callbacks short and non-blocking — use them to schedule work, not do it.
|
|
19
|
+
- Avoid holding locks across flash, storage, or long operations.
|
|
20
|
+
- Size task stacks from worst-case call chains. Recheck high-water marks after adding buffers or deeper call trees.
|
|
21
|
+
- Use ISR-safe APIs for interrupt-to-task handoff. Keep ISR state capture minimal.
|
|
22
|
+
- Avoid priority inversion: don't hold shared locks across blocking I/O or long processing.
|
|
23
|
+
- If a task can be paused/restarted/signaled from multiple places, define resume, timeout, and recovery paths explicitly.
|
|
24
|
+
- For cross-task pointer ownership: make lifetime and invalidation rules obvious.
|
|
25
|
+
- Prefer the smallest critical section that protects the state transition. Don't wrap whole operations in locks when narrower ordering suffices.
|
|
26
|
+
- For objects handed between threads: define whether the receiver owns, borrows, or copies before crossing the boundary.
|
|
27
|
+
|
|
28
|
+
## Interrupts / ISR
|
|
29
|
+
|
|
30
|
+
- Keep the interrupt path short, deterministic, and bounded. Capture minimum state, clear the source, defer expensive work.
|
|
31
|
+
- Do not block, sleep, allocate heap, or call non-ISR-safe APIs from an ISR.
|
|
32
|
+
- Prefer top-half/bottom-half split when the handler needs more than quick state capture and wakeup.
|
|
33
|
+
- Make shared-state ownership explicit. Use minimum synchronization for the data being shared.
|
|
34
|
+
- If an ISR wakes a task, use the ISR-safe RTOS primitive and preserve yield-from-ISR behavior.
|
|
35
|
+
- Define clear read/clear/re-enable ordering to avoid losing edges or creating re-trigger loops.
|
|
36
|
+
- Avoid logging and complex branching in the hot interrupt path.
|
|
37
|
+
- If code runs from both task and ISR context, separate wrappers so the ISR-safe path stays obvious.
|
|
38
|
+
|
|
39
|
+
## Async Lifecycle Cleanup
|
|
40
|
+
|
|
41
|
+
- Any async flag (pending, in-progress, busy, data-ready) that can be set during normal operation must be explicitly cleared in every stop, init, reset, power-off, and error-recovery path. A stale flag silently blocks the next operation.
|
|
42
|
+
- When adding a new async operation, audit all lifecycle entry points and ensure each path resets flags to known-safe.
|
|
43
|
+
- Cleanup must happen before any new operation is attempted, not after.
|
|
44
|
+
|
|
45
|
+
```c
|
|
46
|
+
// CORRECT: every async flag cleared in stop path. No stale state survives restart.
|
|
47
|
+
uint8_t comm_stop_sample(void) {
|
|
48
|
+
g_comm.data_ready = false;
|
|
49
|
+
g_comm.state = COMM_STATE_IDLE;
|
|
50
|
+
g_comm.activating = false;
|
|
51
|
+
g_comm.command_fail_count = 0;
|
|
52
|
+
g_comm.protocol_locked = false;
|
|
53
|
+
g_comm.communication_lost = false;
|
|
54
|
+
g_comm.warmup_start_time = 0;
|
|
55
|
+
comm_command_complete(); // Release any pending I/O
|
|
56
|
+
memset(&g_comm_data, 0, sizeof(g_comm_data));// Reset cached data
|
|
57
|
+
comm_process_faults(false); // Clear fault detection state
|
|
58
|
+
return COMM_OK;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// BAD: half the flags survive — next start inherits stale state
|
|
62
|
+
void comm_stop_bad(void) {
|
|
63
|
+
g_comm.state = COMM_STATE_IDLE; // Only state changed
|
|
64
|
+
// Missing: data_ready, protocol_locked, communication_lost, fail_count...
|
|
65
|
+
// Next start: data_ready==true blocks first sample; fail_count persists
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// CALLER GUARD: clear stale flags at power-off boundaries before re-init
|
|
69
|
+
void comm_handler(void) {
|
|
70
|
+
if (!power_get_status() && g_comm.command_pending) {
|
|
71
|
+
comm_command_complete(); // Clear before deinit
|
|
72
|
+
}
|
|
73
|
+
if (power_get_status()) {
|
|
74
|
+
comm_state_process();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## One-Shot Event Consumption
|
|
80
|
+
|
|
81
|
+
- When a low-level driver produces a transient event that multiple higher-level consumers need, use an atomic check-and-clear (consume) API rather than shared flags each consumer clears manually.
|
|
82
|
+
- Manual clearing by multiple consumers creates races: consumer A clears before B reads, or B reads a flag already set again by the next cycle.
|
|
83
|
+
- The consume primitive returns whether the event occurred and atomically clears the latch — every interested consumer observes the event exactly once per occurrence.
|
|
84
|
+
|
|
85
|
+
```c
|
|
86
|
+
// Atomic check-and-clear: every consumer sees the event exactly once
|
|
87
|
+
static volatile uint32_t event_latch;
|
|
88
|
+
|
|
89
|
+
uint32_t event_consume(uint32_t mask) {
|
|
90
|
+
uint32_t primask = __get_PRIMASK();
|
|
91
|
+
__disable_irq();
|
|
92
|
+
uint32_t pending = event_latch & mask;
|
|
93
|
+
event_latch &= ~mask; // Clear consumed bits atomically
|
|
94
|
+
if (!primask) __enable_irq();
|
|
95
|
+
return pending; // Non-zero = event occurred this cycle
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Each consumer independently observes — no races between consumers
|
|
99
|
+
void ui_consume(void) {
|
|
100
|
+
if (event_consume(EVT_SENSOR_READY)) update_display();
|
|
101
|
+
}
|
|
102
|
+
void log_consume(void) {
|
|
103
|
+
if (event_consume(EVT_SENSOR_READY)) write_log();
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Storage / Persistence
|
|
108
|
+
|
|
109
|
+
- Separate object corruption from schema change. Rebuild the whole store only when versioned layout rules require it.
|
|
110
|
+
- Prefer recoverable write paths: write primary → read back and verify → write backup → read back and verify.
|
|
111
|
+
- During delete, reset, or migration, preserve at least one valid recoverable copy.
|
|
112
|
+
- Prefer targeted repair and re-sync over destructive reinitialization.
|
|
113
|
+
- Treat startup repair, steady-state writes, emergency writes, and factory reset as separate paths with explicit guarantees.
|
|
114
|
+
|
|
115
|
+
## Boundary Analysis
|
|
116
|
+
|
|
117
|
+
- When thresholds trip at edges, inspect debounce latency, sample timing, and ring-vs-bounded assumptions before tuning constants.
|
|
118
|
+
- When behavior diverges by mode, compare all branches side by side instead of debugging only the failing branch.
|
|
119
|
+
- When a defect appears on only one trigger path, diff which state each caller resets, preserves, or derives.
|
|
120
|
+
- For transient inconsistencies, inspect raw state, derived state, and cached state separately — stale data in any layer masquerades as a timing problem.
|
|
121
|
+
- When a system undergoes mode switch, direction reversal, or re-initialization, allow a bounded tolerance window for the first post-transition deviation. Treating it with steady-state thresholds produces false error accumulation.
|
|
122
|
+
|
|
123
|
+
## Deep Reference
|
|
124
|
+
|
|
125
|
+
This skill's `references/` directory contains in-depth material. Load when you need more than the core rules:
|
|
126
|
+
|
|
127
|
+
| Reference | Topic | Load When |
|
|
128
|
+
|-----------|-------|-----------|
|
|
129
|
+
| `architecture-principles.md` | 12 architecture design principles | Designing module boundaries, state ownership, or GUI architecture |
|
|
130
|
+
| `embedded-patterns.md` | GIF timer safety, async lifecycle, state latches | Debugging timer crashes, stale flags, or state corruption |
|
|
131
|
+
| `lvgl-pitfalls.md` | LVGL layout, alignment, alpha, and mask traps | Debugging LVGL rendering artifacts or HardFault in draw paths |
|
|
132
|
+
|
|
133
|
+
See also: `Skill("state-machine-design")` for state transition rules, `Skill("debug-methodology")` for debugging process, `Skill("hardfault-triage")` for stack overflow and ISR crash triage.
|
|
@@ -0,0 +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
|
|
@@ -0,0 +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.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# LVGL Common Pitfalls
|
|
2
|
+
|
|
3
|
+
Non-obvious traps when working with LVGL on embedded targets.
|
|
4
|
+
|
|
5
|
+
## RGB565A8 Custom Decoder Layout
|
|
6
|
+
|
|
7
|
+
**Pitfall**: Assuming a custom PNG decoder outputs interleaved RGBA pixels.
|
|
8
|
+
|
|
9
|
+
**Reality**: On 16-bit color depth targets, the decoder separates color and alpha into distinct planes — RGB565 (2 bytes/pixel) for color and A8 (1 byte/pixel) for alpha. Reading as interleaved RGBA produces garbled output.
|
|
10
|
+
|
|
11
|
+
**Check**: Verify the decoder's output format matches what the draw pipeline expects before writing draw callbacks.
|
|
12
|
+
|
|
13
|
+
## Alignment Flag Mixing
|
|
14
|
+
|
|
15
|
+
**Pitfall**: Combining multiple LVGL alignment flags produces unexpected positioning.
|
|
16
|
+
|
|
17
|
+
**Reality**: LVGL alignment flags are not freely bitwise-combinable. ORing two horizontal flags or two vertical flags produces undefined behavior that depends on internal evaluation order.
|
|
18
|
+
|
|
19
|
+
**Fix**: Use exactly one horizontal flag ORed with exactly one vertical flag. For non-standard positioning, use `lv_obj_set_pos()` with explicit coordinates after layout.
|
|
20
|
+
|
|
21
|
+
## Object Cleanup Order and Stale Pointers
|
|
22
|
+
|
|
23
|
+
**Pitfall**: `lv_obj_clean(parent)` recursively frees children but does not NULL any static pointers that reference those children.
|
|
24
|
+
|
|
25
|
+
**Fix Pattern**:
|
|
26
|
+
|
|
27
|
+
```c
|
|
28
|
+
anim_timer_del(); // 1. Kill async operations
|
|
29
|
+
icon = NULL; // 2. NULL all static pointers
|
|
30
|
+
label = NULL;
|
|
31
|
+
lv_obj_clean(parent); // 3. Clean the parent last
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
On page re-entry, always guard with NULL checks before using any cached LVGL object pointer.
|
|
35
|
+
|
|
36
|
+
## Menu Scroll with Fixed Elements
|
|
37
|
+
|
|
38
|
+
**Pitfall**: A scrollable menu with header/footer inside the scroll container scrolls those elements along with the content.
|
|
39
|
+
|
|
40
|
+
**Fix**: Move fixed elements outside the scrollable container:
|
|
41
|
+
|
|
42
|
+
```text
|
|
43
|
+
Page (flex column)
|
|
44
|
+
├── Header (fixed, outside scroll)
|
|
45
|
+
├── Scroll container (flex grow)
|
|
46
|
+
│ └── Items (scrollable)
|
|
47
|
+
└── Footer (fixed, outside scroll)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Draw Mask Lifecycle
|
|
51
|
+
|
|
52
|
+
**Pitfall**: Creating an LVGL draw mask and not removing it before the next draw pass causes unrelated elements to be incorrectly masked.
|
|
53
|
+
|
|
54
|
+
**Fix**: Always pair mask creation with removal:
|
|
55
|
+
|
|
56
|
+
```c
|
|
57
|
+
int16_t mask_id = lv_draw_mask_angle_init(¶m);
|
|
58
|
+
// ... draw ...
|
|
59
|
+
lv_draw_mask_remove_id(mask_id);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
For masks in animation callbacks, store the mask_id and ensure cleanup in the animation's end handler or page exit.
|
|
63
|
+
|
|
64
|
+
## Alpha Cache Staleness on Overlay Removal
|
|
65
|
+
|
|
66
|
+
**Pitfall**: Removing a gap/clear overlay from a chart leaves ghost artifacts because the alpha blending cache retains intermediate values.
|
|
67
|
+
|
|
68
|
+
**Fix**: After removing an overlay, call `lv_obj_invalidate()` on the parent to force a full redraw. For chart widgets, invalidate the entire chart rather than individual series.
|