From a0124e3a6448624412cda609e5572081c3af75a5 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 21:58:30 +0530 Subject: [PATCH 1/7] Loop the selected startup animation and support ESP32 core 4.0.0 --- .github/workflows/ci.yml | 16 +- PulseShift/PulseShift.ino | 9 +- PulseShift/src/ble_manager.cpp | 3 +- PulseShift/src/ble_protocol.h | 5 +- PulseShift/src/config_manager.cpp | 14 +- PulseShift/src/config_manager.h | 2 +- PulseShift/src/led_controller.cpp | 6 +- PulseShift/src/led_controller.h | 3 +- PulseShift/src/led_effects.cpp | 125 ++++----- PulseShift/src/led_effects.h | 15 +- PulseShift/src/lighting_setup.h | 2 + PulseShift/src/ota_manager.cpp | 45 ++-- PulseShift/src/rpm_candidate.cpp | 9 +- README.md | 6 +- docs/STARTUP-LOOP-ACCEPTANCE.md | 19 ++ docs/TESTING.md | 3 +- test/run.sh | 2 +- test/test_ble_commands.cpp | 26 ++ test/test_candidate_monitor.cpp | 19 ++ test/test_config_nvs.cpp | 1 + test/test_led_effects.cpp | 435 ++++++++++-------------------- 21 files changed, 344 insertions(+), 421 deletions(-) create mode 100644 docs/STARTUP-LOOP-ACCEPTANCE.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71cb498..85ef8a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,9 +16,17 @@ env: 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: + include: + - core: '3.3.12' + nimble: '2.3.8' + - core: '4.0.0' + nimble: '2.5.2' steps: - name: Check out source @@ -35,16 +43,16 @@ jobs: path: | ~/.arduino15 ~/.cache/arduino - key: ${{ runner.os }}-arduino-cli-1.1.1-esp32-3.3.12-nimble-2.3.8 + key: ${{ runner.os }}-arduino-cli-1.1.1-esp32-${{ matrix.core }}-nimble-${{ matrix.nimble }} - 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 core install esp32:esp32@${{ matrix.core }} arduino-cli lib update-index - arduino-cli lib install --no-deps "NimBLE-Arduino@2.3.8" + arduino-cli lib install --no-deps "NimBLE-Arduino@${{ matrix.nimble }}" - name: Compile - production firmware (default) run: | diff --git a/PulseShift/PulseShift.ino b/PulseShift/PulseShift.ino index b7cc4a8..b32a90e 100644 --- a/PulseShift/PulseShift.ino +++ b/PulseShift/PulseShift.ino @@ -309,7 +309,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 +557,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]); 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_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/README.md b/README.md index fbd713e..1fe9a5a 100644 --- a/README.md +++ b/README.md @@ -63,8 +63,10 @@ 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**. +1. Install Arduino CLI with one of the CI-tested board packages and BLE library pairs. + The application-only release build uses Arduino-ESP32 **3.3.12** with + `NimBLE-Arduino` **2.3.8**. Arduino-ESP32 **4.0.0** (ESP-IDF 6.1.1) uses + `NimBLE-Arduino` **2.5.2**. 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. 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..987889d 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -4,7 +4,8 @@ This guide describes verification testing for PulseShift: interactive Arduino Se ## 1. Build the firmware with Arduino CLI -Install Arduino-ESP32 3.3.12 and NimBLE-Arduino 2.3.8. Use the DevKit V1 +Install Arduino-ESP32 3.3.12 with NimBLE-Arduino 2.3.8, or Arduino-ESP32 4.0.0 +with NimBLE-Arduino 2.5.2. 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. diff --git a/test/run.sh b/test/run.sh index 394bb4a..5bf0862 100644 --- a/test/run.sh +++ b/test/run.sh @@ -63,7 +63,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/test_ble_commands.cpp b/test/test_ble_commands.cpp index 81e027b..fc74a1f 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 start = now; + CanFrame zero{}; + zero.id = candidate.decoderSettings().canId; + zero.dlc = 8; + auto render = [&](uint32_t elapsed) { + const uint32_t at = start + 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..1062b3d 100644 --- a/test/test_led_effects.cpp +++ b/test/test_led_effects.cpp @@ -22,6 +22,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 +759,52 @@ 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]); + } + CHECK(loop.isStartupComplete()); } } } @@ -894,10 +895,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,257 +932,101 @@ static void effects_and_warning_scale_to_strip() { } } -static void test_continuous_idle_animation_full_regression() { +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); + }; + auto missing = [&](uint32_t elapsed) { + engine.update(start + elapsed, cfg, monitor.snapshot(start + elapsed), input); + 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); - 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); - } - - // 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); - } - - // 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); - } - } + monitor.setCalibrationVerified(false); + receiveRpm(monitor, start + 3400, 0); + missing(3400); + monitor.setCalibrationVerified(true); + feed(3500, 0); + CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); } int main() { @@ -1193,8 +1039,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 +1058,7 @@ int main() { master_power_off(); change_detection_flags(); effects_and_warning_scale_to_strip(); - test_continuous_idle_animation_full_regression(); + startup_loop_rpm_and_safety(); std::printf("PASS unified LED engine priorities, safeguard, hysteresis, warnings: %u checks\n", checks); return 0; } From 0607103db12ff2faf4440241248fc73c4ab433da Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 22:06:15 +0530 Subject: [PATCH 2/7] Correct BLE loop regression fixture --- docs/BLE-PROTOCOL.md | 1025 ++++++++++++++++++------------------ docs/LIGHTING-SETUP.md | 102 ++-- test/test_ble_commands.cpp | 4 +- 3 files changed, 560 insertions(+), 571 deletions(-) diff --git a/docs/BLE-PROTOCOL.md b/docs/BLE-PROTOCOL.md index d2ccaea..bc23ae6 100644 --- a/docs/BLE-PROTOCOL.md +++ b/docs/BLE-PROTOCOL.md @@ -1,510 +1,515 @@ -# PulseShift BLE Protocol Specification (v1 & v2) - -**Document Version:** 2.3.0 -**Target Hardware:** ESP32 DevKit V1 (ESP32-D0WD-V3) -**Companion App:** PulseShift Android App (`D:\Development\PulseShift\android`) -**Firmware Library:** NimBLE-Arduino 2.3.8 -**Arduino-ESP32 Core:** 3.3.12 (ESP-IDF 5.3+) - ---- - -## 1. Overview and Architecture - -PulseShift BLE Protocol defines the Bluetooth Low Energy GATT communication between the PulseShift ESP32 motorcycle firmware and the companion Android smartphone application. The Android app is the complete command interface: every normal configuration and diagnostic operation is executable over BLE, and the firmware runs fully standalone without USB, serial or a PC. - -### Key Tenets -1. **Unidirectional CAN Safety:** The ESP32 is a passive, receive-only automotive monitor (SN65HVD230 CTX tied to 3V3, GPIO17 air-gapped, listen-only TWAI mode with a zero-length TX queue). BLE configuration changes modify only local LED rendering, RPM thresholds, shift alerts, animations, and candidate monitoring parameters. BLE **never** injects frames into the vehicle CAN bus, and the firmware contains no CAN transmit API at all. -2. **Fixed 20-Byte Wire MTU:** Every characteristic command, response, and telemetry notification is constrained to exactly 20 bytes. No MTU renegotiation or L2CAP segmentation is required; large payloads are reassembled at the application layer. -3. **Little-Endian Architecture:** All multi-byte integers (`uint16_t`, `uint32_t`, `float`) are serialized in standard IEEE 754 little-endian byte ordering. -4. **Resilient and Decoupled:** The ESP32 firmware functions autonomously without an active BLE connection. Telemetry notifications are sent only to subscribed GATT clients. Disconnections automatically re-arm advertising without interrupting CAN reception or LED rendering. -5. **NVS Persistence and Staged Transactions:** Changes can be applied immediately, staged across atomic multi-parameter transactions, and saved to non-volatile storage (NVS) using CRC32 checksums. -6. **Defensible Cryptographic Owner Security:** Physical presence proof (60-second authorization window triggered by the physical BOOT button on the ESP32) is mandatory for owner enrollment and credential recovery. Once enrolled, the phone authenticates via cryptographic challenge-response (SHA-256) without requiring physical button presses for ordinary configuration adjustments. -7. **Acknowledged Execution:** A Bluetooth write returning success is NOT proof of execution. Every v2 command carries a client `sequence` echoed in the result packet together with a status code and result flags; the app requires request/response correlation plus snapshot readback for configuration changes. - ---- - -## 2. GATT Service and Characteristics - -**Advertised Device Name:** `PulseShift` -**Primary Service UUID:** `fe12d210-3d4f-4b9d-a21c-92782ecb4000` - -| Purpose | Full UUID | Properties | Frequency / Access | Description | -|---|---|---|---|---| -| **RPM Telemetry** | `fe12d211-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 10 Hz (100 ms) | Live engine speed, raw candidate byte, age, CAN frame count | -| **System Health** | `fe12d212-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 1 Hz (1000 ms) | CAN bus health, missed/overrun counters, storage status | -| **Diagnostic Logs** | `fe12d213-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Event / Paced (20 ms) | Live diagnostic events, paginated historical logs, CAN capture pages | -| **Control Requests (v1)**| `fe12d214-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | GET_LOG_PAGE / CANCEL_LOGS / GET_CAPTURE_PAGE / CANCEL_CAPTURE | -| **Config Command (v2)** | `fe12d215-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | Configuration write/read requests, device control, transaction controls | -| **Config Result (v2)** | `fe12d216-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | Immediate response | Status code, active revision counter, and result flags | -| **Config Snapshot (v2)**| `fe12d217-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Paced (20 ms stream) | Multi-chunk serialized configuration TLV blob (schema 3) or diagnostics TLV blob (schema 1) with CRC32 | -| **Capabilities (v2)** | `fe12d218-3d4f-4b9d-a21c-92782ecb4000` | `READ` | Static / On revision | Hardware capabilities, feature mask, firmware version | - ---- - -## 3. Protocol v1 Telemetry Packets - -### 3.1 RPM Telemetry Packet (`0xd211`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `statusFlags` | `uint8_t` | Bitmask representing live subsystem states (see Section 3.1.1) | -| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter (0..65535) | -| 4..7 | `uptimeMs` | `uint32_t` | ESP32 monotonic uptime in milliseconds (`millis()`) | -| 8..9 | `provisionalRpm` | `uint16_t` | Estimated RPM from the unified decoder. `65535` = unavailable/stale | -| 10 | `candidateRawByte` | `uint8_t` | Low byte of the raw candidate value (valid only if fresh flag set) | -| 11 | `captureStage` | `uint8_t` | Current field stage: `0`=Standby, `1`=KeyOn, `2`=Idling, `3`=GentleRPM | -| 12..15 | `canFramesRx` | `uint32_t` | Cumulative count of total CAN frames received by TWAI driver | -| 16..17 | `candidateAgeMs` | `uint16_t` | Milliseconds elapsed since last candidate frame. `65535` = never received | -| 18..19 | `experimentalProbe` | `uint16_t` | Optional experimental, uncalibrated standard CAN `0x303` byte 1, encoded as below. Legacy firmware leaves it zero. | - -#### 3.1.0 Optional experimental battery-voltage hypothesis - -**Unverified. Available on paired firmware with a fresh sample.** From the -archived key-on/engine-off capture, CAN ID `0x303` byte 1 ranged from 119 to 122. -The test-only hypothesis is `volts = rawByte / 10.0`, which would suggest -11.9-12.2 V during that recording. This is **not** a calibrated voltage or a -safe battery/charging warning and must be compared against synchronized -multimeter readings at several operating points. - -To avoid a new GATT service or any change to the existing 20-byte packet -length, an optional firmware build uses the previously zero reserved bytes: - -| Offset | Value | Meaning | -|---|---|---| -| 18 | 0-255 | Raw CAN `0x303[1]` from a standard, non-RTR frame with DLC ≥ 2; only meaningful if byte 19 is `0xA5` | -| 19 | `0xA5` | Candidate received within the last 1000 ms; Android may show `raw / 10.0` under **EXPERIMENTAL** label | -| 19 | `0x5A` | Firmware supports probe but frame absent or stale; Android displays unavailable | -| 19 | `0x00` with byte 18 = 0 | Legacy firmware without probe support; Android displays unavailable | - -All other RPM, health, configuration and OTA fields retain their documented -meaning and offsets. The dedicated RPM decoder remains locked to the existing -candidate configuration. The probe never writes NVS/LittleFS or transmits CAN. -DO NOT infer an accurate battery voltage from visual agreement at one point. - -#### 3.1.1 Status Flags Bitmask (`statusFlags`) -- `Bit 0` (`0x01`): `BLE_RPM_FLAG_CANDIDATE_FRESH` (Candidate frame received within the freshness timeout, default 250 ms) -- `Bit 1` (`0x02`): `BLE_RPM_FLAG_CALIBRATION_VERIFIED` (Verification record bound to the current decoder fingerprint) -- `Bit 2` (`0x04`): `BLE_RPM_FLAG_RPM_MAPPED` (The unified candidate decoder is the production RPM mapping; always set on 2.2.0+) -- `Bit 3` (`0x08`): `BLE_RPM_FLAG_SHIFT_LIGHTS_ENABLED` (Set only while RPM-driven lighting is actually rendering from live CAN data: the verified bar (effect 4), the unverified provisional preview (effect 5) or their warning overlay. Clear during decorative effects 0-3, safeguard blanks and the synthetic bench test) -- `Bit 4` (`0x10`): `BLE_RPM_FLAG_CAN_HEALTHY` (TWAI driver in running state) -- `Bit 5` (`0x20`): `BLE_RPM_FLAG_TRAFFIC_ACTIVE` (CAN frames received in last 1000 ms) -- `Bit 6` (`0x40`): `BLE_RPM_FLAG_RECORDING_ACTIVE` (Flash binary capture running) -- `Bit 7` (`0x80`): `BLE_RPM_FLAG_CAPTURE_PRESERVED` (Prior flash recording preserved) - -When the candidate goes stale, `provisionalRpm` reports `65535` and LEDs blank: the device never continues rendering the last received RPM indefinitely. - ---- - -### 3.2 System Health Packet (`0xd212`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `healthFlags` | `uint8_t` | Bit 0: Storage mounted (`0x01`), Bit 1: Storage full (`0x02`), Bit 2: RX degraded (`0x04`), Bit 3: BLE client connected (`0x08`) | -| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter | -| 4..7 | `missedFrames` | `uint32_t` | TWAI driver-missed CAN frames in current session | -| 8..11 | `overrunFrames` | `uint32_t` | Hardware FIFO overruns in current session | -| 12..15 | `busErrors` | `uint32_t` | TWAI bus error counter | -| 16..19 | `recordedFrames` | `uint32_t` | CAN frames recorded to flash in current session | - ---- - -### 3.3 Diagnostic Log Chunk Packet (`0xd213`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `flags` | `uint8_t` | Bit 0: `FIRST_CHUNK` (`0x01`), Bit 1: `FINAL_CHUNK` (`0x02`), Bit 2: `END_OF_PAGE` (`0x04`), Bit 3: `ERROR` (`0x08`), Bit 4: `CAPTURE_LINE` (`0x10`) | -| 2..3 | `messageId` | `uint16_t` | Monotonic log message identifier | -| 4 | `chunkIndex` | `uint8_t` | 0-based chunk index within message | -| 5 | `payloadLength` | `uint8_t` | Number of valid payload bytes in `payload` (1..14) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Raw ASCII log text chunk, or End-of-Page metadata | - -For End-of-Page packets: `payloadLength = 5`, `payload[0..3]` = next byte offset (diagnostic logs) or next record index (capture pages) as `uint32_t` LE, `payload[4]` = finished flag (`1` = no more data). - -Capture pages stream CSV-like lines flagged with `CAPTURE_LINE`: -```text -CAP,,,,,, -``` -These lines are reassembled as multi-chunk messages and routed to the capture flow (never mixed with diagnostic messages). - ---- - -### 3.4 Control Requests (`0xd214`, WRITE) - -**Authorization (2.2.1+):** `GET_LOG_PAGE` and `GET_CAPTURE_PAGE` return vehicle -telemetry (raw CAN capture records and diagnostic history), so they require an -authenticated owner session bound to the requesting connection, exactly like -mutating configuration commands. An unauthenticated request is rejected, logged -to the device diagnostic event log and answered with a single -`BLE_LOG_FLAG_ERROR` chunk ("AUTH REQUIRED...") on the log characteristic. -`CANCEL_LOGS` and `CANCEL_CAPTURE` stay unauthenticated: they only stop a -transfer and disclose nothing. - -| Opcode | Name | Frame | Description | -|---|---|---|---| -| `0x10` | `GET_LOG_PAGE` | `[0x01, 0x10, offset: u32 LE]` (6 bytes) | **Auth required.** Stream one 20-line historical diagnostic log page from `offset` | -| `0x11` | `CANCEL_LOGS` | `[0x01, 0x11]` (2 bytes) | Cancel the diagnostic log page transfer | -| `0x12` | `GET_CAPTURE_PAGE` | `[0x01, 0x12, startRecord: u32 LE]` (6 bytes) | **Auth required.** Stream one bounded page (12 records) of the recorded CAN capture from `startRecord`. Reading never mutates the capture file | -| `0x13` | `CANCEL_CAPTURE` | `[0x01, 0x13]` (2 bytes) | Cancel the capture page transfer | - ---- - -## 4. Protocol v2 Configuration Architecture - -### 4.1 Device Capabilities (`0xd218`, READ, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `physicalLedCount`| `uint8_t` | Physical LED count = `6` | -| 2..5 | `featureMask` | `uint32_t` | Feature bitmask (see below; firmware 2.3.0 includes bits 17..19) | -| 6..9 | `currentRevision` | `uint32_t` | Monotonic active configuration revision counter | -| 10 | `presetCapacity` | `uint8_t` | Hardware preset slots (`0` = smartphone-managed presets) | -| 11 | `securityMode` | `uint8_t` | Security mode: `3` = Hybrid (Physical BOOT window presence OR Challenge-Response) | -| 12 | `firmwareMajor` | `uint8_t` | Firmware version major = `2` | -| 13 | `firmwareMinor` | `uint8_t` | Firmware version minor = `3` | -| 14 | `firmwarePatch` | `uint8_t` | Firmware version patch = `0` | -| 15 | `maxStartupAnimId` | `uint8_t` | Maximum supported startup animation ID (`5` = Strobe Rush; `<= 3` on legacy) | -| 16 | `maxEffectId` | `uint8_t` | Maximum supported effect ID (`5` = Provisional Preview) | -| 17 | `otaActiveSlot` | `uint8_t` | Running OTA slot: `0` = app0, `1` = app1, `0xFF` = unknown/unsupported | -| 18 | `protocolMinor` | `uint8_t` | Canonical protocol minor version (`3` for 2.3.0) | -| 19 | `otaFlags` | `uint8_t` | Bit 0: a rollback candidate exists, bit 1: dual-slot layout detected, bit 2: running app digest query supported | - -#### Feature Mask Bits (`featureMask`) -- `Bit 0` (`0x0001`): `BLE_FEAT_INDIVIDUAL_RGB` -- `Bit 1` (`0x0002`): `BLE_FEAT_EFFECTS` -- `Bit 2` (`0x0004`): `BLE_FEAT_STARTUP_ANIM` -- `Bit 3` (`0x0008`): `BLE_FEAT_RPM_THRESHOLDS` -- `Bit 4` (`0x0010`): `BLE_FEAT_SHIFT_WARNING` -- `Bit 5` (`0x0020`): `BLE_FEAT_RPM_MULTIPLIER` -- `Bit 6` (`0x0040`): `BLE_FEAT_CANDIDATE_SOURCE` -- `Bit 7` (`0x0080`): `BLE_FEAT_PHONE_PRESETS` -- `Bit 8` (`0x0100`): `BLE_FEAT_NVS_PERSISTENCE` -- `Bit 9` (`0x0200`): `BLE_FEAT_AUTH_WRITES` -- `Bit 10` (`0x0400`): `BLE_FEAT_DECODER_EXT` (width/endianness/offset/clamp) -- `Bit 11` (`0x0800`): `BLE_FEAT_HYSTERESIS` -- `Bit 12` (`0x1000`): `BLE_FEAT_CAL_WORKFLOW` -- `Bit 13` (`0x2000`): `BLE_FEAT_DIAGNOSTICS_TLV` -- `Bit 14` (`0x4000`): `BLE_FEAT_CAPTURE_EXPORT` -- `Bit 15` (`0x8000`): `BLE_FEAT_CAPTURE_STAGE` (authenticated stage-label command) -- `Bit 16` (`0x10000`): `BLE_FEAT_LED_BENCH_TEST` (authenticated 10-second synthetic test) -- `Bit 17` (`0x20000`): `BLE_FEAT_EXT_STARTUP_ANIM` (startup animations 4 Center Out and 5 Strobe Rush) -- `Bit 18` (`0x40000`): `BLE_FEAT_RANGE_DISCOVERY` (supports opcode 0x03 GET_ARG_RANGES) -- `Bit 19` (`0x80000`): `BLE_FEAT_OTA_UPDATE` (supports dual-slot authenticated firmware OTA) -- `Bit 20` (`0x100000`): `BLE_FEAT_LOOP_STARTUP` (startup duration bit 15 allows continuous looping) - ---- - -### 4.2 Configuration Command Packet (`0xd215`, WRITE, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `opcode` | `uint8_t` | Command opcode (see Section 4.4) | -| 2..3 | `sequence` | `uint16_t` | Client request sequence counter (echoed in Result) | -| 4 | `payloadLength` | `uint8_t` | Number of valid parameter bytes in `payload` (0..14) | -| 5 | `flags` | `uint8_t` | Bit 0: `IS_STAGED` (1 = stage in active transaction, 0 = apply live) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Command arguments | - -Incoming commands are queued through a bounded SPSC ring (4 entries); overflowed commands are counted and dropped rather than corrupting the queue. - ---- - -### 4.3 Configuration Result Packet (`0xd216`, READ/NOTIFY, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `respondedOpcode`| `uint8_t` | Opcode being acknowledged | -| 2..3 | `sequence` | `uint16_t` | Client sequence counter echoed from request | -| 4 | `statusCode` | `uint8_t` | Execution status (0 = OK, see Section 4.5) | -| 5 | `resultFlags` | `uint8_t` | Result flags (Bit 0=Persisted, Bit 1=Staged, Bit 2=Applied, Bit 3=AuthRequired) | -| 6..9 | `activeRevision` | `uint32_t` | Active configuration revision after command execution | -| 10 | `payloadLength` | `uint8_t` | Number of response bytes in `payload` (0..9) | -| 11..19 | `payload[9]` | `uint8_t[9]` | Optional response data (challenge nonce, calibration fit, statuses) | - ---- - -### 4.4 Command Opcodes - -**Authorization:** read-only queries (`0x01`, `0x02`, `0x43`, `0x46`, `0x50`) and the auth flow itself (`0x24`, `0x25`, `0x26`) are unauthenticated. Every other opcode requires a session bound to the current connection (challenge-response) or an open physical BOOT window. - -| Opcode | Name | Payload Arguments | Description | -|---|---|---|---| -| `0x01` | `GET_CAPABILITIES` | None | Updates Capabilities characteristic | -| `0x02` | `GET_SNAPSHOT` | None | Triggers complete config snapshot streaming on `0xd217` | -| `0x03` | `GET_ARG_RANGES` | None | Range discovery (max brightness, LED count, effect count, anim count, max RPM) | -| `0x10` | `SET_POWER` | `[power: u8 (0 or 1)]` | Master LED strip power switch | -| `0x11` | `SET_BRIGHTNESS` | `[brightness: u8 (0..255)]` | Master LED brightness | -| `0x12` | `SET_GLOBAL_RGB`| `[R: u8, G: u8, B: u8]` | Set uniform color across all 6 LEDs | -| `0x13` | `SET_LED_RGB` | `[index: u8 (0..5), R, G, B]` | Set individual LED color | -| `0x14` | `SET_EFFECT` | `[effectId: u8 (0..5), speed: u8 (0..100)]` | 0=Static, 1=Breathing, 2=Rainbow, 3=Chase, 4=Verified RPM Bar, **5=Provisional CAN RPM Preview (unverified)** | -| `0x15` | `SET_STARTUP` | `[animId: u8 (0..5), durationMs: u16 LE]` | 0=None, 1=Sweep, 2=Wave, 3=Pulse, 4=CenterOut, 5=Strobe Rush | - -**Optional loop extension:** On firmware advertising feature bit 20, the 16-bit startup duration uses bit 15 (`0x8000`) as `loopEnabled`. The low 15 bits remain the animation cycle length (100..10000 ms). With bit 15 cleared, the startup animation plays once as before. This uses the existing Config V2 packet, snapshot and schema-3 NVS blob without changing their sizes. Looping is invalid with animation 0 (None). Old firmware does not advertise the bit and must not receive loop-enabled settings. While enabled, fault, master power-off, commissioning/feedback, bench test, and active RPM or missing-RPM safeguards retain priority. Persist this setting with authenticated `SAVE_CONFIG` after `SET_STARTUP` or the preset transaction. Active RAM settings alone do not survive reboot. -| `0x16` | `SET_LED_THRESHOLD`| `[index: u8 (0..5), rpm: u16 LE]` | Set threshold for LED index (must remain monotonic) | -| `0x17` | `SET_SHIFT_WARNING`| `[warningRpm: u16 LE, patternId: u8]` | Pattern: 0=Flash (10 Hz), 1=Strobe (20 Hz), 2=Solid, 3=Off | -| `0x18` | `SET_RPM_MULTIPLIER`| `[multX1000: u32 LE]` | Provisional multiplier (0.1..1000.0). **Invalidates calibration!** | -| `0x19` | `SET_CANDIDATE_SOURCE` | `[canId: u32 LE, byteIdx: u8, ext: u8]` | Target CAN candidate source. **Invalidates calibration!** | -| `0x1A` | `SET_LED_DIRECTION`| `[direction: u8 (0=Forward, 1=Reverse)]`| Shift light display direction | -| `0x1B` | `SET_WARNING_RGB`| `[R: u8, G: u8, B: u8]` | Warning color for over-rev alert | -| `0x1C` | `SET_RPM_HYSTERESIS` | `[hysteresisRpm: u16 LE (0..2000)]` | Falling-RPM dead band for bar/warning latching | -| `0x1D` | `SET_RPM_DECODER_EXT` | `[width: u8 (1|2), endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` (8 bytes) | Byte width/order, RPM offset, validity clamp. **Invalidates calibration!** | -| `0x20` | `SAVE_CONFIG` | None | Commit active configuration to flash NVS (`"ps_cfg"`) | -| `0x21` | `RESTORE_DEFAULTS` | `[0xA5, 0x5A]` | Restore safe lighting/decoder defaults and save to NVS. **Owner credentials and captures are preserved.** | -| `0x22` | `RELOAD_CONFIG` | None | Re-read the persisted NVS blob and apply it to the active state | -| `0x24` | `ENROLL_OWNER` | `[secret: u8[12]]` | Owner enrollment or credential recovery (requires open BOOT window); safe re-enrollment overwrites the old credential | -| `0x25` | `AUTHENTICATE` | `[proof: u8[8]]` | Authenticate connection session via SHA-256 proof | -| `0x26` | `REQUEST_CHALLENGE`| None | Request 4-byte single-use cryptographic challenge nonce | -| `0x30` | `BEGIN_TRANSACTION`| None | Start staged transaction (30s timeout) | -| `0x31` | `COMMIT_TRANSACTION`| None | Validate all staged changes and apply atomically | -| `0x32` | `ABORT_TRANSACTION` | None | Discard all staged changes without modifying active config | -| `0x40` | `CAL_BEGIN` | None | Start the mobile-assisted calibration session (10 min timeout) | -| `0x41` | `CAL_ABORT` | None | Abort the calibration session | -| `0x42` | `CAL_CAPTURE_START` | None | Open the 2 s raw sampling window at the current operating point | -| `0x43` | `CAL_CAPTURE_STATUS` | None | Query window. Result payload: `[samples: u16 LE, elapsedMs: u16 LE]` | -| `0x44` | `CAL_POINT_COMMIT` | `[refRpm: u16 LE]` | Close the window, require >=10 stable samples (stddev <= 1.5 raw), store the point | -| `0x45` | `CAL_COMPUTE` | `[apply: u8]` | Fit scale/offset over 3..6 points, validate evidence. Result payload on OK (9 bytes): `[multiplierX1000: s32 LE, offsetX1000: s32 LE, info: u8]` where info = pointsUsed (low nibble) \| worst residual in 10-RPM steps clamped to 15 (high nibble); on failure: reason string (<= 9 bytes). Applying binds the verification record to the decoder fingerprint | -| `0x46` | `CAL_STATUS` | None | Query session. Result payload: `[active: u8, points: u8, captureActive: u8, samples: u16 LE]` | -| `0x50` | `GET_DIAGNOSTICS` | None | Stream the diagnostics TLV blob on `0xd217` (Section 4.8) | -| `0x51` | `RESTART_DEVICE` | `[0xA5, 0x5A]` | Acknowledge, then soft-restart the ESP32 | -| `0x52` | `CLEAR_DIAGNOSTICS` | `[0xA5, 0x5A]` | Clear the diagnostic event log ONLY (captures and credentials untouched) | -| `0x53` | `SET_CAPTURE_RECORDING` | `[enable: u8]` | Start/stop flash recording; start is state-gated (damaged/preserved/full storage => `INVALID_STATE`) | -| `0x54` | `SET_CAPTURE_STAGE` | `[stage: u8 (1..3)]` | Label subsequent CAN capture records: 1=KeyOn, 2=Idle, 3=RPM sweep. Does not change operation or synthesize CAN data. | -| `0x55` | `SET_LED_TEST_RPM` | `[testRpm: u16 LE (0..20000), enable: u8 (0 or 1)]` | Authenticated, temporary 10-second synthetic six-LED bench test. `enable=0` stops it; independent of real CAN data. Does not persist or inject CAN frames. | -| `0x60` | `OTA_BEGIN` | `[0xA5, 0x5C, size: u32 LE, shaPrefix: u8[4]]` | Begin authenticated dual-slot OTA update to inactive partition. Validates image size and stationary safety interlock. | -| `0x61` | `OTA_DATA` | `[chunkIdx: u16 LE, dataLen: u8, data...]` | Stream sequential image chunks. The Android client uses 11 data bytes at the baseline ATT MTU and up to 230 with a larger negotiated MTU. | -| `0x62` | `OTA_END` | `[shaTail: u8[4], crc32: u32 LE]` | Conclude transfer, verify full-image FIPS 180-2 SHA-256 hash, set boot partition, schedule restart (1.5s delay). | -| `0x63` | `OTA_ABORT` | None | Cancel active update, discard written data and return OTA engine to Idle state. | -| `0x64` | `OTA_CONFIRM` | `[0xA5, 0x5C]` | Cancel bootloader rollback after successful boot self-test. | -| `0x65` | `OTA_STATUS` | None | Query OTA engine state, active running slot, and written bytes. | -| `0x65` | `OTA_STATUS` digest | `[index: u8, 0..3]` | If capability bit 2 is set, returns index followed by 8 digest bytes at offset `8 * index`. The result fits the same 20-byte frame. | - ---- - -### 4.5 Status Codes - -| Code | Name | Description | -|---|---|---| -| `0` | `BLE_CFG_STATUS_OK` | Command executed successfully | -| `1` | `BLE_CFG_STATUS_INVALID_PARAM` | Parameter out of range or non-monotonic | -| `2` | `BLE_CFG_STATUS_UNSUPPORTED` | Opcode or parameter unsupported | -| `3` | `BLE_CFG_STATUS_BUSY` | Controller busy or under rate-limiting lockout | -| `4` | `BLE_CFG_STATUS_UNAUTHORIZED` | Authorization required; enrollment or authentication needed | -| `5` | `BLE_CFG_STATUS_INVALID_STATE` | Staged outside tx, expired challenge, storage not usable, or invalid session | -| `6` | `BLE_CFG_STATUS_STORAGE_ERROR` | Flash NVS write failed | -| `7` | `BLE_CFG_STATUS_VERSION_MISMATCH`| Protocol version mismatch | -| `8` | `BLE_CFG_STATUS_VALIDATION_FAILED`| Configuration validation failed | -| `9` | `BLE_CFG_STATUS_OTA_CHECKSUM_ERROR`| SHA-256 hash or CRC32 verification failed | -| `10` | `BLE_CFG_STATUS_OTA_FLASH_ERROR`| Flash partition write or erase error | - ---- - -### 4.6 Configuration Snapshot (`0xd217`, NOTIFY, 20-Byte Chunks) - -Streamed with 20 ms pacing between chunks to prevent Bluetooth buffer congestion. The same characteristic carries diagnostics blobs (schema byte `1`) and configuration snapshots (schema byte `3`); clients dispatch on the reassembled schema byte. - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1..2 | `snapshotId` | `uint16_t` | Snapshot identifier (little-endian; the request sequence) | -| 3 | `chunkIndex` | `uint8_t` | 0-based chunk sequence index | -| 4 | `chunkCount` | `uint8_t` | Total chunks comprising the blob | -| 5 | `payloadLength` | `uint8_t` | Number of valid bytes in this chunk (1..14) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Serialized TLV fragment | - -#### Reassembled Configuration Snapshot Binary Layout (schema 3) -```text -[Byte 0] : schemaVersion (uint8_t = 3) -[Bytes 1..4] : activeRevision (uint32_t LE) -[Bytes 5..N-4]: TLV Records (see Section 4.7) -[Bytes N-3..N]: CRC32 (uint32_t LE, IEEE 802.3 over Bytes 0..N-4) -``` - -#### Reassembled Diagnostics Blob Binary Layout (schema 1) -```text -[Byte 0] : schemaVersion (uint8_t = 1) -[Bytes 1..4] : revision (uint32_t LE, always 0) -[Bytes 5..N-4]: Diagnostics TLV Records (see Section 4.8) -[Bytes N-3..N]: CRC32 (uint32_t LE) -``` - ---- - -### 4.7 Configuration Snapshot TLVs (schema 3) - -Every TLV record is formatted as `[Tag: uint8_t, Length: uint8_t, Value: uint8_t[Length]]`. - -All 12 mandatory tags (`0x10` through `0x1B`) are always emitted; schema-3 tags `0x1C`..`0x1E` accompany them. Unknown tags must be tolerated (skipped) by clients for forward compatibility. - -| Tag | Name | Length | Value Format | Description | -|---|---|---|---|---| -| `0x10` | Power | 1 | `[power: u8]` | `0` = Off, `1` = On | -| `0x11` | Brightness | 1 | `[brightness: u8]` | Master brightness `0..255` | -| `0x12` | Global Color | 3 | `[R, G, B]` | Primary single RGB color | -| `0x13` | Per-LED Colors | 18 | `[6 * (R, G, B)]` | Individual RGB colors for LEDs 0..5 | -| `0x14` | Effect & Speed | 2 | `[effectId: u8, speed: u8]` | Effect (0..5), Speed (0..100) | -| `0x15` | Startup Animation | 3 | `[animId: u8, durationMs: u16 LE]` | Startup anim (0..5), duration in ms | -| `0x16` | RPM Thresholds | 12 | `[6 * u16 LE]` | Monotonic thresholds for LEDs 0..5 | -| `0x17` | Shift Warning | 3 | `[warningRpm: u16 LE, patternId: u8]`| Warning threshold and pattern (0..3, 3 = Off) | -| `0x18` | RPM Multiplier | 4 | `[multX1000: u32 LE]` | Multiplier * 1000 (e.g. 40.0 -> 40000) | -| `0x19` | CAN Candidate | 6 | `[canId: u32 LE, byteIdx: u8, ext: u8]`| Target candidate CAN source | -| `0x1A` | LED Direction | 1 | `[direction: u8]` | `0` = Forward (0->5), `1` = Reverse (5->0) | -| `0x1B` | Warning Color | 3 | `[R, G, B]` | Alert over-rev flash color | -| `0x1C` | Decoder Extension | 8 | `[width: u8, endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` | Byte width/order, RPM offset, validity clamp | -| `0x1D` | Calibration Record | 11 | `[verified: u8, fingerprint: u32 LE, pointsUsed: u8, maxResidualRpm: u8, timestampMs: u32 LE]` | Bound verification record | -| `0x1E` | Hysteresis | 2 | `[hysteresisRpm: u16 LE]` | Threshold dead band | - ---- - -### 4.8 Diagnostics Blob TLVs (GET_DIAGNOSTICS, schema 1) - -| Tag | Name | Length | Value Format | -|---|---|---|---| -| `0x40` | Uptime | 4 | `uptimeMs: u32 LE` | -| `0x41` | Firmware Version | 3 | `[major, minor, patch]` | -| `0x42` | Reset Reason | 1 | `esp_reset_reason` of the last boot | -| `0x43` | CAN Status | 26 | `[bitrate: u32, totalRx: u32, accepted: u32, missed: u32, overrun: u32, busErrors: u32, healthy: u8, traffic: u8]` | -| `0x44` | RPM Decoder State | 34 | `[canId: u32, byteIndex: u8, byteWidth: u8, extended: u8, multX1000: s32, offsetX1000: s32, maxValid: u16, raw: u16, estimatedRpm: u16, fresh: u8, valid: u8, calVerified: u8, ageMs: u16, received: u32, rejected: u32]` | -| `0x45` | Storage State | 29 | `[total: u32, used: u32, free: u32, mounted: u8, storageFull: u8, capturePreserved: u8, damaged: u8, recording: u8, records: u32, captureSize: u32, diagLogSize: u32]` | -| `0x46` | BLE State | 5 | `[connected: u8, advertising: u8, securityMode: u8, ownerEnrolled: u8, sessionAuthorized: u8]` | -| `0x47` | Capture Info | 9 | `[stage: u8, sessionId: u32, bootCount: u32]` | -| `0x48` | Last Error | <= 96 | UTF-8 text of the last Error/Critical event this session (absent when none) | -| `0x49` | Calibration State | 13 | `[sessionActive: u8, points: u8, captureActive: u8, samples: u16, calVerified: u8, pointsUsed: u8, maxResidualRpm: u8, fingerprint: u32]` | -| `0x4A` | Experimental CAN bytes | 5 | Freshness bitmask followed by raw `0x302[1]`, `0x302[5]`, `0x452[7]`, `0x540[3]`. Bit index matches byte order. A clear bit means unavailable at snapshot time. Standard non-RTR frames, max sample age 1000 ms. | - ---- - -## 5. Owner Enrollment and Challenge-Response Authentication - -The PulseShift hardware is a dedicated headless embedded unit. To defend against unauthorized vehicle tuning or drive-by configuration tampering, PulseShift enforces physical owner presence and cryptographic authentication: - -```text -[Phone Application] [PulseShift ESP32] - | | - | (User presses physical BOOT button on ESP32) | - | <-------------------------------------------------------| BOOT Window Open (60s) - | | (LEDs pulse Cyan) - | ENROLL_OWNER (0x24) [secret: 12 bytes] | - |--------------------------------------------------------->| Store in NVS ("ps_sec") - | Result (0x24, OK, PERSISTED | APPLIED) | Session Authorized - |<---------------------------------------------------------| - : : - : (Normal Phone Use in subsequent sessions) : - | | - | REQUEST_CHALLENGE (0x26) | - |--------------------------------------------------------->| Generate 32-bit nonce - | Result (0x26, OK, payload: challenge [4 bytes LE]) | 30-second TTL - |<---------------------------------------------------------| - | | - | Compute Proof: | - | SHA-256(secret[12] || challenge[4] || seq[2])[:8] | - | | - | AUTHENTICATE (0x25) [proof: 8 bytes] | Single-use nonce consumed - |--------------------------------------------------------->| Constant-time comparison - | Result (0x25, OK) | Session Authorized (5 min) - |<---------------------------------------------------------| - | | - | SET_BRIGHTNESS, SET_EFFECT, etc. | Writes Permitted - |--------------------------------------------------------->| -``` - -### 5.1 Owner Enrollment Flow (and Credential Recovery) -1. The user presses the physical **BOOT** button (GPIO0) on the ESP32. -2. The controller opens a **60-second authorization window** and pulses the LED strip in cyan. -3. The phone sends opcode `0x24` (`ENROLL_OWNER`) containing a randomly generated 12-byte cryptographic secret. -4. The ESP32 validates the open BOOT window, verifies the secret is non-trivial, and stores it in a dedicated CRC-protected NVS namespace `"ps_sec"`. -5. The session is immediately marked authorized, bound to this connection. -6. **Credential recovery** is the same flow: pressing BOOT and re-enrolling overwrites the previous credential. Credential recovery and configuration reset are deliberately distinct operations. - -### 5.2 Subsequent Authenticated Phone Sessions -1. In future rides, the phone connects via BLE without pressing the BOOT button and automatically performs the challenge-response exchange using its stored credential. -2. The phone sends opcode `0x26` (`REQUEST_CHALLENGE`). -3. The ESP32 returns a 4-byte pseudo-random challenge nonce (`esp_random()`) with a 30-second TTL. -4. The phone computes the 8-byte authentication proof: `SHA-256(secret[12] || challenge[4 LE] || sequence[2 LE])[:8]`. -5. The phone sends opcode `0x25` (`AUTHENTICATE`) with the 8-byte proof. -6. The ESP32 consumes the challenge immediately (defeating replay), computes the matching proof, and verifies in constant time. -7. Upon verification, the session is authorized for 5 minutes of activity (refreshed per command) and is bound to that specific connection handle: another concurrent connection cannot ride the session. - -### 5.3 Negative Security Defenses -- **Proof-Less Session Rejection:** Physical presence alone never grants a session; opcode `0x25` requires a valid proof (`BLE_CFG_STATUS_UNAUTHORIZED = 4`). -- **Replay Attack Defense:** Every challenge is strictly single-use. Re-submitting the same proof without requesting a fresh challenge fails with `BLE_CFG_STATUS_INVALID_STATE = 5`. -- **Challenge Expiration:** Challenges expire after 30 seconds (`BLE_CFG_STATUS_INVALID_STATE = 5`). -- **Brute-Force Rate Limiting:** After 5 consecutive failed authentications, challenge requests are locked out for 3 seconds (`BLE_CFG_STATUS_BUSY = 3`). -- **Disconnect Invalidation:** Client disconnection immediately terminates the authenticated session, invalidates pending challenges and aborts staged transactions. -- **Connection Binding:** Sessions are valid only for the authenticating connection handle (`isAuthorizedFor(connId)`). -- **Configuration Reset vs Credentials:** `RESTORE_DEFAULTS` (`0x21`) resets lighting/decoder preferences but preserves owner credentials and stored captures. `CLEAR_DIAGNOSTICS` (`0x52`) clears only the event log. - ---- - -## 6. Cross-Language Byte Test Vectors - -The following deterministic test vector is published to verify cross-language byte serialization between Python (`test_ble_config_v2.py`), Android Kotlin (`ProtocolV2CodecTest.kt`), and C++ ESP32 firmware: - -### 6.1 Challenge-Response Vector -```text -Owner Secret (12 bytes ASCII): -"PULSE_KEY_96" -> [0x50, 0x55, 0x4c, 0x53, 0x45, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x39, 0x36] - -Challenge Nonce (uint32_t LE = 0x12345678): -[0x78, 0x56, 0x34, 0x12] - -Request Sequence (uint16_t LE = 42): -[0x2a, 0x00] - -Combined Hash Input (18 bytes): -50 55 4c 53 45 5f 4b 45 59 5f 39 36 78 56 34 12 2a 00 - -SHA-256 Full Digest (32 bytes): -12 38 a0 9b 10 7e 9d 79 38 a6 37 da 41 e9 c4 ee fa ec eb c4 e0 e0 0e 86 5d dd d1 fa 1c 35 c4 cc - -Expected Auth Proof (First 8 bytes): -[0x12, 0x38, 0xa0, 0x9b, 0x10, 0x7e, 0x9d, 0x79] -> Hex string: "1238a09b107e9d79" -``` -# Strip, RPM mapping and animation extension (2.5) - -Capability bit 23 and protocol minor ≥ 5 advertise version 1 of Lighting Setup. -Standard Config V2 command, result and snapshot chunk sizes remain 20 bytes. -Multi-byte fields below use little endian. - -| Operation | Request payload | Result | -| --- | --- | --- | -| `GET_SNAPSHOT` (`02`) | Empty for legacy, `[1]` for extended | Adds TLV `21` (setup) and `22` (version, saved count or zero if unconfirmed) to the existing CRC-protected stream | -| `LIGHTING_BEGIN` (`70`) | Version u8, payload length u16, IEEE CRC-32 u32, base revision u32 | Staged; command sequence is the upload ID | -| `LIGHTING_DATA` (`71`) | Upload ID u16, byte offset u16, 1-10 data bytes | Staged, contiguous offsets only | -| `LIGHTING_SAVE` (`72`) | Upload ID u16 | Applied + persisted only after verified NVS readback; storage errors carry the save status | -| `LIGHTING_CANCEL` (`73`) | Upload ID u16 | Discards partial upload | -| `AMBIENT_STATUS` (`74`) | Version u8 | Version, playback status (off 0, playing 1, paused by RPM 2, safety 3, waiting 4), preview eligibility (0/1) | -| `ANIMATION_PREVIEW` (`75`) | Version u8, pattern u8, duration u16 | Authenticated one-shot request, subject to current safety eligibility | - -Setup payload has a 15-byte header. Fields in order are version, installed count, -active count (0 follows installed), mapping mode, entry count, boot enabled, -boot pattern, boot duration u16, ambient enabled, ambient pattern, ambient -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. - -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, -wrong transaction ID, invalid offsets, incomplete payloads and CRC mismatches -fail before changing active settings. Status 11 identifies an integrity error. -Configuration results reference each command sequence. Clients must check the -final revision and the full extended snapshot including the flash-match flag. -An app applying a phone preset can open a standard transaction and set the -staged flag on `LIGHTING_BEGIN` only. In that case `LIGHTING_SAVE` sets the -staged copy and acknowledges Staged. The subsequent standard commit and -verified save retain their existing meanings. - -Old snapshots keep the original six thresholds, strip-count extension and -combined startup field. Legacy startup writes translate the loop bit to the -ambient fields. Legacy single-threshold commands return Unsupported on a -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 -eligibility, migration and hardware validation. +# PulseShift BLE Protocol Specification (v1 & v2) + +**Document Version:** 2.3.0 +**Target Hardware:** ESP32 DevKit V1 (ESP32-D0WD-V3) +**Companion App:** PulseShift Android App (`D:\Development\PulseShift\android`) +**Firmware Library:** NimBLE-Arduino 2.3.8 +**Arduino-ESP32 Core:** 3.3.12 (ESP-IDF 5.3+) + +--- + +## 1. Overview and Architecture + +PulseShift BLE Protocol defines the Bluetooth Low Energy GATT communication between the PulseShift ESP32 motorcycle firmware and the companion Android smartphone application. The Android app is the complete command interface: every normal configuration and diagnostic operation is executable over BLE, and the firmware runs fully standalone without USB, serial or a PC. + +### Key Tenets +1. **Unidirectional CAN Safety:** The ESP32 is a passive, receive-only automotive monitor (SN65HVD230 CTX tied to 3V3, GPIO17 air-gapped, listen-only TWAI mode with a zero-length TX queue). BLE configuration changes modify only local LED rendering, RPM thresholds, shift alerts, animations, and candidate monitoring parameters. BLE **never** injects frames into the vehicle CAN bus, and the firmware contains no CAN transmit API at all. +2. **Fixed 20-Byte Wire MTU:** Every characteristic command, response, and telemetry notification is constrained to exactly 20 bytes. No MTU renegotiation or L2CAP segmentation is required; large payloads are reassembled at the application layer. +3. **Little-Endian Architecture:** All multi-byte integers (`uint16_t`, `uint32_t`, `float`) are serialized in standard IEEE 754 little-endian byte ordering. +4. **Resilient and Decoupled:** The ESP32 firmware functions autonomously without an active BLE connection. Telemetry notifications are sent only to subscribed GATT clients. Disconnections automatically re-arm advertising without interrupting CAN reception or LED rendering. +5. **NVS Persistence and Staged Transactions:** Changes can be applied immediately, staged across atomic multi-parameter transactions, and saved to non-volatile storage (NVS) using CRC32 checksums. +6. **Defensible Cryptographic Owner Security:** Physical presence proof (60-second authorization window triggered by the physical BOOT button on the ESP32) is mandatory for owner enrollment and credential recovery. Once enrolled, the phone authenticates via cryptographic challenge-response (SHA-256) without requiring physical button presses for ordinary configuration adjustments. +7. **Acknowledged Execution:** A Bluetooth write returning success is NOT proof of execution. Every v2 command carries a client `sequence` echoed in the result packet together with a status code and result flags; the app requires request/response correlation plus snapshot readback for configuration changes. + +--- + +## 2. GATT Service and Characteristics + +**Advertised Device Name:** `PulseShift` +**Primary Service UUID:** `fe12d210-3d4f-4b9d-a21c-92782ecb4000` + +| Purpose | Full UUID | Properties | Frequency / Access | Description | +|---|---|---|---|---| +| **RPM Telemetry** | `fe12d211-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 10 Hz (100 ms) | Live engine speed, raw candidate byte, age, CAN frame count | +| **System Health** | `fe12d212-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 1 Hz (1000 ms) | CAN bus health, missed/overrun counters, storage status | +| **Diagnostic Logs** | `fe12d213-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Event / Paced (20 ms) | Live diagnostic events, paginated historical logs, CAN capture pages | +| **Control Requests (v1)**| `fe12d214-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | GET_LOG_PAGE / CANCEL_LOGS / GET_CAPTURE_PAGE / CANCEL_CAPTURE | +| **Config Command (v2)** | `fe12d215-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | Configuration write/read requests, device control, transaction controls | +| **Config Result (v2)** | `fe12d216-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | Immediate response | Status code, active revision counter, and result flags | +| **Config Snapshot (v2)**| `fe12d217-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Paced (20 ms stream) | Multi-chunk serialized configuration TLV blob (schema 3) or diagnostics TLV blob (schema 1) with CRC32 | +| **Capabilities (v2)** | `fe12d218-3d4f-4b9d-a21c-92782ecb4000` | `READ` | Static / On revision | Hardware capabilities, feature mask, firmware version | + +--- + +## 3. Protocol v1 Telemetry Packets + +### 3.1 RPM Telemetry Packet (`0xd211`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `statusFlags` | `uint8_t` | Bitmask representing live subsystem states (see Section 3.1.1) | +| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter (0..65535) | +| 4..7 | `uptimeMs` | `uint32_t` | ESP32 monotonic uptime in milliseconds (`millis()`) | +| 8..9 | `provisionalRpm` | `uint16_t` | Estimated RPM from the unified decoder. `65535` = unavailable/stale | +| 10 | `candidateRawByte` | `uint8_t` | Low byte of the raw candidate value (valid only if fresh flag set) | +| 11 | `captureStage` | `uint8_t` | Current field stage: `0`=Standby, `1`=KeyOn, `2`=Idling, `3`=GentleRPM | +| 12..15 | `canFramesRx` | `uint32_t` | Cumulative count of total CAN frames received by TWAI driver | +| 16..17 | `candidateAgeMs` | `uint16_t` | Milliseconds elapsed since last candidate frame. `65535` = never received | +| 18..19 | `experimentalProbe` | `uint16_t` | Optional experimental, uncalibrated standard CAN `0x303` byte 1, encoded as below. Legacy firmware leaves it zero. | + +#### 3.1.0 Optional experimental battery-voltage hypothesis + +**Unverified. Available on paired firmware with a fresh sample.** From the +archived key-on/engine-off capture, CAN ID `0x303` byte 1 ranged from 119 to 122. +The test-only hypothesis is `volts = rawByte / 10.0`, which would suggest +11.9-12.2 V during that recording. This is **not** a calibrated voltage or a +safe battery/charging warning and must be compared against synchronized +multimeter readings at several operating points. + +To avoid a new GATT service or any change to the existing 20-byte packet +length, an optional firmware build uses the previously zero reserved bytes: + +| Offset | Value | Meaning | +|---|---|---| +| 18 | 0-255 | Raw CAN `0x303[1]` from a standard, non-RTR frame with DLC ≥ 2; only meaningful if byte 19 is `0xA5` | +| 19 | `0xA5` | Candidate received within the last 1000 ms; Android may show `raw / 10.0` under **EXPERIMENTAL** label | +| 19 | `0x5A` | Firmware supports probe but frame absent or stale; Android displays unavailable | +| 19 | `0x00` with byte 18 = 0 | Legacy firmware without probe support; Android displays unavailable | + +All other RPM, health, configuration and OTA fields retain their documented +meaning and offsets. The dedicated RPM decoder remains locked to the existing +candidate configuration. The probe never writes NVS/LittleFS or transmits CAN. +DO NOT infer an accurate battery voltage from visual agreement at one point. + +#### 3.1.1 Status Flags Bitmask (`statusFlags`) +- `Bit 0` (`0x01`): `BLE_RPM_FLAG_CANDIDATE_FRESH` (Candidate frame received within the freshness timeout, default 250 ms) +- `Bit 1` (`0x02`): `BLE_RPM_FLAG_CALIBRATION_VERIFIED` (Verification record bound to the current decoder fingerprint) +- `Bit 2` (`0x04`): `BLE_RPM_FLAG_RPM_MAPPED` (The unified candidate decoder is the production RPM mapping; always set on 2.2.0+) +- `Bit 3` (`0x08`): `BLE_RPM_FLAG_SHIFT_LIGHTS_ENABLED` (Set only while RPM-driven lighting is actually rendering from live CAN data: the verified bar (effect 4), the unverified provisional preview (effect 5) or their warning overlay. Clear during decorative effects 0-3, safeguard blanks and the synthetic bench test) +- `Bit 4` (`0x10`): `BLE_RPM_FLAG_CAN_HEALTHY` (TWAI driver in running state) +- `Bit 5` (`0x20`): `BLE_RPM_FLAG_TRAFFIC_ACTIVE` (CAN frames received in last 1000 ms) +- `Bit 6` (`0x40`): `BLE_RPM_FLAG_RECORDING_ACTIVE` (Flash binary capture running) +- `Bit 7` (`0x80`): `BLE_RPM_FLAG_CAPTURE_PRESERVED` (Prior flash recording preserved) + +When the candidate goes stale, `provisionalRpm` reports `65535` and LEDs blank: the device never continues rendering the last received RPM indefinitely. + +--- + +### 3.2 System Health Packet (`0xd212`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `healthFlags` | `uint8_t` | Bit 0: Storage mounted (`0x01`), Bit 1: Storage full (`0x02`), Bit 2: RX degraded (`0x04`), Bit 3: BLE client connected (`0x08`) | +| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter | +| 4..7 | `missedFrames` | `uint32_t` | TWAI driver-missed CAN frames in current session | +| 8..11 | `overrunFrames` | `uint32_t` | Hardware FIFO overruns in current session | +| 12..15 | `busErrors` | `uint32_t` | TWAI bus error counter | +| 16..19 | `recordedFrames` | `uint32_t` | CAN frames recorded to flash in current session | + +--- + +### 3.3 Diagnostic Log Chunk Packet (`0xd213`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `flags` | `uint8_t` | Bit 0: `FIRST_CHUNK` (`0x01`), Bit 1: `FINAL_CHUNK` (`0x02`), Bit 2: `END_OF_PAGE` (`0x04`), Bit 3: `ERROR` (`0x08`), Bit 4: `CAPTURE_LINE` (`0x10`) | +| 2..3 | `messageId` | `uint16_t` | Monotonic log message identifier | +| 4 | `chunkIndex` | `uint8_t` | 0-based chunk index within message | +| 5 | `payloadLength` | `uint8_t` | Number of valid payload bytes in `payload` (1..14) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Raw ASCII log text chunk, or End-of-Page metadata | + +For End-of-Page packets: `payloadLength = 5`, `payload[0..3]` = next byte offset (diagnostic logs) or next record index (capture pages) as `uint32_t` LE, `payload[4]` = finished flag (`1` = no more data). + +Capture pages stream CSV-like lines flagged with `CAPTURE_LINE`: +```text +CAP,,,,,, +``` +These lines are reassembled as multi-chunk messages and routed to the capture flow (never mixed with diagnostic messages). + +--- + +### 3.4 Control Requests (`0xd214`, WRITE) + +**Authorization (2.2.1+):** `GET_LOG_PAGE` and `GET_CAPTURE_PAGE` return vehicle +telemetry (raw CAN capture records and diagnostic history), so they require an +authenticated owner session bound to the requesting connection, exactly like +mutating configuration commands. An unauthenticated request is rejected, logged +to the device diagnostic event log and answered with a single +`BLE_LOG_FLAG_ERROR` chunk ("AUTH REQUIRED...") on the log characteristic. +`CANCEL_LOGS` and `CANCEL_CAPTURE` stay unauthenticated: they only stop a +transfer and disclose nothing. + +| Opcode | Name | Frame | Description | +|---|---|---|---| +| `0x10` | `GET_LOG_PAGE` | `[0x01, 0x10, offset: u32 LE]` (6 bytes) | **Auth required.** Stream one 20-line historical diagnostic log page from `offset` | +| `0x11` | `CANCEL_LOGS` | `[0x01, 0x11]` (2 bytes) | Cancel the diagnostic log page transfer | +| `0x12` | `GET_CAPTURE_PAGE` | `[0x01, 0x12, startRecord: u32 LE]` (6 bytes) | **Auth required.** Stream one bounded page (12 records) of the recorded CAN capture from `startRecord`. Reading never mutates the capture file | +| `0x13` | `CANCEL_CAPTURE` | `[0x01, 0x13]` (2 bytes) | Cancel the capture page transfer | + +--- + +## 4. Protocol v2 Configuration Architecture + +### 4.1 Device Capabilities (`0xd218`, READ, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `physicalLedCount`| `uint8_t` | Physical LED count = `6` | +| 2..5 | `featureMask` | `uint32_t` | Feature bitmask (see below; firmware 2.3.0 includes bits 17..19) | +| 6..9 | `currentRevision` | `uint32_t` | Monotonic active configuration revision counter | +| 10 | `presetCapacity` | `uint8_t` | Hardware preset slots (`0` = smartphone-managed presets) | +| 11 | `securityMode` | `uint8_t` | Security mode: `3` = Hybrid (Physical BOOT window presence OR Challenge-Response) | +| 12 | `firmwareMajor` | `uint8_t` | Firmware version major = `2` | +| 13 | `firmwareMinor` | `uint8_t` | Firmware version minor = `3` | +| 14 | `firmwarePatch` | `uint8_t` | Firmware version patch = `0` | +| 15 | `maxStartupAnimId` | `uint8_t` | Maximum supported startup animation ID (`5` = Strobe Rush; `<= 3` on legacy) | +| 16 | `maxEffectId` | `uint8_t` | Maximum supported effect ID (`5` = Provisional Preview) | +| 17 | `otaActiveSlot` | `uint8_t` | Running OTA slot: `0` = app0, `1` = app1, `0xFF` = unknown/unsupported | +| 18 | `protocolMinor` | `uint8_t` | Canonical protocol minor version (`3` for 2.3.0) | +| 19 | `otaFlags` | `uint8_t` | Bit 0: a rollback candidate exists, bit 1: dual-slot layout detected, bit 2: running app digest query supported | + +#### Feature Mask Bits (`featureMask`) +- `Bit 0` (`0x0001`): `BLE_FEAT_INDIVIDUAL_RGB` +- `Bit 1` (`0x0002`): `BLE_FEAT_EFFECTS` +- `Bit 2` (`0x0004`): `BLE_FEAT_STARTUP_ANIM` +- `Bit 3` (`0x0008`): `BLE_FEAT_RPM_THRESHOLDS` +- `Bit 4` (`0x0010`): `BLE_FEAT_SHIFT_WARNING` +- `Bit 5` (`0x0020`): `BLE_FEAT_RPM_MULTIPLIER` +- `Bit 6` (`0x0040`): `BLE_FEAT_CANDIDATE_SOURCE` +- `Bit 7` (`0x0080`): `BLE_FEAT_PHONE_PRESETS` +- `Bit 8` (`0x0100`): `BLE_FEAT_NVS_PERSISTENCE` +- `Bit 9` (`0x0200`): `BLE_FEAT_AUTH_WRITES` +- `Bit 10` (`0x0400`): `BLE_FEAT_DECODER_EXT` (width/endianness/offset/clamp) +- `Bit 11` (`0x0800`): `BLE_FEAT_HYSTERESIS` +- `Bit 12` (`0x1000`): `BLE_FEAT_CAL_WORKFLOW` +- `Bit 13` (`0x2000`): `BLE_FEAT_DIAGNOSTICS_TLV` +- `Bit 14` (`0x4000`): `BLE_FEAT_CAPTURE_EXPORT` +- `Bit 15` (`0x8000`): `BLE_FEAT_CAPTURE_STAGE` (authenticated stage-label command) +- `Bit 16` (`0x10000`): `BLE_FEAT_LED_BENCH_TEST` (authenticated 10-second synthetic test) +- `Bit 17` (`0x20000`): `BLE_FEAT_EXT_STARTUP_ANIM` (startup animations 4 Center Out and 5 Strobe Rush) +- `Bit 18` (`0x40000`): `BLE_FEAT_RANGE_DISCOVERY` (supports opcode 0x03 GET_ARG_RANGES) +- `Bit 19` (`0x80000`): `BLE_FEAT_OTA_UPDATE` (supports dual-slot authenticated firmware OTA) +- `Bit 20` (`0x100000`): `BLE_FEAT_LOOP_STARTUP` (startup duration bit 15 allows continuous looping) + +--- + +### 4.2 Configuration Command Packet (`0xd215`, WRITE, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `opcode` | `uint8_t` | Command opcode (see Section 4.4) | +| 2..3 | `sequence` | `uint16_t` | Client request sequence counter (echoed in Result) | +| 4 | `payloadLength` | `uint8_t` | Number of valid parameter bytes in `payload` (0..14) | +| 5 | `flags` | `uint8_t` | Bit 0: `IS_STAGED` (1 = stage in active transaction, 0 = apply live) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Command arguments | + +Incoming commands are queued through a bounded SPSC ring (4 entries); overflowed commands are counted and dropped rather than corrupting the queue. + +--- + +### 4.3 Configuration Result Packet (`0xd216`, READ/NOTIFY, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `respondedOpcode`| `uint8_t` | Opcode being acknowledged | +| 2..3 | `sequence` | `uint16_t` | Client sequence counter echoed from request | +| 4 | `statusCode` | `uint8_t` | Execution status (0 = OK, see Section 4.5) | +| 5 | `resultFlags` | `uint8_t` | Result flags (Bit 0=Persisted, Bit 1=Staged, Bit 2=Applied, Bit 3=AuthRequired) | +| 6..9 | `activeRevision` | `uint32_t` | Active configuration revision after command execution | +| 10 | `payloadLength` | `uint8_t` | Number of response bytes in `payload` (0..9) | +| 11..19 | `payload[9]` | `uint8_t[9]` | Optional response data (challenge nonce, calibration fit, statuses) | + +--- + +### 4.4 Command Opcodes + +**Authorization:** read-only queries (`0x01`, `0x02`, `0x43`, `0x46`, `0x50`) and the auth flow itself (`0x24`, `0x25`, `0x26`) are unauthenticated. Every other opcode requires a session bound to the current connection (challenge-response) or an open physical BOOT window. + +| Opcode | Name | Payload Arguments | Description | +|---|---|---|---| +| `0x01` | `GET_CAPABILITIES` | None | Updates Capabilities characteristic | +| `0x02` | `GET_SNAPSHOT` | None | Triggers complete config snapshot streaming on `0xd217` | +| `0x03` | `GET_ARG_RANGES` | None | Range discovery (max brightness, LED count, effect count, anim count, max RPM) | +| `0x10` | `SET_POWER` | `[power: u8 (0 or 1)]` | Master LED strip power switch | +| `0x11` | `SET_BRIGHTNESS` | `[brightness: u8 (0..255)]` | Master LED brightness | +| `0x12` | `SET_GLOBAL_RGB`| `[R: u8, G: u8, B: u8]` | Set uniform color across all 6 LEDs | +| `0x13` | `SET_LED_RGB` | `[index: u8 (0..5), R, G, B]` | Set individual LED color | +| `0x14` | `SET_EFFECT` | `[effectId: u8 (0..5), speed: u8 (0..100)]` | 0=Static, 1=Breathing, 2=Rainbow, 3=Chase, 4=Verified RPM Bar, **5=Provisional CAN RPM Preview (unverified)** | +| `0x15` | `SET_STARTUP` | `[animId: u8 (0..5), durationMs: u16 LE]` | 0=None, 1=Sweep, 2=Wave, 3=Pulse, 4=CenterOut, 5=Strobe Rush | + +**Optional loop extension:** On firmware advertising feature bit 20, the 16-bit startup duration uses bit 15 (`0x8000`) as `loopEnabled`. The low 15 bits remain the animation cycle length (100..10000 ms). With bit 15 cleared, the startup animation plays once as before. This uses the existing Config V2 packet, snapshot and schema-3 NVS blob without changing their sizes. Looping is invalid with animation 0 (None). Old firmware does not advertise the bit and must not receive loop-enabled settings. While enabled, fault, master power-off, commissioning/feedback, bench test, and active RPM or missing-RPM safeguards retain priority. Persist this setting with authenticated `SAVE_CONFIG` after `SET_STARTUP` or the preset transaction. Active RAM settings alone do not survive reboot. +| `0x16` | `SET_LED_THRESHOLD`| `[index: u8 (0..5), rpm: u16 LE]` | Set threshold for LED index (must remain monotonic) | +| `0x17` | `SET_SHIFT_WARNING`| `[warningRpm: u16 LE, patternId: u8]` | Pattern: 0=Flash (10 Hz), 1=Strobe (20 Hz), 2=Solid, 3=Off | +| `0x18` | `SET_RPM_MULTIPLIER`| `[multX1000: u32 LE]` | Provisional multiplier (0.1..1000.0). **Invalidates calibration!** | +| `0x19` | `SET_CANDIDATE_SOURCE` | `[canId: u32 LE, byteIdx: u8, ext: u8]` | Target CAN candidate source. **Invalidates calibration!** | +| `0x1A` | `SET_LED_DIRECTION`| `[direction: u8 (0=Forward, 1=Reverse)]`| Shift light display direction | +| `0x1B` | `SET_WARNING_RGB`| `[R: u8, G: u8, B: u8]` | Warning color for over-rev alert | +| `0x1C` | `SET_RPM_HYSTERESIS` | `[hysteresisRpm: u16 LE (0..2000)]` | Falling-RPM dead band for bar/warning latching | +| `0x1D` | `SET_RPM_DECODER_EXT` | `[width: u8 (1|2), endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` (8 bytes) | Byte width/order, RPM offset, validity clamp. **Invalidates calibration!** | +| `0x20` | `SAVE_CONFIG` | None | Commit active configuration to flash NVS (`"ps_cfg"`) | +| `0x21` | `RESTORE_DEFAULTS` | `[0xA5, 0x5A]` | Restore safe lighting/decoder defaults and save to NVS. **Owner credentials and captures are preserved.** | +| `0x22` | `RELOAD_CONFIG` | None | Re-read the persisted NVS blob and apply it to the active state | +| `0x24` | `ENROLL_OWNER` | `[secret: u8[12]]` | Owner enrollment or credential recovery (requires open BOOT window); safe re-enrollment overwrites the old credential | +| `0x25` | `AUTHENTICATE` | `[proof: u8[8]]` | Authenticate connection session via SHA-256 proof | +| `0x26` | `REQUEST_CHALLENGE`| None | Request 4-byte single-use cryptographic challenge nonce | +| `0x30` | `BEGIN_TRANSACTION`| None | Start staged transaction (30s timeout) | +| `0x31` | `COMMIT_TRANSACTION`| None | Validate all staged changes and apply atomically | +| `0x32` | `ABORT_TRANSACTION` | None | Discard all staged changes without modifying active config | +| `0x40` | `CAL_BEGIN` | None | Start the mobile-assisted calibration session (10 min timeout) | +| `0x41` | `CAL_ABORT` | None | Abort the calibration session | +| `0x42` | `CAL_CAPTURE_START` | None | Open the 2 s raw sampling window at the current operating point | +| `0x43` | `CAL_CAPTURE_STATUS` | None | Query window. Result payload: `[samples: u16 LE, elapsedMs: u16 LE]` | +| `0x44` | `CAL_POINT_COMMIT` | `[refRpm: u16 LE]` | Close the window, require >=10 stable samples (stddev <= 1.5 raw), store the point | +| `0x45` | `CAL_COMPUTE` | `[apply: u8]` | Fit scale/offset over 3..6 points, validate evidence. Result payload on OK (9 bytes): `[multiplierX1000: s32 LE, offsetX1000: s32 LE, info: u8]` where info = pointsUsed (low nibble) \| worst residual in 10-RPM steps clamped to 15 (high nibble); on failure: reason string (<= 9 bytes). Applying binds the verification record to the decoder fingerprint | +| `0x46` | `CAL_STATUS` | None | Query session. Result payload: `[active: u8, points: u8, captureActive: u8, samples: u16 LE]` | +| `0x50` | `GET_DIAGNOSTICS` | None | Stream the diagnostics TLV blob on `0xd217` (Section 4.8) | +| `0x51` | `RESTART_DEVICE` | `[0xA5, 0x5A]` | Acknowledge, then soft-restart the ESP32 | +| `0x52` | `CLEAR_DIAGNOSTICS` | `[0xA5, 0x5A]` | Clear the diagnostic event log ONLY (captures and credentials untouched) | +| `0x53` | `SET_CAPTURE_RECORDING` | `[enable: u8]` | Start/stop flash recording; start is state-gated (damaged/preserved/full storage => `INVALID_STATE`) | +| `0x54` | `SET_CAPTURE_STAGE` | `[stage: u8 (1..3)]` | Label subsequent CAN capture records: 1=KeyOn, 2=Idle, 3=RPM sweep. Does not change operation or synthesize CAN data. | +| `0x55` | `SET_LED_TEST_RPM` | `[testRpm: u16 LE (0..20000), enable: u8 (0 or 1)]` | Authenticated, temporary 10-second synthetic six-LED bench test. `enable=0` stops it; independent of real CAN data. Does not persist or inject CAN frames. | +| `0x60` | `OTA_BEGIN` | `[0xA5, 0x5C, size: u32 LE, shaPrefix: u8[4]]` | Begin authenticated dual-slot OTA update to inactive partition. Validates image size and stationary safety interlock. | +| `0x61` | `OTA_DATA` | `[chunkIdx: u16 LE, dataLen: u8, data...]` | Stream sequential image chunks. The Android client uses 11 data bytes at the baseline ATT MTU and up to 230 with a larger negotiated MTU. | +| `0x62` | `OTA_END` | `[shaTail: u8[4], crc32: u32 LE]` | Conclude transfer, verify full-image FIPS 180-2 SHA-256 hash, set boot partition, schedule restart (1.5s delay). | +| `0x63` | `OTA_ABORT` | None | Cancel active update, discard written data and return OTA engine to Idle state. | +| `0x64` | `OTA_CONFIRM` | `[0xA5, 0x5C]` | Cancel bootloader rollback after successful boot self-test. | +| `0x65` | `OTA_STATUS` | None | Query OTA engine state, active running slot, and written bytes. | +| `0x65` | `OTA_STATUS` digest | `[index: u8, 0..3]` | If capability bit 2 is set, returns index followed by 8 digest bytes at offset `8 * index`. The result fits the same 20-byte frame. | + +--- + +### 4.5 Status Codes + +| Code | Name | Description | +|---|---|---| +| `0` | `BLE_CFG_STATUS_OK` | Command executed successfully | +| `1` | `BLE_CFG_STATUS_INVALID_PARAM` | Parameter out of range or non-monotonic | +| `2` | `BLE_CFG_STATUS_UNSUPPORTED` | Opcode or parameter unsupported | +| `3` | `BLE_CFG_STATUS_BUSY` | Controller busy or under rate-limiting lockout | +| `4` | `BLE_CFG_STATUS_UNAUTHORIZED` | Authorization required; enrollment or authentication needed | +| `5` | `BLE_CFG_STATUS_INVALID_STATE` | Staged outside tx, expired challenge, storage not usable, or invalid session | +| `6` | `BLE_CFG_STATUS_STORAGE_ERROR` | Flash NVS write failed | +| `7` | `BLE_CFG_STATUS_VERSION_MISMATCH`| Protocol version mismatch | +| `8` | `BLE_CFG_STATUS_VALIDATION_FAILED`| Configuration validation failed | +| `9` | `BLE_CFG_STATUS_OTA_CHECKSUM_ERROR`| SHA-256 hash or CRC32 verification failed | +| `10` | `BLE_CFG_STATUS_OTA_FLASH_ERROR`| Flash partition write or erase error | + +--- + +### 4.6 Configuration Snapshot (`0xd217`, NOTIFY, 20-Byte Chunks) + +Streamed with 20 ms pacing between chunks to prevent Bluetooth buffer congestion. The same characteristic carries diagnostics blobs (schema byte `1`) and configuration snapshots (schema byte `3`); clients dispatch on the reassembled schema byte. + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1..2 | `snapshotId` | `uint16_t` | Snapshot identifier (little-endian; the request sequence) | +| 3 | `chunkIndex` | `uint8_t` | 0-based chunk sequence index | +| 4 | `chunkCount` | `uint8_t` | Total chunks comprising the blob | +| 5 | `payloadLength` | `uint8_t` | Number of valid bytes in this chunk (1..14) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Serialized TLV fragment | + +#### Reassembled Configuration Snapshot Binary Layout (schema 3) +```text +[Byte 0] : schemaVersion (uint8_t = 3) +[Bytes 1..4] : activeRevision (uint32_t LE) +[Bytes 5..N-4]: TLV Records (see Section 4.7) +[Bytes N-3..N]: CRC32 (uint32_t LE, IEEE 802.3 over Bytes 0..N-4) +``` + +#### Reassembled Diagnostics Blob Binary Layout (schema 1) +```text +[Byte 0] : schemaVersion (uint8_t = 1) +[Bytes 1..4] : revision (uint32_t LE, always 0) +[Bytes 5..N-4]: Diagnostics TLV Records (see Section 4.8) +[Bytes N-3..N]: CRC32 (uint32_t LE) +``` + +--- + +### 4.7 Configuration Snapshot TLVs (schema 3) + +Every TLV record is formatted as `[Tag: uint8_t, Length: uint8_t, Value: uint8_t[Length]]`. + +All 12 mandatory tags (`0x10` through `0x1B`) are always emitted; schema-3 tags `0x1C`..`0x1E` accompany them. Unknown tags must be tolerated (skipped) by clients for forward compatibility. + +| Tag | Name | Length | Value Format | Description | +|---|---|---|---|---| +| `0x10` | Power | 1 | `[power: u8]` | `0` = Off, `1` = On | +| `0x11` | Brightness | 1 | `[brightness: u8]` | Master brightness `0..255` | +| `0x12` | Global Color | 3 | `[R, G, B]` | Primary single RGB color | +| `0x13` | Per-LED Colors | 18 | `[6 * (R, G, B)]` | Individual RGB colors for LEDs 0..5 | +| `0x14` | Effect & Speed | 2 | `[effectId: u8, speed: u8]` | Effect (0..5), Speed (0..100) | +| `0x15` | Startup Animation | 3 | `[animId: u8, durationMs: u16 LE]` | Startup anim (0..5), duration in ms | +| `0x16` | RPM Thresholds | 12 | `[6 * u16 LE]` | Monotonic thresholds for LEDs 0..5 | +| `0x17` | Shift Warning | 3 | `[warningRpm: u16 LE, patternId: u8]`| Warning threshold and pattern (0..3, 3 = Off) | +| `0x18` | RPM Multiplier | 4 | `[multX1000: u32 LE]` | Multiplier * 1000 (e.g. 40.0 -> 40000) | +| `0x19` | CAN Candidate | 6 | `[canId: u32 LE, byteIdx: u8, ext: u8]`| Target candidate CAN source | +| `0x1A` | LED Direction | 1 | `[direction: u8]` | `0` = Forward (0->5), `1` = Reverse (5->0) | +| `0x1B` | Warning Color | 3 | `[R, G, B]` | Alert over-rev flash color | +| `0x1C` | Decoder Extension | 8 | `[width: u8, endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` | Byte width/order, RPM offset, validity clamp | +| `0x1D` | Calibration Record | 11 | `[verified: u8, fingerprint: u32 LE, pointsUsed: u8, maxResidualRpm: u8, timestampMs: u32 LE]` | Bound verification record | +| `0x1E` | Hysteresis | 2 | `[hysteresisRpm: u16 LE]` | Threshold dead band | + +--- + +### 4.8 Diagnostics Blob TLVs (GET_DIAGNOSTICS, schema 1) + +| Tag | Name | Length | Value Format | +|---|---|---|---| +| `0x40` | Uptime | 4 | `uptimeMs: u32 LE` | +| `0x41` | Firmware Version | 3 | `[major, minor, patch]` | +| `0x42` | Reset Reason | 1 | `esp_reset_reason` of the last boot | +| `0x43` | CAN Status | 26 | `[bitrate: u32, totalRx: u32, accepted: u32, missed: u32, overrun: u32, busErrors: u32, healthy: u8, traffic: u8]` | +| `0x44` | RPM Decoder State | 34 | `[canId: u32, byteIndex: u8, byteWidth: u8, extended: u8, multX1000: s32, offsetX1000: s32, maxValid: u16, raw: u16, estimatedRpm: u16, fresh: u8, valid: u8, calVerified: u8, ageMs: u16, received: u32, rejected: u32]` | +| `0x45` | Storage State | 29 | `[total: u32, used: u32, free: u32, mounted: u8, storageFull: u8, capturePreserved: u8, damaged: u8, recording: u8, records: u32, captureSize: u32, diagLogSize: u32]` | +| `0x46` | BLE State | 5 | `[connected: u8, advertising: u8, securityMode: u8, ownerEnrolled: u8, sessionAuthorized: u8]` | +| `0x47` | Capture Info | 9 | `[stage: u8, sessionId: u32, bootCount: u32]` | +| `0x48` | Last Error | <= 96 | UTF-8 text of the last Error/Critical event this session (absent when none) | +| `0x49` | Calibration State | 13 | `[sessionActive: u8, points: u8, captureActive: u8, samples: u16, calVerified: u8, pointsUsed: u8, maxResidualRpm: u8, fingerprint: u32]` | +| `0x4A` | Experimental CAN bytes | 5 | Freshness bitmask followed by raw `0x302[1]`, `0x302[5]`, `0x452[7]`, `0x540[3]`. Bit index matches byte order. A clear bit means unavailable at snapshot time. Standard non-RTR frames, max sample age 1000 ms. | + +--- + +## 5. Owner Enrollment and Challenge-Response Authentication + +The PulseShift hardware is a dedicated headless embedded unit. To defend against unauthorized vehicle tuning or drive-by configuration tampering, PulseShift enforces physical owner presence and cryptographic authentication: + +```text +[Phone Application] [PulseShift ESP32] + | | + | (User presses physical BOOT button on ESP32) | + | <-------------------------------------------------------| BOOT Window Open (60s) + | | (LEDs pulse Cyan) + | ENROLL_OWNER (0x24) [secret: 12 bytes] | + |--------------------------------------------------------->| Store in NVS ("ps_sec") + | Result (0x24, OK, PERSISTED | APPLIED) | Session Authorized + |<---------------------------------------------------------| + : : + : (Normal Phone Use in subsequent sessions) : + | | + | REQUEST_CHALLENGE (0x26) | + |--------------------------------------------------------->| Generate 32-bit nonce + | Result (0x26, OK, payload: challenge [4 bytes LE]) | 30-second TTL + |<---------------------------------------------------------| + | | + | Compute Proof: | + | SHA-256(secret[12] || challenge[4] || seq[2])[:8] | + | | + | AUTHENTICATE (0x25) [proof: 8 bytes] | Single-use nonce consumed + |--------------------------------------------------------->| Constant-time comparison + | Result (0x25, OK) | Session Authorized (5 min) + |<---------------------------------------------------------| + | | + | SET_BRIGHTNESS, SET_EFFECT, etc. | Writes Permitted + |--------------------------------------------------------->| +``` + +### 5.1 Owner Enrollment Flow (and Credential Recovery) +1. The user presses the physical **BOOT** button (GPIO0) on the ESP32. +2. The controller opens a **60-second authorization window** and pulses the LED strip in cyan. +3. The phone sends opcode `0x24` (`ENROLL_OWNER`) containing a randomly generated 12-byte cryptographic secret. +4. The ESP32 validates the open BOOT window, verifies the secret is non-trivial, and stores it in a dedicated CRC-protected NVS namespace `"ps_sec"`. +5. The session is immediately marked authorized, bound to this connection. +6. **Credential recovery** is the same flow: pressing BOOT and re-enrolling overwrites the previous credential. Credential recovery and configuration reset are deliberately distinct operations. + +### 5.2 Subsequent Authenticated Phone Sessions +1. In future rides, the phone connects via BLE without pressing the BOOT button and automatically performs the challenge-response exchange using its stored credential. +2. The phone sends opcode `0x26` (`REQUEST_CHALLENGE`). +3. The ESP32 returns a 4-byte pseudo-random challenge nonce (`esp_random()`) with a 30-second TTL. +4. The phone computes the 8-byte authentication proof: `SHA-256(secret[12] || challenge[4 LE] || sequence[2 LE])[:8]`. +5. The phone sends opcode `0x25` (`AUTHENTICATE`) with the 8-byte proof. +6. The ESP32 consumes the challenge immediately (defeating replay), computes the matching proof, and verifies in constant time. +7. Upon verification, the session is authorized for 5 minutes of activity (refreshed per command) and is bound to that specific connection handle: another concurrent connection cannot ride the session. + +### 5.3 Negative Security Defenses +- **Proof-Less Session Rejection:** Physical presence alone never grants a session; opcode `0x25` requires a valid proof (`BLE_CFG_STATUS_UNAUTHORIZED = 4`). +- **Replay Attack Defense:** Every challenge is strictly single-use. Re-submitting the same proof without requesting a fresh challenge fails with `BLE_CFG_STATUS_INVALID_STATE = 5`. +- **Challenge Expiration:** Challenges expire after 30 seconds (`BLE_CFG_STATUS_INVALID_STATE = 5`). +- **Brute-Force Rate Limiting:** After 5 consecutive failed authentications, challenge requests are locked out for 3 seconds (`BLE_CFG_STATUS_BUSY = 3`). +- **Disconnect Invalidation:** Client disconnection immediately terminates the authenticated session, invalidates pending challenges and aborts staged transactions. +- **Connection Binding:** Sessions are valid only for the authenticating connection handle (`isAuthorizedFor(connId)`). +- **Configuration Reset vs Credentials:** `RESTORE_DEFAULTS` (`0x21`) resets lighting/decoder preferences but preserves owner credentials and stored captures. `CLEAR_DIAGNOSTICS` (`0x52`) clears only the event log. + +--- + +## 6. Cross-Language Byte Test Vectors + +The following deterministic test vector is published to verify cross-language byte serialization between Python (`test_ble_config_v2.py`), Android Kotlin (`ProtocolV2CodecTest.kt`), and C++ ESP32 firmware: + +### 6.1 Challenge-Response Vector +```text +Owner Secret (12 bytes ASCII): +"PULSE_KEY_96" -> [0x50, 0x55, 0x4c, 0x53, 0x45, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x39, 0x36] + +Challenge Nonce (uint32_t LE = 0x12345678): +[0x78, 0x56, 0x34, 0x12] + +Request Sequence (uint16_t LE = 42): +[0x2a, 0x00] + +Combined Hash Input (18 bytes): +50 55 4c 53 45 5f 4b 45 59 5f 39 36 78 56 34 12 2a 00 + +SHA-256 Full Digest (32 bytes): +12 38 a0 9b 10 7e 9d 79 38 a6 37 da 41 e9 c4 ee fa ec eb c4 e0 e0 0e 86 5d dd d1 fa 1c 35 c4 cc + +Expected Auth Proof (First 8 bytes): +[0x12, 0x38, 0xa0, 0x9b, 0x10, 0x7e, 0x9d, 0x79] -> Hex string: "1238a09b107e9d79" +``` +# Strip, RPM mapping and animation extension (2.5) + +Capability bit 23 and protocol minor ≥ 5 advertise version 1 of Lighting Setup. +Standard Config V2 command, result and snapshot chunk sizes remain 20 bytes. +Multi-byte fields below use little endian. + +| Operation | Request payload | Result | +| --- | --- | --- | +| `GET_SNAPSHOT` (`02`) | Empty for legacy, `[1]` for extended | Adds TLV `21` (setup) and `22` (version, saved count or zero if unconfirmed) to the existing CRC-protected stream | +| `LIGHTING_BEGIN` (`70`) | Version u8, payload length u16, IEEE CRC-32 u32, base revision u32 | Staged; command sequence is the upload ID | +| `LIGHTING_DATA` (`71`) | Upload ID u16, byte offset u16, 1-10 data bytes | Staged, contiguous offsets only | +| `LIGHTING_SAVE` (`72`) | Upload ID u16 | Applied + persisted only after verified NVS readback; storage errors carry the save status | +| `LIGHTING_CANCEL` (`73`) | Upload ID u16 | Discards partial upload | +| `AMBIENT_STATUS` (`74`) | Version u8 | Version, playback status (off 0, playing 1, paused by RPM 2, safety 3, waiting 4), preview eligibility (0/1) | +| `ANIMATION_PREVIEW` (`75`) | Version u8, pattern u8, duration u16 | Authenticated one-shot request, subject to current safety eligibility | + +Setup payload has a 15-byte header. Fields in order are version, installed count, +active count (0 follows installed), mapping mode, entry count, boot enabled, +boot pattern, boot duration u16, ambient enabled, ambient pattern, ambient +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 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, +wrong transaction ID, invalid offsets, incomplete payloads and CRC mismatches +fail before changing active settings. Status 11 identifies an integrity error. +Configuration results reference each command sequence. Clients must check the +final revision and the full extended snapshot including the flash-match flag. +An app applying a phone preset can open a standard transaction and set the +staged flag on `LIGHTING_BEGIN` only. In that case `LIGHTING_SAVE` sets the +staged copy and acknowledges Staged. The subsequent standard commit and +verified save retain their existing meanings. + +Old snapshots keep the original six thresholds, strip-count extension and +combined startup field. Legacy startup writes translate the loop bit to the +ambient fields. Legacy single-threshold commands return Unsupported on a +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 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..ae06289 100644 --- a/docs/LIGHTING-SETUP.md +++ b/docs/LIGHTING-SETUP.md @@ -1,59 +1,43 @@ -# Strip setup, RPM mapping and ambient animation - -## Strip and RPM - -The installed count is the owner's configuration for the next boot. The running count is the number of pixels configured in the current RMT driver. A verified save reports the stored installed count separately. The renderer uses the smaller of the running and installed counts as its ceiling, so a pending shrink can darken surplus pixels immediately. The driver still sends a complete frame for its running length. When all installed LEDs are enabled, the active count follows that ceiling. An explicit active count is limited to the same ceiling. - -Logical LED 1 starts at the GPIO27 data-input end in Normal direction. Reverse starts at the far end of the running strip. All layers leave pixels outside the active segment dark, including shift warnings and animations. RGB palette selection uses the existing six color zones spread over the active segment. The zones have no role in calculating configurable RPM thresholds. - -- Automatic maps the first and last active LEDs to the configured endpoints. Each intermediate threshold is the integer result of `min + ((max - min) * i + (n - 1) / 2) / (n - 1)`. A single pixel uses the minimum. -- Grouped accepts one or more positive group sizes whose sum equals the configured active count. For 12 pixels, group sizes 3/3/2/2/1/1 activate 3, 6, 8, 10, 11 and 12 pixels at the six respective thresholds. -- Individual accepts a threshold for each active LED. Equal thresholds activate together. All thresholds use whole RPM, are nondecreasing, and are bounded by warning RPM. Warning RPM may equal the highest threshold. When enabled, the warning then takes precedence over the bar. -- A lit pixel releases strictly below `max(0, threshold - hysteresis)`. The warning has its own latch using the same hysteresis and uses the existing color and flash, strobe, solid or off settings. A zero-RPM sample clears the latches. An invalid, stale or nonqualifying sample also clears live RPM latches. Test and real RPM have separate latch histories. - -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 - -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. - -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. - -## 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. - -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. - -## ESP32 RMT and power - -Arduino-ESP32 3.3.12 uses the ESP-IDF RMT copy encoder, four 64-symbol blocks, no DMA and an interrupt-refilled stream for long frames. The HAL borrows the encoded symbols until TX completion. The controller polls completion without waiting in the LED driver and preserves in-flight symbols through a timeout. A rejected enqueue can recover from idle. A stuck transfer after 100 ms quarantines the driver and its buffer until reset. The confirmed frame is updated only on TX completion. CAN ingestion, watchdog servicing and BLE telemetry can continue while the transfer is pending. Main-task flash operations and GATT config dispatch wait for the transfer to finish or be quarantined to reduce refill starvation. An RMT completion confirms peripheral completion only. [Arduino 3.3.12 HAL source](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/esp32-hal-rmt.c), [Arduino RMT API](https://docs.espressif.com/projects/arduino-esp32/en/latest/api/rmt.html), [ESP-IDF RMT guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) - -The verified encoding is GRB, most-significant-bit first. At 10 MHz the high/low pairs are 0.3/0.9 µs for zero and 0.8/0.6 µs for one. Every frame includes 300 µs low reset time. A 64-pixel frame uses 1,537 payload symbols and has a nominal wire duration of 2.143-2.450 ms before software overhead. The pitch between half-buffer refills is about 154-179 µs while sending data. Classic ESP32 refill latency with BLE is a physical validation gate. [Espressif RMT FAQ](https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/rmt.html), [Worldsemi WS2812B-V5 datasheet](https://files.keeb.supply/products/ws2812b-rgb-led/datasheet.pdf) - -GPIO27 is data only. At 5 V use a suitable 3.3 V to 5 V logic buffer, common ground, and the existing electrical protections. Full-white supply allowance at 60 mA per pixel is 0.36 A for six and 3.84 A for 64. These are design budgets, with the actual draw dependent on strip revision, brightness and color. Check voltage drop and provision the strip supply and injection points for its actual wiring. [Adafruit NeoPixel powering guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels) - -## Hardware acceptance checklist - -- 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. -- 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. +# Strip setup, RPM mapping and startup animation + +## Strip and RPM + +The installed count is the owner's configuration for the next boot. The running count is the number of pixels configured in the current RMT driver. A verified save reports the stored installed count separately. The renderer uses the smaller of the running and installed counts as its ceiling, so a pending shrink can darken surplus pixels immediately. The driver still sends a complete frame for its running length. When all installed LEDs are enabled, the active count follows that ceiling. An explicit active count is limited to the same ceiling. + +Logical LED 1 starts at the GPIO27 data-input end in Normal direction. Reverse starts at the far end of the running strip. All layers leave pixels outside the active segment dark, including shift warnings and animations. RGB palette selection uses the existing six color zones spread over the active segment. The zones have no role in calculating configurable RPM thresholds. + +- Automatic maps the first and last active LEDs to the configured endpoints. Each intermediate threshold is the integer result of `min + ((max - min) * i + (n - 1) / 2) / (n - 1)`. A single pixel uses the minimum. +- Grouped accepts one or more positive group sizes whose sum equals the configured active count. For 12 pixels, group sizes 3/3/2/2/1/1 activate 3, 6, 8, 10, 11 and 12 pixels at the six respective thresholds. +- Individual accepts a threshold for each active LED. Equal thresholds activate together. All thresholds use whole RPM, are nondecreasing, and are bounded by warning RPM. Warning RPM may equal the highest threshold. When enabled, the warning then takes precedence over the bar. +- A lit pixel releases strictly below `max(0, threshold - hysteresis)`. The warning has its own latch using the same hysteresis and uses the existing color and flash, strobe, solid or off settings. A zero-RPM sample clears the latches. An invalid, stale or nonqualifying sample also clears live RPM latches. Test and real RPM have separate latch histories. + +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. + +## Startup animation and RPM takeover + +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 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 + +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. + +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 + +Arduino-ESP32 3.3.12 uses the ESP-IDF RMT copy encoder, four 64-symbol blocks, no DMA and an interrupt-refilled stream for long frames. The HAL borrows the encoded symbols until TX completion. The controller polls completion without waiting in the LED driver and preserves in-flight symbols through a timeout. A rejected enqueue can recover from idle. A stuck transfer after 100 ms quarantines the driver and its buffer until reset. The confirmed frame is updated only on TX completion. CAN ingestion, watchdog servicing and BLE telemetry can continue while the transfer is pending. Main-task flash operations and GATT config dispatch wait for the transfer to finish or be quarantined to reduce refill starvation. An RMT completion confirms peripheral completion only. [Arduino 3.3.12 HAL source](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/esp32-hal-rmt.c), [Arduino RMT API](https://docs.espressif.com/projects/arduino-esp32/en/latest/api/rmt.html), [ESP-IDF RMT guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) + +The verified encoding is GRB, most-significant-bit first. At 10 MHz the high/low pairs are 0.3/0.9 µs for zero and 0.8/0.6 µs for one. Every frame includes 300 µs low reset time. A 64-pixel frame uses 1,537 payload symbols and has a nominal wire duration of 2.143-2.450 ms before software overhead. The pitch between half-buffer refills is about 154-179 µs while sending data. Classic ESP32 refill latency with BLE is a physical validation gate. [Espressif RMT FAQ](https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/rmt.html), [Worldsemi WS2812B-V5 datasheet](https://files.keeb.supply/products/ws2812b-rgb-led/datasheet.pdf) + +GPIO27 is data only. At 5 V use a suitable 3.3 V to 5 V logic buffer, common ground, and the existing electrical protections. Full-white supply allowance at 60 mA per pixel is 0.36 A for six and 3.84 A for 64. These are design budgets, with the actual draw dependent on strip revision, brightness and color. Check voltage drop and provision the strip supply and injection points for its actual wiring. [Adafruit NeoPixel powering guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels) + +## Hardware acceptance checklist + +- 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 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/test/test_ble_commands.cpp b/test/test_ble_commands.cpp index fc74a1f..c0c83e8 100644 --- a/test/test_ble_commands.cpp +++ b/test/test_ble_commands.cpp @@ -1782,12 +1782,12 @@ static void test_lighting_setup_transfer() { // BLE link and ending the auth window must leave the loop running in phase. LedEffectEngine engine; engine.reset(now); - const uint32_t start = 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 = start + elapsed; + const uint32_t at = loopStart + elapsed; CHECK(candidate.ingest(zero, at)); LedFrameInput input; input.canTrafficSeen = true; From 81b72b424ff1398a4b0e88aa7806ee8696364740 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 22:07:06 +0530 Subject: [PATCH 3/7] Correct BLE loop regression and update protocol notes --- docs/BLE-PROTOCOL.md | 1030 ++++++++++++++++++++-------------------- docs/LIGHTING-SETUP.md | 86 ++-- 2 files changed, 558 insertions(+), 558 deletions(-) diff --git a/docs/BLE-PROTOCOL.md b/docs/BLE-PROTOCOL.md index bc23ae6..8b1de99 100644 --- a/docs/BLE-PROTOCOL.md +++ b/docs/BLE-PROTOCOL.md @@ -1,515 +1,515 @@ -# PulseShift BLE Protocol Specification (v1 & v2) - -**Document Version:** 2.3.0 -**Target Hardware:** ESP32 DevKit V1 (ESP32-D0WD-V3) -**Companion App:** PulseShift Android App (`D:\Development\PulseShift\android`) -**Firmware Library:** NimBLE-Arduino 2.3.8 -**Arduino-ESP32 Core:** 3.3.12 (ESP-IDF 5.3+) - ---- - -## 1. Overview and Architecture - -PulseShift BLE Protocol defines the Bluetooth Low Energy GATT communication between the PulseShift ESP32 motorcycle firmware and the companion Android smartphone application. The Android app is the complete command interface: every normal configuration and diagnostic operation is executable over BLE, and the firmware runs fully standalone without USB, serial or a PC. - -### Key Tenets -1. **Unidirectional CAN Safety:** The ESP32 is a passive, receive-only automotive monitor (SN65HVD230 CTX tied to 3V3, GPIO17 air-gapped, listen-only TWAI mode with a zero-length TX queue). BLE configuration changes modify only local LED rendering, RPM thresholds, shift alerts, animations, and candidate monitoring parameters. BLE **never** injects frames into the vehicle CAN bus, and the firmware contains no CAN transmit API at all. -2. **Fixed 20-Byte Wire MTU:** Every characteristic command, response, and telemetry notification is constrained to exactly 20 bytes. No MTU renegotiation or L2CAP segmentation is required; large payloads are reassembled at the application layer. -3. **Little-Endian Architecture:** All multi-byte integers (`uint16_t`, `uint32_t`, `float`) are serialized in standard IEEE 754 little-endian byte ordering. -4. **Resilient and Decoupled:** The ESP32 firmware functions autonomously without an active BLE connection. Telemetry notifications are sent only to subscribed GATT clients. Disconnections automatically re-arm advertising without interrupting CAN reception or LED rendering. -5. **NVS Persistence and Staged Transactions:** Changes can be applied immediately, staged across atomic multi-parameter transactions, and saved to non-volatile storage (NVS) using CRC32 checksums. -6. **Defensible Cryptographic Owner Security:** Physical presence proof (60-second authorization window triggered by the physical BOOT button on the ESP32) is mandatory for owner enrollment and credential recovery. Once enrolled, the phone authenticates via cryptographic challenge-response (SHA-256) without requiring physical button presses for ordinary configuration adjustments. -7. **Acknowledged Execution:** A Bluetooth write returning success is NOT proof of execution. Every v2 command carries a client `sequence` echoed in the result packet together with a status code and result flags; the app requires request/response correlation plus snapshot readback for configuration changes. - ---- - -## 2. GATT Service and Characteristics - -**Advertised Device Name:** `PulseShift` -**Primary Service UUID:** `fe12d210-3d4f-4b9d-a21c-92782ecb4000` - -| Purpose | Full UUID | Properties | Frequency / Access | Description | -|---|---|---|---|---| -| **RPM Telemetry** | `fe12d211-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 10 Hz (100 ms) | Live engine speed, raw candidate byte, age, CAN frame count | -| **System Health** | `fe12d212-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 1 Hz (1000 ms) | CAN bus health, missed/overrun counters, storage status | -| **Diagnostic Logs** | `fe12d213-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Event / Paced (20 ms) | Live diagnostic events, paginated historical logs, CAN capture pages | -| **Control Requests (v1)**| `fe12d214-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | GET_LOG_PAGE / CANCEL_LOGS / GET_CAPTURE_PAGE / CANCEL_CAPTURE | -| **Config Command (v2)** | `fe12d215-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | Configuration write/read requests, device control, transaction controls | -| **Config Result (v2)** | `fe12d216-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | Immediate response | Status code, active revision counter, and result flags | -| **Config Snapshot (v2)**| `fe12d217-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Paced (20 ms stream) | Multi-chunk serialized configuration TLV blob (schema 3) or diagnostics TLV blob (schema 1) with CRC32 | -| **Capabilities (v2)** | `fe12d218-3d4f-4b9d-a21c-92782ecb4000` | `READ` | Static / On revision | Hardware capabilities, feature mask, firmware version | - ---- - -## 3. Protocol v1 Telemetry Packets - -### 3.1 RPM Telemetry Packet (`0xd211`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `statusFlags` | `uint8_t` | Bitmask representing live subsystem states (see Section 3.1.1) | -| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter (0..65535) | -| 4..7 | `uptimeMs` | `uint32_t` | ESP32 monotonic uptime in milliseconds (`millis()`) | -| 8..9 | `provisionalRpm` | `uint16_t` | Estimated RPM from the unified decoder. `65535` = unavailable/stale | -| 10 | `candidateRawByte` | `uint8_t` | Low byte of the raw candidate value (valid only if fresh flag set) | -| 11 | `captureStage` | `uint8_t` | Current field stage: `0`=Standby, `1`=KeyOn, `2`=Idling, `3`=GentleRPM | -| 12..15 | `canFramesRx` | `uint32_t` | Cumulative count of total CAN frames received by TWAI driver | -| 16..17 | `candidateAgeMs` | `uint16_t` | Milliseconds elapsed since last candidate frame. `65535` = never received | -| 18..19 | `experimentalProbe` | `uint16_t` | Optional experimental, uncalibrated standard CAN `0x303` byte 1, encoded as below. Legacy firmware leaves it zero. | - -#### 3.1.0 Optional experimental battery-voltage hypothesis - -**Unverified. Available on paired firmware with a fresh sample.** From the -archived key-on/engine-off capture, CAN ID `0x303` byte 1 ranged from 119 to 122. -The test-only hypothesis is `volts = rawByte / 10.0`, which would suggest -11.9-12.2 V during that recording. This is **not** a calibrated voltage or a -safe battery/charging warning and must be compared against synchronized -multimeter readings at several operating points. - -To avoid a new GATT service or any change to the existing 20-byte packet -length, an optional firmware build uses the previously zero reserved bytes: - -| Offset | Value | Meaning | -|---|---|---| -| 18 | 0-255 | Raw CAN `0x303[1]` from a standard, non-RTR frame with DLC ≥ 2; only meaningful if byte 19 is `0xA5` | -| 19 | `0xA5` | Candidate received within the last 1000 ms; Android may show `raw / 10.0` under **EXPERIMENTAL** label | -| 19 | `0x5A` | Firmware supports probe but frame absent or stale; Android displays unavailable | -| 19 | `0x00` with byte 18 = 0 | Legacy firmware without probe support; Android displays unavailable | - -All other RPM, health, configuration and OTA fields retain their documented -meaning and offsets. The dedicated RPM decoder remains locked to the existing -candidate configuration. The probe never writes NVS/LittleFS or transmits CAN. -DO NOT infer an accurate battery voltage from visual agreement at one point. - -#### 3.1.1 Status Flags Bitmask (`statusFlags`) -- `Bit 0` (`0x01`): `BLE_RPM_FLAG_CANDIDATE_FRESH` (Candidate frame received within the freshness timeout, default 250 ms) -- `Bit 1` (`0x02`): `BLE_RPM_FLAG_CALIBRATION_VERIFIED` (Verification record bound to the current decoder fingerprint) -- `Bit 2` (`0x04`): `BLE_RPM_FLAG_RPM_MAPPED` (The unified candidate decoder is the production RPM mapping; always set on 2.2.0+) -- `Bit 3` (`0x08`): `BLE_RPM_FLAG_SHIFT_LIGHTS_ENABLED` (Set only while RPM-driven lighting is actually rendering from live CAN data: the verified bar (effect 4), the unverified provisional preview (effect 5) or their warning overlay. Clear during decorative effects 0-3, safeguard blanks and the synthetic bench test) -- `Bit 4` (`0x10`): `BLE_RPM_FLAG_CAN_HEALTHY` (TWAI driver in running state) -- `Bit 5` (`0x20`): `BLE_RPM_FLAG_TRAFFIC_ACTIVE` (CAN frames received in last 1000 ms) -- `Bit 6` (`0x40`): `BLE_RPM_FLAG_RECORDING_ACTIVE` (Flash binary capture running) -- `Bit 7` (`0x80`): `BLE_RPM_FLAG_CAPTURE_PRESERVED` (Prior flash recording preserved) - -When the candidate goes stale, `provisionalRpm` reports `65535` and LEDs blank: the device never continues rendering the last received RPM indefinitely. - ---- - -### 3.2 System Health Packet (`0xd212`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `healthFlags` | `uint8_t` | Bit 0: Storage mounted (`0x01`), Bit 1: Storage full (`0x02`), Bit 2: RX degraded (`0x04`), Bit 3: BLE client connected (`0x08`) | -| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter | -| 4..7 | `missedFrames` | `uint32_t` | TWAI driver-missed CAN frames in current session | -| 8..11 | `overrunFrames` | `uint32_t` | Hardware FIFO overruns in current session | -| 12..15 | `busErrors` | `uint32_t` | TWAI bus error counter | -| 16..19 | `recordedFrames` | `uint32_t` | CAN frames recorded to flash in current session | - ---- - -### 3.3 Diagnostic Log Chunk Packet (`0xd213`, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `1` | -| 1 | `flags` | `uint8_t` | Bit 0: `FIRST_CHUNK` (`0x01`), Bit 1: `FINAL_CHUNK` (`0x02`), Bit 2: `END_OF_PAGE` (`0x04`), Bit 3: `ERROR` (`0x08`), Bit 4: `CAPTURE_LINE` (`0x10`) | -| 2..3 | `messageId` | `uint16_t` | Monotonic log message identifier | -| 4 | `chunkIndex` | `uint8_t` | 0-based chunk index within message | -| 5 | `payloadLength` | `uint8_t` | Number of valid payload bytes in `payload` (1..14) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Raw ASCII log text chunk, or End-of-Page metadata | - -For End-of-Page packets: `payloadLength = 5`, `payload[0..3]` = next byte offset (diagnostic logs) or next record index (capture pages) as `uint32_t` LE, `payload[4]` = finished flag (`1` = no more data). - -Capture pages stream CSV-like lines flagged with `CAPTURE_LINE`: -```text -CAP,,,,,, -``` -These lines are reassembled as multi-chunk messages and routed to the capture flow (never mixed with diagnostic messages). - ---- - -### 3.4 Control Requests (`0xd214`, WRITE) - -**Authorization (2.2.1+):** `GET_LOG_PAGE` and `GET_CAPTURE_PAGE` return vehicle -telemetry (raw CAN capture records and diagnostic history), so they require an -authenticated owner session bound to the requesting connection, exactly like -mutating configuration commands. An unauthenticated request is rejected, logged -to the device diagnostic event log and answered with a single -`BLE_LOG_FLAG_ERROR` chunk ("AUTH REQUIRED...") on the log characteristic. -`CANCEL_LOGS` and `CANCEL_CAPTURE` stay unauthenticated: they only stop a -transfer and disclose nothing. - -| Opcode | Name | Frame | Description | -|---|---|---|---| -| `0x10` | `GET_LOG_PAGE` | `[0x01, 0x10, offset: u32 LE]` (6 bytes) | **Auth required.** Stream one 20-line historical diagnostic log page from `offset` | -| `0x11` | `CANCEL_LOGS` | `[0x01, 0x11]` (2 bytes) | Cancel the diagnostic log page transfer | -| `0x12` | `GET_CAPTURE_PAGE` | `[0x01, 0x12, startRecord: u32 LE]` (6 bytes) | **Auth required.** Stream one bounded page (12 records) of the recorded CAN capture from `startRecord`. Reading never mutates the capture file | -| `0x13` | `CANCEL_CAPTURE` | `[0x01, 0x13]` (2 bytes) | Cancel the capture page transfer | - ---- - -## 4. Protocol v2 Configuration Architecture - -### 4.1 Device Capabilities (`0xd218`, READ, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `physicalLedCount`| `uint8_t` | Physical LED count = `6` | -| 2..5 | `featureMask` | `uint32_t` | Feature bitmask (see below; firmware 2.3.0 includes bits 17..19) | -| 6..9 | `currentRevision` | `uint32_t` | Monotonic active configuration revision counter | -| 10 | `presetCapacity` | `uint8_t` | Hardware preset slots (`0` = smartphone-managed presets) | -| 11 | `securityMode` | `uint8_t` | Security mode: `3` = Hybrid (Physical BOOT window presence OR Challenge-Response) | -| 12 | `firmwareMajor` | `uint8_t` | Firmware version major = `2` | -| 13 | `firmwareMinor` | `uint8_t` | Firmware version minor = `3` | -| 14 | `firmwarePatch` | `uint8_t` | Firmware version patch = `0` | -| 15 | `maxStartupAnimId` | `uint8_t` | Maximum supported startup animation ID (`5` = Strobe Rush; `<= 3` on legacy) | -| 16 | `maxEffectId` | `uint8_t` | Maximum supported effect ID (`5` = Provisional Preview) | -| 17 | `otaActiveSlot` | `uint8_t` | Running OTA slot: `0` = app0, `1` = app1, `0xFF` = unknown/unsupported | -| 18 | `protocolMinor` | `uint8_t` | Canonical protocol minor version (`3` for 2.3.0) | -| 19 | `otaFlags` | `uint8_t` | Bit 0: a rollback candidate exists, bit 1: dual-slot layout detected, bit 2: running app digest query supported | - -#### Feature Mask Bits (`featureMask`) -- `Bit 0` (`0x0001`): `BLE_FEAT_INDIVIDUAL_RGB` -- `Bit 1` (`0x0002`): `BLE_FEAT_EFFECTS` -- `Bit 2` (`0x0004`): `BLE_FEAT_STARTUP_ANIM` -- `Bit 3` (`0x0008`): `BLE_FEAT_RPM_THRESHOLDS` -- `Bit 4` (`0x0010`): `BLE_FEAT_SHIFT_WARNING` -- `Bit 5` (`0x0020`): `BLE_FEAT_RPM_MULTIPLIER` -- `Bit 6` (`0x0040`): `BLE_FEAT_CANDIDATE_SOURCE` -- `Bit 7` (`0x0080`): `BLE_FEAT_PHONE_PRESETS` -- `Bit 8` (`0x0100`): `BLE_FEAT_NVS_PERSISTENCE` -- `Bit 9` (`0x0200`): `BLE_FEAT_AUTH_WRITES` -- `Bit 10` (`0x0400`): `BLE_FEAT_DECODER_EXT` (width/endianness/offset/clamp) -- `Bit 11` (`0x0800`): `BLE_FEAT_HYSTERESIS` -- `Bit 12` (`0x1000`): `BLE_FEAT_CAL_WORKFLOW` -- `Bit 13` (`0x2000`): `BLE_FEAT_DIAGNOSTICS_TLV` -- `Bit 14` (`0x4000`): `BLE_FEAT_CAPTURE_EXPORT` -- `Bit 15` (`0x8000`): `BLE_FEAT_CAPTURE_STAGE` (authenticated stage-label command) -- `Bit 16` (`0x10000`): `BLE_FEAT_LED_BENCH_TEST` (authenticated 10-second synthetic test) -- `Bit 17` (`0x20000`): `BLE_FEAT_EXT_STARTUP_ANIM` (startup animations 4 Center Out and 5 Strobe Rush) -- `Bit 18` (`0x40000`): `BLE_FEAT_RANGE_DISCOVERY` (supports opcode 0x03 GET_ARG_RANGES) -- `Bit 19` (`0x80000`): `BLE_FEAT_OTA_UPDATE` (supports dual-slot authenticated firmware OTA) -- `Bit 20` (`0x100000`): `BLE_FEAT_LOOP_STARTUP` (startup duration bit 15 allows continuous looping) - ---- - -### 4.2 Configuration Command Packet (`0xd215`, WRITE, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `opcode` | `uint8_t` | Command opcode (see Section 4.4) | -| 2..3 | `sequence` | `uint16_t` | Client request sequence counter (echoed in Result) | -| 4 | `payloadLength` | `uint8_t` | Number of valid parameter bytes in `payload` (0..14) | -| 5 | `flags` | `uint8_t` | Bit 0: `IS_STAGED` (1 = stage in active transaction, 0 = apply live) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Command arguments | - -Incoming commands are queued through a bounded SPSC ring (4 entries); overflowed commands are counted and dropped rather than corrupting the queue. - ---- - -### 4.3 Configuration Result Packet (`0xd216`, READ/NOTIFY, 20 Bytes) - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1 | `respondedOpcode`| `uint8_t` | Opcode being acknowledged | -| 2..3 | `sequence` | `uint16_t` | Client sequence counter echoed from request | -| 4 | `statusCode` | `uint8_t` | Execution status (0 = OK, see Section 4.5) | -| 5 | `resultFlags` | `uint8_t` | Result flags (Bit 0=Persisted, Bit 1=Staged, Bit 2=Applied, Bit 3=AuthRequired) | -| 6..9 | `activeRevision` | `uint32_t` | Active configuration revision after command execution | -| 10 | `payloadLength` | `uint8_t` | Number of response bytes in `payload` (0..9) | -| 11..19 | `payload[9]` | `uint8_t[9]` | Optional response data (challenge nonce, calibration fit, statuses) | - ---- - -### 4.4 Command Opcodes - -**Authorization:** read-only queries (`0x01`, `0x02`, `0x43`, `0x46`, `0x50`) and the auth flow itself (`0x24`, `0x25`, `0x26`) are unauthenticated. Every other opcode requires a session bound to the current connection (challenge-response) or an open physical BOOT window. - -| Opcode | Name | Payload Arguments | Description | -|---|---|---|---| -| `0x01` | `GET_CAPABILITIES` | None | Updates Capabilities characteristic | -| `0x02` | `GET_SNAPSHOT` | None | Triggers complete config snapshot streaming on `0xd217` | -| `0x03` | `GET_ARG_RANGES` | None | Range discovery (max brightness, LED count, effect count, anim count, max RPM) | -| `0x10` | `SET_POWER` | `[power: u8 (0 or 1)]` | Master LED strip power switch | -| `0x11` | `SET_BRIGHTNESS` | `[brightness: u8 (0..255)]` | Master LED brightness | -| `0x12` | `SET_GLOBAL_RGB`| `[R: u8, G: u8, B: u8]` | Set uniform color across all 6 LEDs | -| `0x13` | `SET_LED_RGB` | `[index: u8 (0..5), R, G, B]` | Set individual LED color | -| `0x14` | `SET_EFFECT` | `[effectId: u8 (0..5), speed: u8 (0..100)]` | 0=Static, 1=Breathing, 2=Rainbow, 3=Chase, 4=Verified RPM Bar, **5=Provisional CAN RPM Preview (unverified)** | -| `0x15` | `SET_STARTUP` | `[animId: u8 (0..5), durationMs: u16 LE]` | 0=None, 1=Sweep, 2=Wave, 3=Pulse, 4=CenterOut, 5=Strobe Rush | - -**Optional loop extension:** On firmware advertising feature bit 20, the 16-bit startup duration uses bit 15 (`0x8000`) as `loopEnabled`. The low 15 bits remain the animation cycle length (100..10000 ms). With bit 15 cleared, the startup animation plays once as before. This uses the existing Config V2 packet, snapshot and schema-3 NVS blob without changing their sizes. Looping is invalid with animation 0 (None). Old firmware does not advertise the bit and must not receive loop-enabled settings. While enabled, fault, master power-off, commissioning/feedback, bench test, and active RPM or missing-RPM safeguards retain priority. Persist this setting with authenticated `SAVE_CONFIG` after `SET_STARTUP` or the preset transaction. Active RAM settings alone do not survive reboot. -| `0x16` | `SET_LED_THRESHOLD`| `[index: u8 (0..5), rpm: u16 LE]` | Set threshold for LED index (must remain monotonic) | -| `0x17` | `SET_SHIFT_WARNING`| `[warningRpm: u16 LE, patternId: u8]` | Pattern: 0=Flash (10 Hz), 1=Strobe (20 Hz), 2=Solid, 3=Off | -| `0x18` | `SET_RPM_MULTIPLIER`| `[multX1000: u32 LE]` | Provisional multiplier (0.1..1000.0). **Invalidates calibration!** | -| `0x19` | `SET_CANDIDATE_SOURCE` | `[canId: u32 LE, byteIdx: u8, ext: u8]` | Target CAN candidate source. **Invalidates calibration!** | -| `0x1A` | `SET_LED_DIRECTION`| `[direction: u8 (0=Forward, 1=Reverse)]`| Shift light display direction | -| `0x1B` | `SET_WARNING_RGB`| `[R: u8, G: u8, B: u8]` | Warning color for over-rev alert | -| `0x1C` | `SET_RPM_HYSTERESIS` | `[hysteresisRpm: u16 LE (0..2000)]` | Falling-RPM dead band for bar/warning latching | -| `0x1D` | `SET_RPM_DECODER_EXT` | `[width: u8 (1|2), endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` (8 bytes) | Byte width/order, RPM offset, validity clamp. **Invalidates calibration!** | -| `0x20` | `SAVE_CONFIG` | None | Commit active configuration to flash NVS (`"ps_cfg"`) | -| `0x21` | `RESTORE_DEFAULTS` | `[0xA5, 0x5A]` | Restore safe lighting/decoder defaults and save to NVS. **Owner credentials and captures are preserved.** | -| `0x22` | `RELOAD_CONFIG` | None | Re-read the persisted NVS blob and apply it to the active state | -| `0x24` | `ENROLL_OWNER` | `[secret: u8[12]]` | Owner enrollment or credential recovery (requires open BOOT window); safe re-enrollment overwrites the old credential | -| `0x25` | `AUTHENTICATE` | `[proof: u8[8]]` | Authenticate connection session via SHA-256 proof | -| `0x26` | `REQUEST_CHALLENGE`| None | Request 4-byte single-use cryptographic challenge nonce | -| `0x30` | `BEGIN_TRANSACTION`| None | Start staged transaction (30s timeout) | -| `0x31` | `COMMIT_TRANSACTION`| None | Validate all staged changes and apply atomically | -| `0x32` | `ABORT_TRANSACTION` | None | Discard all staged changes without modifying active config | -| `0x40` | `CAL_BEGIN` | None | Start the mobile-assisted calibration session (10 min timeout) | -| `0x41` | `CAL_ABORT` | None | Abort the calibration session | -| `0x42` | `CAL_CAPTURE_START` | None | Open the 2 s raw sampling window at the current operating point | -| `0x43` | `CAL_CAPTURE_STATUS` | None | Query window. Result payload: `[samples: u16 LE, elapsedMs: u16 LE]` | -| `0x44` | `CAL_POINT_COMMIT` | `[refRpm: u16 LE]` | Close the window, require >=10 stable samples (stddev <= 1.5 raw), store the point | -| `0x45` | `CAL_COMPUTE` | `[apply: u8]` | Fit scale/offset over 3..6 points, validate evidence. Result payload on OK (9 bytes): `[multiplierX1000: s32 LE, offsetX1000: s32 LE, info: u8]` where info = pointsUsed (low nibble) \| worst residual in 10-RPM steps clamped to 15 (high nibble); on failure: reason string (<= 9 bytes). Applying binds the verification record to the decoder fingerprint | -| `0x46` | `CAL_STATUS` | None | Query session. Result payload: `[active: u8, points: u8, captureActive: u8, samples: u16 LE]` | -| `0x50` | `GET_DIAGNOSTICS` | None | Stream the diagnostics TLV blob on `0xd217` (Section 4.8) | -| `0x51` | `RESTART_DEVICE` | `[0xA5, 0x5A]` | Acknowledge, then soft-restart the ESP32 | -| `0x52` | `CLEAR_DIAGNOSTICS` | `[0xA5, 0x5A]` | Clear the diagnostic event log ONLY (captures and credentials untouched) | -| `0x53` | `SET_CAPTURE_RECORDING` | `[enable: u8]` | Start/stop flash recording; start is state-gated (damaged/preserved/full storage => `INVALID_STATE`) | -| `0x54` | `SET_CAPTURE_STAGE` | `[stage: u8 (1..3)]` | Label subsequent CAN capture records: 1=KeyOn, 2=Idle, 3=RPM sweep. Does not change operation or synthesize CAN data. | -| `0x55` | `SET_LED_TEST_RPM` | `[testRpm: u16 LE (0..20000), enable: u8 (0 or 1)]` | Authenticated, temporary 10-second synthetic six-LED bench test. `enable=0` stops it; independent of real CAN data. Does not persist or inject CAN frames. | -| `0x60` | `OTA_BEGIN` | `[0xA5, 0x5C, size: u32 LE, shaPrefix: u8[4]]` | Begin authenticated dual-slot OTA update to inactive partition. Validates image size and stationary safety interlock. | -| `0x61` | `OTA_DATA` | `[chunkIdx: u16 LE, dataLen: u8, data...]` | Stream sequential image chunks. The Android client uses 11 data bytes at the baseline ATT MTU and up to 230 with a larger negotiated MTU. | -| `0x62` | `OTA_END` | `[shaTail: u8[4], crc32: u32 LE]` | Conclude transfer, verify full-image FIPS 180-2 SHA-256 hash, set boot partition, schedule restart (1.5s delay). | -| `0x63` | `OTA_ABORT` | None | Cancel active update, discard written data and return OTA engine to Idle state. | -| `0x64` | `OTA_CONFIRM` | `[0xA5, 0x5C]` | Cancel bootloader rollback after successful boot self-test. | -| `0x65` | `OTA_STATUS` | None | Query OTA engine state, active running slot, and written bytes. | -| `0x65` | `OTA_STATUS` digest | `[index: u8, 0..3]` | If capability bit 2 is set, returns index followed by 8 digest bytes at offset `8 * index`. The result fits the same 20-byte frame. | - ---- - -### 4.5 Status Codes - -| Code | Name | Description | -|---|---|---| -| `0` | `BLE_CFG_STATUS_OK` | Command executed successfully | -| `1` | `BLE_CFG_STATUS_INVALID_PARAM` | Parameter out of range or non-monotonic | -| `2` | `BLE_CFG_STATUS_UNSUPPORTED` | Opcode or parameter unsupported | -| `3` | `BLE_CFG_STATUS_BUSY` | Controller busy or under rate-limiting lockout | -| `4` | `BLE_CFG_STATUS_UNAUTHORIZED` | Authorization required; enrollment or authentication needed | -| `5` | `BLE_CFG_STATUS_INVALID_STATE` | Staged outside tx, expired challenge, storage not usable, or invalid session | -| `6` | `BLE_CFG_STATUS_STORAGE_ERROR` | Flash NVS write failed | -| `7` | `BLE_CFG_STATUS_VERSION_MISMATCH`| Protocol version mismatch | -| `8` | `BLE_CFG_STATUS_VALIDATION_FAILED`| Configuration validation failed | -| `9` | `BLE_CFG_STATUS_OTA_CHECKSUM_ERROR`| SHA-256 hash or CRC32 verification failed | -| `10` | `BLE_CFG_STATUS_OTA_FLASH_ERROR`| Flash partition write or erase error | - ---- - -### 4.6 Configuration Snapshot (`0xd217`, NOTIFY, 20-Byte Chunks) - -Streamed with 20 ms pacing between chunks to prevent Bluetooth buffer congestion. The same characteristic carries diagnostics blobs (schema byte `1`) and configuration snapshots (schema byte `3`); clients dispatch on the reassembled schema byte. - -| Byte Offset | Field Name | Data Type | Description | -|---|---|---|---| -| 0 | `version` | `uint8_t` | Protocol version = `2` | -| 1..2 | `snapshotId` | `uint16_t` | Snapshot identifier (little-endian; the request sequence) | -| 3 | `chunkIndex` | `uint8_t` | 0-based chunk sequence index | -| 4 | `chunkCount` | `uint8_t` | Total chunks comprising the blob | -| 5 | `payloadLength` | `uint8_t` | Number of valid bytes in this chunk (1..14) | -| 6..19 | `payload[14]` | `uint8_t[14]` | Serialized TLV fragment | - -#### Reassembled Configuration Snapshot Binary Layout (schema 3) -```text -[Byte 0] : schemaVersion (uint8_t = 3) -[Bytes 1..4] : activeRevision (uint32_t LE) -[Bytes 5..N-4]: TLV Records (see Section 4.7) -[Bytes N-3..N]: CRC32 (uint32_t LE, IEEE 802.3 over Bytes 0..N-4) -``` - -#### Reassembled Diagnostics Blob Binary Layout (schema 1) -```text -[Byte 0] : schemaVersion (uint8_t = 1) -[Bytes 1..4] : revision (uint32_t LE, always 0) -[Bytes 5..N-4]: Diagnostics TLV Records (see Section 4.8) -[Bytes N-3..N]: CRC32 (uint32_t LE) -``` - ---- - -### 4.7 Configuration Snapshot TLVs (schema 3) - -Every TLV record is formatted as `[Tag: uint8_t, Length: uint8_t, Value: uint8_t[Length]]`. - -All 12 mandatory tags (`0x10` through `0x1B`) are always emitted; schema-3 tags `0x1C`..`0x1E` accompany them. Unknown tags must be tolerated (skipped) by clients for forward compatibility. - -| Tag | Name | Length | Value Format | Description | -|---|---|---|---|---| -| `0x10` | Power | 1 | `[power: u8]` | `0` = Off, `1` = On | -| `0x11` | Brightness | 1 | `[brightness: u8]` | Master brightness `0..255` | -| `0x12` | Global Color | 3 | `[R, G, B]` | Primary single RGB color | -| `0x13` | Per-LED Colors | 18 | `[6 * (R, G, B)]` | Individual RGB colors for LEDs 0..5 | -| `0x14` | Effect & Speed | 2 | `[effectId: u8, speed: u8]` | Effect (0..5), Speed (0..100) | -| `0x15` | Startup Animation | 3 | `[animId: u8, durationMs: u16 LE]` | Startup anim (0..5), duration in ms | -| `0x16` | RPM Thresholds | 12 | `[6 * u16 LE]` | Monotonic thresholds for LEDs 0..5 | -| `0x17` | Shift Warning | 3 | `[warningRpm: u16 LE, patternId: u8]`| Warning threshold and pattern (0..3, 3 = Off) | -| `0x18` | RPM Multiplier | 4 | `[multX1000: u32 LE]` | Multiplier * 1000 (e.g. 40.0 -> 40000) | -| `0x19` | CAN Candidate | 6 | `[canId: u32 LE, byteIdx: u8, ext: u8]`| Target candidate CAN source | -| `0x1A` | LED Direction | 1 | `[direction: u8]` | `0` = Forward (0->5), `1` = Reverse (5->0) | -| `0x1B` | Warning Color | 3 | `[R, G, B]` | Alert over-rev flash color | -| `0x1C` | Decoder Extension | 8 | `[width: u8, endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` | Byte width/order, RPM offset, validity clamp | -| `0x1D` | Calibration Record | 11 | `[verified: u8, fingerprint: u32 LE, pointsUsed: u8, maxResidualRpm: u8, timestampMs: u32 LE]` | Bound verification record | -| `0x1E` | Hysteresis | 2 | `[hysteresisRpm: u16 LE]` | Threshold dead band | - ---- - -### 4.8 Diagnostics Blob TLVs (GET_DIAGNOSTICS, schema 1) - -| Tag | Name | Length | Value Format | -|---|---|---|---| -| `0x40` | Uptime | 4 | `uptimeMs: u32 LE` | -| `0x41` | Firmware Version | 3 | `[major, minor, patch]` | -| `0x42` | Reset Reason | 1 | `esp_reset_reason` of the last boot | -| `0x43` | CAN Status | 26 | `[bitrate: u32, totalRx: u32, accepted: u32, missed: u32, overrun: u32, busErrors: u32, healthy: u8, traffic: u8]` | -| `0x44` | RPM Decoder State | 34 | `[canId: u32, byteIndex: u8, byteWidth: u8, extended: u8, multX1000: s32, offsetX1000: s32, maxValid: u16, raw: u16, estimatedRpm: u16, fresh: u8, valid: u8, calVerified: u8, ageMs: u16, received: u32, rejected: u32]` | -| `0x45` | Storage State | 29 | `[total: u32, used: u32, free: u32, mounted: u8, storageFull: u8, capturePreserved: u8, damaged: u8, recording: u8, records: u32, captureSize: u32, diagLogSize: u32]` | -| `0x46` | BLE State | 5 | `[connected: u8, advertising: u8, securityMode: u8, ownerEnrolled: u8, sessionAuthorized: u8]` | -| `0x47` | Capture Info | 9 | `[stage: u8, sessionId: u32, bootCount: u32]` | -| `0x48` | Last Error | <= 96 | UTF-8 text of the last Error/Critical event this session (absent when none) | -| `0x49` | Calibration State | 13 | `[sessionActive: u8, points: u8, captureActive: u8, samples: u16, calVerified: u8, pointsUsed: u8, maxResidualRpm: u8, fingerprint: u32]` | -| `0x4A` | Experimental CAN bytes | 5 | Freshness bitmask followed by raw `0x302[1]`, `0x302[5]`, `0x452[7]`, `0x540[3]`. Bit index matches byte order. A clear bit means unavailable at snapshot time. Standard non-RTR frames, max sample age 1000 ms. | - ---- - -## 5. Owner Enrollment and Challenge-Response Authentication - -The PulseShift hardware is a dedicated headless embedded unit. To defend against unauthorized vehicle tuning or drive-by configuration tampering, PulseShift enforces physical owner presence and cryptographic authentication: - -```text -[Phone Application] [PulseShift ESP32] - | | - | (User presses physical BOOT button on ESP32) | - | <-------------------------------------------------------| BOOT Window Open (60s) - | | (LEDs pulse Cyan) - | ENROLL_OWNER (0x24) [secret: 12 bytes] | - |--------------------------------------------------------->| Store in NVS ("ps_sec") - | Result (0x24, OK, PERSISTED | APPLIED) | Session Authorized - |<---------------------------------------------------------| - : : - : (Normal Phone Use in subsequent sessions) : - | | - | REQUEST_CHALLENGE (0x26) | - |--------------------------------------------------------->| Generate 32-bit nonce - | Result (0x26, OK, payload: challenge [4 bytes LE]) | 30-second TTL - |<---------------------------------------------------------| - | | - | Compute Proof: | - | SHA-256(secret[12] || challenge[4] || seq[2])[:8] | - | | - | AUTHENTICATE (0x25) [proof: 8 bytes] | Single-use nonce consumed - |--------------------------------------------------------->| Constant-time comparison - | Result (0x25, OK) | Session Authorized (5 min) - |<---------------------------------------------------------| - | | - | SET_BRIGHTNESS, SET_EFFECT, etc. | Writes Permitted - |--------------------------------------------------------->| -``` - -### 5.1 Owner Enrollment Flow (and Credential Recovery) -1. The user presses the physical **BOOT** button (GPIO0) on the ESP32. -2. The controller opens a **60-second authorization window** and pulses the LED strip in cyan. -3. The phone sends opcode `0x24` (`ENROLL_OWNER`) containing a randomly generated 12-byte cryptographic secret. -4. The ESP32 validates the open BOOT window, verifies the secret is non-trivial, and stores it in a dedicated CRC-protected NVS namespace `"ps_sec"`. -5. The session is immediately marked authorized, bound to this connection. -6. **Credential recovery** is the same flow: pressing BOOT and re-enrolling overwrites the previous credential. Credential recovery and configuration reset are deliberately distinct operations. - -### 5.2 Subsequent Authenticated Phone Sessions -1. In future rides, the phone connects via BLE without pressing the BOOT button and automatically performs the challenge-response exchange using its stored credential. -2. The phone sends opcode `0x26` (`REQUEST_CHALLENGE`). -3. The ESP32 returns a 4-byte pseudo-random challenge nonce (`esp_random()`) with a 30-second TTL. -4. The phone computes the 8-byte authentication proof: `SHA-256(secret[12] || challenge[4 LE] || sequence[2 LE])[:8]`. -5. The phone sends opcode `0x25` (`AUTHENTICATE`) with the 8-byte proof. -6. The ESP32 consumes the challenge immediately (defeating replay), computes the matching proof, and verifies in constant time. -7. Upon verification, the session is authorized for 5 minutes of activity (refreshed per command) and is bound to that specific connection handle: another concurrent connection cannot ride the session. - -### 5.3 Negative Security Defenses -- **Proof-Less Session Rejection:** Physical presence alone never grants a session; opcode `0x25` requires a valid proof (`BLE_CFG_STATUS_UNAUTHORIZED = 4`). -- **Replay Attack Defense:** Every challenge is strictly single-use. Re-submitting the same proof without requesting a fresh challenge fails with `BLE_CFG_STATUS_INVALID_STATE = 5`. -- **Challenge Expiration:** Challenges expire after 30 seconds (`BLE_CFG_STATUS_INVALID_STATE = 5`). -- **Brute-Force Rate Limiting:** After 5 consecutive failed authentications, challenge requests are locked out for 3 seconds (`BLE_CFG_STATUS_BUSY = 3`). -- **Disconnect Invalidation:** Client disconnection immediately terminates the authenticated session, invalidates pending challenges and aborts staged transactions. -- **Connection Binding:** Sessions are valid only for the authenticating connection handle (`isAuthorizedFor(connId)`). -- **Configuration Reset vs Credentials:** `RESTORE_DEFAULTS` (`0x21`) resets lighting/decoder preferences but preserves owner credentials and stored captures. `CLEAR_DIAGNOSTICS` (`0x52`) clears only the event log. - ---- - -## 6. Cross-Language Byte Test Vectors - -The following deterministic test vector is published to verify cross-language byte serialization between Python (`test_ble_config_v2.py`), Android Kotlin (`ProtocolV2CodecTest.kt`), and C++ ESP32 firmware: - -### 6.1 Challenge-Response Vector -```text -Owner Secret (12 bytes ASCII): -"PULSE_KEY_96" -> [0x50, 0x55, 0x4c, 0x53, 0x45, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x39, 0x36] - -Challenge Nonce (uint32_t LE = 0x12345678): -[0x78, 0x56, 0x34, 0x12] - -Request Sequence (uint16_t LE = 42): -[0x2a, 0x00] - -Combined Hash Input (18 bytes): -50 55 4c 53 45 5f 4b 45 59 5f 39 36 78 56 34 12 2a 00 - -SHA-256 Full Digest (32 bytes): -12 38 a0 9b 10 7e 9d 79 38 a6 37 da 41 e9 c4 ee fa ec eb c4 e0 e0 0e 86 5d dd d1 fa 1c 35 c4 cc - -Expected Auth Proof (First 8 bytes): -[0x12, 0x38, 0xa0, 0x9b, 0x10, 0x7e, 0x9d, 0x79] -> Hex string: "1238a09b107e9d79" -``` -# Strip, RPM mapping and animation extension (2.5) - -Capability bit 23 and protocol minor ≥ 5 advertise version 1 of Lighting Setup. -Standard Config V2 command, result and snapshot chunk sizes remain 20 bytes. -Multi-byte fields below use little endian. - -| Operation | Request payload | Result | -| --- | --- | --- | -| `GET_SNAPSHOT` (`02`) | Empty for legacy, `[1]` for extended | Adds TLV `21` (setup) and `22` (version, saved count or zero if unconfirmed) to the existing CRC-protected stream | -| `LIGHTING_BEGIN` (`70`) | Version u8, payload length u16, IEEE CRC-32 u32, base revision u32 | Staged; command sequence is the upload ID | -| `LIGHTING_DATA` (`71`) | Upload ID u16, byte offset u16, 1-10 data bytes | Staged, contiguous offsets only | -| `LIGHTING_SAVE` (`72`) | Upload ID u16 | Applied + persisted only after verified NVS readback; storage errors carry the save status | -| `LIGHTING_CANCEL` (`73`) | Upload ID u16 | Discards partial upload | -| `AMBIENT_STATUS` (`74`) | Version u8 | Version, playback status (off 0, playing 1, paused by RPM 2, safety 3, waiting 4), preview eligibility (0/1) | -| `ANIMATION_PREVIEW` (`75`) | Version u8, pattern u8, duration u16 | Authenticated one-shot request, subject to current safety eligibility | - -Setup payload has a 15-byte header. Fields in order are version, installed count, -active count (0 follows installed), mapping mode, entry count, boot enabled, -boot pattern, boot duration u16, ambient enabled, ambient pattern, ambient -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 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, -wrong transaction ID, invalid offsets, incomplete payloads and CRC mismatches -fail before changing active settings. Status 11 identifies an integrity error. -Configuration results reference each command sequence. Clients must check the -final revision and the full extended snapshot including the flash-match flag. -An app applying a phone preset can open a standard transaction and set the -staged flag on `LIGHTING_BEGIN` only. In that case `LIGHTING_SAVE` sets the -staged copy and acknowledges Staged. The subsequent standard commit and -verified save retain their existing meanings. - -Old snapshots keep the original six thresholds, strip-count extension and -combined startup field. Legacy startup writes translate the loop bit to the -ambient fields. Legacy single-threshold commands return Unsupported on a -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 startup animation](LIGHTING-SETUP.md) for -eligibility, migration and hardware validation. +# PulseShift BLE Protocol Specification (v1 & v2) + +**Document Version:** 2.3.0 +**Target Hardware:** ESP32 DevKit V1 (ESP32-D0WD-V3) +**Companion App:** PulseShift Android App (`D:\Development\PulseShift\android`) +**Firmware Library:** NimBLE-Arduino 2.3.8 +**Arduino-ESP32 Core:** 3.3.12 (ESP-IDF 5.3+) + +--- + +## 1. Overview and Architecture + +PulseShift BLE Protocol defines the Bluetooth Low Energy GATT communication between the PulseShift ESP32 motorcycle firmware and the companion Android smartphone application. The Android app is the complete command interface: every normal configuration and diagnostic operation is executable over BLE, and the firmware runs fully standalone without USB, serial or a PC. + +### Key Tenets +1. **Unidirectional CAN Safety:** The ESP32 is a passive, receive-only automotive monitor (SN65HVD230 CTX tied to 3V3, GPIO17 air-gapped, listen-only TWAI mode with a zero-length TX queue). BLE configuration changes modify only local LED rendering, RPM thresholds, shift alerts, animations, and candidate monitoring parameters. BLE **never** injects frames into the vehicle CAN bus, and the firmware contains no CAN transmit API at all. +2. **Fixed 20-Byte Wire MTU:** Every characteristic command, response, and telemetry notification is constrained to exactly 20 bytes. No MTU renegotiation or L2CAP segmentation is required; large payloads are reassembled at the application layer. +3. **Little-Endian Architecture:** All multi-byte integers (`uint16_t`, `uint32_t`, `float`) are serialized in standard IEEE 754 little-endian byte ordering. +4. **Resilient and Decoupled:** The ESP32 firmware functions autonomously without an active BLE connection. Telemetry notifications are sent only to subscribed GATT clients. Disconnections automatically re-arm advertising without interrupting CAN reception or LED rendering. +5. **NVS Persistence and Staged Transactions:** Changes can be applied immediately, staged across atomic multi-parameter transactions, and saved to non-volatile storage (NVS) using CRC32 checksums. +6. **Defensible Cryptographic Owner Security:** Physical presence proof (60-second authorization window triggered by the physical BOOT button on the ESP32) is mandatory for owner enrollment and credential recovery. Once enrolled, the phone authenticates via cryptographic challenge-response (SHA-256) without requiring physical button presses for ordinary configuration adjustments. +7. **Acknowledged Execution:** A Bluetooth write returning success is NOT proof of execution. Every v2 command carries a client `sequence` echoed in the result packet together with a status code and result flags; the app requires request/response correlation plus snapshot readback for configuration changes. + +--- + +## 2. GATT Service and Characteristics + +**Advertised Device Name:** `PulseShift` +**Primary Service UUID:** `fe12d210-3d4f-4b9d-a21c-92782ecb4000` + +| Purpose | Full UUID | Properties | Frequency / Access | Description | +|---|---|---|---|---| +| **RPM Telemetry** | `fe12d211-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 10 Hz (100 ms) | Live engine speed, raw candidate byte, age, CAN frame count | +| **System Health** | `fe12d212-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | 1 Hz (1000 ms) | CAN bus health, missed/overrun counters, storage status | +| **Diagnostic Logs** | `fe12d213-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Event / Paced (20 ms) | Live diagnostic events, paginated historical logs, CAN capture pages | +| **Control Requests (v1)**| `fe12d214-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | GET_LOG_PAGE / CANCEL_LOGS / GET_CAPTURE_PAGE / CANCEL_CAPTURE | +| **Config Command (v2)** | `fe12d215-3d4f-4b9d-a21c-92782ecb4000` | `WRITE` | On-demand | Configuration write/read requests, device control, transaction controls | +| **Config Result (v2)** | `fe12d216-3d4f-4b9d-a21c-92782ecb4000` | `READ`, `NOTIFY` | Immediate response | Status code, active revision counter, and result flags | +| **Config Snapshot (v2)**| `fe12d217-3d4f-4b9d-a21c-92782ecb4000` | `NOTIFY` | Paced (20 ms stream) | Multi-chunk serialized configuration TLV blob (schema 3) or diagnostics TLV blob (schema 1) with CRC32 | +| **Capabilities (v2)** | `fe12d218-3d4f-4b9d-a21c-92782ecb4000` | `READ` | Static / On revision | Hardware capabilities, feature mask, firmware version | + +--- + +## 3. Protocol v1 Telemetry Packets + +### 3.1 RPM Telemetry Packet (`0xd211`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `statusFlags` | `uint8_t` | Bitmask representing live subsystem states (see Section 3.1.1) | +| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter (0..65535) | +| 4..7 | `uptimeMs` | `uint32_t` | ESP32 monotonic uptime in milliseconds (`millis()`) | +| 8..9 | `provisionalRpm` | `uint16_t` | Estimated RPM from the unified decoder. `65535` = unavailable/stale | +| 10 | `candidateRawByte` | `uint8_t` | Low byte of the raw candidate value (valid only if fresh flag set) | +| 11 | `captureStage` | `uint8_t` | Current field stage: `0`=Standby, `1`=KeyOn, `2`=Idling, `3`=GentleRPM | +| 12..15 | `canFramesRx` | `uint32_t` | Cumulative count of total CAN frames received by TWAI driver | +| 16..17 | `candidateAgeMs` | `uint16_t` | Milliseconds elapsed since last candidate frame. `65535` = never received | +| 18..19 | `experimentalProbe` | `uint16_t` | Optional experimental, uncalibrated standard CAN `0x303` byte 1, encoded as below. Legacy firmware leaves it zero. | + +#### 3.1.0 Optional experimental battery-voltage hypothesis + +**Unverified. Available on paired firmware with a fresh sample.** From the +archived key-on/engine-off capture, CAN ID `0x303` byte 1 ranged from 119 to 122. +The test-only hypothesis is `volts = rawByte / 10.0`, which would suggest +11.9-12.2 V during that recording. This is **not** a calibrated voltage or a +safe battery/charging warning and must be compared against synchronized +multimeter readings at several operating points. + +To avoid a new GATT service or any change to the existing 20-byte packet +length, an optional firmware build uses the previously zero reserved bytes: + +| Offset | Value | Meaning | +|---|---|---| +| 18 | 0-255 | Raw CAN `0x303[1]` from a standard, non-RTR frame with DLC ≥ 2; only meaningful if byte 19 is `0xA5` | +| 19 | `0xA5` | Candidate received within the last 1000 ms; Android may show `raw / 10.0` under **EXPERIMENTAL** label | +| 19 | `0x5A` | Firmware supports probe but frame absent or stale; Android displays unavailable | +| 19 | `0x00` with byte 18 = 0 | Legacy firmware without probe support; Android displays unavailable | + +All other RPM, health, configuration and OTA fields retain their documented +meaning and offsets. The dedicated RPM decoder remains locked to the existing +candidate configuration. The probe never writes NVS/LittleFS or transmits CAN. +DO NOT infer an accurate battery voltage from visual agreement at one point. + +#### 3.1.1 Status Flags Bitmask (`statusFlags`) +- `Bit 0` (`0x01`): `BLE_RPM_FLAG_CANDIDATE_FRESH` (Candidate frame received within the freshness timeout, default 250 ms) +- `Bit 1` (`0x02`): `BLE_RPM_FLAG_CALIBRATION_VERIFIED` (Verification record bound to the current decoder fingerprint) +- `Bit 2` (`0x04`): `BLE_RPM_FLAG_RPM_MAPPED` (The unified candidate decoder is the production RPM mapping; always set on 2.2.0+) +- `Bit 3` (`0x08`): `BLE_RPM_FLAG_SHIFT_LIGHTS_ENABLED` (Set only while RPM-driven lighting is actually rendering from live CAN data: the verified bar (effect 4), the unverified provisional preview (effect 5) or their warning overlay. Clear during decorative effects 0-3, safeguard blanks and the synthetic bench test) +- `Bit 4` (`0x10`): `BLE_RPM_FLAG_CAN_HEALTHY` (TWAI driver in running state) +- `Bit 5` (`0x20`): `BLE_RPM_FLAG_TRAFFIC_ACTIVE` (CAN frames received in last 1000 ms) +- `Bit 6` (`0x40`): `BLE_RPM_FLAG_RECORDING_ACTIVE` (Flash binary capture running) +- `Bit 7` (`0x80`): `BLE_RPM_FLAG_CAPTURE_PRESERVED` (Prior flash recording preserved) + +When the candidate goes stale, `provisionalRpm` reports `65535` and LEDs blank: the device never continues rendering the last received RPM indefinitely. + +--- + +### 3.2 System Health Packet (`0xd212`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `healthFlags` | `uint8_t` | Bit 0: Storage mounted (`0x01`), Bit 1: Storage full (`0x02`), Bit 2: RX degraded (`0x04`), Bit 3: BLE client connected (`0x08`) | +| 2..3 | `sequenceNumber` | `uint16_t` | Incremental rolling packet sequence counter | +| 4..7 | `missedFrames` | `uint32_t` | TWAI driver-missed CAN frames in current session | +| 8..11 | `overrunFrames` | `uint32_t` | Hardware FIFO overruns in current session | +| 12..15 | `busErrors` | `uint32_t` | TWAI bus error counter | +| 16..19 | `recordedFrames` | `uint32_t` | CAN frames recorded to flash in current session | + +--- + +### 3.3 Diagnostic Log Chunk Packet (`0xd213`, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `1` | +| 1 | `flags` | `uint8_t` | Bit 0: `FIRST_CHUNK` (`0x01`), Bit 1: `FINAL_CHUNK` (`0x02`), Bit 2: `END_OF_PAGE` (`0x04`), Bit 3: `ERROR` (`0x08`), Bit 4: `CAPTURE_LINE` (`0x10`) | +| 2..3 | `messageId` | `uint16_t` | Monotonic log message identifier | +| 4 | `chunkIndex` | `uint8_t` | 0-based chunk index within message | +| 5 | `payloadLength` | `uint8_t` | Number of valid payload bytes in `payload` (1..14) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Raw ASCII log text chunk, or End-of-Page metadata | + +For End-of-Page packets: `payloadLength = 5`, `payload[0..3]` = next byte offset (diagnostic logs) or next record index (capture pages) as `uint32_t` LE, `payload[4]` = finished flag (`1` = no more data). + +Capture pages stream CSV-like lines flagged with `CAPTURE_LINE`: +```text +CAP,,,,,, +``` +These lines are reassembled as multi-chunk messages and routed to the capture flow (never mixed with diagnostic messages). + +--- + +### 3.4 Control Requests (`0xd214`, WRITE) + +**Authorization (2.2.1+):** `GET_LOG_PAGE` and `GET_CAPTURE_PAGE` return vehicle +telemetry (raw CAN capture records and diagnostic history), so they require an +authenticated owner session bound to the requesting connection, exactly like +mutating configuration commands. An unauthenticated request is rejected, logged +to the device diagnostic event log and answered with a single +`BLE_LOG_FLAG_ERROR` chunk ("AUTH REQUIRED...") on the log characteristic. +`CANCEL_LOGS` and `CANCEL_CAPTURE` stay unauthenticated: they only stop a +transfer and disclose nothing. + +| Opcode | Name | Frame | Description | +|---|---|---|---| +| `0x10` | `GET_LOG_PAGE` | `[0x01, 0x10, offset: u32 LE]` (6 bytes) | **Auth required.** Stream one 20-line historical diagnostic log page from `offset` | +| `0x11` | `CANCEL_LOGS` | `[0x01, 0x11]` (2 bytes) | Cancel the diagnostic log page transfer | +| `0x12` | `GET_CAPTURE_PAGE` | `[0x01, 0x12, startRecord: u32 LE]` (6 bytes) | **Auth required.** Stream one bounded page (12 records) of the recorded CAN capture from `startRecord`. Reading never mutates the capture file | +| `0x13` | `CANCEL_CAPTURE` | `[0x01, 0x13]` (2 bytes) | Cancel the capture page transfer | + +--- + +## 4. Protocol v2 Configuration Architecture + +### 4.1 Device Capabilities (`0xd218`, READ, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `physicalLedCount`| `uint8_t` | Physical LED count = `6` | +| 2..5 | `featureMask` | `uint32_t` | Feature bitmask (see below; firmware 2.3.0 includes bits 17..19) | +| 6..9 | `currentRevision` | `uint32_t` | Monotonic active configuration revision counter | +| 10 | `presetCapacity` | `uint8_t` | Hardware preset slots (`0` = smartphone-managed presets) | +| 11 | `securityMode` | `uint8_t` | Security mode: `3` = Hybrid (Physical BOOT window presence OR Challenge-Response) | +| 12 | `firmwareMajor` | `uint8_t` | Firmware version major = `2` | +| 13 | `firmwareMinor` | `uint8_t` | Firmware version minor = `3` | +| 14 | `firmwarePatch` | `uint8_t` | Firmware version patch = `0` | +| 15 | `maxStartupAnimId` | `uint8_t` | Maximum supported startup animation ID (`5` = Strobe Rush; `<= 3` on legacy) | +| 16 | `maxEffectId` | `uint8_t` | Maximum supported effect ID (`5` = Provisional Preview) | +| 17 | `otaActiveSlot` | `uint8_t` | Running OTA slot: `0` = app0, `1` = app1, `0xFF` = unknown/unsupported | +| 18 | `protocolMinor` | `uint8_t` | Canonical protocol minor version (`3` for 2.3.0) | +| 19 | `otaFlags` | `uint8_t` | Bit 0: a rollback candidate exists, bit 1: dual-slot layout detected, bit 2: running app digest query supported | + +#### Feature Mask Bits (`featureMask`) +- `Bit 0` (`0x0001`): `BLE_FEAT_INDIVIDUAL_RGB` +- `Bit 1` (`0x0002`): `BLE_FEAT_EFFECTS` +- `Bit 2` (`0x0004`): `BLE_FEAT_STARTUP_ANIM` +- `Bit 3` (`0x0008`): `BLE_FEAT_RPM_THRESHOLDS` +- `Bit 4` (`0x0010`): `BLE_FEAT_SHIFT_WARNING` +- `Bit 5` (`0x0020`): `BLE_FEAT_RPM_MULTIPLIER` +- `Bit 6` (`0x0040`): `BLE_FEAT_CANDIDATE_SOURCE` +- `Bit 7` (`0x0080`): `BLE_FEAT_PHONE_PRESETS` +- `Bit 8` (`0x0100`): `BLE_FEAT_NVS_PERSISTENCE` +- `Bit 9` (`0x0200`): `BLE_FEAT_AUTH_WRITES` +- `Bit 10` (`0x0400`): `BLE_FEAT_DECODER_EXT` (width/endianness/offset/clamp) +- `Bit 11` (`0x0800`): `BLE_FEAT_HYSTERESIS` +- `Bit 12` (`0x1000`): `BLE_FEAT_CAL_WORKFLOW` +- `Bit 13` (`0x2000`): `BLE_FEAT_DIAGNOSTICS_TLV` +- `Bit 14` (`0x4000`): `BLE_FEAT_CAPTURE_EXPORT` +- `Bit 15` (`0x8000`): `BLE_FEAT_CAPTURE_STAGE` (authenticated stage-label command) +- `Bit 16` (`0x10000`): `BLE_FEAT_LED_BENCH_TEST` (authenticated 10-second synthetic test) +- `Bit 17` (`0x20000`): `BLE_FEAT_EXT_STARTUP_ANIM` (startup animations 4 Center Out and 5 Strobe Rush) +- `Bit 18` (`0x40000`): `BLE_FEAT_RANGE_DISCOVERY` (supports opcode 0x03 GET_ARG_RANGES) +- `Bit 19` (`0x80000`): `BLE_FEAT_OTA_UPDATE` (supports dual-slot authenticated firmware OTA) +- `Bit 20` (`0x100000`): `BLE_FEAT_LOOP_STARTUP` (startup duration bit 15 allows continuous looping) + +--- + +### 4.2 Configuration Command Packet (`0xd215`, WRITE, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `opcode` | `uint8_t` | Command opcode (see Section 4.4) | +| 2..3 | `sequence` | `uint16_t` | Client request sequence counter (echoed in Result) | +| 4 | `payloadLength` | `uint8_t` | Number of valid parameter bytes in `payload` (0..14) | +| 5 | `flags` | `uint8_t` | Bit 0: `IS_STAGED` (1 = stage in active transaction, 0 = apply live) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Command arguments | + +Incoming commands are queued through a bounded SPSC ring (4 entries); overflowed commands are counted and dropped rather than corrupting the queue. + +--- + +### 4.3 Configuration Result Packet (`0xd216`, READ/NOTIFY, 20 Bytes) + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1 | `respondedOpcode`| `uint8_t` | Opcode being acknowledged | +| 2..3 | `sequence` | `uint16_t` | Client sequence counter echoed from request | +| 4 | `statusCode` | `uint8_t` | Execution status (0 = OK, see Section 4.5) | +| 5 | `resultFlags` | `uint8_t` | Result flags (Bit 0=Persisted, Bit 1=Staged, Bit 2=Applied, Bit 3=AuthRequired) | +| 6..9 | `activeRevision` | `uint32_t` | Active configuration revision after command execution | +| 10 | `payloadLength` | `uint8_t` | Number of response bytes in `payload` (0..9) | +| 11..19 | `payload[9]` | `uint8_t[9]` | Optional response data (challenge nonce, calibration fit, statuses) | + +--- + +### 4.4 Command Opcodes + +**Authorization:** read-only queries (`0x01`, `0x02`, `0x43`, `0x46`, `0x50`) and the auth flow itself (`0x24`, `0x25`, `0x26`) are unauthenticated. Every other opcode requires a session bound to the current connection (challenge-response) or an open physical BOOT window. + +| Opcode | Name | Payload Arguments | Description | +|---|---|---|---| +| `0x01` | `GET_CAPABILITIES` | None | Updates Capabilities characteristic | +| `0x02` | `GET_SNAPSHOT` | None | Triggers complete config snapshot streaming on `0xd217` | +| `0x03` | `GET_ARG_RANGES` | None | Range discovery (max brightness, LED count, effect count, anim count, max RPM) | +| `0x10` | `SET_POWER` | `[power: u8 (0 or 1)]` | Master LED strip power switch | +| `0x11` | `SET_BRIGHTNESS` | `[brightness: u8 (0..255)]` | Master LED brightness | +| `0x12` | `SET_GLOBAL_RGB`| `[R: u8, G: u8, B: u8]` | Set uniform color across all 6 LEDs | +| `0x13` | `SET_LED_RGB` | `[index: u8 (0..5), R, G, B]` | Set individual LED color | +| `0x14` | `SET_EFFECT` | `[effectId: u8 (0..5), speed: u8 (0..100)]` | 0=Static, 1=Breathing, 2=Rainbow, 3=Chase, 4=Verified RPM Bar, **5=Provisional CAN RPM Preview (unverified)** | +| `0x15` | `SET_STARTUP` | `[animId: u8 (0..5), durationMs: u16 LE]` | 0=None, 1=Sweep, 2=Wave, 3=Pulse, 4=CenterOut, 5=Strobe Rush | + +**Optional loop extension:** On firmware advertising feature bit 20, the 16-bit startup duration uses bit 15 (`0x8000`) as `loopEnabled`. The low 15 bits remain the animation cycle length (100..10000 ms). With bit 15 cleared, the startup animation plays once as before. This uses the existing Config V2 packet, snapshot and schema-3 NVS blob without changing their sizes. Looping is invalid with animation 0 (None). Old firmware does not advertise the bit and must not receive loop-enabled settings. While enabled, fault, master power-off, commissioning/feedback, bench test, and active RPM or missing-RPM safeguards retain priority. Persist this setting with authenticated `SAVE_CONFIG` after `SET_STARTUP` or the preset transaction. Active RAM settings alone do not survive reboot. +| `0x16` | `SET_LED_THRESHOLD`| `[index: u8 (0..5), rpm: u16 LE]` | Set threshold for LED index (must remain monotonic) | +| `0x17` | `SET_SHIFT_WARNING`| `[warningRpm: u16 LE, patternId: u8]` | Pattern: 0=Flash (10 Hz), 1=Strobe (20 Hz), 2=Solid, 3=Off | +| `0x18` | `SET_RPM_MULTIPLIER`| `[multX1000: u32 LE]` | Provisional multiplier (0.1..1000.0). **Invalidates calibration!** | +| `0x19` | `SET_CANDIDATE_SOURCE` | `[canId: u32 LE, byteIdx: u8, ext: u8]` | Target CAN candidate source. **Invalidates calibration!** | +| `0x1A` | `SET_LED_DIRECTION`| `[direction: u8 (0=Forward, 1=Reverse)]`| Shift light display direction | +| `0x1B` | `SET_WARNING_RGB`| `[R: u8, G: u8, B: u8]` | Warning color for over-rev alert | +| `0x1C` | `SET_RPM_HYSTERESIS` | `[hysteresisRpm: u16 LE (0..2000)]` | Falling-RPM dead band for bar/warning latching | +| `0x1D` | `SET_RPM_DECODER_EXT` | `[width: u8 (1|2), endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` (8 bytes) | Byte width/order, RPM offset, validity clamp. **Invalidates calibration!** | +| `0x20` | `SAVE_CONFIG` | None | Commit active configuration to flash NVS (`"ps_cfg"`) | +| `0x21` | `RESTORE_DEFAULTS` | `[0xA5, 0x5A]` | Restore safe lighting/decoder defaults and save to NVS. **Owner credentials and captures are preserved.** | +| `0x22` | `RELOAD_CONFIG` | None | Re-read the persisted NVS blob and apply it to the active state | +| `0x24` | `ENROLL_OWNER` | `[secret: u8[12]]` | Owner enrollment or credential recovery (requires open BOOT window); safe re-enrollment overwrites the old credential | +| `0x25` | `AUTHENTICATE` | `[proof: u8[8]]` | Authenticate connection session via SHA-256 proof | +| `0x26` | `REQUEST_CHALLENGE`| None | Request 4-byte single-use cryptographic challenge nonce | +| `0x30` | `BEGIN_TRANSACTION`| None | Start staged transaction (30s timeout) | +| `0x31` | `COMMIT_TRANSACTION`| None | Validate all staged changes and apply atomically | +| `0x32` | `ABORT_TRANSACTION` | None | Discard all staged changes without modifying active config | +| `0x40` | `CAL_BEGIN` | None | Start the mobile-assisted calibration session (10 min timeout) | +| `0x41` | `CAL_ABORT` | None | Abort the calibration session | +| `0x42` | `CAL_CAPTURE_START` | None | Open the 2 s raw sampling window at the current operating point | +| `0x43` | `CAL_CAPTURE_STATUS` | None | Query window. Result payload: `[samples: u16 LE, elapsedMs: u16 LE]` | +| `0x44` | `CAL_POINT_COMMIT` | `[refRpm: u16 LE]` | Close the window, require >=10 stable samples (stddev <= 1.5 raw), store the point | +| `0x45` | `CAL_COMPUTE` | `[apply: u8]` | Fit scale/offset over 3..6 points, validate evidence. Result payload on OK (9 bytes): `[multiplierX1000: s32 LE, offsetX1000: s32 LE, info: u8]` where info = pointsUsed (low nibble) \| worst residual in 10-RPM steps clamped to 15 (high nibble); on failure: reason string (<= 9 bytes). Applying binds the verification record to the decoder fingerprint | +| `0x46` | `CAL_STATUS` | None | Query session. Result payload: `[active: u8, points: u8, captureActive: u8, samples: u16 LE]` | +| `0x50` | `GET_DIAGNOSTICS` | None | Stream the diagnostics TLV blob on `0xd217` (Section 4.8) | +| `0x51` | `RESTART_DEVICE` | `[0xA5, 0x5A]` | Acknowledge, then soft-restart the ESP32 | +| `0x52` | `CLEAR_DIAGNOSTICS` | `[0xA5, 0x5A]` | Clear the diagnostic event log ONLY (captures and credentials untouched) | +| `0x53` | `SET_CAPTURE_RECORDING` | `[enable: u8]` | Start/stop flash recording; start is state-gated (damaged/preserved/full storage => `INVALID_STATE`) | +| `0x54` | `SET_CAPTURE_STAGE` | `[stage: u8 (1..3)]` | Label subsequent CAN capture records: 1=KeyOn, 2=Idle, 3=RPM sweep. Does not change operation or synthesize CAN data. | +| `0x55` | `SET_LED_TEST_RPM` | `[testRpm: u16 LE (0..20000), enable: u8 (0 or 1)]` | Authenticated, temporary 10-second synthetic six-LED bench test. `enable=0` stops it; independent of real CAN data. Does not persist or inject CAN frames. | +| `0x60` | `OTA_BEGIN` | `[0xA5, 0x5C, size: u32 LE, shaPrefix: u8[4]]` | Begin authenticated dual-slot OTA update to inactive partition. Validates image size and stationary safety interlock. | +| `0x61` | `OTA_DATA` | `[chunkIdx: u16 LE, dataLen: u8, data...]` | Stream sequential image chunks. The Android client uses 11 data bytes at the baseline ATT MTU and up to 230 with a larger negotiated MTU. | +| `0x62` | `OTA_END` | `[shaTail: u8[4], crc32: u32 LE]` | Conclude transfer, verify full-image FIPS 180-2 SHA-256 hash, set boot partition, schedule restart (1.5s delay). | +| `0x63` | `OTA_ABORT` | None | Cancel active update, discard written data and return OTA engine to Idle state. | +| `0x64` | `OTA_CONFIRM` | `[0xA5, 0x5C]` | Cancel bootloader rollback after successful boot self-test. | +| `0x65` | `OTA_STATUS` | None | Query OTA engine state, active running slot, and written bytes. | +| `0x65` | `OTA_STATUS` digest | `[index: u8, 0..3]` | If capability bit 2 is set, returns index followed by 8 digest bytes at offset `8 * index`. The result fits the same 20-byte frame. | + +--- + +### 4.5 Status Codes + +| Code | Name | Description | +|---|---|---| +| `0` | `BLE_CFG_STATUS_OK` | Command executed successfully | +| `1` | `BLE_CFG_STATUS_INVALID_PARAM` | Parameter out of range or non-monotonic | +| `2` | `BLE_CFG_STATUS_UNSUPPORTED` | Opcode or parameter unsupported | +| `3` | `BLE_CFG_STATUS_BUSY` | Controller busy or under rate-limiting lockout | +| `4` | `BLE_CFG_STATUS_UNAUTHORIZED` | Authorization required; enrollment or authentication needed | +| `5` | `BLE_CFG_STATUS_INVALID_STATE` | Staged outside tx, expired challenge, storage not usable, or invalid session | +| `6` | `BLE_CFG_STATUS_STORAGE_ERROR` | Flash NVS write failed | +| `7` | `BLE_CFG_STATUS_VERSION_MISMATCH`| Protocol version mismatch | +| `8` | `BLE_CFG_STATUS_VALIDATION_FAILED`| Configuration validation failed | +| `9` | `BLE_CFG_STATUS_OTA_CHECKSUM_ERROR`| SHA-256 hash or CRC32 verification failed | +| `10` | `BLE_CFG_STATUS_OTA_FLASH_ERROR`| Flash partition write or erase error | + +--- + +### 4.6 Configuration Snapshot (`0xd217`, NOTIFY, 20-Byte Chunks) + +Streamed with 20 ms pacing between chunks to prevent Bluetooth buffer congestion. The same characteristic carries diagnostics blobs (schema byte `1`) and configuration snapshots (schema byte `3`); clients dispatch on the reassembled schema byte. + +| Byte Offset | Field Name | Data Type | Description | +|---|---|---|---| +| 0 | `version` | `uint8_t` | Protocol version = `2` | +| 1..2 | `snapshotId` | `uint16_t` | Snapshot identifier (little-endian; the request sequence) | +| 3 | `chunkIndex` | `uint8_t` | 0-based chunk sequence index | +| 4 | `chunkCount` | `uint8_t` | Total chunks comprising the blob | +| 5 | `payloadLength` | `uint8_t` | Number of valid bytes in this chunk (1..14) | +| 6..19 | `payload[14]` | `uint8_t[14]` | Serialized TLV fragment | + +#### Reassembled Configuration Snapshot Binary Layout (schema 3) +```text +[Byte 0] : schemaVersion (uint8_t = 3) +[Bytes 1..4] : activeRevision (uint32_t LE) +[Bytes 5..N-4]: TLV Records (see Section 4.7) +[Bytes N-3..N]: CRC32 (uint32_t LE, IEEE 802.3 over Bytes 0..N-4) +``` + +#### Reassembled Diagnostics Blob Binary Layout (schema 1) +```text +[Byte 0] : schemaVersion (uint8_t = 1) +[Bytes 1..4] : revision (uint32_t LE, always 0) +[Bytes 5..N-4]: Diagnostics TLV Records (see Section 4.8) +[Bytes N-3..N]: CRC32 (uint32_t LE) +``` + +--- + +### 4.7 Configuration Snapshot TLVs (schema 3) + +Every TLV record is formatted as `[Tag: uint8_t, Length: uint8_t, Value: uint8_t[Length]]`. + +All 12 mandatory tags (`0x10` through `0x1B`) are always emitted; schema-3 tags `0x1C`..`0x1E` accompany them. Unknown tags must be tolerated (skipped) by clients for forward compatibility. + +| Tag | Name | Length | Value Format | Description | +|---|---|---|---|---| +| `0x10` | Power | 1 | `[power: u8]` | `0` = Off, `1` = On | +| `0x11` | Brightness | 1 | `[brightness: u8]` | Master brightness `0..255` | +| `0x12` | Global Color | 3 | `[R, G, B]` | Primary single RGB color | +| `0x13` | Per-LED Colors | 18 | `[6 * (R, G, B)]` | Individual RGB colors for LEDs 0..5 | +| `0x14` | Effect & Speed | 2 | `[effectId: u8, speed: u8]` | Effect (0..5), Speed (0..100) | +| `0x15` | Startup Animation | 3 | `[animId: u8, durationMs: u16 LE]` | Startup anim (0..5), duration in ms | +| `0x16` | RPM Thresholds | 12 | `[6 * u16 LE]` | Monotonic thresholds for LEDs 0..5 | +| `0x17` | Shift Warning | 3 | `[warningRpm: u16 LE, patternId: u8]`| Warning threshold and pattern (0..3, 3 = Off) | +| `0x18` | RPM Multiplier | 4 | `[multX1000: u32 LE]` | Multiplier * 1000 (e.g. 40.0 -> 40000) | +| `0x19` | CAN Candidate | 6 | `[canId: u32 LE, byteIdx: u8, ext: u8]`| Target candidate CAN source | +| `0x1A` | LED Direction | 1 | `[direction: u8]` | `0` = Forward (0->5), `1` = Reverse (5->0) | +| `0x1B` | Warning Color | 3 | `[R, G, B]` | Alert over-rev flash color | +| `0x1C` | Decoder Extension | 8 | `[width: u8, endian: u8, offsetX1000: s32 LE, maxValid: u16 LE]` | Byte width/order, RPM offset, validity clamp | +| `0x1D` | Calibration Record | 11 | `[verified: u8, fingerprint: u32 LE, pointsUsed: u8, maxResidualRpm: u8, timestampMs: u32 LE]` | Bound verification record | +| `0x1E` | Hysteresis | 2 | `[hysteresisRpm: u16 LE]` | Threshold dead band | + +--- + +### 4.8 Diagnostics Blob TLVs (GET_DIAGNOSTICS, schema 1) + +| Tag | Name | Length | Value Format | +|---|---|---|---| +| `0x40` | Uptime | 4 | `uptimeMs: u32 LE` | +| `0x41` | Firmware Version | 3 | `[major, minor, patch]` | +| `0x42` | Reset Reason | 1 | `esp_reset_reason` of the last boot | +| `0x43` | CAN Status | 26 | `[bitrate: u32, totalRx: u32, accepted: u32, missed: u32, overrun: u32, busErrors: u32, healthy: u8, traffic: u8]` | +| `0x44` | RPM Decoder State | 34 | `[canId: u32, byteIndex: u8, byteWidth: u8, extended: u8, multX1000: s32, offsetX1000: s32, maxValid: u16, raw: u16, estimatedRpm: u16, fresh: u8, valid: u8, calVerified: u8, ageMs: u16, received: u32, rejected: u32]` | +| `0x45` | Storage State | 29 | `[total: u32, used: u32, free: u32, mounted: u8, storageFull: u8, capturePreserved: u8, damaged: u8, recording: u8, records: u32, captureSize: u32, diagLogSize: u32]` | +| `0x46` | BLE State | 5 | `[connected: u8, advertising: u8, securityMode: u8, ownerEnrolled: u8, sessionAuthorized: u8]` | +| `0x47` | Capture Info | 9 | `[stage: u8, sessionId: u32, bootCount: u32]` | +| `0x48` | Last Error | <= 96 | UTF-8 text of the last Error/Critical event this session (absent when none) | +| `0x49` | Calibration State | 13 | `[sessionActive: u8, points: u8, captureActive: u8, samples: u16, calVerified: u8, pointsUsed: u8, maxResidualRpm: u8, fingerprint: u32]` | +| `0x4A` | Experimental CAN bytes | 5 | Freshness bitmask followed by raw `0x302[1]`, `0x302[5]`, `0x452[7]`, `0x540[3]`. Bit index matches byte order. A clear bit means unavailable at snapshot time. Standard non-RTR frames, max sample age 1000 ms. | + +--- + +## 5. Owner Enrollment and Challenge-Response Authentication + +The PulseShift hardware is a dedicated headless embedded unit. To defend against unauthorized vehicle tuning or drive-by configuration tampering, PulseShift enforces physical owner presence and cryptographic authentication: + +```text +[Phone Application] [PulseShift ESP32] + | | + | (User presses physical BOOT button on ESP32) | + | <-------------------------------------------------------| BOOT Window Open (60s) + | | (LEDs pulse Cyan) + | ENROLL_OWNER (0x24) [secret: 12 bytes] | + |--------------------------------------------------------->| Store in NVS ("ps_sec") + | Result (0x24, OK, PERSISTED | APPLIED) | Session Authorized + |<---------------------------------------------------------| + : : + : (Normal Phone Use in subsequent sessions) : + | | + | REQUEST_CHALLENGE (0x26) | + |--------------------------------------------------------->| Generate 32-bit nonce + | Result (0x26, OK, payload: challenge [4 bytes LE]) | 30-second TTL + |<---------------------------------------------------------| + | | + | Compute Proof: | + | SHA-256(secret[12] || challenge[4] || seq[2])[:8] | + | | + | AUTHENTICATE (0x25) [proof: 8 bytes] | Single-use nonce consumed + |--------------------------------------------------------->| Constant-time comparison + | Result (0x25, OK) | Session Authorized (5 min) + |<---------------------------------------------------------| + | | + | SET_BRIGHTNESS, SET_EFFECT, etc. | Writes Permitted + |--------------------------------------------------------->| +``` + +### 5.1 Owner Enrollment Flow (and Credential Recovery) +1. The user presses the physical **BOOT** button (GPIO0) on the ESP32. +2. The controller opens a **60-second authorization window** and pulses the LED strip in cyan. +3. The phone sends opcode `0x24` (`ENROLL_OWNER`) containing a randomly generated 12-byte cryptographic secret. +4. The ESP32 validates the open BOOT window, verifies the secret is non-trivial, and stores it in a dedicated CRC-protected NVS namespace `"ps_sec"`. +5. The session is immediately marked authorized, bound to this connection. +6. **Credential recovery** is the same flow: pressing BOOT and re-enrolling overwrites the previous credential. Credential recovery and configuration reset are deliberately distinct operations. + +### 5.2 Subsequent Authenticated Phone Sessions +1. In future rides, the phone connects via BLE without pressing the BOOT button and automatically performs the challenge-response exchange using its stored credential. +2. The phone sends opcode `0x26` (`REQUEST_CHALLENGE`). +3. The ESP32 returns a 4-byte pseudo-random challenge nonce (`esp_random()`) with a 30-second TTL. +4. The phone computes the 8-byte authentication proof: `SHA-256(secret[12] || challenge[4 LE] || sequence[2 LE])[:8]`. +5. The phone sends opcode `0x25` (`AUTHENTICATE`) with the 8-byte proof. +6. The ESP32 consumes the challenge immediately (defeating replay), computes the matching proof, and verifies in constant time. +7. Upon verification, the session is authorized for 5 minutes of activity (refreshed per command) and is bound to that specific connection handle: another concurrent connection cannot ride the session. + +### 5.3 Negative Security Defenses +- **Proof-Less Session Rejection:** Physical presence alone never grants a session; opcode `0x25` requires a valid proof (`BLE_CFG_STATUS_UNAUTHORIZED = 4`). +- **Replay Attack Defense:** Every challenge is strictly single-use. Re-submitting the same proof without requesting a fresh challenge fails with `BLE_CFG_STATUS_INVALID_STATE = 5`. +- **Challenge Expiration:** Challenges expire after 30 seconds (`BLE_CFG_STATUS_INVALID_STATE = 5`). +- **Brute-Force Rate Limiting:** After 5 consecutive failed authentications, challenge requests are locked out for 3 seconds (`BLE_CFG_STATUS_BUSY = 3`). +- **Disconnect Invalidation:** Client disconnection immediately terminates the authenticated session, invalidates pending challenges and aborts staged transactions. +- **Connection Binding:** Sessions are valid only for the authenticating connection handle (`isAuthorizedFor(connId)`). +- **Configuration Reset vs Credentials:** `RESTORE_DEFAULTS` (`0x21`) resets lighting/decoder preferences but preserves owner credentials and stored captures. `CLEAR_DIAGNOSTICS` (`0x52`) clears only the event log. + +--- + +## 6. Cross-Language Byte Test Vectors + +The following deterministic test vector is published to verify cross-language byte serialization between Python (`test_ble_config_v2.py`), Android Kotlin (`ProtocolV2CodecTest.kt`), and C++ ESP32 firmware: + +### 6.1 Challenge-Response Vector +```text +Owner Secret (12 bytes ASCII): +"PULSE_KEY_96" -> [0x50, 0x55, 0x4c, 0x53, 0x45, 0x5f, 0x4b, 0x45, 0x59, 0x5f, 0x39, 0x36] + +Challenge Nonce (uint32_t LE = 0x12345678): +[0x78, 0x56, 0x34, 0x12] + +Request Sequence (uint16_t LE = 42): +[0x2a, 0x00] + +Combined Hash Input (18 bytes): +50 55 4c 53 45 5f 4b 45 59 5f 39 36 78 56 34 12 2a 00 + +SHA-256 Full Digest (32 bytes): +12 38 a0 9b 10 7e 9d 79 38 a6 37 da 41 e9 c4 ee fa ec eb c4 e0 e0 0e 86 5d dd d1 fa 1c 35 c4 cc + +Expected Auth Proof (First 8 bytes): +[0x12, 0x38, 0xa0, 0x9b, 0x10, 0x7e, 0x9d, 0x79] -> Hex string: "1238a09b107e9d79" +``` +# Strip, RPM mapping and animation extension (2.5) + +Capability bit 23 and protocol minor ≥ 5 advertise version 1 of Lighting Setup. +Standard Config V2 command, result and snapshot chunk sizes remain 20 bytes. +Multi-byte fields below use little endian. + +| Operation | Request payload | Result | +| --- | --- | --- | +| `GET_SNAPSHOT` (`02`) | Empty for legacy, `[1]` for extended | Adds TLV `21` (setup) and `22` (version, saved count or zero if unconfirmed) to the existing CRC-protected stream | +| `LIGHTING_BEGIN` (`70`) | Version u8, payload length u16, IEEE CRC-32 u32, base revision u32 | Staged; command sequence is the upload ID | +| `LIGHTING_DATA` (`71`) | Upload ID u16, byte offset u16, 1-10 data bytes | Staged, contiguous offsets only | +| `LIGHTING_SAVE` (`72`) | Upload ID u16 | Applied + persisted only after verified NVS readback; storage errors carry the save status | +| `LIGHTING_CANCEL` (`73`) | Upload ID u16 | Discards partial upload | +| `AMBIENT_STATUS` (`74`) | Version u8 | Version, playback status (off 0, playing 1, paused by RPM 2, safety 3, waiting 4), preview eligibility (0/1) | +| `ANIMATION_PREVIEW` (`75`) | Version u8, pattern u8, duration u16 | Authenticated one-shot request, subject to current safety eligibility | + +Setup payload has a 15-byte header. Fields in order are version, installed count, +active count (0 follows installed), mapping mode, entry count, boot enabled, +boot pattern, boot duration u16, ambient enabled, ambient pattern, ambient +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 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, +wrong transaction ID, invalid offsets, incomplete payloads and CRC mismatches +fail before changing active settings. Status 11 identifies an integrity error. +Configuration results reference each command sequence. Clients must check the +final revision and the full extended snapshot including the flash-match flag. +An app applying a phone preset can open a standard transaction and set the +staged flag on `LIGHTING_BEGIN` only. In that case `LIGHTING_SAVE` sets the +staged copy and acknowledges Staged. The subsequent standard commit and +verified save retain their existing meanings. + +Old snapshots keep the original six thresholds, strip-count extension and +combined startup field. Legacy startup writes translate the loop bit to the +ambient fields. Legacy single-threshold commands return Unsupported on a +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 startup animation](LIGHTING-SETUP.md) for +eligibility, migration and hardware validation. diff --git a/docs/LIGHTING-SETUP.md b/docs/LIGHTING-SETUP.md index ae06289..4d52e2e 100644 --- a/docs/LIGHTING-SETUP.md +++ b/docs/LIGHTING-SETUP.md @@ -1,43 +1,43 @@ -# Strip setup, RPM mapping and startup animation - -## Strip and RPM - -The installed count is the owner's configuration for the next boot. The running count is the number of pixels configured in the current RMT driver. A verified save reports the stored installed count separately. The renderer uses the smaller of the running and installed counts as its ceiling, so a pending shrink can darken surplus pixels immediately. The driver still sends a complete frame for its running length. When all installed LEDs are enabled, the active count follows that ceiling. An explicit active count is limited to the same ceiling. - -Logical LED 1 starts at the GPIO27 data-input end in Normal direction. Reverse starts at the far end of the running strip. All layers leave pixels outside the active segment dark, including shift warnings and animations. RGB palette selection uses the existing six color zones spread over the active segment. The zones have no role in calculating configurable RPM thresholds. - -- Automatic maps the first and last active LEDs to the configured endpoints. Each intermediate threshold is the integer result of `min + ((max - min) * i + (n - 1) / 2) / (n - 1)`. A single pixel uses the minimum. -- Grouped accepts one or more positive group sizes whose sum equals the configured active count. For 12 pixels, group sizes 3/3/2/2/1/1 activate 3, 6, 8, 10, 11 and 12 pixels at the six respective thresholds. -- Individual accepts a threshold for each active LED. Equal thresholds activate together. All thresholds use whole RPM, are nondecreasing, and are bounded by warning RPM. Warning RPM may equal the highest threshold. When enabled, the warning then takes precedence over the bar. -- A lit pixel releases strictly below `max(0, threshold - hysteresis)`. The warning has its own latch using the same hysteresis and uses the existing color and flash, strobe, solid or off settings. A zero-RPM sample clears the latches. An invalid, stale or nonqualifying sample also clears live RPM latches. Test and real RPM have separate latch histories. - -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. - -## Startup animation and RPM takeover - -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 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 - -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. - -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 - -Arduino-ESP32 3.3.12 uses the ESP-IDF RMT copy encoder, four 64-symbol blocks, no DMA and an interrupt-refilled stream for long frames. The HAL borrows the encoded symbols until TX completion. The controller polls completion without waiting in the LED driver and preserves in-flight symbols through a timeout. A rejected enqueue can recover from idle. A stuck transfer after 100 ms quarantines the driver and its buffer until reset. The confirmed frame is updated only on TX completion. CAN ingestion, watchdog servicing and BLE telemetry can continue while the transfer is pending. Main-task flash operations and GATT config dispatch wait for the transfer to finish or be quarantined to reduce refill starvation. An RMT completion confirms peripheral completion only. [Arduino 3.3.12 HAL source](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/esp32-hal-rmt.c), [Arduino RMT API](https://docs.espressif.com/projects/arduino-esp32/en/latest/api/rmt.html), [ESP-IDF RMT guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) - -The verified encoding is GRB, most-significant-bit first. At 10 MHz the high/low pairs are 0.3/0.9 µs for zero and 0.8/0.6 µs for one. Every frame includes 300 µs low reset time. A 64-pixel frame uses 1,537 payload symbols and has a nominal wire duration of 2.143-2.450 ms before software overhead. The pitch between half-buffer refills is about 154-179 µs while sending data. Classic ESP32 refill latency with BLE is a physical validation gate. [Espressif RMT FAQ](https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/rmt.html), [Worldsemi WS2812B-V5 datasheet](https://files.keeb.supply/products/ws2812b-rgb-led/datasheet.pdf) - -GPIO27 is data only. At 5 V use a suitable 3.3 V to 5 V logic buffer, common ground, and the existing electrical protections. Full-white supply allowance at 60 mA per pixel is 0.36 A for six and 3.84 A for 64. These are design budgets, with the actual draw dependent on strip revision, brightness and color. Check voltage drop and provision the strip supply and injection points for its actual wiring. [Adafruit NeoPixel powering guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels) - -## Hardware acceptance checklist - -- 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 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. +# Strip setup, RPM mapping and startup animation + +## Strip and RPM + +The installed count is the owner's configuration for the next boot. The running count is the number of pixels configured in the current RMT driver. A verified save reports the stored installed count separately. The renderer uses the smaller of the running and installed counts as its ceiling, so a pending shrink can darken surplus pixels immediately. The driver still sends a complete frame for its running length. When all installed LEDs are enabled, the active count follows that ceiling. An explicit active count is limited to the same ceiling. + +Logical LED 1 starts at the GPIO27 data-input end in Normal direction. Reverse starts at the far end of the running strip. All layers leave pixels outside the active segment dark, including shift warnings and animations. RGB palette selection uses the existing six color zones spread over the active segment. The zones have no role in calculating configurable RPM thresholds. + +- Automatic maps the first and last active LEDs to the configured endpoints. Each intermediate threshold is the integer result of `min + ((max - min) * i + (n - 1) / 2) / (n - 1)`. A single pixel uses the minimum. +- Grouped accepts one or more positive group sizes whose sum equals the configured active count. For 12 pixels, group sizes 3/3/2/2/1/1 activate 3, 6, 8, 10, 11 and 12 pixels at the six respective thresholds. +- Individual accepts a threshold for each active LED. Equal thresholds activate together. All thresholds use whole RPM, are nondecreasing, and are bounded by warning RPM. Warning RPM may equal the highest threshold. When enabled, the warning then takes precedence over the bar. +- A lit pixel releases strictly below `max(0, threshold - hysteresis)`. The warning has its own latch using the same hysteresis and uses the existing color and flash, strobe, solid or off settings. A zero-RPM sample clears the latches. An invalid, stale or nonqualifying sample also clears live RPM latches. Test and real RPM have separate latch histories. + +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. + +## Startup animation and RPM takeover + +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 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 + +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. + +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 + +Arduino-ESP32 3.3.12 uses the ESP-IDF RMT copy encoder, four 64-symbol blocks, no DMA and an interrupt-refilled stream for long frames. The HAL borrows the encoded symbols until TX completion. The controller polls completion without waiting in the LED driver and preserves in-flight symbols through a timeout. A rejected enqueue can recover from idle. A stuck transfer after 100 ms quarantines the driver and its buffer until reset. The confirmed frame is updated only on TX completion. CAN ingestion, watchdog servicing and BLE telemetry can continue while the transfer is pending. Main-task flash operations and GATT config dispatch wait for the transfer to finish or be quarantined to reduce refill starvation. An RMT completion confirms peripheral completion only. [Arduino 3.3.12 HAL source](https://github.com/espressif/arduino-esp32/blob/3.3.12/cores/esp32/esp32-hal-rmt.c), [Arduino RMT API](https://docs.espressif.com/projects/arduino-esp32/en/latest/api/rmt.html), [ESP-IDF RMT guide](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) + +The verified encoding is GRB, most-significant-bit first. At 10 MHz the high/low pairs are 0.3/0.9 µs for zero and 0.8/0.6 µs for one. Every frame includes 300 µs low reset time. A 64-pixel frame uses 1,537 payload symbols and has a nominal wire duration of 2.143-2.450 ms before software overhead. The pitch between half-buffer refills is about 154-179 µs while sending data. Classic ESP32 refill latency with BLE is a physical validation gate. [Espressif RMT FAQ](https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/rmt.html), [Worldsemi WS2812B-V5 datasheet](https://files.keeb.supply/products/ws2812b-rgb-led/datasheet.pdf) + +GPIO27 is data only. At 5 V use a suitable 3.3 V to 5 V logic buffer, common ground, and the existing electrical protections. Full-white supply allowance at 60 mA per pixel is 0.36 A for six and 3.84 A for 64. These are design budgets, with the actual draw dependent on strip revision, brightness and color. Check voltage drop and provision the strip supply and injection points for its actual wiring. [Adafruit NeoPixel powering guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels) + +## Hardware acceptance checklist + +- 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 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. From a826e5e02018827729f886d15b58a17265f10598 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 23:04:29 +0530 Subject: [PATCH 4/7] Make Arduino startup protection part of the supported build --- .github/workflows/ci.yml | 58 +++-------- .github/workflows/release.yml | 63 ++++-------- Build-PulseShift.cmd | 6 ++ Build-PulseShift.ps1 | 158 +++++++++++++++++++++++++++++ PulseShift/PulseShift.ino | 71 ++++--------- PulseShift/partitions.csv | 7 ++ PulseShift/src/startup_guard.cpp | 45 ++++++++ PulseShift/src/startup_guard.h | 8 ++ PulseShift/src/storage_manager.cpp | 68 +++---------- PulseShift/src/storage_manager.h | 7 +- README.md | 15 ++- docs/OTA-BENCH-TEST-PLAN.md | 23 ++--- docs/TESTING.md | 21 ++-- docs/WINDOWS-BUILD.md | 24 +++++ test/VERIFICATION.md | 10 +- test/run.sh | 20 +++- test/stubs/LittleFS.h | 10 +- test/stubs/Preferences.h | 3 +- test/stubs/esp_err.h | 5 + test/stubs/esp_partition.h | 21 +++- test/stubs/nvs_flash.cpp | 9 ++ test/stubs/nvs_flash.h | 6 ++ test/test_led_effects.cpp | 82 ++++++++++++++- test/test_startup_guard.cpp | 28 +++++ test/test_storage_startup.cpp | 26 +++++ 25 files changed, 552 insertions(+), 242 deletions(-) create mode 100644 Build-PulseShift.cmd create mode 100644 Build-PulseShift.ps1 create mode 100644 PulseShift/partitions.csv create mode 100644 PulseShift/src/startup_guard.cpp create mode 100644 PulseShift/src/startup_guard.h create mode 100644 docs/WINDOWS-BUILD.md create mode 100644 test/stubs/esp_err.h create mode 100644 test/stubs/nvs_flash.cpp create mode 100644 test/stubs/nvs_flash.h create mode 100644 test/test_startup_guard.cpp create mode 100644 test/test_storage_startup.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 85ef8a0..28e2637 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,11 +9,6 @@ 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 (ESP32 ${{ matrix.core }}) @@ -22,11 +17,7 @@ jobs: strategy: fail-fast: false matrix: - include: - - core: '3.3.12' - nimble: '2.3.8' - - core: '4.0.0' - nimble: '2.5.2' + core: ['3.3.12', '4.0.0'] steps: - name: Check out source @@ -40,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-${{ matrix.core }}-nimble-${{ matrix.nimble }} - - - 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@${{ matrix.core }} - arduino-cli lib update-index - arduino-cli lib install --no-deps "NimBLE-Arduino@${{ matrix.nimble }}" + 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: | @@ -81,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..8f48912 --- /dev/null +++ b/Build-PulseShift.ps1 @@ -0,0 +1,158 @@ +[CmdletBinding()] +param( + [ValidateSet('3.3.12', '4.0.0')][string]$CoreVersion = '3.3.12', + [switch]$Headless, + [string]$BuildDirectory, + [string]$CacheDirectory = (Join-Path $PSScriptRoot '.tools/arduino'), + [string]$ArduinoCli, + [string]$SketchDirectory = (Join-Path $PSScriptRoot 'PulseShift') +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$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 } + +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-FileHash -LiteralPath $zip -Algorithm SHA256).Hash -ne $sha) { + throw "Arduino CLI archive SHA-256 mismatch. Replace this cached download and retry: $zip" + } + Expand-Archive -LiteralPath $zip -DestinationPath $cliDir -Force + } +} + +$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-FileHash -LiteralPath $partition -Algorithm SHA256).Hash.ToLowerInvariant() +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-FileHash -LiteralPath $boot -Algorithm SHA256).Hash -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-FileHash -LiteralPath $app -Algorithm SHA256).Hash.ToLowerInvariant() + 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 b32a90e..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()); @@ -644,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(); @@ -736,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"); } @@ -872,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/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 1fe9a5a..6e8be09 100644 --- a/README.md +++ b/README.md @@ -63,15 +63,12 @@ For complete electrical schematics, noise filtering, and circuit protection, see ## Quick Start (Windows / Arduino) -1. Install Arduino CLI with one of the CI-tested board packages and BLE library pairs. - The application-only release build uses Arduino-ESP32 **3.3.12** with - `NimBLE-Arduino` **2.3.8**. Arduino-ESP32 **4.0.0** (ESP-IDF 6.1.1) uses - `NimBLE-Arduino` **2.5.2**. -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/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/TESTING.md b/docs/TESTING.md index 987889d..b3e13fc 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -2,20 +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 with NimBLE-Arduino 2.3.8, or Arduino-ESP32 4.0.0 -with NimBLE-Arduino 2.5.2. 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) @@ -45,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 5bf0862..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. 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_led_effects.cpp b/test/test_led_effects.cpp index 1062b3d..2b30aec 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{}; @@ -803,6 +823,9 @@ static void startup_loop_repeats_the_selected_animation() { 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()); } @@ -932,6 +955,36 @@ static void effects_and_warning_scale_to_strip() { } } +static void chase_laps_preserve_timing_and_direction() { + 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(base, 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; auto monitor = verifiedMonitor(); @@ -948,9 +1001,12 @@ static void startup_loop_rpm_and_safety() { 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) { - engine.update(start + elapsed, cfg, monitor.snapshot(start + elapsed), input); + 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)); }; @@ -1027,9 +1083,29 @@ static void startup_loop_rpm_and_safety() { monitor.setCalibrationVerified(true); feed(3500, 0); CHECK(engine.activeLayer() == LedActiveLayer::StartupLoop); + feed(3600, 2000); + CHECK(engine.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); } -int main() { +int main(int argc, char** argv) { + if (argc > 2) { + std::fprintf(stderr, "Usage: %s [frame-trace.csv]\n", argv[0]); + return 2; + } + 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); + } fault_priority_wins_over_everything(); unverified_rpm_bar_renders_nothing(); provisional_rpm_preview_tracks_throttle_without_calibration(); @@ -1058,7 +1134,9 @@ int main() { master_power_off(); change_detection_flags(); effects_and_warning_scale_to_strip(); + 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"); +} From a93410ca92b1c1f2dcc92a4c80883b02b48020b1 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 23:07:22 +0530 Subject: [PATCH 5/7] Restore the full gamma range in Color Chase and smooth effects --- PulseShift/src/led_color.h | 36 +++++++++++++++++++----------------- test/test_led_effects.cpp | 6 +++++- 2 files changed, 24 insertions(+), 18 deletions(-) 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/test/test_led_effects.cpp b/test/test_led_effects.cpp index 2b30aec..ed525e7 100644 --- a/test/test_led_effects.cpp +++ b/test/test_led_effects.cpp @@ -956,6 +956,10 @@ static void effects_and_warning_scale_to_strip() { } 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; @@ -967,7 +971,7 @@ static void chase_laps_preserve_timing_and_direction() { cfg.effectSpeed = 50; const RgbColor base{230, 115, 70}; for (auto& color : cfg.ledColors) color = base; - const auto bright = scaleColor(base, cfg.brightness); + const auto bright = scaleColor(scaleColorGamma(base, 255), cfg.brightness); LedEffectEngine chase; chase.reset(0, pixels); const auto active = cfg.rpmMapping.activeCount(pixels); From 2304ec412069203b69e98d5f2bcc6252e547c605 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 23:14:32 +0530 Subject: [PATCH 6/7] Resolve build directories under Windows PowerShell 5.1 --- Build-PulseShift.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Build-PulseShift.ps1 b/Build-PulseShift.ps1 index 8f48912..a2b3e2c 100644 --- a/Build-PulseShift.ps1 +++ b/Build-PulseShift.ps1 @@ -3,13 +3,15 @@ param( [ValidateSet('3.3.12', '4.0.0')][string]$CoreVersion = '3.3.12', [switch]$Headless, [string]$BuildDirectory, - [string]$CacheDirectory = (Join-Path $PSScriptRoot '.tools/arduino'), + [string]$CacheDirectory, [string]$ArduinoCli, - [string]$SketchDirectory = (Join-Path $PSScriptRoot 'PulseShift') + [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 = @{ From 335bce35b62e7610feac5d797fac8d8ab2ffc501 Mon Sep 17 00:00:00 2001 From: Aritra Saha Date: Mon, 23 Nov 2026 23:17:30 +0530 Subject: [PATCH 7/7] Verify build hashes without PowerShell module autoloading --- Build-PulseShift.ps1 | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Build-PulseShift.ps1 b/Build-PulseShift.ps1 index a2b3e2c..fe33aad 100644 --- a/Build-PulseShift.ps1 +++ b/Build-PulseShift.ps1 @@ -35,6 +35,17 @@ New-Item -ItemType Directory -Force -Path $coreCache, $downloads, $data, $sketch $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.' @@ -48,10 +59,11 @@ if (!$ArduinoCli) { 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-FileHash -LiteralPath $zip -Algorithm SHA256).Hash -ne $sha) { + if ((Get-Sha256 $zip) -ne $sha) { throw "Arduino CLI archive SHA-256 mismatch. Replace this cached download and retry: $zip" } - Expand-Archive -LiteralPath $zip -DestinationPath $cliDir -Force + Add-Type -AssemblyName System.IO.Compression.FileSystem + [IO.Compression.ZipFile]::ExtractToDirectory($zip, $cliDir) } } @@ -126,12 +138,12 @@ foreach ($setting in @('CONFIG_APP_ROLLBACK_ENABLE=y', 'CONFIG_BOOTLOADER_APP_RO if (!(Select-String -LiteralPath $sdk -Pattern "^$setting$" -Quiet)) { throw "Missing SDK setting $setting" } } $partition = Join-Path $build 'PulseShift.ino.partitions.bin' -$partitionHash = (Get-FileHash -LiteralPath $partition -Algorithm SHA256).Hash.ToLowerInvariant() +$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-FileHash -LiteralPath $boot -Algorithm SHA256).Hash -ne $bootloaderHash) { +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' @@ -152,7 +164,7 @@ if ($bytes.Length -lt 65536 -or $bytes.Length + 76 -gt 0x140000 -or bootloaderAddress = '0x1000' bootloaderSha256 = $bootloaderHash.ToLowerInvariant() partitionSha256 = $partitionHash - applicationSha256 = (Get-FileHash -LiteralPath $app -Algorithm SHA256).Hash.ToLowerInvariant() + applicationSha256 = Get-Sha256 $app applicationBytes = $bytes.Length signedPackageBytes = $bytes.Length + 76 slotBytes = 0x140000