diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71cb498..28e2637 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,16 +9,15 @@ on: permissions: contents: read -env: - ESP32_INDEX_URL: https://espressif.github.io/arduino-esp32/package_esp32_index.json - ESP32_FQBN: esp32:esp32:esp32doit-devkit-v1 - NVS_GUARD: compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init - jobs: build: - name: Compile Arduino sketch + name: Compile Arduino sketch (ESP32 ${{ matrix.core }}) runs-on: ubuntu-latest timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + core: ['3.3.12', '4.0.0'] steps: - name: Check out source @@ -32,39 +31,24 @@ jobs: - name: Cache Arduino packages uses: actions/cache@v4 with: - path: | - ~/.arduino15 - ~/.cache/arduino - key: ${{ runner.os }}-arduino-cli-1.1.1-esp32-3.3.12-nimble-2.3.8 - - - name: Install ESP32 core and libraries - run: | - arduino-cli config init --overwrite - arduino-cli config add board_manager.additional_urls "$ESP32_INDEX_URL" - arduino-cli core update-index - arduino-cli core install esp32:esp32@3.3.12 - arduino-cli lib update-index - arduino-cli lib install --no-deps "NimBLE-Arduino@2.3.8" + path: .tools/arduino + key: ${{ runner.os }}-protected-arduino-1.1.1-${{ matrix.core }}-${{ hashFiles('Build-PulseShift.ps1') }} - name: Compile - production firmware (default) - run: | - arduino-cli compile \ - --fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \ - --build-path "$RUNNER_TEMP/build-production" \ - PulseShift - test "$(( $(wc -c < "$RUNNER_TEMP/build-production/PulseShift.ino.bin") + 76 ))" -le 1310720 + run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' -BuildDirectory "$RUNNER_TEMP/build-production" - name: Compile - fully headless variant (serial diagnostics off) + run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' -Headless -BuildDirectory "$RUNNER_TEMP/build-headless" + + - name: Reject an unprotected Arduino IDE-style build run: | - mkdir -p "$RUNNER_TEMP/variants/headless" - cp -r PulseShift "$RUNNER_TEMP/variants/headless/PulseShift" - sed -i 's/#define PULSESHIFT_SERIAL_DIAGNOSTICS 1/#define PULSESHIFT_SERIAL_DIAGNOSTICS 0/' \ - "$RUNNER_TEMP/variants/headless/PulseShift/UserConfig.h" - arduino-cli compile \ - --fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \ - --build-path "$RUNNER_TEMP/build-headless" \ - "$RUNNER_TEMP/variants/headless/PulseShift" - test "$(( $(wc -c < "$RUNNER_TEMP/build-headless/PulseShift.ino.bin") + 76 ))" -le 1310720 + log="$RUNNER_TEMP/unsupported-build.log" + if arduino-cli --config-file ".tools/arduino/esp32-${{ matrix.core }}/arduino-cli.yaml" compile \ + --fqbn esp32:esp32:esp32doit-devkit-v1 --build-path "$RUNNER_TEMP/build-unsupported" PulseShift > "$log" 2>&1; then + echo 'Unprotected build unexpectedly compiled' >&2 + exit 1 + fi + grep -F 'PulseShift needs its protected build' "$log" - name: Reject invalid user configuration run: | @@ -73,10 +57,8 @@ jobs: sed -i 's/#define PULSESHIFT_LED_COUNT 6/#define PULSESHIFT_LED_COUNT 0/' \ "$RUNNER_TEMP/variants/invalid/PulseShift/UserConfig.h" log="$RUNNER_TEMP/invalid-config.log" - if arduino-cli compile \ - --fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \ - --build-path "$RUNNER_TEMP/build-invalid" \ - "$RUNNER_TEMP/variants/invalid/PulseShift" > "$log" 2>&1; then + if pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -CoreVersion '${{ matrix.core }}' \ + -BuildDirectory "$RUNNER_TEMP/build-invalid" -SketchDirectory "$RUNNER_TEMP/variants/invalid/PulseShift" > "$log" 2>&1; then echo "Invalid config unexpectedly compiled" >&2 exit 1 fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed3b229..507fe70 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,66 +1,47 @@ -name: Publish GitHub Release +name: Prepare firmware OTA candidate on: - push: - tags: - - "v*" + workflow_dispatch: concurrency: group: release-${{ github.ref_name }} cancel-in-progress: false permissions: - contents: write + contents: read jobs: release: - name: Build and publish release + name: Build application for offline signing runs-on: ubuntu-latest timeout-minutes: 30 - env: - ESP32_INDEX_URL: https://espressif.github.io/arduino-esp32/package_esp32_index.json - ESP32_FQBN: esp32:esp32:esp32doit-devkit-v1 - NVS_GUARD: compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init - steps: - name: Check out source uses: actions/checkout@v4 + with: + persist-credentials: false - name: Set up Arduino CLI uses: arduino/setup-arduino-cli@v2 with: version: 1.1.1 - - name: Install ESP32 core and libraries - run: | - arduino-cli config init --overwrite - arduino-cli config add board_manager.additional_urls "$ESP32_INDEX_URL" - arduino-cli core update-index - arduino-cli core install esp32:esp32@3.3.12 - arduino-cli lib update-index - arduino-cli lib install --no-deps "NimBLE-Arduino@2.3.8" - - - name: Compile and verify sketch - run: | - arduino-cli compile \ - --fqbn "$ESP32_FQBN" --build-property "$NVS_GUARD" \ - --build-path "$RUNNER_TEMP/build-release" \ - PulseShift - test "$(( $(wc -c < "$RUNNER_TEMP/build-release/PulseShift.ino.bin") + 76 ))" -le 1310720 + - name: Compile and verify application + run: pwsh -NoProfile -File ./Build-PulseShift.ps1 -ArduinoCli arduino-cli -BuildDirectory "$RUNNER_TEMP/build-release" - - name: Package Arduino sketch ZIP + - name: Prepare offline signing input run: | - ZIP="PulseShift-Arduino-$GITHUB_REF_NAME.zip" - git archive --format=zip --output="$RUNNER_TEMP/$ZIP" HEAD PulseShift/ docs/TESTING.md - (cd "$RUNNER_TEMP" && sha256sum "$ZIP" > "$ZIP.sha256") - echo "ZIP=$RUNNER_TEMP/$ZIP" >> "$GITHUB_ENV" - echo "SHA=$RUNNER_TEMP/$ZIP.sha256" >> "$GITHUB_ENV" - - - name: Upload release assets - uses: softprops/action-gh-release@v2 + set -euo pipefail + mkdir "$RUNNER_TEMP/ota-candidate" + cd "$RUNNER_TEMP/ota-candidate" + cp "$RUNNER_TEMP/build-release/"{PulseShift.ino.bin,PulseShift.ino.partitions.bin,partitions.csv,build-verification.json} . + git -C "$GITHUB_WORKSPACE" rev-parse HEAD > source.txt + sha256sum PulseShift.ino.bin PulseShift.ino.partitions.bin partitions.csv build-verification.json source.txt > SHA256SUMS.txt + + - name: Store application-only signing input + uses: actions/upload-artifact@v4 with: - files: | - ${{ env.ZIP }} - ${{ env.SHA }} - draft: true - generate_release_notes: true + name: PulseShift-OTA-signing-input-${{ github.sha }} + path: ${{ runner.temp }}/ota-candidate/ + if-no-files-found: error + retention-days: 7 diff --git a/Build-PulseShift.cmd b/Build-PulseShift.cmd new file mode 100644 index 0000000..8671ca2 --- /dev/null +++ b/Build-PulseShift.cmd @@ -0,0 +1,6 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Build-PulseShift.ps1" %* +set "PULSESHIFT_BUILD_EXIT=%ERRORLEVEL%" +if not "%PULSESHIFT_BUILD_EXIT%"=="0" echo PulseShift build failed. See the diagnostic above. +pause +exit /b %PULSESHIFT_BUILD_EXIT% diff --git a/Build-PulseShift.ps1 b/Build-PulseShift.ps1 new file mode 100644 index 0000000..fe33aad --- /dev/null +++ b/Build-PulseShift.ps1 @@ -0,0 +1,172 @@ +[CmdletBinding()] +param( + [ValidateSet('3.3.12', '4.0.0')][string]$CoreVersion = '3.3.12', + [switch]$Headless, + [string]$BuildDirectory, + [string]$CacheDirectory, + [string]$ArduinoCli, + [string]$SketchDirectory +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$CacheDirectory = if ($CacheDirectory) { $CacheDirectory } else { Join-Path $PSScriptRoot '.tools/arduino' } +$SketchDirectory = if ($SketchDirectory) { $SketchDirectory } else { Join-Path $PSScriptRoot 'PulseShift' } +$cliVersion = '1.1.1' +$nimble = @{ '3.3.12' = '2.3.8'; '4.0.0' = '2.5.2' }[$CoreVersion] +$bootloaderHash = @{ + '3.3.12' = '7c5e6c42dcd3b658a81374d51e42aa839559b936df3ec181e94e864880b29fc2' + '4.0.0' = 'e81751780c46fffddf6deeb4c9a1c01c169952aefd114c6ae3086a9b9c5d0198' +}[$CoreVersion] +$isWindowsBuild = $env:OS -eq 'Windows_NT' +$cache = [IO.Path]::GetFullPath($CacheDirectory) +$coreCache = Join-Path $cache "esp32-$CoreVersion" +$downloads = Join-Path $cache 'downloads' +$data = Join-Path $coreCache 'data' +$sketchbook = Join-Path $coreCache 'sketchbook' +$index = 'https://espressif.github.io/arduino-esp32/package_esp32_index.json' +if (!$BuildDirectory) { + $variant = if ($Headless) { 'headless' } else { 'production' } + $BuildDirectory = Join-Path $PSScriptRoot "build/esp32-$CoreVersion/$variant" +} +$build = [IO.Path]::GetFullPath($BuildDirectory) +$sketch = (Resolve-Path -LiteralPath $SketchDirectory).Path +New-Item -ItemType Directory -Force -Path $coreCache, $downloads, $data, $sketchbook, $build | Out-Null +$reportPath = Join-Path $build 'build-verification.json' +if (Test-Path -LiteralPath $reportPath) { Remove-Item -LiteralPath $reportPath } + +function Get-Sha256([string]$PathValue) { + $sha256 = [Security.Cryptography.SHA256]::Create() + $inputStream = [IO.File]::OpenRead($PathValue) + try { + return [BitConverter]::ToString($sha256.ComputeHash($inputStream)).Replace('-', '').ToLowerInvariant() + } finally { + $inputStream.Dispose() + $sha256.Dispose() + } +} + +if (!$ArduinoCli) { + if (!$isWindowsBuild -or $env:PROCESSOR_ARCHITECTURE -ne 'AMD64') { + throw 'The one-click installer needs x64 Windows. On Linux x64 provide Arduino CLI 1.1.1 with -ArduinoCli.' + } + $cliDir = Join-Path $cache "cli-$cliVersion" + $ArduinoCli = Join-Path $cliDir 'arduino-cli.exe' + if (!(Test-Path -LiteralPath $ArduinoCli)) { + $zip = Join-Path $downloads "arduino-cli_${cliVersion}_Windows_64bit.zip" + $sha = 'f49a61865ff5d91d2732a19c51b0ac767cce51213db84b0b28b98ee070879f66' + if (!(Test-Path -LiteralPath $zip)) { + Write-Host "Downloading Arduino CLI $cliVersion from Arduino." + Invoke-WebRequest -UseBasicParsing -Uri "https://github.com/arduino/arduino-cli/releases/download/v$cliVersion/arduino-cli_${cliVersion}_Windows_64bit.zip" -OutFile $zip + } + if ((Get-Sha256 $zip) -ne $sha) { + throw "Arduino CLI archive SHA-256 mismatch. Replace this cached download and retry: $zip" + } + Add-Type -AssemblyName System.IO.Compression.FileSystem + [IO.Compression.ZipFile]::ExtractToDirectory($zip, $cliDir) + } +} + +$version = & $ArduinoCli version +if ($LASTEXITCODE -ne 0 -or ($version -join ' ') -notmatch '\bVersion:\s+1\.1\.1(?:\s|$)') { + throw "PulseShift requires Arduino CLI $cliVersion. Got: $version" +} + +function YamlPath([string]$PathValue) { + return "'" + $PathValue.Replace('\', '/').Replace("'", "''") + "'" +} + +$cfg = Join-Path $coreCache 'arduino-cli.yaml' +@" +board_manager: + additional_urls: [$index] +directories: + data: $(YamlPath $data) + downloads: $(YamlPath $downloads) + user: $(YamlPath $sketchbook) +build_cache: + path: $(YamlPath (Join-Path $coreCache 'cache')) +"@ | Set-Content -LiteralPath $cfg -Encoding UTF8 + +function Invoke-Arduino([string[]]$Arguments) { + & $ArduinoCli --config-file $cfg @Arguments + if ($LASTEXITCODE -ne 0) { throw "Arduino CLI failed ($LASTEXITCODE): $($Arguments -join ' ')" } +} + +$effective = (Invoke-Arduino @('config', 'dump', '--format', 'json') | Out-String | ConvertFrom-Json).config +foreach ($entry in @(@('data', $data), @('downloads', $downloads), @('user', $sketchbook))) { + if ([IO.Path]::GetFullPath($effective.directories.($entry[0])) -ne $entry[1]) { + throw "Arduino environment overrides the isolated $($entry[0]) directory. Clear that override to build safely." + } +} + +$platform = Join-Path $data "packages/esp32/hardware/esp32/$CoreVersion/platform.txt" +if (!(Test-Path -LiteralPath $platform)) { + Write-Host "Installing Espressif board package $CoreVersion to $data." + Invoke-Arduino @('core', 'update-index') + Invoke-Arduino @('core', 'install', "esp32:esp32@$CoreVersion") +} +$library = Join-Path $sketchbook 'libraries/NimBLE-Arduino/library.properties' +if (!(Test-Path -LiteralPath $library) -or !(Select-String -LiteralPath $library -Pattern "^version=$([regex]::Escape($nimble))$" -Quiet)) { + Invoke-Arduino @('lib', 'update-index') + Invoke-Arduino @('lib', 'install', '--no-deps', "NimBLE-Arduino@$nimble") +} + +$defines = '-DPULSESHIFT_PROTECTED_BUILD=1' +if ($Headless) { $defines += ' -DPULSESHIFT_SERIAL_DIAGNOSTICS=0' } +$compile = @('compile', '--fqbn', 'esp32:esp32:esp32doit-devkit-v1', '--build-path', $build, + '--build-property', "compiler.cpp.extra_flags=$defines", + '--build-property', 'compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init') +Write-Host "Building for ESP32 $CoreVersion with NimBLE-Arduino $nimble." +Invoke-Arduino ($compile + $sketch) + +$props = Invoke-Arduino ($compile + @('--show-properties=expanded', $sketch)) +$compilerPath = ($props | Where-Object { $_ -like 'compiler.path=*' } | Select-Object -First 1) -replace '^compiler.path=', '' +$compilerName = ($props | Where-Object { $_ -like 'compiler.cpp.cmd=*' } | Select-Object -First 1) -replace '^compiler.cpp.cmd=', '' +if (!$compilerPath -or !$compilerName -or $props -notcontains 'build.bootloader_addr=0x1000' -or $props -notcontains 'build.flash_size=4MB') { + throw 'Unexpected ESP32 compiler, bootloader offset or flash size.' +} +$suffix = if ($isWindowsBuild) { '.exe' } else { '' } +$objdump = Join-Path $compilerPath (($compilerName -replace 'g\+\+(\.exe)?$', 'objdump') + $suffix) +$elf = Join-Path $build 'PulseShift.ino.elf' +$startup = & $objdump -d --disassemble=initArduino $elf | Out-String +if ($LASTEXITCODE -ne 0 -or $startup -notmatch '<__wrap_nvs_flash_init>' -or $startup -notmatch '') { + throw 'Linked initArduino() does not call both the NVS guard and the rollback hook.' +} +$sdk = Join-Path $build 'sdkconfig' +foreach ($setting in @('CONFIG_APP_ROLLBACK_ENABLE=y', 'CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y')) { + if (!(Select-String -LiteralPath $sdk -Pattern "^$setting$" -Quiet)) { throw "Missing SDK setting $setting" } +} +$partition = Join-Path $build 'PulseShift.ino.partitions.bin' +$partitionHash = Get-Sha256 $partition +if ($partitionHash -ne '148b959cbff1c38aa8e1d5c0ba9d612c54997b945e56a63f41223eef650653a1') { + throw 'Compiled partition table differs from the installed PulseShift 4 MiB layout.' +} +$boot = Join-Path $build 'PulseShift.ino.bootloader.bin' +if ((Get-Sha256 $boot) -ne $bootloaderHash) { + throw 'Unexpected bootloader binary for the pinned board package and flash configuration.' +} +$app = Join-Path $build 'PulseShift.ino.bin' +$bytes = [IO.File]::ReadAllBytes($app) +if ($bytes.Length -lt 65536 -or $bytes.Length + 76 -gt 0x140000 -or + $bytes[0] -ne 0xe9 -or $bytes[12] -ne 0 -or $bytes[13] -ne 0 -or + [BitConverter]::ToString($bytes, 32, 4) -ne '32-54-CD-AB') { + throw 'The build did not produce a classic ESP32 application that fits the signed OTA slot.' +} + +[ordered]@{ + arduinoCli = $cliVersion + esp32Core = $CoreVersion + nimble = $nimble + headless = [bool]$Headless + nvsStartupGuard = 'Verified in linked initArduino' + deferredRollback = 'Verified hook, SDK flags and build bootloader hash' + bootloaderAddress = '0x1000' + bootloaderSha256 = $bootloaderHash.ToLowerInvariant() + partitionSha256 = $partitionHash + applicationSha256 = Get-Sha256 $app + applicationBytes = $bytes.Length + signedPackageBytes = $bytes.Length + 76 + slotBytes = 0x140000 +} | ConvertTo-Json | Set-Content -LiteralPath $reportPath -Encoding UTF8 +Write-Host "Build and protection checks passed. Application: $app" diff --git a/PulseShift/PulseShift.ino b/PulseShift/PulseShift.ino index b7cc4a8..f9f735c 100644 --- a/PulseShift/PulseShift.ino +++ b/PulseShift/PulseShift.ino @@ -11,8 +11,8 @@ // (BLE) is the complete command interface; the serial port below is an // optional bench diagnostic console. // -// Arduino build: ESP32 DevKit V1, default 4 MB partition layout. -// See the release build instructions for the required NVS startup linker guard. +// ESP32 DevKit V1, project-owned 4 MiB partition table. Build with the +// repository entry point to enable the protected Arduino startup. // // Serial Monitor (115200 baud) - bench diagnostics only, not required to run: // STATUS / HELP / LOGS / BLE STATUS / CONFIG STATUS / CONFIG RESET / AUTH @@ -45,49 +45,7 @@ #include #include #include -#include -#endif - -// Do not ship an OTA-capable image with app-level rollback compiled out. -#if defined(ARDUINO) && !defined(CONFIG_APP_ROLLBACK_ENABLE) -#error "PulseShift OTA requires Arduino-ESP32 with CONFIG_APP_ROLLBACK_ENABLE" -#endif - -// Arduino-ESP32 3.3.12 calls initArduino() before setup(). Its default weak -// verifyRollbackLater() hook returns false and immediately marks OTA images -// VALID, bypassing PulseShift's pending-verification checks and 120s rollback. -// Override that C symbol so ONLY our explicit OTA_CONFIRM validates the image. -#if defined(ARDUINO) && defined(CONFIG_APP_ROLLBACK_ENABLE) -extern "C" bool verifyRollbackLater(void) { - return true; -} -#endif - -#if defined(ARDUINO) -namespace { -bool startupNvsChecked = false; -esp_err_t startupNvsResult = ESP_FAIL; -} - -// Arduino-ESP32's initArduino() erases the NVS partition when initialization -// reports NO_FREE_PAGES or NEW_VERSION_FOUND. Preserve the data on either error. -extern "C" esp_err_t __real_nvs_flash_init(void); -extern "C" esp_err_t __wrap_nvs_flash_init(void) { - startupNvsResult = __real_nvs_flash_init(); - startupNvsChecked = true; - if (startupNvsResult == ESP_ERR_NVS_NO_FREE_PAGES || - startupNvsResult == ESP_ERR_NVS_NEW_VERSION_FOUND) { - return ESP_FAIL; - } - return startupNvsResult; -} - -static bool nvsReady() { - // Retain a reference to the wrapper, so a link without --wrap fails on - // __real_nvs_flash_init instead of silently omitting the erase protection. - if (!startupNvsChecked) __wrap_nvs_flash_init(); - return startupNvsResult == ESP_OK; -} +#include "src/startup_guard.h" #endif namespace { @@ -107,13 +65,16 @@ public: // Initialize non-volatile persistent storage (LittleFS & Preferences NVS) #if defined(ARDUINO) - const bool nvsOk = nvsReady(); + const esp_err_t nvsResult = startupNvsStatus(); + const bool nvsOk = nvsResult == ESP_OK; #if PULSESHIFT_SERIAL_DIAGNOSTICS - if (!nvsOk) Serial.printf("[NVS] Initialization failed (0x%X). NVS retained.\r\n", startupNvsResult); + if (!nvsOk) Serial.printf("[NVS] Initialization failed (0x%X). NVS retained.\r\n", nvsResult); #endif +#else + const bool nvsOk = true; #endif auto& sm = StorageManager::instance(); - const bool fsOk = sm.begin(false); // Non-destructive mount + const bool fsOk = sm.begin(nvsOk); // Initialize diagnostic logger auto& diag = DiagLogger::instance(); @@ -148,7 +109,7 @@ public: #if PULSESHIFT_SERIAL_DIAGNOSTICS if (!fsOk) { - Serial.println("[STORAGE WARNING] LittleFS mount failed; offline logging disabled until formatted."); + Serial.println("[STORAGE WARNING] LittleFS mount failed; recording disabled. INIT STORAGE is for blank flash only."); } else { Serial.printf("[STORAGE] LittleFS mounted: %lu / %lu bytes used (%lu free)\r\n", (unsigned long)sm.usedBytes(), (unsigned long)sm.totalBytes(), (unsigned long)sm.freeBytes()); @@ -309,7 +270,8 @@ public: const uint32_t renderNow = millis(); ledController_.update(candidateMonitor_.snapshot(renderNow), renderNow, - transport_.healthy(), transport_.totalRx() != 0); + transport_.healthy(), transport_.totalRx() != 0, + OtaManager::instance().state() != OtaEngineState::Idle); #if PULSESHIFT_SERIAL_DIAGNOSTICS // Rate-limited live RPM candidate streaming (10 Hz, 100 ms) @@ -556,6 +518,12 @@ private: c.effect, c.effectSpeed, c.ledDirection ? "REVERSED" : "FORWARD"); Serial.printf("Global Color: R=%u G=%u B=%u\r\n", c.globalColor.r, c.globalColor.g, c.globalColor.b); Serial.printf("Startup Anim: %u | Startup Duration: %u ms\r\n", c.startupAnimation, c.startupDurationMs); + Serial.printf("Boot one-shot: %s | Startup loop: %s | Takeover: %u | Resume below: %u for %u ms\r\n", + c.bootEnabled ? "ON" : "OFF", c.ambient.enabled ? "ON" : "OFF", + c.ambient.takeoverRpm, c.ambient.resumeRpm, c.ambient.stabilizationMs); + Serial.printf("Flash match: %s | Installed LED count: %u | Active LED count: %u\r\n", + ConfigManager::instance().activeMatchesNvs() ? "YES" : "NO", c.installedLedCount, + c.rpmMapping.activeCount(c.installedLedCount)); Serial.printf("RPM Thresholds: [%u, %u, %u, %u, %u, %u]\r\n", c.rpmThresholds[0], c.rpmThresholds[1], c.rpmThresholds[2], c.rpmThresholds[3], c.rpmThresholds[4], c.rpmThresholds[5]); @@ -637,6 +605,15 @@ private: } else if (strcasecmp(cmd, "STREAM OFF") == 0 || strcasecmp(cmd, "LIVE OFF") == 0) { liveStreamEnabled_ = false; Serial.println("[STREAM] Live raw CAN frame streaming DISABLED (default)."); + } else if (strcasecmp(cmd, "INIT STORAGE") == 0) { + auto& storage = StorageManager::instance(); + if (OtaManager::instance().state() != OtaEngineState::Idle || !storage.initializeBlank()) { + Serial.println("[STORAGE] Initialization unavailable. Existing or unreadable data is preserved."); + } else { + CanRecorder::instance().begin(storage.currentSessionId(), storage.bootCount(), config::bitrate, + config::modeName, config::vehicle); + Serial.println("[STORAGE] Blank LittleFS initialized and mounted."); + } } else if (strcasecmp(cmd, "CLEAR YES") == 0) { DiagLogger::instance().clear(); CanRecorder::instance().clear(); @@ -729,6 +706,7 @@ private: Serial.println(" STREAM OFF : Disable live streaming (default: concise summaries only)"); Serial.println(" CLEAR : Request erasing stored diagnostic logs and CAN capture"); Serial.println(" CLEAR YES : Confirm erase and start a fresh capture session"); + Serial.println(" INIT STORAGE : Initialize LittleFS only when the entire partition is blank"); Serial.println(" OTA STATUS : Show running OTA slot and bootloader verification state"); Serial.println(" OTA CONFIRM : Mark newly booted OTA firmware valid and cancel rollback"); } @@ -865,7 +843,7 @@ private: Serial.println("DIAGNOSTIC: STORAGE_ERROR"); Serial.println(" Observation: LittleFS filesystem mount failed."); Serial.println(" Possible Causes: Unformatted flash partition on fresh board, or flash hardware fault."); - Serial.println(" Recommendation: Type 'CLEAR YES' to format the partition for first-time use."); + Serial.println(" Recommendation: Type 'INIT STORAGE' for first-time use on blank flash."); } else if (rec.isDamagedRecording()) { Serial.println("DIAGNOSTIC: DAMAGED_CAPTURE_PRESERVED"); Serial.println(" Observation: Incomplete or damaged capture file is preserved on flash."); diff --git a/PulseShift/partitions.csv b/PulseShift/partitions.csv new file mode 100644 index 0000000..960469b --- /dev/null +++ b/PulseShift/partitions.csv @@ -0,0 +1,7 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x140000, +app1, app, ota_1, 0x150000,0x140000, +spiffs, data, spiffs, 0x290000,0x160000, +coredump, data, coredump,0x3F0000,0x10000, diff --git a/PulseShift/src/ble_manager.cpp b/PulseShift/src/ble_manager.cpp index 76faaec..0d38f9c 100644 --- a/PulseShift/src/ble_manager.cpp +++ b/PulseShift/src/ble_manager.cpp @@ -334,7 +334,8 @@ void BleManager::updateCapabilitiesChar() { BLE_FEAT_CAPTURE_EXPORT | BLE_FEAT_CAPTURE_STAGE | BLE_FEAT_LED_BENCH_TEST | BLE_FEAT_EXT_STARTUP_ANIM | BLE_FEAT_RANGE_DISCOVERY | BLE_FEAT_LOOP_STARTUP | BLE_FEAT_STRIP_CONFIG | - BLE_FEAT_VERIFIED_SAVE | BLE_FEAT_LIGHTING_SETUP | BLE_FEAT_IDLE_ANIMATION; + BLE_FEAT_VERIFIED_SAVE | BLE_FEAT_LIGHTING_SETUP | BLE_FEAT_IDLE_ANIMATION | + BLE_FEAT_STARTUP_LOOP; if (dualSlotDetected && PULSESHIFT_OTA_ENABLED) { featureMask |= BLE_FEAT_OTA_UPDATE; } diff --git a/PulseShift/src/ble_protocol.h b/PulseShift/src/ble_protocol.h index ff3abfd..5c304ff 100644 --- a/PulseShift/src/ble_protocol.h +++ b/PulseShift/src/ble_protocol.h @@ -117,7 +117,7 @@ struct BleLogChunkPacket { // Firmware version reported in the Capabilities packet. #define PULSESHIFT_FW_VERSION_MAJOR 2 #define PULSESHIFT_FW_VERSION_MINOR 6 -#define PULSESHIFT_FW_VERSION_PATCH 0 +#define PULSESHIFT_FW_VERSION_PATCH 1 // Configuration Opcodes enum BleConfigOpcode : uint8_t { @@ -243,7 +243,8 @@ enum BleFeatureMaskBits : uint32_t { BLE_FEAT_STRIP_CONFIG = (1u << 21), // Snapshot TLV 0x1F and SET_LED_COUNT BLE_FEAT_VERIFIED_SAVE = (1u << 22), // SAVE_CONFIG may include expected revision BLE_FEAT_LIGHTING_SETUP = (1u << 23), // Versioned strip/RPM/animation extension - BLE_FEAT_IDLE_ANIMATION = (1u << 24) // Continuous idle animation with RPM takeover & hysteresis + BLE_FEAT_IDLE_ANIMATION = (1u << 24), // Idle enablement and RPM thresholds in lighting setup v2 + BLE_FEAT_STARTUP_LOOP = (1u << 25) // Idle enablement repeats the selected startup animation }; // BLE_RPM packet extended flags usage (schema 3): Bit 1 additionally requires diff --git a/PulseShift/src/config_manager.cpp b/PulseShift/src/config_manager.cpp index e3b261c..2ebb869 100644 --- a/PulseShift/src/config_manager.cpp +++ b/PulseShift/src/config_manager.cpp @@ -14,7 +14,7 @@ #include #if !defined(PULSESHIFT_TEST_BUILD) #include -#include +#include #endif #elif defined(PULSESHIFT_TEST_BUILD) #include @@ -1424,7 +1424,7 @@ bool ConfigManager::requestChallenge(uint32_t nowMs, uint32_t& outChallenge) { return true; } -void ConfigManager::computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uint32_t challenge, uint16_t sequence, uint8_t outProof[8]) { +bool ConfigManager::computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uint32_t challenge, uint16_t sequence, uint8_t outProof[8]) { uint8_t msg[18]; // 12 bytes secret + 4 bytes challenge + 2 bytes sequence memcpy(&msg[0], secret, OWNER_SECRET_LEN); msg[12] = static_cast(challenge & 0xFF); @@ -1436,7 +1436,10 @@ void ConfigManager::computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uin #if defined(ARDUINO) && !defined(PULSESHIFT_TEST_BUILD) uint8_t fullHash[32]; - mbedtls_sha256(msg, sizeof(msg), fullHash, 0); // 0 = SHA-256 + size_t hashLength = 0; + if (psa_crypto_init() != PSA_SUCCESS || + psa_hash_compute(PSA_ALG_SHA_256, msg, sizeof(msg), fullHash, sizeof(fullHash), &hashLength) != PSA_SUCCESS || + hashLength != sizeof(fullHash)) return false; memcpy(outProof, fullHash, 8); #else // Host test stub digest simulation (NEVER used on hardware) @@ -1451,6 +1454,7 @@ void ConfigManager::computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uin outProof[6] = static_cast((c2 >> 16) & 0xFF); outProof[7] = static_cast((c2 >> 24) & 0xFF); #endif + return true; } BleConfigStatusCode ConfigManager::authenticateChallenge(const uint8_t* proof, size_t len, uint16_t sequence, @@ -1498,7 +1502,9 @@ BleConfigStatusCode ConfigManager::authenticateChallenge(const uint8_t* proof, s // 4. Compute expected proof and compare in constant time uint8_t expectedProof[8]; - computeAuthProof(ownerSecret_, challengeToVerify, sequence, expectedProof); + if (!computeAuthProof(ownerSecret_, challengeToVerify, sequence, expectedProof)) { + return BLE_CFG_STATUS_INVALID_STATE; + } uint8_t diff = 0; for (size_t i = 0; i < 8; ++i) { diff --git a/PulseShift/src/config_manager.h b/PulseShift/src/config_manager.h index 5ce127b..76f07b9 100644 --- a/PulseShift/src/config_manager.h +++ b/PulseShift/src/config_manager.h @@ -191,7 +191,7 @@ class ConfigManager { static constexpr size_t OWNER_SECRET_LEN = 12; // Cryptographic Auth Proof Helper - static void computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uint32_t challenge, uint16_t sequence, uint8_t outProof[8]); + static bool computeAuthProof(const uint8_t secret[OWNER_SECRET_LEN], uint32_t challenge, uint16_t sequence, uint8_t outProof[8]); // Static CRC32 Helper static uint32_t computeCrc32(const uint8_t* data, size_t length); diff --git a/PulseShift/src/led_color.h b/PulseShift/src/led_color.h index bdaa68e..beb2643 100644 --- a/PulseShift/src/led_color.h +++ b/PulseShift/src/led_color.h @@ -31,24 +31,26 @@ inline constexpr RgbColor scaleColor(RgbColor c, uint8_t factor) { }; } -// 256-entry CIE 1931 perceptual gamma correction table for WS2812B LEDs (gamma ~ 2.2). -// Eliminates linear PWM stepping and low-brightness popping in smooth animations. -static constexpr uint8_t GAMMA_TABLE[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, - 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, - 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 14, - 15, 15, 16, 16, 17, 17, 18, 19, 19, 20, 20, 21, 22, 22, 23, 24, - 24, 25, 26, 27, 27, 28, 29, 30, 30, 31, 32, 33, 34, 34, 35, 36, - 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - 53, 54, 55, 56, 58, 59, 60, 61, 62, 64, 65, 66, 67, 69, 70, 71, - 73, 74, 75, 77, 78, 80, 81, 83, 84, 86, 87, 89, 90, 92, 94, 95, - 97, 99, 100, 102, 104, 106, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, - 127, 129, 131, 133, 135, 137, 140, 142, 144, 146, 149, 151, 153, 156, 158, 161, - 163, 166, 168, 171, 173, 176, 178, 181, 184, 186, 189, 192, 195, 197, 200, 203, - 206, 209, 212, 215, 218, 221, 224, 227, 230, 233, 236, 240, 243, 246, 250, 253, - 255 +// Gamma 2.2 lookup for the complete 8-bit PWM range. +static constexpr uint8_t GAMMA_TABLE[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, + 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, + 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, + 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, + 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28, 29, + 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, + 42, 43, 43, 44, 45, 46, 47, 48, 49, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, + 73, 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 87, 88, 89, 90, + 91, 93, 94, 95, 97, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 111, + 113, 114, 116, 117, 119, 120, 121, 123, 124, 126, 127, 129, 130, 132, 133, 135, + 137, 138, 140, 141, 143, 145, 146, 148, 149, 151, 153, 154, 156, 158, 159, 161, + 163, 165, 166, 168, 170, 172, 173, 175, 177, 179, 181, 182, 184, 186, 188, 190, + 192, 194, 196, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, + 223, 225, 227, 229, 231, 234, 236, 238, 240, 242, 244, 246, 248, 251, 253, 255, }; +static_assert(sizeof(GAMMA_TABLE) == 256, "Gamma lookup must cover every byte"); inline constexpr RgbColor scaleColorGamma(RgbColor c, uint8_t factor) { const uint8_t rLin = static_cast((static_cast(c.r) * factor + 127) / 255); diff --git a/PulseShift/src/led_controller.cpp b/PulseShift/src/led_controller.cpp index 5def692..bb863b4 100644 --- a/PulseShift/src/led_controller.cpp +++ b/PulseShift/src/led_controller.cpp @@ -111,7 +111,8 @@ bool LedController::serviceTransmission(uint32_t now) { return !driver_->ownsPendingSymbols(); } -void LedController::update(const LiveRpmSnapshot& rpm, uint32_t now, bool healthy, bool canTrafficSeen) { +void LedController::update(const LiveRpmSnapshot& rpm, uint32_t now, bool healthy, bool canTrafficSeen, + bool otaBusy) { if (!driver_) return; // Safety, power and feedback layers can interrupt the preview. Its request @@ -133,6 +134,7 @@ void LedController::update(const LiveRpmSnapshot& rpm, uint32_t now, bool health input.testRpmActive = testRpmActive_; input.testRpm = testRpm_; input.canTrafficSeen = canTrafficSeen; + input.otaBusy = otaBusy; const uint32_t previewElapsed = now - previewStartMs_; if (previewElapsed >= previewDurationMs_) previewPattern_ = 0; input.previewPattern = previewPattern_; @@ -222,7 +224,7 @@ void LedController::printStatus(uint32_t now) const { case LedActiveLayer::Decorative: layerName = "DECORATIVE (Configured Effect)"; break; case LedActiveLayer::Warning: layerName = "WARNING (RPM Shift Warning Overlay)"; break; case LedActiveLayer::ProvisionalRpm: layerName = "PROVISIONAL_RPM (Diagnostic Preview)"; break; - case LedActiveLayer::Ambient: layerName = "AMBIENT"; break; + case LedActiveLayer::StartupLoop: layerName = "STARTUP_LOOP"; break; case LedActiveLayer::AnimationPreview: layerName = "ANIMATION_PREVIEW"; break; } Serial.printf("Active Layer: %s\r\n", layerName); diff --git a/PulseShift/src/led_controller.h b/PulseShift/src/led_controller.h index 6ac4050..b463c24 100644 --- a/PulseShift/src/led_controller.h +++ b/PulseShift/src/led_controller.h @@ -31,7 +31,8 @@ class LedController { // Poll completion before main-task flash I/O can interrupt RMT refills. bool serviceTransmission(uint32_t now); // Render one frame and flush to hardware when output changed, retry is due, or periodic refresh is due. - void update(const LiveRpmSnapshot& rpm, uint32_t now, bool healthy, bool canTrafficSeen = false); + void update(const LiveRpmSnapshot& rpm, uint32_t now, bool healthy, bool canTrafficSeen = false, + bool otaBusy = false); void previewAnimation(uint8_t pattern, uint16_t duration, uint32_t now) { previewPattern_ = pattern; diff --git a/PulseShift/src/led_effects.cpp b/PulseShift/src/led_effects.cpp index 357c8b5..6ab5505 100644 --- a/PulseShift/src/led_effects.cpp +++ b/PulseShift/src/led_effects.cpp @@ -20,7 +20,8 @@ void LedEffectEngine::reset(uint32_t nowMs, uint8_t pixelCount) { lastBarCount_ = 0; barFromBenchTest_ = false; rpmActive_ = false; - rpmStabilizeStartMs_ = 0; + rpmStabilizing_ = false; + rpmStaleTransitions_ = 0; resetRpmLatches(); } @@ -56,7 +57,7 @@ void LedEffectEngine::setAllPixels(RgbColor color) { } void LedEffectEngine::renderAnimation(uint8_t pattern, uint32_t dur, uint32_t elapsed, - const PulseShiftConfig& cfg, bool ambient) { + const PulseShiftConfig& cfg) { // Animation 1: Sweep if (pattern == 1) { const uint32_t half = dur / 2; @@ -105,10 +106,7 @@ void LedEffectEngine::renderAnimation(uint8_t pattern, uint32_t dur, uint32_t el for (uint8_t i = 0; i < renderCount_; ++i) { const uint8_t opposite = renderCount_ - 1 - i; const uint8_t ring = rings - 1 - (i < opposite ? i : opposite); - const uint8_t factor = ambient ? static_cast( - 255 - (elapsed * 255 / dur)) : 255; - logicalPixels_[i] = ring < visibleRings ? - scaleColor(cfg.ledColors[colorZone(i)], factor) : RgbColor{}; + logicalPixels_[i] = ring < visibleRings ? cfg.ledColors[colorZone(i)] : RgbColor{}; } } // Animation 5: Strobe Rush (F1 Grid Start - multi-burst sequence transitioning to full solid) @@ -254,57 +252,52 @@ bool LedEffectEngine::update(uint32_t nowMs, const PulseShiftConfig& cfg, const bool running = decoded && rpm.engineRunning; const bool stopped = qualified && !rpm.engineRunning; const bool initiallyQuiet = !canEvidenceSeen_; - const bool safeguard = rpmMode && !qualified && !initiallyQuiet; + const bool loopEnabled = cfg.ambient.enabled && cfg.startupAnimation != 0; + const bool safeguard = (rpmMode || loopEnabled) && !qualified && !initiallyQuiet; - // Continuous idle animation vs qualified RPM shift light arbitration - if (safeguard || !qualified || !decoded) { - rpmActive_ = false; - rpmStabilizeStartMs_ = 0; - } else if (!running) { - // Engine stopped (0 RPM) - rpmActive_ = false; - rpmStabilizeStartMs_ = 0; - } else if (!cfg.ambient.enabled) { - // Continuous idle animation disabled: shift lights have full running priority + if (rpm.staleTransitions != rpmStaleTransitions_) rpmStabilizing_ = false; + rpmStaleTransitions_ = rpm.staleTransitions; + if (!loopEnabled) { + rpmActive_ = qualified && running; + rpmStabilizing_ = false; + } else if (!qualified || !input.canHealthy) { + // Keep an established takeover latched across faults/dropouts, but + // require a new uninterrupted run of low RPM samples before resuming. + rpmStabilizing_ = false; + } else if (rpm.rpm >= cfg.ambient.takeoverRpm) { rpmActive_ = true; - rpmStabilizeStartMs_ = 0; - } else { - // Continuous idle animation enabled with hysteresis & stabilization - if (!rpmActive_) { - if (rpm.rpm >= cfg.ambient.takeoverRpm) { - rpmActive_ = true; - rpmStabilizeStartMs_ = 0; - } - } else { - if (rpm.rpm >= cfg.ambient.resumeRpm) { - rpmStabilizeStartMs_ = 0; // Spike or fluctuation above resume: cancel stabilization - } else { - if (rpmStabilizeStartMs_ == 0) { - rpmStabilizeStartMs_ = nowMs; - } else if (uint32_t(nowMs - rpmStabilizeStartMs_) >= cfg.ambient.stabilizationMs) { - rpmActive_ = false; - rpmStabilizeStartMs_ = 0; - } - } + rpmStabilizing_ = false; + } else if (!stopped && rpm.rpm >= cfg.ambient.resumeRpm) { + rpmStabilizing_ = false; + } else if (rpmActive_) { + if (!rpmStabilizing_) { + rpmStabilizeStartMs_ = nowMs; + rpmStabilizing_ = true; + } + if (uint32_t(nowMs - rpmStabilizeStartMs_) >= cfg.ambient.stabilizationMs) { + rpmActive_ = false; + rpmStabilizing_ = false; } } - const bool safeIdle = initiallyQuiet || stopped || (cfg.ambient.enabled && qualified && running && !rpmActive_); - const bool liveRpm = rpmMode && qualified && running && (!cfg.ambient.enabled || rpmActive_); + const bool safeIdle = qualified && !rpmActive_ && (stopped || loopEnabled); + const bool liveRpm = rpmMode && qualified && running && rpmActive_; const uint32_t bootElapsed = nowMs - startupStartMs_; startupComplete_ |= !cfg.bootEnabled || cfg.startupAnimation == 0 || bootElapsed >= cfg.startupDurationMs || (running && rpmActive_) || input.testRpmActive; - animationEligible_ = input.canHealthy && cfg.isPowerOn && safeIdle && - !input.feedbackActive && !input.testRpmActive && !input.authWindowOpen; + const bool animationAvailable = input.canHealthy && cfg.isPowerOn && + !input.feedbackActive && !input.testRpmActive && !input.otaBusy; + const bool playLoop = loopEnabled && safeIdle && animationAvailable; + // The commissioning window can coexist with idle playback. Explicit + // previews retain the stricter authorization and idle checks. + animationEligible_ = animationAvailable && (initiallyQuiet || safeIdle) && !input.authWindowOpen; ambientStatus_ = AmbientStatus::Off; - if (cfg.ambient.enabled && cfg.isPowerOn) { - if (!input.canHealthy || safeguard) { + if (loopEnabled && cfg.isPowerOn) { + if (!input.canHealthy || safeguard || input.otaBusy) { ambientStatus_ = AmbientStatus::SuppressedBySafety; - } else if (running && rpmActive_) { + } else if (rpmActive_) { ambientStatus_ = AmbientStatus::PausedByRpm; - } else if (animationEligible_) { - ambientStatus_ = AmbientStatus::Playing; } else { ambientStatus_ = AmbientStatus::Waiting; } @@ -329,38 +322,34 @@ bool LedEffectEngine::update(uint32_t nowMs, const PulseShiftConfig& cfg, const bool warning = renderRpmBar(nowMs, cfg, rpm.rpm, false); activeLayer_ = warning ? LedActiveLayer::Warning : (verifiedBar ? LedActiveLayer::RpmBar : LedActiveLayer::ProvisionalRpm); - } else if (input.authWindowOpen && !engineWasRunning_) { + } else if (safeguard) { + activeLayer_ = LedActiveLayer::SafeguardBlank; + setAllPixels(RgbColor{}); + } else if (input.authWindowOpen && !engineWasRunning_ && !playLoop && !input.otaBusy) { activeLayer_ = LedActiveLayer::Commissioning; const uint32_t phase = nowMs % 1000; const uint32_t level = phase < 500 ? phase : 1000 - phase; setAllPixels(scaleColor(RgbColor{0, 255, 255}, static_cast(level * 255 / 500))); - } else if (safeguard) { - activeLayer_ = LedActiveLayer::SafeguardBlank; - setAllPixels(RgbColor{}); } else if (animationEligible_ && input.previewPattern != 0) { activeLayer_ = LedActiveLayer::AnimationPreview; - renderAnimation(input.previewPattern, input.previewDurationMs, input.previewElapsedMs, cfg, false); - } else if (!startupComplete_ && safeIdle) { - activeLayer_ = LedActiveLayer::Startup; - renderAnimation(cfg.startupAnimation, cfg.startupDurationMs, bootElapsed, cfg, false); - } else if (cfg.ambient.enabled && animationEligible_) { - activeLayer_ = LedActiveLayer::Ambient; + renderAnimation(input.previewPattern, input.previewDurationMs, input.previewElapsedMs, cfg); + } else if (playLoop) { + activeLayer_ = LedActiveLayer::StartupLoop; ambientStatus_ = AmbientStatus::Playing; - if (previous != LedActiveLayer::Ambient || ambientPattern_ != cfg.ambient.pattern || - ambientCycleMs_ != cfg.ambient.cycleMs) { - ambientPhaseMs_ = 0; - ambientPattern_ = cfg.ambient.pattern; - ambientCycleMs_ = cfg.ambient.cycleMs; - ambientLastMs_ = nowMs; + if (previous != LedActiveLayer::StartupLoop || loopPattern_ != cfg.startupAnimation || + loopCycleMs_ != cfg.startupDurationMs) { + loopPhaseMs_ = 0; + loopPattern_ = cfg.startupAnimation; + loopCycleMs_ = cfg.startupDurationMs; } else { - const uint32_t elapsed = nowMs - ambientLastMs_; - if (ambientCycleMs_ > 0) { - ambientPhaseMs_ = static_cast((static_cast(ambientPhaseMs_) + elapsed) % ambientCycleMs_); - } - ambientLastMs_ = nowMs; + const uint32_t elapsed = nowMs - loopLastMs_; + loopPhaseMs_ = (loopPhaseMs_ + elapsed % loopCycleMs_) % loopCycleMs_; } - ambientLastMs_ = nowMs; - renderAnimation(ambientPattern_, ambientCycleMs_, ambientPhaseMs_, cfg, true); + loopLastMs_ = nowMs; + renderAnimation(loopPattern_, loopCycleMs_, loopPhaseMs_, cfg); + } else if (!startupComplete_ && (initiallyQuiet || safeIdle) && !input.otaBusy) { + activeLayer_ = LedActiveLayer::Startup; + renderAnimation(cfg.startupAnimation, cfg.startupDurationMs, bootElapsed, cfg); } else if (rpmMode) { activeLayer_ = qualified ? (verifiedBar ? LedActiveLayer::RpmBar : LedActiveLayer::ProvisionalRpm) : LedActiveLayer::SafeguardBlank; diff --git a/PulseShift/src/led_effects.h b/PulseShift/src/led_effects.h index f716d96..f3e1b87 100644 --- a/PulseShift/src/led_effects.h +++ b/PulseShift/src/led_effects.h @@ -24,7 +24,7 @@ enum class LedActiveLayer : uint8_t { Decorative = 8, // P7 manual effect Warning = 9, // shift warning overlay (reported as its own layer) ProvisionalRpm = 10, // Unverified diagnostic preview - Ambient = 11, + StartupLoop = 11, AnimationPreview = 12 }; @@ -39,6 +39,7 @@ struct LedFrameInput { uint8_t previewPattern = 0; uint16_t previewDurationMs = 0; uint32_t previewElapsedMs = 0; + bool otaBusy = false; }; class LedEffectEngine { @@ -63,7 +64,7 @@ class LedEffectEngine { private: void renderAnimation(uint8_t pattern, uint32_t dur, uint32_t elapsed, - const PulseShiftConfig& cfg, bool ambient); + const PulseShiftConfig& cfg); void renderEffect(uint32_t nowMs, const PulseShiftConfig& cfg); bool renderRpmBar(uint32_t nowMs, const PulseShiftConfig& cfg, uint16_t rpm, bool benchTest); void resetRpmLatches(); @@ -81,15 +82,17 @@ class LedEffectEngine { uint32_t startupStartMs_ = 0; bool canEvidenceSeen_ = false; bool engineWasRunning_ = false; - uint32_t ambientLastMs_ = 0; - uint16_t ambientPhaseMs_ = 0; - uint16_t ambientCycleMs_ = 0; - uint8_t ambientPattern_ = 0; + uint32_t loopLastMs_ = 0; + uint16_t loopPhaseMs_ = 0; + uint16_t loopCycleMs_ = 0; + uint8_t loopPattern_ = 0; AmbientStatus ambientStatus_ = AmbientStatus::Off; bool animationEligible_ = false; bool barFromBenchTest_ = false; bool rpmActive_ = false; + bool rpmStabilizing_ = false; uint32_t rpmStabilizeStartMs_ = 0; + uint32_t rpmStaleTransitions_ = 0; // Per-LED hysteresis latch: LED i stays lit until rpm falls below // thresholds[i] - hysteresis, preventing flicker around a threshold. diff --git a/PulseShift/src/lighting_setup.h b/PulseShift/src/lighting_setup.h index ac8cf6a..22a5cf9 100644 --- a/PulseShift/src/lighting_setup.h +++ b/PulseShift/src/lighting_setup.h @@ -75,6 +75,8 @@ struct RpmMapping { }; struct AmbientAnimation { + // Since firmware 2.6.1 this enables the selected startup animation loop. + // Preserve the old independent pattern and duration for older clients and rollback. bool enabled = false; uint8_t pattern = 1; uint16_t cycleMs = 2000; diff --git a/PulseShift/src/ota_manager.cpp b/PulseShift/src/ota_manager.cpp index 8ab5be7..b2ad316 100644 --- a/PulseShift/src/ota_manager.cpp +++ b/PulseShift/src/ota_manager.cpp @@ -7,11 +7,9 @@ #include #include #include -#include -#include +#include #elif defined(PULSESHIFT_USE_MBEDTLS) -#include -#include +#include #include "esp_ota_ops.h" #include "esp_partition.h" #elif defined(_WIN32) @@ -118,7 +116,7 @@ static void sha256_transform(uint32_t state[8], const uint8_t data[64]) { state[4] += e; state[5] += f; state[6] += g; state[7] += h; } -// Cryptographic signature verification using mbedtls (ESP32/Linux) or Windows CNG +// Cryptographic signature verification using PSA Crypto (ESP32/Linux) or Windows CNG. static bool verifyEcdsaP256Signature(const uint8_t* pubKeySec1, size_t pubKeyLen, const uint8_t* sha256Digest, const uint8_t* rawSig, size_t sigLen) { @@ -126,31 +124,18 @@ static bool verifyEcdsaP256Signature(const uint8_t* pubKeySec1, size_t pubKeyLen if (pubKeySec1[0] != 0x04) return false; #if defined(ARDUINO) || defined(PULSESHIFT_USE_MBEDTLS) - mbedtls_ecp_group grp; - mbedtls_ecp_group_init(&grp); - mbedtls_ecp_point Q; - mbedtls_ecp_point_init(&Q); - mbedtls_mpi r, s; - mbedtls_mpi_init(&r); - mbedtls_mpi_init(&s); - - bool ok = false; - if (mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256R1) == 0) { - if (mbedtls_ecp_point_read_binary(&grp, &Q, pubKeySec1, pubKeyLen) == 0) { - if (mbedtls_mpi_read_binary(&r, rawSig, 32) == 0 && - mbedtls_mpi_read_binary(&s, rawSig + 32, 32) == 0) { - if (mbedtls_ecdsa_verify(&grp, sha256Digest, 32, &Q, &r, &s) == 0) { - ok = true; - } - } - } - } - - mbedtls_mpi_free(&r); - mbedtls_mpi_free(&s); - mbedtls_ecp_point_free(&Q); - mbedtls_ecp_group_free(&grp); - return ok; + if (psa_crypto_init() != PSA_SUCCESS) return false; + constexpr psa_algorithm_t algorithm = PSA_ALG_ECDSA(PSA_ALG_SHA_256); + psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; + psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)); + psa_set_key_bits(&attributes, 256); + psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH); + psa_set_key_algorithm(&attributes, algorithm); + mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT; + if (psa_import_key(&attributes, pubKeySec1, pubKeyLen, &key) != PSA_SUCCESS) return false; + const bool verified = psa_verify_hash(key, algorithm, sha256Digest, 32, rawSig, sigLen) == PSA_SUCCESS; + psa_destroy_key(key); + return verified; #elif defined(_WIN32) BCRYPT_ALG_HANDLE hAlg = NULL; BCRYPT_KEY_HANDLE hKey = NULL; diff --git a/PulseShift/src/rpm_candidate.cpp b/PulseShift/src/rpm_candidate.cpp index 3926f89..cfb6457 100644 --- a/PulseShift/src/rpm_candidate.cpp +++ b/PulseShift/src/rpm_candidate.cpp @@ -173,7 +173,7 @@ bool RpmCandidateMonitor::ingest(const CanFrame& frame, uint32_t nowMs) { rawValue16_ = extracted; // Count a signal dropout: this frame arrives after the freshness window // already expired, so RPM rendering would have been blanked in between. - if (hasUpdate_ && uint32_t(nowMs - lastUpdateMs_) > freshnessTimeoutMs_) { + if (hasUpdate_ && uint32_t(nowMs - lastUpdateMs_) >= freshnessTimeoutMs_) { ++staleTransitions_; } lastUpdateMs_ = nowMs; @@ -273,7 +273,11 @@ LiveRpmSnapshot RpmCandidateMonitor::snapshot(uint32_t nowMs) const { if (s.fresh) { s.rpm = estimatedRpm(nowMs); - s.valid = (rawValue16_ > 0) && s.rpm <= settings_.maxRpm && validMultiplier(settings_.multiplier); + // Frame provenance comes from ingest/isFresh. A zero field is a sample, + // while a negative decoded estimate clamped to zero is not valid RPM. + const float estimate = static_cast(rawValue16_) * settings_.multiplier + settings_.offset; + s.valid = validMultiplier(settings_.multiplier) && estimate >= -0.5f && + s.rpm <= settings_.maxRpm; s.engineRunning = s.valid && s.rpm > 0; } else { s.rpm = 0; @@ -327,6 +331,7 @@ void RpmCandidateMonitor::printStatus(uint32_t nowMs, RPM_PRINTF("Multiplier : %.1f (offset %.1f, clamp %u)\r\n", settings_.multiplier, settings_.offset, (unsigned)settings_.maxRpm); RPM_PRINTF("Signal Fresh : %s\r\n", fresh ? "YES" : (hasUpdate_ ? "NO (STALE)" : "NO (WAITING)")); + RPM_PRINTF("Decoded RPM Valid: %s\r\n", snapshot(nowMs).valid ? "YES" : "NO"); if (hasUpdate_) { RPM_PRINTF("Last Update : %lu ms ago | Rate: %.1f Hz\r\n", diff --git a/PulseShift/src/startup_guard.cpp b/PulseShift/src/startup_guard.cpp new file mode 100644 index 0000000..178b0f7 --- /dev/null +++ b/PulseShift/src/startup_guard.cpp @@ -0,0 +1,45 @@ +// Copyright (c) 2026 Aritra Saha. All rights reserved. +#include "startup_guard.h" +#include + +#if defined(ARDUINO) +#include +#if !defined(PULSESHIFT_PROTECTED_BUILD) +#error "PulseShift needs its protected build. Run Build-PulseShift.cmd on Windows or Build-PulseShift.ps1." +#endif +#if !defined(CONFIG_IDF_TARGET_ESP32) || !defined(CONFIG_APP_ROLLBACK_ENABLE) || !defined(CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE) +#error "PulseShift requires the classic ESP32 and an Arduino SDK with application rollback enabled." +#endif +#endif + +extern "C" esp_err_t __real_nvs_flash_init(); +extern "C" esp_err_t __wrap_nvs_flash_init(); + +namespace { +esp_err_t result = ESP_FAIL; + +// Keep the link dependency on __real_nvs_flash_init even if someone sets the +// build marker without the linker wrap. An unwrapped image must fail to link. +esp_err_t (*volatile guardLink)(void) = &__wrap_nvs_flash_init; +} + +// Before setup(), initArduino() erases the NVS partition only on these two +// initialization errors. Leave the original status available to the sketch. +extern "C" esp_err_t __wrap_nvs_flash_init() { + result = __real_nvs_flash_init(); + if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) { + return ESP_FAIL; + } + return result; +} + +esp_err_t startupNvsStatus() { + (void)guardLink; + return result; +} + +// Override Arduino's weak hook before setup(). Only PulseShift's authenticated +// confirmation may mark a pending OTA slot valid after the boot self-test. +extern "C" bool verifyRollbackLater() { + return true; +} diff --git a/PulseShift/src/startup_guard.h b/PulseShift/src/startup_guard.h new file mode 100644 index 0000000..ac8db10 --- /dev/null +++ b/PulseShift/src/startup_guard.h @@ -0,0 +1,8 @@ +// Copyright (c) 2026 Aritra Saha. All rights reserved. +#pragma once + +#include + +// Result of the protected pre-sketch initialization. ESP_FAIL also means +// startup never called the guard. The sketch must not initialize NVS again. +esp_err_t startupNvsStatus(); diff --git a/PulseShift/src/storage_manager.cpp b/PulseShift/src/storage_manager.cpp index f221bbe..9130e12 100644 --- a/PulseShift/src/storage_manager.cpp +++ b/PulseShift/src/storage_manager.cpp @@ -29,51 +29,16 @@ bool StorageManager::isPartitionBlank() const { return true; // Every byte across the entire partition is verified 0xFF (virgin flash) } -bool StorageManager::begin(bool allowFormatIfCorrupt) { - // Step 1: Attempt non-destructive mount without formatting +bool StorageManager::begin(bool nvsAvailable) { + nvsAvailable_ = nvsAvailable; + // A failed mount never formats, even if the partition is new. mounted_ = LittleFS.begin(false, "/littlefs", 10, "spiffs"); - - if (!mounted_) { - // Check if the partition is genuinely blank (every byte across the entire partition is 0xFF). - // On a brand-new ESP32 out of the box, the partition is unformatted. - // Formatting virgin flash on first boot ensures persistent storage works out-of-the-box, - // while NEVER formatting an existing partition that contains data. - const bool isVirgin = isPartitionBlank(); - - if (isVirgin || allowFormatIfCorrupt) { - Serial.println(isVirgin - ? "[STORAGE] Blank unformatted partition verified (all 0xFF). Formatting LittleFS for first boot..." - : "[STORAGE] Formatting LittleFS as explicitly requested..."); - if (LittleFS.format()) { - mounted_ = LittleFS.begin(false, "/littlefs", 10, "spiffs"); - if (mounted_) { - Serial.println("[STORAGE] LittleFS formatted and mounted successfully."); - } else { - Serial.println("[STORAGE ERROR] LittleFS format succeeded, but mount failed."); - } - } else { - Serial.println("[STORAGE ERROR] LittleFS format failed."); - } - } else { - // Partition is NOT blank (contains non-0xFF bytes, such as existing recordings or corrupted filesystem). - // Automatic formatting is strictly suppressed to protect potentially recoverable data. - Serial.println("[STORAGE WARNING] LittleFS mount failed on partition containing data."); - Serial.println("[STORAGE WARNING] Automatic format suppressed to protect existing recordings."); - Serial.println("[STORAGE WARNING] Use Serial Monitor command 'CLEAR YES' via USB if you wish to wipe."); - } - } - mountFailed_ = !mounted_; - - if (mounted_) { - storageFull_ = (freeBytes() < MIN_FREE_BYTES); - } else { - storageFull_ = false; - } + storageFull_ = mounted_ && freeBytes() < MIN_FREE_BYTES; // Step 2: Initialize NVS preferences for monotonic boot & session tracking Preferences prefs; - if (prefs.begin("ps_diag", false)) { + if (nvsAvailable_ && prefs.begin("ps_diag", false)) { bootCount_ = prefs.getUInt("boot_cnt", 0) + 1; prefs.putUInt("boot_cnt", bootCount_); sessionId_ = prefs.getUInt("sess_id", 0); @@ -103,19 +68,12 @@ size_t StorageManager::freeBytes() { return (total > used) ? (total - used) : 0; } -bool StorageManager::format() { - if (mounted_) { - LittleFS.end(); - mounted_ = false; - } - if (LittleFS.format()) { - mounted_ = LittleFS.begin(false, "/littlefs", 10, "spiffs"); - mountFailed_ = !mounted_; - storageFull_ = false; - return mounted_; - } - mountFailed_ = true; - return false; +bool StorageManager::initializeBlank() { + if (mounted_ || !isPartitionBlank()) return false; + mounted_ = LittleFS.format() && LittleFS.begin(false, "/littlefs", 10, "spiffs"); + mountFailed_ = !mounted_; + storageFull_ = mounted_ && freeBytes() < MIN_FREE_BYTES; + return mounted_; } File StorageManager::open(const char* path, const char* mode) { @@ -149,7 +107,7 @@ size_t StorageManager::size(const char* path) { uint32_t StorageManager::incrementBootCount() { Preferences prefs; - if (prefs.begin("ps_diag", false)) { + if (nvsAvailable_ && prefs.begin("ps_diag", false)) { bootCount_ = prefs.getUInt("boot_cnt", 0) + 1; prefs.putUInt("boot_cnt", bootCount_); prefs.end(); @@ -159,7 +117,7 @@ uint32_t StorageManager::incrementBootCount() { uint32_t StorageManager::nextSessionId() { Preferences prefs; - if (prefs.begin("ps_diag", false)) { + if (nvsAvailable_ && prefs.begin("ps_diag", false)) { sessionId_ = prefs.getUInt("sess_id", 0) + 1; prefs.putUInt("sess_id", sessionId_); prefs.end(); diff --git a/PulseShift/src/storage_manager.h b/PulseShift/src/storage_manager.h index 2f381e6..3fbad05 100644 --- a/PulseShift/src/storage_manager.h +++ b/PulseShift/src/storage_manager.h @@ -15,18 +15,17 @@ class StorageManager { return mgr; } - bool begin(bool allowFormatIfCorrupt = false); + bool begin(bool nvsAvailable = true); bool isMounted() const { return mounted_; } bool mountFailed() const { return mountFailed_; } bool isStorageFull() const { return storageFull_; } void setStorageFull(bool full) { storageFull_ = full; } - bool isPartitionBlank() const; size_t totalBytes(); size_t usedBytes(); size_t freeBytes(); - bool format(); + bool initializeBlank(); File open(const char* path, const char* mode); bool exists(const char* path); bool remove(const char* path); @@ -42,10 +41,12 @@ class StorageManager { private: StorageManager() = default; ~StorageManager() = default; + bool isPartitionBlank() const; bool mounted_ = false; bool mountFailed_ = false; bool storageFull_ = false; + bool nvsAvailable_ = false; uint32_t bootCount_ = 0; uint32_t sessionId_ = 0; }; diff --git a/README.md b/README.md index fbd713e..6e8be09 100644 --- a/README.md +++ b/README.md @@ -63,13 +63,12 @@ For complete electrical schematics, noise filtering, and circuit protection, see ## Quick Start (Windows / Arduino) -1. Install Arduino CLI with Arduino-ESP32 **3.3.12** (ESP-IDF 5.5.5) and - `NimBLE-Arduino` **2.3.8**. -2. Follow the [build instructions](docs/TESTING.md#1-build-the-firmware-with-arduino-cli) - for the **ESP32 DevKit V1** and the NVS startup guard. The default 4 MB - layout has two 1.25 MiB app slots and a separate LittleFS partition. -3. Use the Serial Monitor at **115200 baud** with CRLF line endings. -4. On an existing device, use an approved application-only update procedure +1. Clone the repository and double-click **Build-PulseShift.cmd**. It installs the pinned + toolchain in the checkout and builds and verifies the firmware. See the + [Windows build guide](docs/WINDOWS-BUILD.md) for Arduino ESP32 4.0.0, diagnostics and headless builds. +2. Use the Arduino IDE for editing or the Serial Monitor at **115200 baud** with CRLF line endings. + Compile with the repository entry point so the NVS startup guard is active before sketch code. +3. On an existing device, use an approved application-only update procedure with a verified backup. Preserve the bootloader, partition table, NVS, and LittleFS. diff --git a/docs/BLE-PROTOCOL.md b/docs/BLE-PROTOCOL.md index d2ccaea..8b1de99 100644 --- a/docs/BLE-PROTOCOL.md +++ b/docs/BLE-PROTOCOL.md @@ -486,7 +486,12 @@ cycle duration u16 and warning RPM u16. The entries after the header are min/max u16 for Automatic (mode 0), threshold u16 followed by size u8 for each Grouped entry (1), and one u16 per Individual pixel (2). Historical grouped mode (3) has no extra entries and uses the six base thresholds. The -maximum setup size is 207 bytes. +maximum setup size is 207 bytes for version 1. Version 2 (capability bit 24) +uses a 21-byte header with takeover RPM, resume RPM and stabilization time in +milliseconds as three additional u16 fields before the entries. Maximum size +is 213 bytes. Firmware 2.6.1 adds bit 25 to indicate that the enable flag and +AMBIENT_STATUS apply to the selected startup animation. The old independent +pattern and duration remain in the payload for compatibility. One authenticated, connection-bound upload is kept in RAM for up to 30 seconds. Disconnect clears it. Replayed or out-of-order starts, a stale base revision, @@ -506,5 +511,5 @@ custom map. New clients applying historical six-stage profiles may send `BEGIN_TRANSACTION [1]` to stage selection of the legacy map along with the other preset fields. Older transactions keep their original empty payload. -See [Strip setup, RPM mapping and ambient animation](LIGHTING-SETUP.md) for +See [Strip setup, RPM mapping and startup animation](LIGHTING-SETUP.md) for eligibility, migration and hardware validation. diff --git a/docs/LIGHTING-SETUP.md b/docs/LIGHTING-SETUP.md index aff3c16..4d52e2e 100644 --- a/docs/LIGHTING-SETUP.md +++ b/docs/LIGHTING-SETUP.md @@ -1,4 +1,4 @@ -# Strip setup, RPM mapping and ambient animation +# Strip setup, RPM mapping and startup animation ## Strip and RPM @@ -13,33 +13,17 @@ Logical LED 1 starts at the GPIO27 data-input end in Normal direction. Reverse s The Android phone preview simulates the draft thresholds and warning phases, including direction, brightness, active count and hysteresis. The optional controller bench test uses synthetic RPM for ten seconds with the controller's current mapping. The CAN decoder and separate calibration rules still control which live RPM indications qualify. -## Animation failure reproduced on 2.4.0 +## Startup animation and RPM takeover -The baseline used startup-duration bit 15 for continuous looping. Its pattern code already used modulo, and a configured loop had no total runtime limit. The renderer nevertheless used the same startup path for both purposes. With effect 5 selected, a persisted loop and zero CAN samples, `sampleQualified` was false, `rpmPriority` was true, the startup branch was skipped, and the next branch drew `SafeguardBlank`. Feeding fresh zero RPM re-entered the loop at the original boot clock phase. Letting the sample go stale immediately returned the strip to its blank safeguard. The same source path blocked a loop during active RPM and while a verified mode lacked its required calibration match. A host reproduction against merge commit `85fe474` verified missing → blank, fresh zero → animation, stale → blank. It also verified that 12 pixels lit in pairs under the first two RPM pixels' shared threshold. +Firmware 2.6.1 repeats the selected startup pattern and duration when its loop is enabled and qualified RPM is below takeover. The existing boot toggle controls the separate one-shot shown during the initial power-on window. The default takeover is 1,500 RPM. After takeover, playback resumes once qualified RPM stays below 1,200 RPM for 400 ms. Fresh decoded zero is a valid sample. In verified Shift Light mode, RPM also requires a matching calibration. Explicit provisional mode remains diagnostic. -The old completion latch could be set by a bench preview, but its loop conditional bypassed the latch. Changing animation ID or encoded duration restarted the same startup clock and could replay the one-shot after boot. The last phases of Sweep, Center Out and Strobe can look steady within a cycle. Their phases did wrap whenever the renderer was eligible. Android 1.2.0 preserved the old bit on the wire and queued saves in order, but its Startup panel mirrored configuration via local fields and a readback effect. A controller readback could select an older displayed value during edits. The replacement uses a single authoritative readback plus an explicitly unsaved form and sends the two animations together. - -## Renderer priority and timing - -1. A halted or unhealthy CAN controller displays the existing red fault blink. -2. Physical button acknowledgement flashes white, including with master power off. -3. Master lighting power off blanks all pixels. -4. An authorized synthetic RPM bench test has its existing finite lifetime. -5. Qualified running RPM in an RPM display mode preempts boot and ambient immediately. The verified shift-light effect still requires a matching calibration record. The provisional mode remains diagnostic. -6. Physical commissioning may pulse cyan while no engine-running evidence is outstanding. When running RPM has been observed, missing RPM preserves the safeguard. -7. In an RPM mode, invalid or unqualified RPM after CAN evidence shows the existing blank safeguard. CAN evidence remains latched across BLE disconnect and decoder refresh until reboot. -8. A requested animation preview runs once if idle and eligible. A higher layer cancels it. -9. The configured boot animation plays only during its initial time window. Running RPM and an authorized bench test end it early. -10. Ambient runs continuously after boot when power is on, CAN hardware is healthy, and either the controller has seen no CAN traffic since boot or fresh, valid RPM confirms zero. In verified RPM mode a zero reading must also satisfy calibration qualification. Boot, commissioning, feedback and owner previews may temporarily occupy the strip. A stopped sample becoming stale removes idle eligibility even if the last value was zero. -11. A manual decorative effect remains available in its own mode. In RPM modes without valid RPM and without eligible ambient, the strip displays its RPM safeguard. - -Ambient starts a new cycle on entry after preemption. The cycle is advanced by unsigned elapsed time accumulated modulo the duration. This preserves phase across `millis()` rollover and avoids phase drift or a 10-second lifetime. The five patterns are exercised in virtual time through 10 minutes. The controller owns timing without BLE or an open Android app. +The loop has its own phase clock and uses the same frame renderer as the one-shot. It restarts a cycle after preemption and advances with unsigned elapsed time, including across millis rollover. Master power, CAN faults, explicit previews, shift warnings and OTA activity retain priority. With no CAN since boot, the optional one-shot can play and the loop waits for qualified RPM. Missing or stale RPM after earlier CAN activity triggers the safeguard. Playback does not require an open BLE connection. ## Migration and persistence -Schema 5 is stored at `ps_cfg/blob5`. It retains the original config fields and adds the versioned lighting setup bytes under one CRC-protected NVS record. Existing `blob4` and `blob` records remain readable and are left in place. The historical six thresholds and historical pixel assignment `floor(i*6/n)` are preserved, including strips with fewer than six physical pixels. The new editor materializes the occupied stages when saving an edited grouped map. An old loop maps to an enabled boot and ambient animation of the same pattern and period. An old one-shot maps to boot only. The first verified save writes schema 5. +The schema-6 record at `ps_cfg/blob6` preserves the version-2 lighting setup, and the verified save writes a schema-5 compatibility record at `ps_cfg/blob5`. Existing `blob4` and `blob` records remain readable. The previous ambient enable flag and RPM thresholds control the startup loop. The independent ambient pattern and duration stay in the stored record for older firmware. An older combined startup setting retains its loop flag and selected pattern. Owner credentials, calibration binding, CAN capture files and diagnostic storage stay in their existing namespaces and partitions. -An extension upload validates the whole candidate and commits and rereads the NVS record before publishing it as active. NVS commit success followed by readback failure leaves the controller RAM configuration unchanged and reports an unverified save. Reconnect and inspect the persisted state before retrying. On boot a corrupt schema-5 record can fall back to an intact historical record. An old firmware image ignores schema 5 and sees its previous schema-4 or older settings. Owner credentials, calibration binding, CAN capture files and diagnostic storage are outside the migration. No storage erase is used. +A lighting upload applies only after complete validation, commit and verified readback. A failed verification leaves RAM unchanged and reports an unverified save. Reconnect and inspect the persisted revision before retrying. ## ESP32 RMT and power @@ -54,6 +38,6 @@ GPIO27 is data only. At 5 V use a suitable 3.3 V to 5 V logic buffer, common gro - Record controller/phone versions and pre-update NVS, calibration and capture status. Use the existing signed OTA procedure and retain previous backups. - Exercise six, 12 and 64 physical pixels on a bench, plus the intermediate lengths where available. Capture GPIO27 and first-pixel DIN under BLE traffic, log recording and configuration writes. Check data pulse widths, reset low, final pixel, refresh behavior, output stalls and voltage drop at full white. - On a safely isolated controller verify Normal and Reverse, a shorter active segment, warning override, and a 12-entry individual mapping. Check 12 independent activations using synthetic RPM, then repeat for automatic and the 3/3/2/2/1/1 group counts. -- Confirm the running count stays stable until reboot. Save and power-cycle, then compare the full snapshot and verify the driver uses the saved count. Check boot and ambient settings independently. -- Leave each ambient pattern running with BLE disconnected for over ten minutes. Exercise fresh zero, live RPM, loss during running, stale zero, unrelated CAN traffic after quiet startup, true CAN fault, and power-off. Check commissioning and preview priority with an authorized owner session. +- Confirm the running count stays stable until reboot. Save and power-cycle, then compare the full snapshot and verify the driver uses the saved count. Check the one-shot and loop settings after reboot. +- Run the [startup loop acceptance procedure](STARTUP-LOOP-ACCEPTANCE.md). - Install the APK over the existing debug app and check owner access, preset restoration, BLE reconnection and service lifecycle. Interrupt a configuration upload, reconnect and inspect the full snapshot. Check simulated RPM remains separate from telemetry and that the installed controller remains receive-only. diff --git a/docs/OTA-BENCH-TEST-PLAN.md b/docs/OTA-BENCH-TEST-PLAN.md index 69de25f..b0bfc5a 100644 --- a/docs/OTA-BENCH-TEST-PLAN.md +++ b/docs/OTA-BENCH-TEST-PLAN.md @@ -23,7 +23,7 @@ Perform all OTA tests on a dedicated test bench before flashing or deploying on - **USB-UART Interface:** Connected to PC for continuous diagnostic serial capture at 115200 baud. ### 1.2 Bootloader and Partition Verification -The production firmware relies on the standard ESP32 dual-OTA partition scheme (`default.csv`): +The production firmware uses the checked-in ESP32 dual-OTA [partition table](../PulseShift/partitions.csv): - `bootloader.bin`: `0x1000`. The build uses Arduino-ESP32 3.3.12 and ESP-IDF 5.5.5 with app rollback enabled. The installed bootloader still requires separate verification. - `partitions.bin`: `0x8000` (NVS at `0x9000`, otadata at `0xe000`, `app0` at `0x10000`, `app1` at `0x150000`, `spiffs` at `0x290000`) - `boot_app0.bin`: `0xe000` (Initial otadata pointing to active `app0`) @@ -51,13 +51,8 @@ The PulseShift OTA pipeline enforces cryptographic image authenticity using NIST Keep the existing trust anchor and signing key in place. ### 2.2 Compilation and Signing Workflow -1. Compile the firmware binary: - ```bash - arduino-cli compile --fqbn esp32:esp32:esp32doit-devkit-v1 --build-property "compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init" PulseShift - ``` - The linker option guards the installed NVS partition against Arduino-ESP32's - automatic erase on NVS initialization errors. The same option is required for - production and headless builds. +1. Compile and verify the firmware with the [protected build entry point](WINDOWS-BUILD.md). + Bootloader and partition files are build evidence for an application-only update. 2. Sign the binary and attach the 76-byte `PSOT` authentication trailer: ```bash uv run --with cryptography python tools/sign_firmware.py sign \ @@ -161,12 +156,10 @@ The PulseShift OTA pipeline enforces cryptographic image authenticity using NIST ### Scenario 5: Intentional First-Boot Failure and Automatic Rollback - **Objective:** Verify hardware rollback when a newly flashed image fails its startup self-test. - **Steps:** - 1. Build firmware with the boot-failure fault injection flag: - ```bash - arduino-cli compile --fqbn esp32:esp32:esp32doit-devkit-v1 \ - --build-property "compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init" \ - --build-property "compiler.cpp.extra_flags=-DPULSESHIFT_TEST_FORCE_BOOT_FAIL=1" \ - PulseShift + 1. Copy the sketch to a separate directory still named `PulseShift` and define + `PULSESHIFT_TEST_FORCE_BOOT_FAIL` as `1` in its `UserConfig.h`. Build it to a dedicated test directory: + ```powershell + ./Build-PulseShift.ps1 -SketchDirectory C:/bench/PulseShift -BuildDirectory C:/bench/rollback-test ``` 2. Sign the binary with `tools/sign_firmware.py`. 3. Upload the binary via Android companion app OTA. @@ -216,7 +209,7 @@ metadata and logs. ## 5. Arduino-ESP32 deferred OTA confirmation check -Arduino-ESP32 core 3.3.12 invokes a weak `verifyRollbackLater()` hook before +Both supported Arduino-ESP32 cores invoke a weak `verifyRollbackLater()` hook before the sketch's `setup()`. Without an override, the core can immediately mark a new OTA image VALID, bypassing the product's 120-second owner-confirmation gate. PulseShift now provides a strong C-linkage override returning `true`, leaving diff --git a/docs/STARTUP-LOOP-ACCEPTANCE.md b/docs/STARTUP-LOOP-ACCEPTANCE.md new file mode 100644 index 0000000..c9a6fc2 --- /dev/null +++ b/docs/STARTUP-LOOP-ACCEPTANCE.md @@ -0,0 +1,19 @@ +# Startup loop acceptance + +## Configuration migration + +Firmware 2.6.1 uses the saved idle-animation enable flag and RPM thresholds to repeat the selected startup pattern and duration. Older independent ambient pattern and duration fields stay in the lighting setup and NVS for compatibility. If the old Ambient pattern was Wave and Startup was Sweep, an enabled idle setting now repeats Sweep. Older Android clients can still transfer the existing layout. The updated app uses the controller capability flag to show the single loop setting. It labels the independent setting **Legacy Ambient Animation** on firmware 2.6.0. The one-shot boot setting continues to control playback before RPM is known. + +Fresh, accepted, plausible decoded RPM qualifies for playback. Verified Shift Light mode also requires a matching calibration. When the controller has seen CAN traffic and RPM becomes unqualified, the loop and RPM display go dark. A cold boot without any CAN traffic may play the configured one-shot and then wait for RPM. Qualified zero starts the loop when idle, or starts the 400 ms resume interval after takeover. A CAN fault, master lighting off, or OTA operation suppresses the loop. Owner authentication remains required for configuration writes and previews. Saved playback runs without an active BLE session. + +## Stationary controller and motorcycle or isolated CAN bench + +1. Record the candidate SHA-256, board package, controller firmware, OTA slot state, partition layout, existing NVS revision, and any retained log counts. Back up the existing settings and capture before a separately authorized app-only install. Keep the installed bootloader and partition table. Follow the [OTA bench plan](OTA-BENCH-TEST-PLAN.md) for the transfer and confirmations. +2. Open **Lighting → Startup** in Android, authenticate as owner, select **Sweep**, and set a clearly visible duration such as 2,000 ms. Enable **Loop Startup Animation Until RPM Takeover** and save. Set master lighting on and choose verified Shift Light mode with a matching calibration. Set the first shift-light stage no higher than 1,500 RPM so the bar is visible at takeover. +3. Record `CONFIG STATUS`, `RPM STATUS`, and `LED STATUS` at 115200 baud. Require flash match and the requested pattern, thresholds, direction, and installed/active LED counts. While feeding fresh accepted zero-RPM frames and then holding about 1,000 RPM, require `STARTUP_LOOP` and visible Sweep cycles. Compare the calculated and RMT-confirmed output while watching the actual strip. +4. Disconnect Bluetooth and keep RPM frames fresh for at least 30 minutes. Observe repeated, identical Sweep cycles at the start, midpoint, and finish. Verify at least one uninterrupted observation across multiple cycle boundaries. Reconnect, read the unchanged settings, restart the controller, and verify the saved values and playback again. +5. Raise RPM to 1,500 and verify immediate bar takeover. Exercise the configured warning. Drop to exactly 1,200 and confirm the loop stays paused. Hold below 1,200 for at least 400 ms and verify Sweep restarts. Repeat with valid zero and a brief excursion to 1,200 during stabilization. +6. Stop CAN RPM frames while the bar is active. Verify `SAFEGUARD_BLANK` after the freshness timeout, including with other CAN traffic still present. It must not animate until qualified readings return and the resume condition is satisfied. Repeat with a cold boot and no CAN, an unmatched decoder, and a controlled CAN controller fault on the bench. Keep the PulseShift CAN transmitter isolated throughout. +7. Repeat at 6, 12, 24, and 64 LEDs with the appropriate installed count. Confirm reverse direction and inactive-pixel blanking. Exercise master power, an authorized preview, the physical commissioning window, BLE loss, and OTA preflight while stationary. Record video or timed observations alongside serial output, firmware digest, and controller conditions. + +If Settings shows the saved revision and `CONFIG STATUS` reports the enabled loop but the strip does not play, check `RPM STATUS` and `LED STATUS` for an arbitration or driver condition. A draft-only setting or revision mismatch points to the BLE save and readback path. A correct `STARTUP_LOOP` and RMT completion with a dark strip requires a physical output check. diff --git a/docs/TESTING.md b/docs/TESTING.md index e05f2c7..b3e13fc 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -2,19 +2,12 @@ This guide describes verification testing for PulseShift: interactive Arduino Serial Monitor diagnostic commands and automated regression test suites. -## 1. Build the firmware with Arduino CLI +## 1. Build the firmware -Install Arduino-ESP32 3.3.12 and NimBLE-Arduino 2.3.8. Use the DevKit V1 -with its default 4 MB partition scheme. The link flag routes NVS startup errors -around Arduino-ESP32's automatic NVS erase path. - -```bash -arduino-cli compile --fqbn esp32:esp32:esp32doit-devkit-v1 --build-property "compiler.c.elf.extra_flags=-Wl,--wrap=nvs_flash_init" PulseShift -``` - -The same flag applies to a headless copy. For bench diagnostics, use the -Arduino Serial Monitor at 115200 baud. Firmware compilation and field -operation require neither Python nor WSL. +Use **Build-PulseShift.cmd** on Windows. See the [build guide](WINDOWS-BUILD.md) +for the pinned toolchains and `-Headless` option. The build validates the +linked NVS and rollback guards and the project partition binary. For bench +diagnostics, use the Arduino Serial Monitor at 115200 baud. ## 2. Interactive Serial Monitor Commands (115200 baud) @@ -44,7 +37,8 @@ operation require neither Python nor WSL. | `DUMP CANCEL` | Reset export cursor to Page 1 | Resets cursor | | `DUMP PAGE ` | Export specific page number n | `DUMP PAGE 3` | | `CLEAR` | Prompt with instructions to clear | Shows warning requiring `CLEAR YES` | -| `CLEAR YES` | Confirm erase and reinitialize | Formats storage and increments session ID | +| `CLEAR YES` | Confirm capture and current log deletion | Deletes those files and advances the capture session | +| `INIT STORAGE` | Provision LittleFS on blank flash | Only available through the diagnostic console and requires an entirely blank readable partition | The bench preview takes precedence over startup animation and owner commissioning. A CAN fault, button feedback or the master power switch can interrupt the diff --git a/docs/WINDOWS-BUILD.md b/docs/WINDOWS-BUILD.md new file mode 100644 index 0000000..f13025c --- /dev/null +++ b/docs/WINDOWS-BUILD.md @@ -0,0 +1,24 @@ +# Build PulseShift on Windows + +1. Clone or extract this repository to a local directory. +2. Double-click **Build-PulseShift.cmd**. The first build downloads Arduino CLI and the pinned Espressif and NimBLE packages into `.tools/arduino`. Allow several gigabytes for the toolchain. This entry point compiles and verifies the firmware without connecting to a board. +3. Open `build/esp32-3.3.12/production`. Use `PulseShift.ino.bin` as the application input for signing. `build-verification.json` records the linked startup checks, partition and bootloader hashes, and OTA size. Keep the generated bootloader, merged flash image and partition binary out of application-only updates. + +| Board package | NimBLE-Arduino | Use | +| --- | --- | --- | +| ESP32 3.3.12 | 2.3.8 | Default and application-only release builds | +| ESP32 4.0.0 | 2.5.2 | Supported builds and CI compatibility | + +To build with ESP32 4.0.0 from PowerShell, run `./Build-PulseShift.cmd -CoreVersion 4.0.0`. Add `-Headless` to compile without serial diagnostics. The default is the classic ESP32 DOIT DevKit V1 with the checked-in 4 MiB partition table. On Linux, CI runs the same PowerShell entry point with the pinned Arduino CLI 1.1.1 binary. + +Arduino IDE can edit the sketch and monitor a supported diagnostic build at 115200 baud. Use the repository entry point for compilation. Plain IDE Verify and Upload stop at the protected-build diagnostic. Keep the installed Arduino core and its `platform.txt` as supplied by Espressif. + +## Why the build entry point is required + +In both supported cores, `app_main()` calls `initArduino()` before launching the sketch task. `initArduino()` handles the rollback hook, then initializes NVS and can erase the NVS partition if initialization reports no free pages or an incompatible version. A guard in `setup()` would run after that erase path. [Core 3.3.12 startup](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/main.cpp#L89) · [Core 3.3.12 NVS and rollback](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/esp32-hal-misc.c#L311-L349) · [Core 4.0.0 startup](https://github.com/espressif/arduino-esp32/blob/4.0.0/cores/esp32/main.cpp#L103) · [Core 4.0.0 NVS and rollback](https://github.com/espressif/arduino-esp32/blob/4.0.0/cores/esp32/esp32-hal-misc.c#L309-L350) + +The vendor's `build_opt.h` response file is used by the C, C++ and assembly compile recipes. The final link recipe uses the platform linker properties and omits that file. The original sketch depended on a GNU linker wrapper and a direct IDE build could not resolve `__real_nvs_flash_init`. The maintained build supplies that linker option automatically, checks the actual `initArduino()` call targets in the ELF, and rejects builds without the guard. A separate dependency makes a build with the protection marker but without the linker wrap fail to link. [Core 3.3.12 platform recipes](https://github.com/espressif/arduino-esp32/blob/3.3.12/platform.txt#L132-L166) · [Core 4.0.0 platform recipes](https://github.com/espressif/arduino-esp32/blob/4.0.0/platform.txt#L142-L181) + +The guard preserves the original NVS status for diagnostics and prevents both core erase triggers. The strong `verifyRollbackLater()` hook keeps pending OTA confirmation under PulseShift's existing policy. Build verification checks the linked calls, rollback SDK options, the pinned bootloader build, the compiled partition hash and application size. The bootloader on a specific device still needs separate verification. [Espressif OTA and rollback](https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/ota.html#app-rollback) + +LittleFS startup mounts without formatting. A new blank device can be provisioned with `INIT STORAGE` over the diagnostic serial console. It refuses a mounted, unreadable, or nonblank partition. A headless build can use storage that has already been provisioned. Preserve and back up existing storage before any manual recovery. diff --git a/test/VERIFICATION.md b/test/VERIFICATION.md index 75b2ae9..67ff85a 100644 --- a/test/VERIFICATION.md +++ b/test/VERIFICATION.md @@ -8,7 +8,15 @@ bash test/run.sh Native C++ checks enable ASan, UBSan, and warnings treated as errors. -For firmware compilation, use Arduino IDE or Arduino CLI with ESP32 board support (esp32:esp32@3.3.12) as documented in [the README](../README.md). +For firmware compilation, use the repository's [protected firmware build](../docs/WINDOWS-BUILD.md). + +Set `PULSESHIFT_LED_TRACE` to a writable CSV path before running `bash test/run.sh` to record +frames verified by the host LED suite. `pixels_rgb` is six uppercase hex characters per installed +pixel in physical strip order. `elapsed_ms` stays monotonic while `clock_ms` demonstrates 32-bit +wraparound. The numeric layers and loop states correspond to `LedActiveLayer` and `AmbientStatus`. +The trace includes a 30-minute Sweep timeline, the first three cycles for all other startup and +strip combinations, Color Chase laps, and RPM transition and safety events. The suite uses the +production animation renderer and CAN RPM decoder. Physical WS2812B transmission needs separate verification. ## Verification scope and hardware limits diff --git a/test/run.sh b/test/run.sh index 394bb4a..80689d3 100644 --- a/test/run.sh +++ b/test/run.sh @@ -13,6 +13,20 @@ mkdir -p "$BUILD_DIR" CXXFLAGS="-std=c++17 -Wall -Wextra -Werror -pedantic -g -fsanitize=address,undefined -fno-omit-frame-pointer" +# Exercise the production pre-sketch wrapper with the same GNU symbol rewrite +# as the target. A link without that rewrite must fail closed. +startup_sources=(PulseShift/src/startup_guard.cpp test/stubs/nvs_flash.cpp test/test_startup_guard.cpp) +g++ $CXXFLAGS -Itest/stubs -IPulseShift/src "${startup_sources[@]}" -Wl,--wrap=nvs_flash_init -o "$BUILD_DIR/test_startup_guard" +"$BUILD_DIR/test_startup_guard" +if g++ $CXXFLAGS -Itest/stubs -IPulseShift/src "${startup_sources[@]}" -o "$BUILD_DIR/unguarded" > "$BUILD_DIR/unguarded.log" 2>&1; then + echo 'Startup guard unexpectedly linked without GNU wrapping' >&2 + exit 1 +fi +grep -F '__real_nvs_flash_init' "$BUILD_DIR/unguarded.log" + +g++ $CXXFLAGS -Itest/stubs -IPulseShift/src PulseShift/src/storage_manager.cpp test/test_storage_startup.cpp -o "$BUILD_DIR/test_storage_startup" +"$BUILD_DIR/test_storage_startup" + # Core logic tests: config state machine, calibration binding, snapshot TLV # serialization, event pacing and serial parsing (pure C++, no Arduino stubs; # serial diagnostics are compiled out so no Serial symbol is referenced). @@ -38,7 +52,11 @@ g++ $CXXFLAGS \ PulseShift/src/rpm_candidate.cpp PulseShift/src/config_manager.cpp \ PulseShift/src/led_effects.cpp \ test/test_led_effects.cpp -o "$BUILD_DIR/test_led_effects" -"$BUILD_DIR/test_led_effects" +if [[ -n "${PULSESHIFT_LED_TRACE:-}" ]]; then + "$BUILD_DIR/test_led_effects" "$PULSESHIFT_LED_TRACE" +else + "$BUILD_DIR/test_led_effects" +fi # LedController tests: tri-state buffer architecture, transmission failure recovery, # periodic complete-frame refresh, mock driver assertions. @@ -63,7 +81,7 @@ g++ $CXXFLAGS \ -DPULSESHIFT_TEST_BUILD -DPULSESHIFT_SERIAL_DIAGNOSTICS=1 -DPULSESHIFT_USE_MBEDTLS \ -Itest/stubs -IPulseShift -IPulseShift/src \ PulseShift/src/ble_manager.cpp PulseShift/src/config_manager.cpp \ - PulseShift/src/rpm_candidate.cpp PulseShift/src/can_transport.cpp \ + PulseShift/src/rpm_candidate.cpp PulseShift/src/can_transport.cpp PulseShift/src/led_effects.cpp \ PulseShift/src/frame_log.cpp PulseShift/src/can_recorder.cpp \ PulseShift/src/storage_manager.cpp PulseShift/src/ota_manager.cpp \ test/test_ble_commands.cpp -lmbedcrypto -o "$BUILD_DIR/test_ble_commands" diff --git a/test/stubs/LittleFS.h b/test/stubs/LittleFS.h index 4f84229..6cfa050 100644 --- a/test/stubs/LittleFS.h +++ b/test/stubs/LittleFS.h @@ -3,11 +3,15 @@ class LittleFSFS : public fs::FS { public: + bool mountSucceeds = true; + unsigned formatCalls = 0; + bool mountAllowedFormat = false; bool begin(bool formatOnFail = false, const char* basePath = "/littlefs", uint8_t maxOpenFiles = 10, const char* partitionLabel = "spiffs") { - (void)formatOnFail; (void)basePath; (void)maxOpenFiles; (void)partitionLabel; - return true; + (void)basePath; (void)maxOpenFiles; (void)partitionLabel; + mountAllowedFormat |= formatOnFail; + return mountSucceeds; } - bool format() { return true; } + bool format() { ++formatCalls; mountSucceeds = true; return true; } }; inline LittleFSFS LittleFS; diff --git a/test/stubs/Preferences.h b/test/stubs/Preferences.h index 9d72d6d..aa9a7d1 100644 --- a/test/stubs/Preferences.h +++ b/test/stubs/Preferences.h @@ -8,7 +8,8 @@ // sizes, matching an unwritten flash on the host. class Preferences { public: - bool begin(const char* = nullptr, bool readOnly = false) { (void)readOnly; return true; } + inline static unsigned opens = 0; + bool begin(const char* = nullptr, bool readOnly = false) { (void)readOnly; ++opens; return true; } void end() {} bool clear() { return true; } uint32_t getUInt(const char*, uint32_t defaultValue) { return defaultValue; } diff --git a/test/stubs/esp_err.h b/test/stubs/esp_err.h new file mode 100644 index 0000000..bf15b70 --- /dev/null +++ b/test/stubs/esp_err.h @@ -0,0 +1,5 @@ +#pragma once + +using esp_err_t = int; +constexpr esp_err_t ESP_OK = 0; +constexpr esp_err_t ESP_FAIL = -1; diff --git a/test/stubs/esp_partition.h b/test/stubs/esp_partition.h index 59acc7f..0c06da2 100644 --- a/test/stubs/esp_partition.h +++ b/test/stubs/esp_partition.h @@ -2,9 +2,9 @@ #pragma once #include #include +#include -// Host test stub for esp_partition: no partition is ever found, so the -// blank-partition scan conservatively reports "not blank". +// Host test stub. The simulated LittleFS partition is absent by default. #define ESP_OK 0 #define ESP_FAIL -1 #define ESP_PARTITION_TYPE_APP 0 @@ -19,10 +19,21 @@ struct esp_partition_t { char label[16] = ""; }; -inline const esp_partition_t* esp_partition_find_first(uint32_t, uint32_t, const char*) { +inline esp_partition_t mockSpiffs{600, "spiffs"}; +inline bool mockSpiffsPresent = false; +inline bool mockSpiffsReadFails = false; +inline bool mockSpiffsDirtyTail = false; + +inline const esp_partition_t* esp_partition_find_first(uint32_t type, uint32_t subtype, const char*) { + if (mockSpiffsPresent && type == ESP_PARTITION_TYPE_DATA && subtype == ESP_PARTITION_SUBTYPE_DATA_SPIFFS) { + return &mockSpiffs; + } return nullptr; } -inline int esp_partition_read(const esp_partition_t*, size_t, void*, size_t) { - return ESP_FAIL; +inline int esp_partition_read(const esp_partition_t* part, size_t offset, void* data, size_t size) { + if (part != &mockSpiffs || mockSpiffsReadFails || offset + size > part->size) return ESP_FAIL; + memset(data, 0xff, size); + if (mockSpiffsDirtyTail && size && offset + size == part->size) static_cast(data)[size - 1] = 0; + return ESP_OK; } diff --git a/test/stubs/nvs_flash.cpp b/test/stubs/nvs_flash.cpp new file mode 100644 index 0000000..abcc3fd --- /dev/null +++ b/test/stubs/nvs_flash.cpp @@ -0,0 +1,9 @@ +#include "nvs_flash.h" + +esp_err_t mockNvsResult = ESP_FAIL; +unsigned mockNvsCalls = 0; + +extern "C" esp_err_t nvs_flash_init() { + ++mockNvsCalls; + return mockNvsResult; +} diff --git a/test/stubs/nvs_flash.h b/test/stubs/nvs_flash.h new file mode 100644 index 0000000..c44ddeb --- /dev/null +++ b/test/stubs/nvs_flash.h @@ -0,0 +1,6 @@ +#pragma once + +#include "esp_err.h" +constexpr esp_err_t ESP_ERR_NVS_NO_FREE_PAGES = 0x110d; +constexpr esp_err_t ESP_ERR_NVS_NEW_VERSION_FOUND = 0x1110; +extern "C" esp_err_t nvs_flash_init(); diff --git a/test/test_ble_commands.cpp b/test/test_ble_commands.cpp index 81e027b..c0c83e8 100644 --- a/test/test_ble_commands.cpp +++ b/test/test_ble_commands.cpp @@ -2,6 +2,7 @@ // authorization binding, staged transactions, calibration workflow and the // device control commands, all through the real BleManager dispatcher. #include "ble_manager.h" +#include "led_effects.h" #include "config_manager.h" #include "ota_manager.h" #include "rpm_candidate.h" @@ -1777,6 +1778,31 @@ static void test_lighting_setup_transfer() { CHECK(cfg.active().rpmMapping.thresholds[63] == 7500); CHECK(send(BLE_CFG_OP_SET_LED_THRESHOLD, {0, 0xE8, 3}).statusCode == BLE_CFG_STATUS_UNSUPPORTED); + // A verified, persisted lighting setup belongs to the controller. Dropping the + // BLE link and ending the auth window must leave the loop running in phase. + LedEffectEngine engine; + engine.reset(now); + const uint32_t loopStart = now; + CanFrame zero{}; + zero.id = candidate.decoderSettings().canId; + zero.dlc = 8; + auto render = [&](uint32_t elapsed) { + const uint32_t at = loopStart + elapsed; + CHECK(candidate.ingest(zero, at)); + LedFrameInput input; + input.canTrafficSeen = true; + input.authWindowOpen = cfg.isAuthWindowOpen(at); + engine.update(at, cfg.active(), candidate.snapshot(at), input); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + return engine.getPixel(0); + }; + const auto initial = render(0); + ble.testResetDisconnectedLink(); + CHECK(cfg.activeMatchesNvs() && cfg.activeRevision() == 2); + for (uint32_t elapsed = 100; elapsed < 2000; elapsed += 100) render(elapsed); + CHECK(render(2000) == initial); + cfg.triggerAuthWindow(now); + uint8_t old[512]{}, extended[512]{}; const size_t oldLen = cfg.serializeSnapshot(old, sizeof(old)); const size_t extLen = cfg.serializeSnapshot(extended, sizeof(extended), true); diff --git a/test/test_candidate_monitor.cpp b/test/test_candidate_monitor.cpp index 9e09203..70b5305 100644 --- a/test/test_candidate_monitor.cpp +++ b/test/test_candidate_monitor.cpp @@ -285,6 +285,24 @@ void test_stale_dropout_counting() { pass("staleTransitions counts real signal dropouts"); } +void test_decoded_zero_validity() { + RpmCandidateMonitor mon; + CHECK(!mon.snapshot(0).valid); + CHECK(!mon.ingest(make301Frame(0, 0), 50)); + CHECK(!mon.snapshot(50).valid); + CHECK(mon.ingest(make301Frame(0), 100)); + auto sample = mon.snapshot(100); + CHECK(sample.valid && sample.fresh && !sample.engineRunning && sample.rpm == 0); + CHECK(!mon.snapshot(350).valid); + mon.setOffset(-1000); + CHECK(mon.ingest(make301Frame(0), 400)); + CHECK(!mon.snapshot(400).valid); + mon.setOffset(1000); + sample = mon.snapshot(400); + CHECK(sample.valid && sample.engineRunning && sample.rpm == 1000); + pass("fresh zero is valid, a negative or missing estimate is not"); +} + } // namespace int main() { @@ -298,6 +316,7 @@ int main() { test_extended_can_id_support(); test_status_and_stream_formatting(); test_stale_dropout_counting(); + test_decoded_zero_validity(); std::printf("ALL PASS: %u cases, %u assertions\n", cases, assertions); return 0; diff --git a/test/test_config_nvs.cpp b/test/test_config_nvs.cpp index 1643048..daef6b0 100644 --- a/test/test_config_nvs.cpp +++ b/test/test_config_nvs.cpp @@ -173,6 +173,7 @@ int main() { cfg.begin(); CHECK(cfg.activeMatchesNvs() && cfg.runningLedCount() == 64 && cfg.active().rpmMapping.entries == 64); CHECK(cfg.active().rpmMapping.thresholds[63] == 7300 && !cfg.active().bootEnabled); + CHECK(cfg.active().startupAnimation == 3 && cfg.active().startupDurationMs == 2000); CHECK(cfg.active().ambient.enabled && cfg.active().ambient.pattern == 5 && cfg.active().ambient.cycleMs == 10000); CHECK(cfg.active().ambient.takeoverRpm == 1500 && cfg.active().ambient.resumeRpm == 1200 && cfg.active().ambient.stabilizationMs == 400); CHECK(cfg.active().rpmMultiplier == 40.0f && cfg.active().calFingerprint == old.calFingerprint); diff --git a/test/test_led_effects.cpp b/test/test_led_effects.cpp index 9ba7485..ed525e7 100644 --- a/test/test_led_effects.cpp +++ b/test/test_led_effects.cpp @@ -8,6 +8,26 @@ #define CHECK(x) do {++checks;if(!(x)){std::fprintf(stderr,"LED FAIL %d: %s\n",__LINE__,#x);std::exit(1);}}while(0) static unsigned checks=0; +static std::FILE* traceFile = nullptr; + +static void traceFrame(const char* scenario, uint32_t elapsed, uint32_t now, + const PulseShiftConfig& cfg, const LiveRpmSnapshot& rpm, + const LedFrameInput& input, const LedEffectEngine& engine) { + if (!traceFile) return; + std::fprintf(traceFile, "%s,%lu,%lu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,", + scenario, static_cast(elapsed), static_cast(now), + cfg.effect, cfg.startupAnimation, cfg.startupDurationMs, cfg.installedLedCount, + cfg.rpmMapping.activeCount(cfg.installedLedCount), cfg.ledDirection, cfg.brightness, + cfg.isPowerOn, input.canHealthy, rpm.raw, rpm.rpm, rpm.available, rpm.fresh, + rpm.valid); + std::fprintf(traceFile, "%u,%u,", static_cast(engine.activeLayer()), + static_cast(engine.ambientStatus())); + for (uint8_t i = 0; i < cfg.installedLedCount; ++i) { + const auto color = engine.getPixel(i); + std::fprintf(traceFile, "%02X%02X%02X", color.r, color.g, color.b); + } + std::fputc('\n', traceFile); +} static LiveRpmSnapshot freshVerifiedSnapshot(uint16_t rpm) { LiveRpmSnapshot s{}; @@ -22,6 +42,27 @@ static LiveRpmSnapshot freshVerifiedSnapshot(uint16_t rpm) { return s; } +static RpmCandidateMonitor verifiedMonitor() { + RpmCandidateMonitor monitor; + auto settings = monitor.decoderSettings(); + settings.byteWidth = 2; + settings.multiplier = 1; + monitor.applyDecoderSettings(settings, 0); + monitor.setCalibrationVerified(true); + return monitor; +} + +static LiveRpmSnapshot receiveRpm(RpmCandidateMonitor& monitor, uint32_t now, uint16_t rpm) { + CanFrame frame{}; + const auto settings = monitor.decoderSettings(); + frame.id = settings.canId; + frame.dlc = 8; + frame.data[settings.byteIndex] = rpm & 0xff; + frame.data[settings.byteIndex + 1] = rpm >> 8; + CHECK(monitor.ingest(frame, now)); + return monitor.snapshot(now); +} + // Configured as a verified six-stage bar: thresholds 1000..6000, warning 7000. static PulseShiftConfig verifiedBarConfig() { PulseShiftConfig cfg{}; @@ -738,72 +779,55 @@ static void test_zero_hysteresis_uses_exact_threshold() { } -static void ambient_eligibility_and_priority() { - LedEffectEngine engine; - engine.reset(0); - PulseShiftConfig cfg = verifiedBarConfig(); - cfg.effect = 5; - cfg.ambient = {true, 2, 1000}; - LedFrameInput input{}; - engine.update(100, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Startup); - engine.update(2000, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient && engine.isStartupComplete()); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - cfg.startupAnimation = 5; - engine.update(5000, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); // edits cannot restart boot - - input.canTrafficSeen = true; - engine.update(5100, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank && allBlack(engine)); - CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); - engine.update(5200, cfg, freshVerifiedSnapshot(4500), input); - CHECK(engine.activeLayer() == LedActiveLayer::ProvisionalRpm && countLit(engine) == 4); - CHECK(engine.ambientStatus() == AmbientStatus::PausedByRpm); - input.authWindowOpen = true; - engine.update(5300, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank && allBlack(engine)); - input.authWindowOpen = false; - engine.update(5400, cfg, freshVerifiedSnapshot(0), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - - cfg.isPowerOn = false; - engine.update(5500, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Off && allBlack(engine)); - input.canHealthy = false; - engine.update(5600, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Fault); - input.canHealthy = cfg.isPowerOn = true; - engine.update(5650, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank); - engine.update(5700, cfg, freshVerifiedSnapshot(0), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); -} - -static void all_ambient_patterns_keep_time() { +static void startup_loop_repeats_the_selected_animation() { for (uint8_t pattern = 1; pattern <= 5; ++pattern) { - for (uint8_t pixels : std::initializer_list{1, 6, 64}) { - LedEffectEngine engine; + for (uint8_t pixels : {6, 12, 24, 64}) { + LedEffectEngine loop; + LedEffectEngine oneShot; const uint32_t start = UINT32_MAX - 517; - engine.reset(start, pixels); + loop.reset(start, pixels); + oneShot.reset(start, pixels); + auto monitor = verifiedMonitor(); PulseShiftConfig cfg = verifiedBarConfig(); - cfg.bootEnabled = false; cfg.installedLedCount = pixels; - cfg.ambient = {true, pattern, 1000}; - RgbColor first[64]{}; + cfg.rpmMapping.activeLedCount = pixels - 2; + cfg.ledDirection = pixels % 4 == 0; + cfg.brightness = 173; + for (uint8_t zone = 0; zone < config::rpmStages; ++zone) { + cfg.ledColors[zone] = RgbColor{static_cast(50 + 20 * zone), 37, 61}; + } + cfg.startupAnimation = pattern; + cfg.startupDurationMs = 1100; + cfg.ambient = {true, static_cast(pattern % 5 + 1), 3000}; + auto bootCfg = cfg; + bootCfg.ambient.enabled = false; + + RgbColor reference[22][64]{}; bool changes = false; - engine.update(start, cfg, {}, {}); - for (uint8_t i = 0; i < pixels; ++i) first[i] = engine.getPixel(i); - for (uint32_t delta = 50; delta <= 601000; delta += 50) { - engine.update(start + delta, cfg, {}, {}); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); + for (uint32_t phase = 0; phase < cfg.startupDurationMs; phase += 50) { + oneShot.update(start + phase, bootCfg, {}, {}); + CHECK(oneShot.activeLayer() == LedActiveLayer::Startup); for (uint8_t i = 0; i < pixels; ++i) { - if (delta % 1000 == 0) CHECK(first[i] == engine.getPixel(i)); - else changes |= first[i] != engine.getPixel(i); + reference[phase / 50][i] = oneShot.getPixel(i); + changes |= reference[phase / 50][i] != reference[0][i]; } } CHECK(changes); + + // Run with no Android/BLE dependency for over 30 minutes, across millis rollover. + for (uint32_t elapsed = 0; elapsed <= 1801000; elapsed += 50) { + const auto rpm = receiveRpm(monitor, start + elapsed, elapsed < 550 ? 0 : 1000); + CHECK(rpm.available && rpm.fresh && rpm.valid); + loop.update(start + elapsed, cfg, rpm, {}); + CHECK(loop.activeLayer() == LedActiveLayer::StartupLoop); + CHECK(loop.ambientStatus() == AmbientStatus::Playing); + const auto& expected = reference[(elapsed % cfg.startupDurationMs) / 50]; + for (uint8_t i = 0; i < pixels; ++i) CHECK(loop.getPixel(i) == expected[i]); + if (elapsed <= 3300 || (pattern == 1 && pixels == 6 && elapsed % 100 == 0)) { + traceFrame("startup_loop", elapsed, start + elapsed, cfg, rpm, {}, loop); + } + } + CHECK(loop.isStartupComplete()); } } } @@ -894,10 +918,11 @@ static void effects_and_warning_scale_to_strip() { }; for (uint8_t animation = 1; animation <= 5; ++animation) { cfg.bootEnabled = false; - cfg.ambient = {true, animation, 2000}; + cfg.startupAnimation = animation; + cfg.ambient.enabled = true; cfg.effect = 0; for (uint32_t elapsed : {0u, 674u, 1300u, 1975u, 2674u}) { - renderBoth(animation * 3000 + elapsed, {}, LedActiveLayer::Ambient); + renderBoth(animation * 3000 + elapsed, freshVerifiedSnapshot(1000), LedActiveLayer::StartupLoop); } } cfg.ambient.enabled = false; @@ -930,260 +955,161 @@ static void effects_and_warning_scale_to_strip() { } } -static void test_continuous_idle_animation_full_regression() { +static void chase_laps_preserve_timing_and_direction() { + for (unsigned intensity = 1; intensity <= 255; ++intensity) { + CHECK(GAMMA_TABLE[intensity] >= GAMMA_TABLE[intensity - 1]); + } + CHECK(GAMMA_TABLE[0] == 0 && GAMMA_TABLE[255] == 255); + for (uint8_t pixels : {6, 12, 24, 64}) { + auto cfg = verifiedBarConfig(); + cfg.installedLedCount = pixels; + cfg.rpmMapping.activeLedCount = pixels - 2; + cfg.bootEnabled = false; + cfg.ledDirection = 1; + cfg.brightness = 160; + cfg.effect = 3; + cfg.effectSpeed = 50; + const RgbColor base{230, 115, 70}; + for (auto& color : cfg.ledColors) color = base; + const auto bright = scaleColor(scaleColorGamma(base, 255), cfg.brightness); + LedEffectEngine chase; + chase.reset(0, pixels); + const auto active = cfg.rpmMapping.activeCount(pixels); + for (uint32_t step = 0; step <= 2u * active; ++step) { + const uint32_t time = step * 200; + chase.update(time, cfg, {}, {}); + CHECK(chase.activeLayer() == LedActiveLayer::Decorative); + const auto head = pixels - 1 - step % active; + for (uint8_t pixel = 0; pixel < pixels; ++pixel) { + CHECK((chase.getPixel(pixel) == bright) == (pixel == head)); + } + CHECK(chase.getPixel(0) == RgbColor{} && chase.getPixel(1) == RgbColor{}); + traceFrame("color_chase", time, time, cfg, {}, {}, chase); + } + } +} + +static void startup_loop_rpm_and_safety() { LedEffectEngine engine; - engine.reset(0); - PulseShiftConfig cfg = verifiedBarConfig(); - cfg.effect = 4; // Verified RPM Bar + auto monitor = verifiedMonitor(); + auto cfg = verifiedBarConfig(); cfg.ambient.enabled = true; - cfg.ambient.pattern = 3; // Breathe - cfg.ambient.cycleMs = 2000; - cfg.ambient.takeoverRpm = 1500; - cfg.ambient.resumeRpm = 1200; - cfg.ambient.stabilizationMs = 400; - cfg.warningRpm = 7000; - cfg.warningPatternId = 0; // Flash - cfg.warningColor = RgbColor{255, 0, 0}; + cfg.bootEnabled = false; LedFrameInput input{}; - - // 1. Engine off from boot (0 RPM, initially quiet) - // Boot animation runs during startupDurationMs (2000ms) - engine.update(500, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Startup); - CHECK(!engine.isStartupComplete()); - - // Past boot animation, transitions to continuous idle Ambient animation - engine.update(2100, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - CHECK(engine.isStartupComplete()); - CHECK(!engine.isRpmActive()); - - // Loops indefinitely while engine off - engine.update(6000, cfg, {}, input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - - // 2. Continuous idle at 1000 RPM (CAN active, engine running) + const uint32_t start = UINT32_MAX - 999; + engine.reset(start); + + auto feed = [&](uint32_t elapsed, uint16_t rpm) { + input.canTrafficSeen = true; + const auto sample = receiveRpm(monitor, start + elapsed, rpm); + CHECK(sample.available && sample.fresh && sample.valid && sample.rpm == rpm); + CHECK(sample.engineRunning == (rpm != 0)); + engine.update(start + elapsed, cfg, sample, input); + traceFrame("rpm_arbitration", elapsed, start + elapsed, cfg, sample, input, engine); + }; + auto missing = [&](uint32_t elapsed) { + const auto sample = monitor.snapshot(start + elapsed); + engine.update(start + elapsed, cfg, sample, input); + traceFrame("rpm_arbitration", elapsed, start + elapsed, cfg, sample, input, engine); + CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank && allBlack(engine)); + }; + + missing(0); // No CAN since boot is unknown, even with looping enabled. + CHECK(engine.ambientStatus() == AmbientStatus::Waiting); input.canTrafficSeen = true; - engine.update(7000, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - CHECK(!engine.isRpmActive()); - - // 3. RPM transition from 1000 to 1499 RPM (below 1500 takeover) - engine.update(7100, cfg, freshVerifiedSnapshot(1200), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(!engine.isRpmActive()); - engine.update(7200, cfg, freshVerifiedSnapshot(1499), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(!engine.isRpmActive()); - - // 4. RPM reaches 1500 takeover threshold -> RPM shift lights take priority! - engine.update(7300, cfg, freshVerifiedSnapshot(1500), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); + missing(50); // Bus traffic without a qualified RPM source is also unknown. + CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); + input.authWindowOpen = true; + feed(100, 0); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + CHECK(!engine.animationEligible()); // Commissioning still disallows preview. + input.authWindowOpen = false; + feed(200, 1000); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + feed(300, 1499); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + feed(500, 1500); + CHECK(engine.activeLayer() == LedActiveLayer::RpmBar && countLit(engine) == 1); CHECK(engine.ambientStatus() == AmbientStatus::PausedByRpm); + feed(600, 7500); + CHECK(engine.activeLayer() == LedActiveLayer::Warning); + feed(700, 1100); CHECK(engine.isRpmActive()); - CHECK(countLit(engine) == 1); // 1000 RPM stage lit, 2000 not yet - - // 5. RPM rises higher (2500, 4500) -> shift lights scale - engine.update(7400, cfg, freshVerifiedSnapshot(2500), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(countLit(engine) == 2); - engine.update(7500, cfg, freshVerifiedSnapshot(4500), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(countLit(engine) == 4); - - // 6. RPM drops to 1300 (> 1200 resume) -> shift lights stay active, no stabilization started - engine.update(7600, cfg, freshVerifiedSnapshot(1300), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(engine.isRpmActive()); - CHECK(engine.ambientStatus() == AmbientStatus::PausedByRpm); - - // 7. RPM drops below 1200 (1100 RPM) -> stabilization timer begins - engine.update(8000, cfg, freshVerifiedSnapshot(1100), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(engine.isRpmActive()); // Still active during stabilization! - CHECK(engine.ambientStatus() == AmbientStatus::PausedByRpm); - - // Still within 400ms stabilization window (at 8200ms -> 200ms elapsed) - engine.update(8200, cfg, freshVerifiedSnapshot(1100), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); + feed(800, 1200); // Equality interrupts the low-RPM interval. CHECK(engine.isRpmActive()); - - // 8. Repeated throttle blip before stabilization completes (at 8300ms, RPM blips to 1400) - engine.update(8300, cfg, freshVerifiedSnapshot(1400), input); + feed(1000, 1000); // Stabilization starts at the exact millis rollover to zero. + feed(1200, 1000); + feed(1399, 1000); CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(engine.isRpmActive()); + feed(1400, 1000); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); - // RPM falls back to 1050 at 8400ms -> full 400ms timer must start fresh - engine.update(8400, cfg, freshVerifiedSnapshot(1050), input); + feed(1500, 4500); CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(engine.isRpmActive()); - - // At 8700ms (300ms elapsed), still in stabilization window - engine.update(8700, cfg, freshVerifiedSnapshot(1050), input); + missing(1750); // Last frame became stale while RPM held priority. + CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); + feed(1800, 1300); CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); + feed(1900, 0); + CHECK(engine.isRpmActive() && allBlack(engine)); + feed(2200, 0); // Unobserved 300 ms dropout interrupts the confirmation window. + feed(2400, 0); + feed(2599, 0); CHECK(engine.isRpmActive()); - - // At 8850ms (450ms elapsed since 8400ms with RPM stably < 1200) -> Resumes Ambient! - engine.update(8850, cfg, freshVerifiedSnapshot(1050), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - CHECK(!engine.isRpmActive()); - - // 9. RPM oscillation near thresholds: - // Oscillation near resume threshold: 1150 -> 1180 -> 1120 -> no flickering, stays in Ambient - engine.update(9000, cfg, freshVerifiedSnapshot(1150), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - engine.update(9100, cfg, freshVerifiedSnapshot(1180), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - // Oscillation near takeover threshold: 1450 -> 1480 -> 1460 -> stays in Ambient - engine.update(9200, cfg, freshVerifiedSnapshot(1450), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - engine.update(9300, cfg, freshVerifiedSnapshot(1480), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - // Only crossing >= 1500 takes over - engine.update(9400, cfg, freshVerifiedSnapshot(1500), input); - CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - - // 10. RPM drop to zero (engine stalled/stopped) -> immediate return to Ambient - engine.update(9500, cfg, freshVerifiedSnapshot(0), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - CHECK(!engine.isRpmActive()); - - // 11. Invalid and stale RPM after CAN activity -> Safeguard blank - engine.update(9600, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - LiveRpmSnapshot stale = freshVerifiedSnapshot(1000); - stale.fresh = false; - engine.update(9700, cfg, stale, input); - CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank); - CHECK(allBlack(engine)); + feed(2600, 0); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + missing(2850); // A previously confirmed zero is not sufficient once stale. + + input.previewPattern = 2; + input.previewDurationMs = 400; + feed(2900, 1000); + CHECK(engine.activeLayer() == LedActiveLayer::AnimationPreview); + input.otaBusy = true; + feed(3000, 0); + CHECK(engine.activeLayer() != LedActiveLayer::AnimationPreview); CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); - - LiveRpmSnapshot invalid = freshVerifiedSnapshot(1000); - invalid.valid = false; - engine.update(9800, cfg, invalid, input); - CHECK(engine.activeLayer() == LedActiveLayer::SafeguardBlank); - CHECK(allBlack(engine)); - CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); - - // Recovery when fresh valid RPM returns at idle - engine.update(9900, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - - // 12. Lost CAN communication / Hardware CAN fault -> Fault layer (flashing red) + CHECK(!engine.animationEligible() && allBlack(engine)); + input.otaBusy = false; + input.previewPattern = 0; + feed(3100, 0); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); input.canHealthy = false; - engine.update(10000, cfg, freshVerifiedSnapshot(1000), input); + feed(3200, 0); CHECK(engine.activeLayer() == LedActiveLayer::Fault); - CHECK(engine.ambientStatus() == AmbientStatus::SuppressedBySafety); input.canHealthy = true; - - // 13. Master lighting off -> Off layer (all black) cfg.isPowerOn = false; - engine.update(10100, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Off); - CHECK(allBlack(engine)); - CHECK(engine.ambientStatus() == AmbientStatus::Off); + feed(3300, 0); + CHECK(engine.activeLayer() == LedActiveLayer::Off && allBlack(engine)); cfg.isPowerOn = true; - - // 14. Shift warning priority - engine.update(10200, cfg, freshVerifiedSnapshot(7500), input); // Above 7000 warning - CHECK(engine.activeLayer() == LedActiveLayer::Warning); - CHECK(engine.ambientStatus() == AmbientStatus::PausedByRpm); - - // 15. Drop back to idle (1000 RPM): stabilization window active - engine.update(10300, cfg, freshVerifiedSnapshot(1000), input); + monitor.setCalibrationVerified(false); + receiveRpm(monitor, start + 3400, 0); + missing(3400); + monitor.setCalibrationVerified(true); + feed(3500, 0); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + feed(3600, 2000); CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); - CHECK(engine.isRpmActive()); - - // Past 400ms stabilization (at 10700ms), resumes Ambient! - engine.update(10700, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - CHECK(engine.ambientStatus() == AmbientStatus::Playing); - - // 16. Test all 5 animation patterns over time - for (uint8_t p = 1; p <= 5; ++p) { - cfg.ambient.pattern = p; - engine.update(11000 + p * 100, cfg, freshVerifiedSnapshot(1000), input); - CHECK(engine.activeLayer() == LedActiveLayer::Ambient); - } - - // 17. Test various strip lengths (6, 12, 24, 64) and shorter active counts - for (uint8_t stripLen : std::initializer_list{6, 12, 24, 64}) { - LedEffectEngine multiEngine; - multiEngine.reset(0, stripLen); - PulseShiftConfig stripCfg = cfg; - stripCfg.installedLedCount = stripLen; - stripCfg.rpmMapping.activeLedCount = stripLen / 2; // shorter active segment - completeStartup(multiEngine); - - // Idle - multiEngine.update(15000, stripCfg, freshVerifiedSnapshot(1000), input); - CHECK(multiEngine.activeLayer() == LedActiveLayer::Ambient); - - // Running above takeover - multiEngine.update(15100, stripCfg, freshVerifiedSnapshot(5000), input); - CHECK(multiEngine.activeLayer() == LedActiveLayer::RpmBar); - } + input.canHealthy = false; + const auto stale = monitor.snapshot(start + 3900); + engine.update(start + 3900, cfg, stale, input); + traceFrame("rpm_arbitration", 3900, start + 3900, cfg, stale, input, engine); + CHECK(engine.activeLayer() == LedActiveLayer::Fault); + input.canHealthy = true; + missing(3950); + feed(4000, 1000); + CHECK(engine.activeLayer() == LedActiveLayer::RpmBar); +} - // 18. Individual, grouped, and automatic RPM mapping modes - { - LedEffectEngine mapEngine; - mapEngine.reset(0, 6); - PulseShiftConfig mapCfg = cfg; - mapCfg.installedLedCount = 6; - completeStartup(mapEngine); - - // Automatic mode: 1000..6000 - mapCfg.rpmMapping.mode = RpmMappingMode::Automatic; - mapCfg.rpmMapping.activeLedCount = 6; - mapCfg.rpmMapping.entries = 2; - mapCfg.rpmMapping.thresholds[0] = 1000; - mapCfg.rpmMapping.thresholds[1] = 6000; - mapEngine.update(16000, mapCfg, freshVerifiedSnapshot(1000), input); - CHECK(mapEngine.activeLayer() == LedActiveLayer::Ambient); - mapEngine.update(16100, mapCfg, freshVerifiedSnapshot(3500), input); - CHECK(mapEngine.activeLayer() == LedActiveLayer::RpmBar); - - // Grouped mode: 3 groups of 2 LEDs - mapCfg.rpmMapping.mode = RpmMappingMode::Grouped; - mapCfg.rpmMapping.entries = 3; - mapCfg.rpmMapping.thresholds[0] = 2000; - mapCfg.rpmMapping.thresholds[1] = 4000; - mapCfg.rpmMapping.thresholds[2] = 6000; - mapCfg.rpmMapping.groupSizes[0] = 2; - mapCfg.rpmMapping.groupSizes[1] = 2; - mapCfg.rpmMapping.groupSizes[2] = 2; - mapEngine.update(16200, mapCfg, freshVerifiedSnapshot(1000), input); - CHECK(mapEngine.activeLayer() == LedActiveLayer::RpmBar); // Stabilization in progress (100ms) - mapEngine.update(16650, mapCfg, freshVerifiedSnapshot(1000), input); - CHECK(mapEngine.activeLayer() == LedActiveLayer::Ambient); // Resumed after 400ms delay (450ms elapsed) - mapEngine.update(16750, mapCfg, freshVerifiedSnapshot(4500), input); - CHECK(mapEngine.activeLayer() == LedActiveLayer::RpmBar); +int main(int argc, char** argv) { + if (argc > 2) { + std::fprintf(stderr, "Usage: %s [frame-trace.csv]\n", argv[0]); + return 2; } - - // 19. Continuous animation over ten minutes (>600,000 ms) and millis() rollover - { - LedEffectEngine timeEngine; - const uint32_t rolloverStart = UINT32_MAX - 5000; - timeEngine.reset(rolloverStart, 6); - PulseShiftConfig timeCfg = cfg; - timeCfg.bootEnabled = false; - - // Run across millis() 32-bit rollover boundary and for over 10 minutes (650,000 ms) - for (uint32_t step = 0; step <= 650000; step += 1000) { - const uint32_t currentMs = rolloverStart + step; - timeEngine.update(currentMs, timeCfg, freshVerifiedSnapshot(1000), input); - CHECK(timeEngine.activeLayer() == LedActiveLayer::Ambient); - CHECK(timeEngine.ambientStatus() == AmbientStatus::Playing); - } + if (argc == 2) { + traceFile = std::fopen(argv[1], "wb"); + if (!traceFile) { std::perror(argv[1]); return 2; } + std::fputs("scenario,elapsed_ms,clock_ms,effect,startup_pattern,startup_duration_ms,installed_leds,active_leds,reversed,brightness,power_on,can_healthy,raw,rpm,rpm_available,rpm_fresh,rpm_valid,layer,loop_status,pixels_rgb\n", traceFile); } -} - -int main() { fault_priority_wins_over_everything(); unverified_rpm_bar_renders_nothing(); provisional_rpm_preview_tracks_throttle_without_calibration(); @@ -1193,8 +1119,7 @@ int main() { boot_button_auth_window_does_not_obscure_active_rpm(); feedback_overrides_decorative_not_fault(); startup_then_decorative(); - ambient_eligibility_and_priority(); - all_ambient_patterns_keep_time(); + startup_loop_repeats_the_selected_animation(); dynamic_thresholds_and_inactive_pixels(); startup_animations_center_out_and_strobe(); rpm_bar_latches_and_hysteresis(); @@ -1213,7 +1138,9 @@ int main() { master_power_off(); change_detection_flags(); effects_and_warning_scale_to_strip(); - test_continuous_idle_animation_full_regression(); + chase_laps_preserve_timing_and_direction(); + startup_loop_rpm_and_safety(); + if (traceFile && std::fclose(traceFile) != 0) { std::perror(argv[1]); return 2; } std::printf("PASS unified LED engine priorities, safeguard, hysteresis, warnings: %u checks\n", checks); return 0; } diff --git a/test/test_startup_guard.cpp b/test/test_startup_guard.cpp new file mode 100644 index 0000000..3960904 --- /dev/null +++ b/test/test_startup_guard.cpp @@ -0,0 +1,28 @@ +#include "startup_guard.h" +#include +#include +#include + +extern esp_err_t mockNvsResult; +extern unsigned mockNvsCalls; +extern "C" bool verifyRollbackLater(); + +int main() { + assert(startupNvsStatus() == ESP_FAIL && mockNvsCalls == 0); + assert(verifyRollbackLater()); + + const esp_err_t cases[] = {ESP_ERR_NVS_NO_FREE_PAGES, ESP_ERR_NVS_NEW_VERSION_FOUND, 42, ESP_OK}; + unsigned calls = 0; + for (const auto raw : cases) { + mockNvsResult = raw; + // The call originates in a separate translation unit, as it does in Arduino HAL. + const auto coreStatus = nvs_flash_init(); + const bool triggersCoreErase = coreStatus == ESP_ERR_NVS_NO_FREE_PAGES || + coreStatus == ESP_ERR_NVS_NEW_VERSION_FOUND; + assert(!triggersCoreErase); + assert(coreStatus == (raw == ESP_OK || raw == 42 ? raw : ESP_FAIL)); + assert(startupNvsStatus() == raw); + assert(mockNvsCalls == ++calls); + } + std::puts("PASS pre-sketch NVS guard prevents both erase triggers and defers OTA confirmation"); +} diff --git a/test/test_storage_startup.cpp b/test/test_storage_startup.cpp new file mode 100644 index 0000000..b150bcb --- /dev/null +++ b/test/test_storage_startup.cpp @@ -0,0 +1,26 @@ +#include "storage_manager.h" +#include +#include +#include +#include + +int main() { + auto& storage = StorageManager::instance(); + mockSpiffsPresent = true; + LittleFS.mountSucceeds = false; + assert(!storage.begin(false) && storage.mountFailed()); + assert(Preferences::opens == 0 && LittleFS.formatCalls == 0 && !LittleFS.mountAllowedFormat); + assert(storage.nextSessionId() == 1 && Preferences::opens == 0); + + mockSpiffsDirtyTail = true; + assert(!storage.initializeBlank() && LittleFS.formatCalls == 0); + mockSpiffsDirtyTail = false; + mockSpiffsReadFails = true; + assert(!storage.initializeBlank() && LittleFS.formatCalls == 0); + mockSpiffsReadFails = false; + + assert(storage.initializeBlank() && LittleFS.formatCalls == 1 && !storage.mountFailed()); + assert(!storage.initializeBlank() && LittleFS.formatCalls == 1); + assert(storage.begin(true) && Preferences::opens == 1 && LittleFS.formatCalls == 1); + std::puts("PASS mount-only startup, no NVS access after init failure, explicit blank-only provisioning"); +}