1. Today's topic
Design recovery under an explicit power-fail model: recover complete OLD or NEW state, not mixed fields. A/B on one chip does not cover every common-mode corruption, worn-out device or supply outside its specified limits. If both records are invalid, enter a defined safe recovery mode rather than inventing valid state.
2. Why this matters
Configuration is interconnected: ADC thresholds, debounce, APN, MQTT host and retry policy. If these are stored as separate keys, power loss can leave a mixture of generations.
3. Theory
A brownout detector is not a graceful shutdown
A brownout detector triggers when voltage has already become unsafe. It does not mean there is time left to calmly write NVS. Early warning
A separate POWER_FAIL_WARNING above the reset threshold is needed: PVD/comparator/ADC monitoring of the upstream supply.
Crash consistency
Storage contract:
after any power loss: OLD or NEW, never HALF-NEWNVS semantics
After nvs_set_*(), successful nvs_commit() is required by the API to ensure durability. An implementation may write earlier: this is neither a promise of RAM-only changes before commit nor an atomic transaction across keys. Check every return value and acknowledge only a coherent application record.
An application transaction on top of NVS
Store a complete logical record with explicit length and version. The structure below models fields; separately specify storage encoding and CRC coverage without accidental padding, uninitialized reserved bytes or ambiguous byte order:
typedef struct {
uint32_t magic;
uint16_t schema;
uint16_t reserved;
uint64_t generation;
config_payload_t payload;
uint32_t crc32;
} config_record_t;A/B records
At boot, read cfg_a and cfg_b and validate length, magic, schema, CRC and semantics. Select the newest eligible generation within the defined non-wrapping epoch. Equal generations with differing content are a conflict; no valid record requires safe recovery. A separate active_slot is unnecessary when this selection rule is complete.
Update transaction
ACTIVE generation 41
-> build generation 42
-> validate
-> write inactive slot
-> nvs_commit
-> read-back verify
-> publish runtime snapshot
-> ACK backendRaw Flash commit marker
For raw Flash, write the commit marker last while obeying program granularity, ECC and repeat-programming restrictions. Validate the marker together with the full-format CRC; interruption during marker programming must not certify corrupted content:
erase -> header -> payload -> CRC -> verify -> VALID marker LAST4. Common mistakes
- Treating brownout as a graceful interrupt.
- Starting a Flash write after a low-voltage warning.
- Storing related configuration as independent keys.
- Acknowledging the backend before nvs_commit().
- Treating nvs_set_*() as durable.
- Keeping only one copy of critical configuration.
- Using A/B without CRC.
- Using CRC without a generation.
- Writing the VALID marker before the payload.
- Immediately erasing the old generation.
- Not performing semantic validation after CRC.
- Calling nvs_commit() every second for counters.
- Not testing a power cut in the middle of a transaction.
5. Practical task
Implement A/B configuration on top of NVS:
cfg_a
cfg_bAt boot:
read A/B -> validate -> choose highest valid generation -> publish runtimeAdd fault points:
AFTER_SET
AFTER_COMMIT
AFTER_VERIFY
AFTER_RUNTIME_PUBLISHIn an isolated test build, call esp_restart() at each point. Expect a complete generation 41 or 42 afterward. This checks software recovery paths, not an electrical interruption. Illustrative CLI format:
config storage
slot A: valid=yes generation=41 crc=OK
slot B: valid=yes generation=42 crc=OK
active=B6. What to try next
- Perform a real HIL power cut with a Raspberry Pi and a USB/MOSFET power switch.
- For STM32, study PVD + EEPROM emulation.
- Separate factory read-only NVS from runtime writable NVS.
Exercise
Active A is generation 41. An update builds generation 42 in B, but power fails during the update. Describe the boot selection rule and the acceptable outcomes. Does a test-build esp_restart() alone prove electrical power-cut behaviour?
Self-check criteria: Require complete OLD or NEW, validate both copies and distinguish software restart from real power loss.
Show the supplied answer
At boot, read both slots and validate CRC plus semantics, then select the highest valid generation. The resulting configuration must be a complete generation 41 or 42, never mixed fields. A software restart tests reboot recovery paths but does not reproduce every electrical interruption; the lesson separately suggests actual HIL power cuts.