1. Today’s topic

We examine configuration storage:

text
NVS / key-value storage
Flash settings
factory defaults
versioned config schema
migration
CRC / validation
atomic commit
rollback settings
OTA compatibility
STM32 EEPROM emulation

The central idea: configuration is part of firmware. If Flash parameters are corrupt, outdated, or incompatible with a new firmware version, the device should load safe defaults and clearly explain the reason rather than hang.

2. Why this matters

Projects contain many parameters that cannot live only in #define:

text
EC25 / MQTT:
  APN, broker, port, client_id, TLS flags, reconnect policy
Traffic-light inputs:
  active level, filter window, debounce time, conflict policy
ADS1115 / GPIO-expander:
  I2C addresses, enabled devices, diagnostic thresholds
CAN / RS-485:
  bitrate, node_id, Modbus address, timeout
watchdog / health:
  warn/fault timeouts, degraded mode policy

Problems arise when new firmware expects a field missing from old configuration; a user saves an invalid broker; power is lost during a write; or the new version cannot read old settings after OTA.

3. Theory

Good configuration

Example logical header fields. Do not treat a raw C structure as a portable storage format: specify byte order, exact lengths, CRC coverage and serialization without uninitialized padding.

c
typedef struct {
    uint32_t magic;
    uint16_t version;
    uint16_t size;
    uint32_t crc32;
    uint32_t generation;
} cfg_header_t;

Meaning of the fields:

text
magic:
  expected format signature; not proof of authenticity
version:
  supported format version
size:
  expected length after bounds checks
crc32:
  accidental-corruption check; collisions remain possible
generation:
  ordering of valid A/B copies under an explicit wrap rule

Defaults are mandatory

c
static const app_config_t APP_CONFIG_DEFAULT = {
    .mqtt = {
        .enabled = false,
        .broker = "",
        .port = 1883,
        .keepalive_s = 60,
    },
    .input = {
        .poll_period_ms = 2,
        .ac_window_ms = 80,
        .debounce_ms = 30,
        .conflict_hold_ms = 100,
    },
};

Handle missing settings safely. MQTT defaults to disabled until broker, authentication and trusted certificates are configured. Not every setting has a universally safe default: critical configuration may require inhibiting the main function with an explicit fault rather than continuing.

Separate config, state, and counters

text
config:
  settings that change rarely and determine behavior
state:
  runtime state that may survive reboot
counters:
  diagnostic counters that may change frequently
calibration:
  factory/service coefficients
secrets:
  keys, certificates, passwords

Do not write frequent events to Flash: every phase_event, MQTT reconnect, ADC sample, or UART timeout. Keep frequent counters in RAM; save only important snapshots to Flash.

A/B config

Store two copies:

text
cfg_a
cfg_b

At startup:

text
1. read cfg_a;
2. check magic/version/size/crc;
3. read cfg_b;
4. check magic/version/size/crc;
5. choose the valid copy with the higher generation;
6. if both are invalid - defaults.

Write the new serialized configuration to the inactive copy, verify read-back and use the documented commit mechanism. Keep the old copy until the new one is confirmed. Define generation-wrap and equal-generation selection. NVS requires nvs_commit(), but lack of its successful return does not prove that no new data reached Flash. After a fault, accept only an intact validated old or new copy under the chosen format, never mixed fields.

Migration

Validate the old format length/header first, then decode it into a fully allocated, initialized current-version structure. The following function migrates that decoded model; it does not permit casting a short old Flash blob to app_config_t. Reject unknown future versions and retain the old copy for OTA rollback. Network-security changes require explicit configuration, not silently disabling TLS.

c
static bool config_migrate_to_current(app_config_t *cfg)
{
    if (cfg->version == 1) {
        cfg->mqtt.keepalive_s = 60;
        cfg->mqtt.enabled = false;
        cfg->mqtt.tls_enabled = true;
        cfg->version = 2;
    }
    if (cfg->version == 2) {
        cfg->transport.mode = TRANSPORT_MQTT;
        cfg->version = 3;
    }
    return cfg->version == APP_CONFIG_VERSION;
}

Validation

CRC detects many accidental corruptions, but collisions are possible. It does not authenticate data or establish sensible values. Check lengths, ranges and cross-field constraints separately, and use cryptographic authentication where required.

c
if (cfg->mqtt.port == 0 || cfg->mqtt.port > 65535) {
    r.ok = false;
}
if (cfg->input.poll_period_ms < 1 || cfg->input.poll_period_ms > 100) {
    r.ok = false;
}

If validation fails: do not apply the invalid configuration; load defaults or last known good; record a fault event; show config status.

4. Common mistakes

  • Storing settings without a version.
  • Trusting CRC without validation.
  • Writing counters frequently to NVS/Flash.
  • Not calling nvs_commit() after nvs_set_*().
  • Erasing all NVS on every error.
  • Writing STM32 Flash directly as if it were EEPROM.
  • Confirming OTA before checking and migrating configuration.

5. Practical assignment

Create CONFIG_STORAGE_POLICY.md.

markdown
# Config storage policy
## Main rule
Device must boot safely with missing, old, corrupted or invalid configuration.
## Rules
1. Every persistent config has magic, version, size and CRC.
2. Every config field has a default.
3. Config, state, counters, calibration and secrets are separate.
4. Fast path never writes Flash/NVS.
5. Config writes are handled by config_manager_task.
6. Saved config is validated before apply and after read-back.
7. OTA is confirmed only after config migration and critical self-test.
8. STM32 internal Flash is not treated as byte-addressable EEPROM.

Add CLI commands:

text
config show
config validate
config save
config defaults
config factory-reset
config status

6. What to try next

  • Implement config_manager_task.
  • Create an A/B blob with generation.
  • Add HIL tests: empty NVS, corrupted cfg_a, both copies corrupted, old version, invalid value, power loss during save, and factory reset.

Exercise

Power fails during an A/B save after writing the inactive copy but before the commit operation returns successfully. How should startup select settings and prove that only an intact valid version is accepted?

Self-check criteria: Distinguish writing from committing, allow either intact old or intact new data after an ambiguous failure, and verify the selected state after reboot.

Show the supplied answer

Validate both copies: length, format, CRC, semantic values and the completion marker if the format has one. Select a valid generation under the defined commit and wrap rules. An ambiguous failure may leave the old or the new intact version; never accept mixed fields. If neither is valid, apply the explicitly chosen safe policy. Inject the fault and verify the selected values and config status.

Exercise

A configuration has a correct CRC but an invalid broker or timing value. Explain why CRC alone is insufficient and define the fallback and diagnostic evidence.

Self-check criteria: Name a value-level validation rule, a safe fallback, and evidence that invalid settings were not applied.

Show the supplied answer

CRC detects byte corruption, not whether settings are usable. Reject values that fail semantic validation, load safe defaults or last known good, record the fault, and expose the reason through config status.