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 →

1. Firmware Bootloader, OTP Security, HAL, Fault/Health Supervision & Factory Toolchain

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

1. Business Purpose & Actors

Guarantees that every RP2350 Planovi Edge Converter boots only cryptographically signed Planovi firmware, binds each physical unit to an immutable hardware identity (serial number, AES-256 master key, ECDSA P-256 OTA public key, mTLS client certificate/key, and unique setup password stored in RP2350 OTP), automatically recovers from faulty firmware updates or stalled FreeRTOS tasks via one-shot A/B rollback and hardware watchdog supervision, and survives sudden AC power loss with Last-Gasp alerting.

  • Actors: Manufacturing/Factory Operator (tools/provision_device.py, tools/provision_otp.py, tools/make_factory_uf2.py), Field Service Technician (tools/service_update_usb.py, physical reset button on GPIO 22), RP2350 Bootloader & FreeRTOS Health Supervisor (autonomous), Build/Release Pipeline (build.sh, tools/build_firmware_docker.sh, tools/sign_firmware.py).

2. All Features & End-to-End Flows

  • Factory Provisioning & UF2 Release Pipeline:
    • Trigger: Operator runs tools/provision_device.py or manual tools/generate_keys.py + tools/provision_otp.py + build.sh (planovi_release).
    • Validation: sign_firmware.py validates payload bounds (8..0x1DFF00 B), RP2350 SRAM MSP alignment, Thumb reset vector bounds, prepends 256 B firmware_image_header_t with SHA-256 + ECDSA P-256 signature + CRC-32, and emits JSON manifest. make_factory_uf2.py packs Bootloader (64 KiB) + Slot A (1,920 KiB) + 0xFF-erased Slot B (1,920 KiB) + 0xFF-erased NVS (192 KiB) into a single 4 MiB RP2350 UF2 (family_id = 0xE48BFF59). provision_otp.py validates X.509 leaf/CA chain, EKU CLIENT_AUTH, P-256 private key match, password complexity, and PEM length limits before interactive "PROVISION" confirmation.
    • State Change: picotool otp set -e burns OTP rows 0x0082..0x0487, applies --permissions-file (unless --allow-unlocked-otp), then burns OTP_ROW_MAGIC (0x0500..0x0501) last so a failed lock leaves the chip unprovisioned.
    • Failure: Any readback verification mismatch or invalid cert aborts exit code non-zero before magic burn.
  • Signed A/B Boot & One-Shot Trial Failover (src/bootloader/bootloader_main.c, bootloader.c, boot_state.c):
    • Trigger: Power-on, watchdog, or software reset enters bootloader at 0x10000000.
    • Validation: bootloader_init() initializes OTP; bootloader_select_slot() runs bootloader_verify_slot() on Slot A (0x10010000) and Slot B (0x101F0000): checks magic (ASLF/PLNV), header CRC-32, header_version == 2, allowed flags (IMAGE_FLAG_ENCRYPTED forbidden), board_id == "PICO2W-RP2350", vector table MSP & Thumb entry point, payload SHA-256, and ECDSA P-256 signature against OTP OTA pubkey.
    • State Change: If boot_state.phase == BOOT_STATE_TRIAL_PENDING and target slot is valid, carries IMAGE_FLAG_TEST_BOOT, and satisfies version >= confirmed_version, bootloader persists BOOT_STATE_TRIAL_ATTEMPTED to alternating 4 KiB NVS sector before jumping via bootloader_jump_to_app(). Otherwise selects confirmed_slot (or highest non-trial version if uninitialized; Slot A wins ties).
    • Failure: If no valid bootable slot exists (or jump vectors fail), bootloader calls reset_usb_boot(0, 0) to enter RP2350 ROM BOOTSEL mode for USB recovery.
  • Trial Confirmation & Automatic Rollback (src/main.c:72-90, 409-421, src/net/ota_update.c):
    • Trigger: Running app checks boot_state_is_trial_active(PLANOVI_RUNNING_SLOT) on boot and evaluates ota_trial_health_ready() every 100 ms in NetSysTask.
    • Validation: Requires all 6 conditions: system_health_is_ready(), cloud_client_is_connected(), sd_journal_get_state() == SD_JOURNAL_STATE_READY, time_sync_has_trusted_server_time(), telemetry.is_running, and (!telemetry_enabled || meter_count == 0 || telemetry.total_cycles > 0).
    • State Change: On pass -> ota_confirm_successful_boot() writes {slot=NONE, phase=BOOT_STATE_IDLE, confirmed_slot=PLANOVI_RUNNING_SLOT, confirmed_version=running_version()}. On 60,000 ms timeout -> records PLANOVI_FAULT_OTA_TRIAL_TIMEOUT and reboots (watchdog_mgr_reboot(false)); on reboot, bootloader sees BOOT_STATE_TRIAL_ATTEMPTED and boots previous confirmed_slot.
  • Offline USB A/B Service Update (tools/service_update_usb.py):
    • Trigger: Technician runs CLI against USB-connected converter (dry-run by default; --execute flashes).
    • Validation: Verifies manifest, flags == IMAGE_FLAG_VALID | IMAGE_FLAG_TEST_BOOT, payload SHA-256, header CRC-32, vector table, both ECDSA signatures, target_slot != current_slot, strict monotonic upgrade new_version > current_version, and no existing TRIAL_PENDING in boot-state Flash (0x103D0000..0x103D2000).
    • State Change: Writes inactive slot via picotool load, writes BOOT_STATE_TRIAL_PENDING to alternating boot-state sector, reboots, and optionally checks confirmation after --wait-seconds.
  • FreeRTOS Health Supervisor & Hardware Watchdog (src/app/system_health.c, src/hal/watchdog.c):
    • Trigger: Health task wakes every 500 ms (HEALTH_CHECK_PERIOD_MS).
    • Validation: Checks every bit in required_components (SYSTEM_HEALTH_NET, SYSTEM_HEALTH_TELEMETRY, SYSTEM_HEALTH_STORAGE) pulsed within <= 10,000 ms (HEALTH_STALE_TIMEOUT_MS).
    • State Change: All fresh -> clears pending health fault and calls watchdog_mgr_feed() (HW timeout 15,000 ms). Any stale -> stops feeding HW watchdog and records PLANOVI_FAULT_HEALTH_TIMEOUT with stale_mask | (net_context << 8) in watchdog scratch registers -> HW reset after ~15 s.
  • Physical Button & Last-Gasp Power Loss (src/hal/button.c, src/hal/power_mgr.c, src/main.c):
    • Button: Debounced 50 ms on GPIO 22 (active low, pull-up). At boot with unprovisioned SD: holding >= 20 s authorizes sd_fs_format() (button_suppress_until_release() prevents re-trigger). At runtime on release: >= 20 s -> factory reset (sd_journal_force_reprovision() if not ready + config_store_factory_reset() + reboot); 10..19.999 s -> Wi-Fi AP reset to Planovi-<serial> + reboot; < 3 s -> SHORT_CLICK (ignored); 3..9.999 s -> dead zone (no event).
    • Last Gasp: Falling edge IRQ on GPIO 26 (GPIO_POWER_AC_DETECT) sets POWER_AC_LOST and notifies TelemetryTask via vTaskNotifyGiveFromISR() to immediately persist POWER_LOSS_LAST_GASP (code_num=6001).

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

  • BR-BOOT-01 (4 MiB Contiguous Flash Layout): src/bootloader/flash_layout.h:13-51 enforces compile-time #if checks across PLANOVI_FLASH_SIZE = 0x00400000 (4 MiB): Bootloader 0x000000..0x00FFFF (64 KiB), Slot A 0x010000..0x1EFFFF (1,920 KiB = 256 B header + 0x1DFF00 payload), Slot B 0x1F0000..0x3CFFFF (1,920 KiB), NVS 0x3D0000..0x3FFFFF (192 KiB: Boot State A/B 0x3D0000..0x3D1FFF [8 KiB], 168 KiB unused gap, Encrypted Config A/B 0x3FC000..0x3FFFFF [16 KiB]).
  • BR-BOOT-02 (Strict Image Verification Order): bootloader_verify_slot() (src/bootloader/bootloader.c:145-192) rejects any slot failing (1) exact slot address match, (2) magic 0x41534C46 (ASLF) or 0x504C4E56 (PLNV), (3) IEEE CRC-32 over header bytes 0..251, (4) header_version == 2, IMAGE_FLAG_VALID set, IMAGE_FLAG_ENCRYPTED absent, board_id == "PICO2W-RP2350", 8 <= image_size <= 0x1DFF00, 8-byte aligned MSP in [0x20000000, 0x20082000], Thumb entry_point == vectors[1] inside payload bounds, (5) payload SHA-256, or (6) ECDSA P-256 signature over SHA-256 of canonical header (bytes 0..251 with r, s, crc32 zeroed) using OTP OTA pubkey.
  • BR-BOOT-03 (One-Shot Trial & Monotonic Anti-Rollback): bootloader_select_slot() (src/bootloader/bootloader.c:209-272) allows a IMAGE_FLAG_TEST_BOOT image to boot only once when boot_state.phase == BOOT_STATE_TRIAL_PENDING and packed_version >= confirmed_version ((major<<24)|(minor<<16)|(patch<<8)|build). Bootloader writes BOOT_STATE_TRIAL_ATTEMPTED before jumping; any crash, watchdog reset, or 60 s confirmation timeout (src/main.c:413) guarantees rollback to confirmed_slot. Trial images are strictly excluded from fresh/fallback boot selection.
  • BR-BOOT-04 (Mandatory OTP Provisioning & ECC Validation): otp_keys_init() (src/security/otp_keys.c:130-198) reads RP2350 OTP via rom_func_otp_access() with OTP_CMD_ECC_BITS and fails startup if any of the 7 regions fail validation: OTP_ROW_MAGIC (0x0500, ASLD/PLNV), serial (0x0082, 1..31 chars [A-Za-z0-9._:@-]+), non-all-0x00/non-all-0xFF 32 B AES key (0x0092) and 64 B P-256 OTA pubkey (0x00A2), PEM markers on client cert (0x00C2, <1500 B) and key (0x03B0, <400 B), and setup password (0x0478, 12..31 printable non-space ASCII with upper+lower+digit+special). Production builds have zero mock fallback.
  • BR-BOOT-05 (Heap-Safe mbedTLS Allocator & HW SHA-256 Lock): planovi_mbedtls_calloc() (src/security/mbedtls_platform_freertos.c) denies allocation (NULL) if xPortGetFreeHeapSize() < bytes + 4096u (MBEDTLS_HEAP_RESERVE_BYTES), preventing vApplicationMallocFailedHook() system reboots during TLS spikes. Weak pico_sha256_lock()/unlock() are overridden with a FreeRTOS priority-inheritance mutex (g_sha256_mutex).
  • BR-BOOT-06 (Hardware Watchdog Bounds & Supervision): watchdog_mgr_init() caps hardware timeout at WATCHDOG_RP2350_SAFE_MAX_TIMEOUT_MS = 16000u (src/hal/watchdog.c); system_health.c sets HW timeout 15000 ms, stale threshold 10000 ms, check cadence 500 ms, supervising NetSysTask (SYSTEM_HEALTH_NET) plus TelemetryTask and SdWriter when storage is ready (SYSTEM_HEALTH_TELEMETRY, SYSTEM_HEALTH_STORAGE).
  • BR-BOOT-07 (Runtime Network OTA Disabled in v1): While src/net/ota_update.c compiles streaming Flash-write/readback/ECDSA verification logic, only ota_init() and ota_confirm_successful_boot() are wired in src/main.c. All v1 field updates use offline USB tools/service_update_usb.py requiring strict new_version > current_version.
  • BR-BOOT-08 (Single-Core Flash Exclusion & UART0 Reservation): CMakeLists.txt:439,460-461 sets PICO_FLASH_ASSUME_CORE1_SAFE=1 (configNUMBER_OF_CORES = 1), disables UART stdio (pico_enable_stdio_uart(..., 0)), and enables USB CDC stdio (pico_enable_stdio_usb(..., 1)) so UART0 (GP0/GP1) never emits console text onto the RS-485 bus.
  • BR-BOOT-09 (VSYS ADC Voltage Formula): power_mgr_read_vsys_voltage() (src/hal/power_mgr.c) acquires cyw43_thread_enter() (shared PICO_VSYS_PIN GP29), discards 3 samples, averages 3 samples, and computes adc_avg * (3.3f / 4096.0f) * 3.0f.

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> BOOT_STATE_IDLE: Factory UF2 / Confirmed boot
    BOOT_STATE_IDLE --> BOOT_STATE_TRIAL_PENDING: service_update_usb.py writes inactive slot + trial request
    BOOT_STATE_TRIAL_PENDING --> BOOT_STATE_TRIAL_ATTEMPTED: Bootloader verifies ECDSA+SHA256+anti-rollback & marks attempted before jump
    BOOT_STATE_TRIAL_ATTEMPTED --> BOOT_STATE_IDLE: App passes 6-point ota_trial_health_ready() within 60s -> confirmed_slot updated
    BOOT_STATE_TRIAL_ATTEMPTED --> ROLLBACK_CONFIRMED: Crash / Watchdog reset / 60s timeout -> next boot skips trial & boots confirmed_slot
    ROLLBACK_CONFIRMED --> BOOT_STATE_IDLE: Confirmed slot continues normal operation
    BOOT_STATE_IDLE --> ROM_BOOTSEL: Neither Slot A nor Slot B passes verification
  • OTA Engine States (ota_state_t, src/net/ota_update.h): IDLE -> DOWNLOADING -> VERIFYING -> READY_TO_APPLY -> APPLYING (or ERROR). Currently unwired at runtime.
  • Fault Diagnostic Codes (planovi_fault_reason_t, src/app/fault_diagnostics.h): NONE (0), HARDFAULT (1), STACK_OVERFLOW (2), MALLOC_FAILED (3), HEALTH_TIMEOUT (4), OTA_TRIAL_TIMEOUT (5) persisted in watchdog_hw->scratch[0..7] with magic 0xA51A0000u.

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

  • Inputs: RP2350 OTP ECC rows (0x0082..0x0501), Flash XIP slots (0x10010000, 0x101F0000), NVS boot state (0x103D0000..0x103D1FFF), GPIO 22 button, GPIO 26 AC detect IRQ, GP29 VSYS ADC, USB picotool commands.
  • Processing: ECDSA P-256 + SHA-256 verification, ping-pong Flash sector writes via flash_safe_execute(), FreeRTOS 1000 Hz preemptive scheduler (160 KiB heap_4, 11 tasks including transient Reboot and SDK/RTOS tasks), HardFault/malloc/stack-overflow capture into watchdog scratch registers.
  • Side Effects: Direct XIP jump (VTOR/MSP handoff), Flash erase/program on boot state and NVS, hardware watchdog reboot, ROM BOOTSEL entry, USB CDC diagnostic logs, and Cloud API calls during manufacturing (GET /converters-next-serial, POST /converters/prepare-usb-provisioning, GET /converters/firmware/info, GET /converters/firmware/latest-uf2, POST /converters/{serial}/confirm-flash).

