Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Converters (IoT & Cloud) v1.0 (frozen on 2026-11-23, commit 71e82be). Switch to Latest →

3. Encrypted NVS, MicroSD LittleFS & Portable Journal FIFO, Card Transfer & RTC/Time Sync

Repository: Converters (planovi-converter) • Rule Prefix: BR-STOR • Documented Rules: 8 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Provides power-loss-safe encrypted configuration persistence in RP2350 Flash, multi-week AES-256-GCM encrypted telemetry/event buffering on removable microSD cards (scaling across full 32–128 GB media with zero un-ACKed data loss), non-destructive hardware replacement via cloud-escrowed SD card adoption (moving a microSD card from a failed converter to a spare without losing queued telemetry or meter configuration), and tamper-/drift-resistant UTC timekeeping via PCF8523 RTC + cloud trusted time.

  • Actors: Firmware subsystems (config_store, fifo_buffer, sd_journal, portable_config, storage_transfer, time_sync), Field Technician (physical microSD swap, 20 s button format authorization, local time set), Cloud Backend (/storage escrow, /sync / MQTT time-sync).

2. All Features & End-to-End Flows

  • Encrypted A/B Flash Configuration (src/storage/config_store.c):
    • Trigger: Any settings mutation (Wi-Fi, cloud endpoint, meters, telemetry policy, admin credentials, trusted time, storage failure state) or boot initialization.
    • Processing: Encrypts system_config_t (7096 B, with IEEE CRC-32) via AES-256-GCM using OTP key + TRNG 12 B nonce + 12 B AAD ('A','S','L',2 || domain+slot || generation), erases and programs inactive 8 KiB Flash slot (0x3FC000/0x3FE000) via flash_safe_execute(), then reads back, decrypts, and memcmp-verifies before flipping g_active_slot. Auto-migrates v2 (104 B meter struct) to v3 (136 B meter struct) on boot.
  • Portable Encrypted MicroSD Journal & Async FIFO (src/storage/sd_journal.c, fifo_buffer.c, storage_io_retry.c, sd_card.c):
    • Trigger: Boot init (sd_journal_init() + fifo_buffer_init()), async push from TelemetryTask/cloud_client (SdWriter task, 32-item RAM queue), cloud ACK (fifo_buffer_ack_head()), or replay request.
    • Processing: SPI0 microSD runs at 400 kHz init -> 12 MHz runtime with hardware-verified SPI CRC-7/CRC-16 enabled (CMD59(1)). Active journal resides starting at sector 589,824 (after the 288 MiB legacy encrypted LittleFS area 0..589,823): dual superblocks (589824..589825), portable config A/B copies (589826..589883), and 1024 B (2-sector) data slots from sector 589,888 to end of card. Each slot encrypts a 528 B fifo_telemetry_item_t (64-bit seq, 32-bit ts, 16-bit len, 16-bit CRC-16, 512 B payload) under the card’s random 32 B DEK (AES-256-GCM) with trailing CRC-32. Every append runs up to 3 full write+sync+readback+memcmp attempts (storage_io_retry_execute()). Superblock checkpoints every 32 appends or 32 ACKs; boot recover_tail_locked() scans forward to recover uncheckpointed tail records.
    • Failure / Quarantine: If head slot fails twice consecutively with the exact same corruption class (ENVELOPE_ERROR, CRC_ERROR, AEAD_ERROR) and no prior quarantine report is pending, sd_journal_quarantine_corrupt_head() advances upload_head, seals authenticated quarantine metadata (ASQ1) in superblock, and schedules SD_RECORD_QUARANTINED (2008). Transient SD_JOURNAL_READ_IO_ERROR is never skipped.
  • Portable Card Registration & Hardware Swap Adoption (src/storage/storage_transfer.c, portable_config.c):
    • Trigger: (a) New card provisioned (!key_registered) -> every 15 s sends {"operation":"register","card_id","claim_token","data_key"} to cloud; on registered reply sets JOURNAL_FLAG_KEY_REGISTERED. (b) Card physically moved to a different converter -> OTP KEK unwrap fails -> enters SD_JOURNAL_STATE_NEEDS_ADOPTION (non-destructive; telemetry paused, Wi-Fi/mTLS starts) -> every 15 s sends {"operation":"adopt","card_id","claim_token"} -> cloud verifies same owner & claim token hash, reassigns meters, returns {"operation":"adopt-key","card_id","data_key"} -> sd_journal_adopt_key() authenticates superblock, re-wraps DEK under new converter’s OTP KEK, runs tail recovery, restores portable meter/telemetry config from card (aborting with "configuration_conflict" if spare converter already has a differing meter map), and starts TelemetryTask + SYSTEM_HEALTH_TELEMETRY.
  • PCF8523 RTC & Trusted Time Bootstrap / Monotonic Hold (src/rtc/rtc_pcf8523.c, rtc_calendar.c, src/net/time_sync.c):
    • Trigger: Boot (time_sync_init()), cloud time sync (MQTT commands/time-sync every 6 h, or HTTPS /sync server_time_utc), or local POST /api/system/time.
    • Processing: PCF8523 (I2C0 0x68, 100 kHz) sets CONTROL3.PM = 000 (enables CR1220 battery switchover & low-battery flag BLF) and double-reads seconds to prevent BCD rollover tearing. If OS flag is set (dead battery), time_sync_init() bootstraps RTC from NVS trusted_time_timestamp + uptime_sec (TIME_SYNC_SOURCE_TRUSTED_FLOOR), sets bootstrap_pending = true, pauses cloud delivery (cloud_client_set_delivery_paused(true)), and blocks measurements (time_sync_is_measurement_ready() == false) while keeping TLS cert date checks active so the unit can fetch fresh UTC. Any backward RTC step sets RAM measurement_hold_until = previous + 1 to guarantee strictly monotonic timestamps.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-STOR-01 (Zero Eviction of Unsent Records): sd_journal.c maintains three 64-bit cursors retention_head <= upload_head <= tail. When tail - retention_head >= slot_capacity, the journal advances and commits retention_head only if retention_head < upload_head (oldest record already cloud-ACKed). If retention_head >= upload_head (all slots hold un-ACKed data), append returns false — unsent telemetry is never overwritten.
  • BR-STOR-02 (No Silent Auto-Formatting of MicroSD): Neither sd_littlefs.c nor sd_journal.c auto-formats an unknown/FAT/corrupt card on boot. Formatting an unprovisioned card requires a continuous 20-second physical reset-button hold at boot (src/main.c:153-164) or explicit sd_journal_force_reprovision() via factory reset / remote reset_sd command.
  • BR-STOR-03 (Full-Media Dynamic Capacity & Legacy Migration): Journal capacity is slot_capacity = (physical_sector_count - 589888) / 2 (1024 B/slot), dynamically using full 32 GB / 64 GB+ SD cards (no longer capped at legacy LittleFS MAX_FIFO_RECORDS_LIMIT = 205,000). On first boot with a legacy encrypted LittleFS volume (288 MiB, 4096 B A/B blocks, 524 B records), fifo_buffer_init() automatically migrates all valid records to 528 B journal slots and sets JOURNAL_FLAG_LEGACY_MIGRATED.
  • BR-STOR-04 (Storage Write-Failure Flash Wear Protection): fifo_buffer_push() persists STORAGE_WRITE_FAILURE_ACTIVE_PENDING to NVS once per failure incident (not on every retry), and fifo_buffer_push_storage_diagnostic() suppresses failure counter increments to prevent recursive alarm loops.
  • BR-STOR-05 (Portable Config Scope & Conflict Gate): portable_config.c backs up only meters[50], meters_count, telemetry_interval_sec, telemetry_enabled, telemetry_source, and remote_config_version (encrypted under card DEK in A/B sectors 589856/589870, retried every 5 s by "SdConfig" task). Wi-Fi, cloud host/certs, and installer credentials are never written to the SD card. On adoption, if the target converter already holds a differing non-empty local meter map, restore aborts with PORTABLE_CONFIG_RESTORE_CONFLICT.
  • BR-STOR-06 (Card Key Escrow & Wipe Discipline): sd_journal.c generates a random UUIDv4 card_id (16 B), 32 B claim_token, and 32 B AES-256 DEK, wrapping the DEK with the converter’s OTP AES key + owner_hash = SHA-256(serial) (canonicalizing superblock generation = 0 in AAD so commits remain decryptable). storage_transfer.c wipes plaintext key/token buffers via secure_clear() immediately after serialization.
  • BR-STOR-07 (Trusted Time Bounds, Anti-Replay & Backward Jump Limits): Valid UTC range is [1577836800 (2020-01-01), 4102444800 (2100-01-01)). Cloud MQTT time-sync commands reject replayed command_version ((int32_t)(v - stored) < 0) and reject backward jumps > 300 s (TRUSTED_TIME_MAX_BACKWARD_SEC, result TIME_SYNC_RESULT_BACKWARD_JUMP). Local installer time_sync_set_utc() has no backward cap, relying on monotonic hold (measurement_hold_until = previous + 1).
  • BR-STOR-08 (RTC Hardware Oscillator-Stop Rejection): rtc_calendar_decode_pcf8523_registers() rejects any register read with bit 7 (OS) of SECONDS (0x03) set or invalid BCD nibbles > 9.

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> UNPROVISIONED: Blank/FAT SD or forced reprovision
    [*] --> READY: Valid superblock + OTP KEK unwrap OK
    [*] --> NEEDS_ADOPTION: Valid superblock + OTP owner_hash/KEK mismatch
    [*] --> ERROR: No SD / SPI CRC fault / corrupt both superblocks
    UNPROVISIONED --> READY: 20s boot button format + provision (or legacy LittleFS migration)
    NEEDS_ADOPTION --> READY: Cloud sends adopt-key -> DEK re-wrapped -> tail recovered -> portable config restored
    READY --> READY: Append / Checkpoint(32) / ACK / Quarantine(ASQ1) / Replay
  • Time Sync Sources (time_sync_source_t): NONE (0), RTC (1), INSTALLER (2), TRUSTED_SERVER (3), TRUSTED_FLOOR (4).

