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 (/storageescrow,/sync/ MQTTtime-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) viaflash_safe_execute(), then reads back, decrypts, andmemcmp-verifies before flippingg_active_slot. Auto-migrates v2 (104 Bmeter struct) to v3 (136 Bmeter 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 fromTelemetryTask/cloud_client(SdWritertask, 32-item RAM queue), cloud ACK (fifo_buffer_ack_head()), or replay request. - Processing: SPI0 microSD runs at
400 kHzinit ->12 MHzruntime with hardware-verified SPI CRC-7/CRC-16 enabled (CMD59(1)). Active journal resides starting at sector589,824(after the 288 MiB legacy encrypted LittleFS area0..589,823): dual superblocks (589824..589825), portable config A/B copies (589826..589883), and 1024 B (2-sector) data slots from sector589,888to end of card. Each slot encrypts a 528 Bfifo_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 to3full write+sync+readback+memcmpattempts (storage_io_retry_execute()). Superblock checkpoints every32appends or32ACKs; bootrecover_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()advancesupload_head, seals authenticated quarantine metadata (ASQ1) in superblock, and schedulesSD_RECORD_QUARANTINED(2008). TransientSD_JOURNAL_READ_IO_ERRORis never skipped.
- Trigger: Boot init (
- Portable Card Registration & Hardware Swap Adoption (
src/storage/storage_transfer.c,portable_config.c):- Trigger: (a) New card provisioned (
!key_registered) -> every15 ssends{"operation":"register","card_id","claim_token","data_key"}to cloud; onregisteredreply setsJOURNAL_FLAG_KEY_REGISTERED. (b) Card physically moved to a different converter -> OTP KEK unwrap fails -> entersSD_JOURNAL_STATE_NEEDS_ADOPTION(non-destructive; telemetry paused, Wi-Fi/mTLS starts) -> every15 ssends{"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 startsTelemetryTask+SYSTEM_HEALTH_TELEMETRY.
- Trigger: (a) New card provisioned (
- 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 (MQTTcommands/time-syncevery 6 h, or HTTPS/syncserver_time_utc), or localPOST /api/system/time. - Processing: PCF8523 (
I2C0 0x68,100 kHz) setsCONTROL3.PM = 000(enables CR1220 battery switchover & low-battery flagBLF) and double-reads seconds to prevent BCD rollover tearing. IfOSflag is set (dead battery),time_sync_init()bootstraps RTC from NVStrusted_time_timestamp + uptime_sec(TIME_SYNC_SOURCE_TRUSTED_FLOOR), setsbootstrap_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 RAMmeasurement_hold_until = previous + 1to guarantee strictly monotonic timestamps.
- Trigger: Boot (
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-STOR-01(Zero Eviction of Unsent Records):sd_journal.cmaintains three 64-bit cursorsretention_head <= upload_head <= tail. Whentail - retention_head >= slot_capacity, the journal advances and commitsretention_headonly ifretention_head < upload_head(oldest record already cloud-ACKed). Ifretention_head >= upload_head(all slots hold un-ACKed data), append returnsfalse— unsent telemetry is never overwritten.BR-STOR-02(No Silent Auto-Formatting of MicroSD): Neithersd_littlefs.cnorsd_journal.cauto-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 explicitsd_journal_force_reprovision()via factory reset / remotereset_sdcommand.BR-STOR-03(Full-Media Dynamic Capacity & Legacy Migration): Journal capacity isslot_capacity = (physical_sector_count - 589888) / 2(1024 B/slot), dynamically using full 32 GB / 64 GB+ SD cards (no longer capped at legacy LittleFSMAX_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 setsJOURNAL_FLAG_LEGACY_MIGRATED.BR-STOR-04(Storage Write-Failure Flash Wear Protection):fifo_buffer_push()persistsSTORAGE_WRITE_FAILURE_ACTIVE_PENDINGto NVS once per failure incident (not on every retry), andfifo_buffer_push_storage_diagnostic()suppresses failure counter increments to prevent recursive alarm loops.BR-STOR-05(Portable Config Scope & Conflict Gate):portable_config.cbacks up onlymeters[50],meters_count,telemetry_interval_sec,telemetry_enabled,telemetry_source, andremote_config_version(encrypted under card DEK in A/B sectors589856/589870, retried every5 sby"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 withPORTABLE_CONFIG_RESTORE_CONFLICT.BR-STOR-06(Card Key Escrow & Wipe Discipline):sd_journal.cgenerates a random UUIDv4card_id(16 B), 32 Bclaim_token, and 32 B AES-256DEK, wrapping the DEK with the converter’s OTP AES key +owner_hash = SHA-256(serial)(canonicalizing superblockgeneration = 0in AAD so commits remain decryptable).storage_transfer.cwipes plaintext key/token buffers viasecure_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 MQTTtime-synccommands reject replayedcommand_version((int32_t)(v - stored) < 0) and reject backward jumps> 300 s(TRUSTED_TIME_MAX_BACKWARD_SEC, resultTIME_SYNC_RESULT_BACKWARD_JUMP). Local installertime_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) ofSECONDS(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, addr0x68), OTP AES-256 key & serial, TRNG (get_rand_32()), cloudstorage-key&time-synccommands. - 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..589823legacy LittleFS;589824..endjournal), cloudregister/adoptrequests andattributesstatus reports,SYSTEM_HEALTH_STORAGEpulses.
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) | JSONStorageRequestSchema/StorageCommandSchema.src/net/time_sync.c<->cloud/services/time_sync.py(MQTT) andcloud/api/telemetry_ingress.py:_process_sync_record(HTTPSserver_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 reusesg_portable_config_plainto 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 Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
sd_state: "needs_adoption", telemetry paused | SD 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/meters | Clear meters on spare converter (or factory reset) so portable config can restore cleanly |
SD_RECORD_QUARANTINED (2008) event raised | Head 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 paused | PCF8523 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) |