6. Cross-Repository Dependencies

  • tools/provision_device.py -> cloud/api/converters.py | HTTPS (unauthenticated!) | GET /api/v1/converters-next-serial, POST /api/v1/converters/prepare-usb-provisioning, GET /api/v1/converters/firmware/info, GET /api/v1/converters/firmware/latest-uf2, POST /api/v1/converters/{serial}/confirm-flash.
  • CMakeLists.txt -> Pico SDK (2.3.0) & FreeRTOS-Kernel (11.1+) | Build-time external SDK paths (PICO_SDK_PATH, FREERTOS_KERNEL_PATH).

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

  • Ping-Pong 4 KiB Boot State Sectors (boot_state.c): Alternates 0x3D0000/0x3D1000 with monotonic generation and CRC-32 so power loss mid-erase never destroys the prior valid state.
  • Pico SDK 2.3.0 PSA RNG Workaround (CMakeLists.txt:129-150): Manually appends ${PICO_MBEDTLS_PATH}/library/psa_crypto_random.c because Pico SDK 2.3.0 enables PSA core for TLS 1.3 while omitting that translation unit.
  • CYW43_TASK_STACK_SIZE=2048 words (8 KiB) (CMakeLists.txt:434): Doubled from Pico SDK default 4 KiB to prevent stack overflows during post-login HTTP bursts.
  • Confirmed Bug (src/main.c:414-417 vs src/hal/watchdog.c:88): On OTA trial timeout, main.c writes PLANOVI_FAULT_OTA_TRIAL_TIMEOUT into watchdog_hw->scratch[0], then immediately calls watchdog_mgr_reboot(false) which overwrites scratch[0] = RESET_REASON_SOFTWARE, erasing the fault diagnostic before reboot.
  • [TEAM_WHY_NEEDED: tools/provision_device.py:263 unconditionally passes --allow-unlocked-otp to provision_otp.py (marked LAB ONLY) and never supplies --permissions-file. Is OTP locking deferred for current production batches, or is this a security bug?]
  • [TEAM_WHY_NEEDED: tools/provision_otp.py:32-33 still burns OTP_MAGIC_VALUE = 0x41534C44 ("ASLD", rev 1) instead of OTP_MAGIC_PLANOVI = 0x504C4E56 ("PLNV"), and sign_firmware.py still emits 0x41534C46 ("ASLF"). When should new series switch to PLNV?]
  • [TEAM_WHY_NEEDED: tools/build_firmware_docker.sh:21-61 silently generates temporary self-signed CA and ephemeral signing keys in /tmp/ if production PEM files are missing, and tools/provision_device.py:28 defaults PLANOVI_API_URL to https://dev-cloud.planovi.app/api/v1. Should release builds fail closed instead?]
  • [TEAM_WHY_NEEDED: src/bootloader/flash_layout.h leaves a 168 KiB unused gap inside the 192 KiB NVS partition (0x003D2000..0x003FBFFF), and src/hal/button.c silently drops button holds between 3.0s and 9.999s. Are both intentional (future NVS expansion & accidental-press guard band)?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact CommandFix
Device drops directly into RP2350 USB RPI-RP2 BOOTSEL on power-upbootloader_select_slot() returned false (unsigned/corrupt image, wrong board_id, unprovisioned OTP, or signature mismatch) (bootloader_main.c:17)Inspect image with python3 tools/service_update_usb.py --package <bin> --manifest <json> --public-key tools/ota-public-key.pem and check OTP magic picotool otp get -e 0x0500Provision OTP (provision_otp.py) and flash signed planovi_full_factory.uf2
Rapid reboot loop every ~15 s; USB CDC prints PLANOVI_FAULT_HEALTH_TIMEOUT with status=0x0N0MSupervised task (bit 0=NET, 1=TELEMETRY, 2=STORAGE) failed to pulse within 10 s (system_health.c); bits [15:8] give net_context (0=LOOP..9=STORAGE_TRANSFER)Capture USB CDC boot log via python3 tools/capture_serial.pyDiagnose hung subsystem indicated by stale_mask and net_context
USB update rolls back to previous slot after ~60 sTrial slot failed 1 of 6 ota_trial_health_ready() checks (e.g., no mTLS cloud connect, SD not ready, or no trusted UTC time) (main.c:72-90, 413)Read 8 KiB boot state (picotool save -r 0x103D0000 0x103D2000) and inspect USB serial logs during the 60 s windowEnsure Wi-Fi/mTLS/SD/time are healthy before upgrading, or fix regression in trial build
HardFault / StackOverflow / MallocFailed rebootTask stack exhaustion (configCHECK_FOR_STACK_OVERFLOW=2) or 160 KiB FreeRTOS heap exhaustion (freertos_hooks.c, fault_diagnostics.c)Connect USB CDC (tools/capture_serial.py) to read retained PC/LR/PSP/PSPLIM/task name from watchdog_hw->scratch[0..7]Increase offending task stack or reduce dynamic allocations; resolve PC via arm-none-eabi-addr2line on .elf