5. Technical Contract (Inputs -> Processing -> Side Effects)

  • Inputs: SPI0 microSD (GPIO 16-19), I2C0 PCF8523 (GPIO 4-5, addr 0x68), OTP AES-256 key & serial, TRNG (get_rand_32()), cloud storage-key & time-sync commands.
  • Processing: Software mbedTLS AES-256-GCM (not hardware AES), CRC-16/CRC-32, SPI CRC-16-CCITT (0x1021), binary search replay over [retention_head, upload_head).
  • Side Effects: Flash NVS writes (0x3FC000/0x3FE000), raw SD sector writes (0..589823 legacy LittleFS; 589824..end journal), cloud register/adopt requests and attributes status reports, SYSTEM_HEALTH_STORAGE pulses.

6. Cross-Repository Dependencies

  • src/storage/storage_transfer.c <-> cloud/services/storage_transfer.py | mTLS HTTPS (/functions/v1/ingest-telemetry, X-Planovi-Record-Type: storage) or MQTTS (v1/devices/{cn}/storage & commands/storage-key) | JSON StorageRequestSchema / StorageCommandSchema.
  • src/net/time_sync.c <-> cloud/services/time_sync.py (MQTT) and cloud/api/telemetry_ingress.py:_process_sync_record (HTTPS server_time_utc).

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • Raw Sector Ring Journal vs LittleFS: Replacing LittleFS FIFO with a fixed 1024 B sector ring (sd_journal.c) eliminates filesystem metadata overhead on 32–128 GB cards, enables O(log N) binary-search replay across retained history, and isolates single-slot corruption for quarantine without losing the whole volume.
  • Static Buffer Reuse (sd_journal.c:1207-1266): sd_journal_replay_from_sequence() intentionally reuses g_portable_config_plain to avoid stack/heap allocation.
  • Staging Lab Re-Registration Hook (storage_transfer.c:156-164): Under #ifdef PLANOVI_CLOUD_STAGING_LAB, forces card re-registration on every reconnect to handle disposable staging DB resets.
  • [TEAM_WHY_NEEDED: src/storage/crypto_aes.h claims "Hardware-Accelerated AES-256" while crypto_aes.c uses software mbedTLS GCM (RP2350 only has hardware SHA-256). Confirm documentation should reflect software mbedTLS AES-256-GCM.]
  • [TEAM_WHY_NEEDED: src/storage/config_store.c:937-950 factory reset writes defaults to the inactive Flash slot without erasing the prior slot (old encrypted Wi-Fi/config stays in Flash until the next save). Should factory reset erase both slots?]
  • [TEAM_WHY_NEEDED: src/net/time_sync.c:141-162 imposes no backward jump limit on local installer time_sync_set_utc(), so accidentally setting an old date puts measurement_hold_until = previous + 1 in RAM and halts telemetry until reboot or catch-up.]
  • [TEAM_WHY_NEEDED: src/storage/sd_journal.c:1292 caps skipped quarantined slots in sd_journal_read_recent() at 64. Why 64?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact CommandFix
sd_state: "needs_adoption", telemetry pausedSD card moved from another converter; OTP KEK unwrap failed (sd_journal.c)GET /api/data (storage_needs_adoption: true, storage_stream_id)Connect replacement converter to Wi-Fi/cloud under same company/facility with empty meter map; adoption runs automatically every 15 s
Adoption stalls with "configuration_conflict"Spare converter already has local meters differing from card’s portable config (portable_config.c)Check device_events / cloud logs or GET /api/metersClear meters on spare converter (or factory reset) so portable config can restore cleanly
SD_RECORD_QUARANTINED (2008) event raisedHead slot failed two consecutive reads with identical envelope_error/crc_error/aead_error (sd_journal.c:1085-1202)GET /api/status (storage_quarantined, storage_last_quarantine_*)Journal auto-advanced past damaged slot; inspect/replace aging microSD if count grows
time_bootstrap_pending: true, cloud delivery pausedPCF8523 OS flag set (CR1220 battery dead/removed) and RTC initialized from NVS floor (time_sync.c)GET /api/status (rtc_battery_low, time_bootstrap_pending, time_source: "trusted_floor")Replace CR1220 coin cell and allow cloud /sync or set UTC via POST /api/system/time (tools/set_device_utc.py)