diff --git a/docs/qa/persisted-file-upgrade.md b/docs/qa/persisted-file-upgrade.md index 0dd43425d..8fdd73afa 100644 --- a/docs/qa/persisted-file-upgrade.md +++ b/docs/qa/persisted-file-upgrade.md @@ -2,7 +2,7 @@ This runbook verifies PR 709's physical filename migration without treating a synthetic fixture as production evidence. The automated harness is destructive only to one explicitly selected disposable emulator and one exact package name; it never clears data during an upgrade. -The harness default `-ExpectedSchemaVersion` is 65, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it. +The harness default `-ExpectedSchemaVersion` is 66, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it. ## Automated v0.9.6 debug-lineage matrix diff --git a/docs/qa/profile-schema42-fixture.md b/docs/qa/profile-schema42-fixture.md index 24f12fe15..2ee2807a8 100644 --- a/docs/qa/profile-schema42-fixture.md +++ b/docs/qa/profile-schema42-fixture.md @@ -1,6 +1,6 @@ # Profile schema-42 Android fixture -This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 65 (highest migration file + 1). +This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 66 (highest migration file + 1). All commands below are PowerShell commands. Start at the repository root. They use the installed Android SDK (`ANDROID_HOME`, else `ANDROID_SDK_ROOT`, else `%LOCALAPPDATA%\Android\Sdk`) and must not contact Supabase. The only network use is the explicit `git fetch` of the pinned fixture commit and Gradle dependency resolution for that commit. Do not pass `--offline`. @@ -171,9 +171,9 @@ foreach ($suffix in @('-wal', '-shm')) { if ($LASTEXITCODE -eq 0) { Receive-SandboxBytes $relative "$inspectDb$suffix" -AllowEmpty } } $userVersion = (& $hostSqlite -readonly -batch $inspectDb 'PRAGMA user_version;').Trim() -if ($userVersion -ne '65') { throw "Expected user_version 65 after upgrade, got $userVersion" } +if ($userVersion -ne '66') { throw "Expected user_version 66 after upgrade, got $userVersion" } & $hostSqlite -readonly -batch $inspectDb 'SELECT profile_id, legacy_migration_version, body_weight_kg, weight_unit, weight_increment, led_color_scheme_id, equipment_rack_json, workout_preferences_json, vbt_preferences_json FROM UserProfilePreferences ORDER BY profile_id;' & $adb shell run-as $package cat shared_prefs/phoenix_preferences.xml ``` -The host `sqlite3` query must report `user_version` 65, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections. +The host `sqlite3` query must report `user_version` 66, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections. diff --git a/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 b/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 index c576fc338..1a9535693 100644 --- a/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 +++ b/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 @@ -28,7 +28,7 @@ param( [string] $EvidenceDirectory = (Join-Path ([IO.Path]::GetTempPath()) 'phoenix-persisted-file-upgrade'), [Parameter()] - [int] $ExpectedSchemaVersion = 65 + [int] $ExpectedSchemaVersion = 66 ) Set-StrictMode -Version Latest diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt index 6ad506d89..c5d974088 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt @@ -23,7 +23,7 @@ import org.robolectric.annotation.SQLiteMode /** * Android-driver reproduction of a canonical 1.0.8 (v59) database opening in the - * current build (v65). The old DDL is pinned to the released tag, not reconstructed from today's + * current build (v66). The old DDL is pinned to the released tag, not reconstructed from today's * schema. Native SQLite exercises Android's open-helper callbacks without JDBC. * * SDK 35 is a representative Pixel 9 platform, not evidence of the reporting @@ -45,7 +45,7 @@ class Android109UpgradeTest { @Test fun v108Database_upgradesThroughProductionDriver_andReopensWithOldAndNewData() { - assertEquals(65L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances") + assertEquals(66L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances") seedReleased108Database() val upgraded = DriverFactory(context).createDriver() @@ -136,7 +136,7 @@ class Android109UpgradeTest { } private fun assertHealthyUpgrade(driver: SqlDriver) { - assertEquals(65L, driver.longValue("PRAGMA user_version")) + assertEquals(66L, driver.longValue("PRAGMA user_version")) assertEquals("ok", driver.textValue("PRAGMA quick_check")) assertEquals(1L, driver.longValue("PRAGMA foreign_keys")) driver.executeQuery(null, "PRAGMA foreign_key_check", { cursor -> @@ -162,9 +162,12 @@ class Android109UpgradeTest { val metric = queries.selectMetricById(41).executeAsOne() assertEquals(SESSION_ID, metric.sessionId) assertEquals(1_730_000_000_100L, metric.timestamp) - assertEquals(100.5, metric.position) + // Issue #1400 (migration 65): the released fixture's cm-scale position is + // scaled x10 to mm exactly once; loads are untouched. + assertEquals(1005.0, metric.position) assertEquals(21.5, metric.loadB) assertEquals(2L, metric.status) + assertEquals(2L, metric.metric_unit_version, "Legacy row must carry the new metric unit version after the x10 migration") assertNull(metric.heartRateBpm) assertNull(metric.chestAccZMg) } diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt index 1a78e01f4..6b71f0237 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt @@ -537,7 +537,7 @@ class IntervalsMigrationTest { // ==================== EXPECTED 63.sqm SHAPE ==================== private companion object { - private const val EXPECTED_SCHEMA_VERSION = 65L + private const val EXPECTED_SCHEMA_VERSION = 66L private val EXPECTED_TABLES: Map> = linkedMapOf( "IntervalsConnection" to linkedMapOf( diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Issue1400Migration65UnitScalingTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Issue1400Migration65UnitScalingTest.kt new file mode 100644 index 000000000..5df4bb2af --- /dev/null +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Issue1400Migration65UnitScalingTest.kt @@ -0,0 +1,188 @@ +package com.devil.phoenixproject.data.local + +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import com.devil.phoenixproject.database.PhoenixDatabase +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import org.junit.Test + +/** + * Issue #1400 F1: migration 65 scales legacy cm / cm-s metric values to mm / mm-s + * exactly once. Every scaling statement is row-guarded by `metric_unit_version` + * (1 = legacy, 2 = mm), so replaying the step — including the one-statement-at-a-time + * replay `applyMigrationResilient` performs after a partial failure — can never + * double-scale, while rows that arrive after a partial run are still scaled. + * + * Loads, percentages and counts are untouched. Old-scale derived estimates + * (personal MVT samples, stored velocity-1RM estimates) are invalidated, not rescaled. + */ +class Issue1400Migration65UnitScalingTest { + + private val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) + + @Test + fun `migration 65 scales legacy metric values exactly once and is idempotent`() { + PhoenixDatabase.Schema.create(driver) + seedLegacyRows() + + val first = applyMigrationResilient(driver, 65) + assertTrue( + first.none { !it.success && !it.recoverable }, + "migration 65 must apply cleanly: ${first.filter { !it.success }.map { it.error }}", + ) + + assertScaledExactlyOnce() + assertInvalidationApplied() + + // Replay the whole step (the resilient fallback re-runs every statement one by + // one after a partial failure): the row guard makes the second application a no-op. + applyMigrationResilient(driver, 65) + assertScaledExactlyOnce() + assertInvalidationApplied() + + // A row that arrives AFTER the first application (staged legacy data, restore of + // an old payload) is still scaled on the next replay, while scaled rows stay put. + insertLegacyMetricRow(id = 42, position = 10.0, velocity = 20.0, power = 30.0) + applyMigrationResilient(driver, 65) + assertScaledExactlyOnce() + assertDouble( + id = 42, + position = 100.0, + velocity = 200.0, + power = 300.0, + message = "a late legacy row must scale exactly once on replay", + ) + } + + private fun assertScaledExactlyOnce() { + assertDouble(id = 41, position = 350.0, velocity = 700.0, power = 14000.0, message = "MetricSample") + assertEquals(360.0, scalar("SELECT positionB FROM MetricSample WHERE id = 41")) + assertEquals(710.0, scalar("SELECT velocityB FROM MetricSample WHERE id = 41")) + assertEquals(20.5, scalar("SELECT load FROM MetricSample WHERE id = 41"), "loads must not scale") + assertEquals(21.5, scalar("SELECT loadB FROM MetricSample WHERE id = 41"), "loads must not scale") + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM MetricSample WHERE id = 41")) + + assertEquals(700.0, scalar("SELECT peakVelocity FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(600.0, scalar("SELECT avgVelocityConcentric FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(500.0, scalar("SELECT avgVelocityEccentric FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(350.0, scalar("SELECT rangeOfMotionMm FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(14000.0, scalar("SELECT peakPowerWatts FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(12000.0, scalar("SELECT avgPowerWatts FROM RepMetric WHERE sessionId = 's1'")) + assertEquals(40.0, scalar("SELECT peakForceA FROM RepMetric WHERE sessionId = 's1'"), "loads must not scale") + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM RepMetric WHERE sessionId = 's1'")) + + assertEquals(700.0, scalar("SELECT mcvMmS FROM RepBiomechanics WHERE sessionId = 's1'")) + assertEquals(800.0, scalar("SELECT peakVelocityMmS FROM RepBiomechanics WHERE sessionId = 's1'")) + assertEquals(25.0, scalar("SELECT velocityLossPercent FROM RepBiomechanics WHERE sessionId = 's1'"), "percentages must not scale") + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM RepBiomechanics WHERE sessionId = 's1'")) + + assertEquals(450.0, scalar("SELECT avgMcvMmS FROM WorkoutSession WHERE id = 's1'")) + assertEquals(20.0, scalar("SELECT heaviestLiftKg FROM WorkoutSession WHERE id = 's1'"), "loads must not scale") + assertEquals(25.0, scalar("SELECT totalVelocityLossPercent FROM WorkoutSession WHERE id = 's1'"), "percentages must not scale") + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM WorkoutSession WHERE id = 's1'")) + + assertEquals(700.0, scalar("SELECT concentricVelAvg FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(800.0, scalar("SELECT concentricVelMax FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(14000.0, scalar("SELECT concentricWattAvg FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(15000.0, scalar("SELECT concentricWattMax FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(500.0, scalar("SELECT eccentricVelAvg FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(600.0, scalar("SELECT eccentricVelMax FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(11000.0, scalar("SELECT eccentricWattAvg FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(12000.0, scalar("SELECT eccentricWattMax FROM PhaseStatistics WHERE sessionId = 's1'")) + assertEquals(20.0, scalar("SELECT concentricKgAvg FROM PhaseStatistics WHERE sessionId = 's1'"), "loads must not scale") + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM PhaseStatistics WHERE sessionId = 's1'")) + } + + private fun assertInvalidationApplied() { + assertEquals(0L, scalarLong("SELECT COUNT(*) FROM ExerciseMvt"), "old-scale personal MVT must be invalidated") + assertEquals(0L, scalarLong("SELECT COUNT(*) FROM VelocityOneRepMaxEstimate"), "old-scale velocity-1RM estimates must be invalidated") + } + + private fun assertDouble(id: Long, position: Double, velocity: Double, power: Double, message: String) { + assertEquals(position, scalar("SELECT position FROM MetricSample WHERE id = $id"), message) + assertEquals(velocity, scalar("SELECT velocity FROM MetricSample WHERE id = $id"), message) + assertEquals(power, scalar("SELECT power FROM MetricSample WHERE id = $id"), message) + assertEquals(2L, scalarLong("SELECT metric_unit_version FROM MetricSample WHERE id = $id"), message) + } + + // ==================== seeding ==================== + + private fun seedLegacyRows() { + // metric_unit_version is left unset on purpose: the default of 1 marks these + // rows exactly like migration 65 finds pre-upgrade rows. + driver.execute( + null, + "INSERT INTO WorkoutSession (id, timestamp, mode, targetReps, weightPerCableKg, avgMcvMmS, heaviestLiftKg, totalVelocityLossPercent) " + + "VALUES ('s1', 1700000000000, 'OldSchool', 5, 20.0, 45.0, 20.0, 25.0)", + 0, + ) + insertLegacyMetricRow(id = 41, position = 35.0, velocity = 70.0, power = 1400.0) + driver.execute( + null, + "INSERT INTO RepMetric (sessionId, repNumber, startTimestamp, endTimestamp, durationMs, concentricDurationMs, " + + "concentricPositions, concentricLoadsA, concentricLoadsB, concentricVelocities, concentricTimestamps, " + + "eccentricDurationMs, eccentricPositions, eccentricLoadsA, eccentricLoadsB, eccentricVelocities, eccentricTimestamps, " + + "peakForceA, peakForceB, avgForceConcentricA, avgForceConcentricB, avgForceEccentricA, avgForceEccentricB, " + + "peakVelocity, avgVelocityConcentric, avgVelocityEccentric, rangeOfMotionMm, peakPowerWatts, avgPowerWatts) " + + "VALUES ('s1', 1, 1, 2, 1, 1, '[35]', '[20]', '[21]', '[70]', '[0]', 1, '[10]', '[20]', '[21]', '[50]', '[1]', " + + "40, 41, 40, 41, 40, 41, 70, 60, 50, 35, 1400, 1200)", + 0, + ) + driver.execute( + null, + "INSERT INTO RepBiomechanics (sessionId, repNumber, mcvMmS, peakVelocityMmS, velocityZone, velocityLossPercent, " + + "normalizedForceN, normalizedPositionPct, strengthProfile, asymmetryPercent, dominantSide, avgLoadA, avgLoadB, timestamp) " + + "VALUES ('s1', 1, 70, 80, 'GRIND', 25, '[1]', '[0]', 'FLAT', 1, 'A', 20, 21, 2)", + 0, + ) + driver.execute( + null, + "INSERT INTO ExerciseMvt (exerciseId, profile_id, personalMvtMs, sampleCount, updatedAt) " + + "VALUES ('e1', 'default', 0.45, 3, 1)", + 0, + ) + driver.execute( + null, + "INSERT INTO PhaseStatistics (sessionId, concentricKgAvg, concentricKgMax, concentricVelAvg, concentricVelMax, " + + "concentricWattAvg, concentricWattMax, eccentricKgAvg, eccentricKgMax, eccentricVelAvg, eccentricVelMax, " + + "eccentricWattAvg, eccentricWattMax, timestamp) " + + "VALUES ('s1', 20, 21, 70, 80, 1400, 1500, 19, 20, 50, 60, 1100, 1200, 3)", + 0, + ) + driver.execute( + null, + "INSERT INTO VelocityOneRepMaxEstimate (exerciseId, estimatedPerCableKg, mvtUsedMs, r2, distinctLoads, passedQualityGate, computedAt) " + + "VALUES ('e1', 55, 0.45, 0.9, 3, 1, 1)", + 0, + ) + } + + private fun insertLegacyMetricRow(id: Long, position: Double, velocity: Double, power: Double) { + driver.execute( + null, + "INSERT INTO MetricSample (id, sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power) " + + "VALUES ($id, 's1', 1700000000000, $position, ${position + 1}, $velocity, ${velocity + 1}, 20.5, 21.5, $power)", + 0, + ) + } + + // ==================== query helpers ==================== + + private fun scalar(sql: String): Double { + var value: Double? = null + driver.executeQuery(null, sql, { cursor -> + if (cursor.next().value) value = cursor.getDouble(0) + app.cash.sqldelight.db.QueryResult.Value(Unit) + }, 0).value + return requireNotNull(value) { "no result for $sql" } + } + + private fun scalarLong(sql: String): Long { + var value: Long? = null + driver.executeQuery(null, sql, { cursor -> + if (cursor.next().value) value = cursor.getLong(0) + app.cash.sqldelight.db.QueryResult.Value(Unit) + }, 0).value + return requireNotNull(value) { "no result for $sql" } + } +} diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt index 97f40e6b6..8ede41390 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt @@ -1381,7 +1381,7 @@ class SchemaParityTest { // ==================== HELPERS ==================== companion object { - private const val EXPECTED_SCHEMA_VERSION = 65L + private const val EXPECTED_SCHEMA_VERSION = 66L /** * A database built the way every existing user gets it: minimal v1 schema, each diff --git a/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTabPreviews.kt b/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTabPreviews.kt index ca3fe199d..3d026f312 100644 --- a/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTabPreviews.kt +++ b/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTabPreviews.kt @@ -144,7 +144,7 @@ private fun EnhancedPositionBarsPreview() { // Inactive - Grey EnhancedCablePositionBar( label = "X", - currentPosition = 300f, // mm + currentPosition = 3000f, // mm velocity = 0.0, isActive = false, modifier = Modifier diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetector.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetector.kt index f17cea227..f28aa0259 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetector.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetector.kt @@ -34,7 +34,7 @@ class HandleStateDetector( companion object { /** Position threshold (mm) for simple left/right handle detection booleans */ - private const val SIMPLE_DETECTION_THRESHOLD = 50.0f + private const val SIMPLE_DETECTION_THRESHOLD = 500.0f /** [minPositionSeen] before any sample. */ internal const val UNSET_MIN_POSITION_MM = Double.MAX_VALUE diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessor.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessor.kt index 3f4c6a9b5..2c8798733 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessor.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessor.kt @@ -20,7 +20,7 @@ import kotlin.math.abs * 2. Status flag processing (deload debounce, ROM violation callbacks) * 3. Issue #210: Position tracking update BEFORE jump validation (cascade prevention) * 4. Sample validation (range, load, jump filter) - * 5. Firmware velocity (raw firmware velocity divided by 10) + * 5. Firmware velocity (raw firmware velocity, mm/s) * 6. EMA smoothing (with cold-start seeding and filtered-sample edge case) * 7. WorkoutMetric construction * @@ -65,7 +65,7 @@ class MonitorDataProcessor( // Position-jump filter reference and poll clock // lastPositionA/B: previous cable positions compared by the jump filter. // lastTimestamp: poll clock of the last accepted sample; 0 skips the - // first jump check. Velocity comes from firmware (divided by 10). + // first jump check. Velocity comes from firmware (mm/s). // ------------------------------------------------------------------------- private var lastPositionA = 0.0f private var lastPositionB = 0.0f @@ -189,15 +189,16 @@ class MonitorDataProcessor( } } - // Firmware velocity is raw signed int16 in 0.1mm/s units (matching position's 0.1mm - // resolution). Scale by /10.0 to convert to mm/s for downstream consistency: - // - HandleStateDetector thresholds: 50.0 / 20.0 mm/s - // - Power calculation: load_kg * velocity_mm_s + // Firmware velocity is raw signed int16 in mm/s (issue #1400 RCA §5a: the raw + // velocity shares the raw position's mm unit per second, and raw position is mm). + // The legacy /10 here produced cm/s values that every consumer labelled mm/s. + // Downstream consumers (all in mm/s after this fix): + // - HandleStateDetector thresholds: 500.0 / 200.0 mm/s + // - Power calculation: load_kg * velocity_mm_s / 1000 * g // - MetricSample DB: stored in mm/s // - UI display: shown in mm/s - // Hardware-validated: firmware velA=832 at grab ≈ 83.2 mm/s, matching old client-side scale. - val rawVelocityA = packet.firmwareVelA / 10.0 - val rawVelocityB = packet.firmwareVelB / 10.0 + val rawVelocityA = packet.firmwareVelA.toDouble() + val rawVelocityB = packet.firmwareVelB.toDouble() // ===== STAGE 6: EMA SMOOTHING ===== // Firmware velocity is already hardware-timed so less smoothing is needed, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/ProtocolParser.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/ProtocolParser.kt index c6e854192..857374f5c 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/ProtocolParser.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/ble/ProtocolParser.kt @@ -137,8 +137,10 @@ fun parseRepPacket(data: ByteArray, hasOpcodePrefix: Boolean, timestamp: Long): // MODERN 24-byte format - parse all 8 fields val upCounter = getInt32LE(data, offset + 0) val downCounter = getInt32LE(data, offset + 4) - val rangeTop = getFloatLE(data, offset + 8) - val rangeBottom = getFloatLE(data, offset + 12) + // ROM boundary floats are wire-scaled like the old parsed position (0.1x mm); + // multiply by 10 so they match the mm position scale (issue #1400, arch constraint 2). + val rangeTop = getFloatLE(data, offset + 8) * 10f + val rangeBottom = getFloatLE(data, offset + 12) * 10f val repsRomCount = getUInt16LE(data, offset + 16) val repsRomTotal = getUInt16LE(data, offset + 18) val repsSetCount = getUInt16LE(data, offset + 20) @@ -186,11 +188,11 @@ fun parseRepPacket(data: ByteArray, hasOpcodePrefix: Boolean, timestamp: Long): * Hardware-validated format (26 bytes, Little Endian) — confirmed 2026-02-17: * - (0-1): ticks low (uint16) * - (2-3): ticks high (uint16) - * - (4-5): posA (signed int16, /10.0f for mm) - * - (6-7): velA (signed int16, firmware velocity for cable A) + * - (4-5): posA (signed int16, raw mm) + * - (6-7): velA (signed int16, firmware velocity for cable A, raw mm/s) * - (8-9): loadA (uint16, /100.0f for kg) - * - (10-11): posB (signed int16, /10.0f for mm) - * - (12-13): velB (signed int16, firmware velocity for cable B) + * - (10-11): posB (signed int16, raw mm) + * - (12-13): velB (signed int16, firmware velocity for cable B, raw mm/s) * - (14-15): loadB (uint16, /100.0f for kg) * - (16-17): status flags (uint16, optional) * - (18-25): unknown (8 bytes, unread) @@ -213,9 +215,10 @@ fun parseMonitorPacket(data: ByteArray): MonitorPacket? { // Reconstruct 32-bit tick counter using Long to avoid Int overflow when f1 >= 0x8000 val ticks = f0.toLong() or (f1.toLong() shl 16) - // Position values scaled to millimeters - val posA = posARaw / 10.0f - val posB = posBRaw / 10.0f + // Position values are millimeters (raw int16 = mm; issue #1400 RCA §5a). The + // legacy /10 here produced cm-scale values that every consumer labelled mm. + val posA = posARaw.toFloat() + val posB = posBRaw.toFloat() // Load in kg (device sends kg * 100) val loadA = loadARaw / 100.0f diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/integration/intervals/CompletionJournalCodec.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/integration/intervals/CompletionJournalCodec.kt index db458bfc8..452f9f2e2 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/integration/intervals/CompletionJournalCodec.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/integration/intervals/CompletionJournalCodec.kt @@ -12,6 +12,8 @@ import com.devil.phoenixproject.domain.model.StrengthProfile import com.devil.phoenixproject.domain.model.VelocityResult import com.devil.phoenixproject.domain.model.WorkoutMetric import com.devil.phoenixproject.domain.model.WorkoutSession +import com.devil.phoenixproject.util.METRIC_UNIT_VERSION_LEGACY +import com.devil.phoenixproject.util.METRIC_UNIT_VERSION_MM import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json @@ -30,14 +32,19 @@ import kotlinx.serialization.json.Json * `BiomechanicsRepResult`) are not `@Serializable`, so this file defines explicit * persistence DTOs covering every field of those constructors and converts both ways. * - * Versioning: the envelope carries a `v` field. [decode] rejects unknown versions and - * malformed payloads by returning null — a malformed child must block finalization, never - * be silently dropped or partially replayed. + * Versioning: the envelope carries a `v` field and an explicit `metricUnitVersion`. + * [decode] rejects unknown versions and malformed payloads by returning null — a + * malformed child must block finalization, never be silently dropped or partially + * replayed. v1 payloads predate the issue #1400 metric-unit fix: their unit-bearing + * values are cm / cm-s and are scaled to mm / mm-s exactly once at decode. */ object CompletionJournalCodec { - /** Current payload version. Bump only with a matching decoder branch. */ - const val CURRENT_VERSION = 1 + /** Current payload version (issue #1400: mm / mm-s metric units). */ + const val CURRENT_VERSION = 2 + + /** Payload version written before the issue #1400 metric-unit fix (cm / cm-s). */ + const val LEGACY_VERSION = 1 private val json = Json { ignoreUnknownKeys = false @@ -48,7 +55,8 @@ object CompletionJournalCodec { fun encode(write: PendingChildWrite): String = json.encodeToString( PendingChildWriteEnvelopeDto.serializer(), PendingChildWriteEnvelopeDto( - v = CURRENT_VERSION, + v = if (write.metricUnitVersion == METRIC_UNIT_VERSION_LEGACY) LEGACY_VERSION else CURRENT_VERSION, + metricUnitVersion = write.metricUnitVersion, session = PersistedSessionDto.from(write.session), metrics = write.metrics.map { PersistedMetricDto.from(it) }, completedSet = write.completedSet?.let { PersistedCompletedSetDto.from(it) }, @@ -60,24 +68,76 @@ object CompletionJournalCodec { /** * Decodes a pending child write, or null when the payload is malformed or its * version is unknown. Unknown versions are rejected, never best-effort parsed. + * A v1 payload is old-scale: its unit-bearing values are scaled to mm / mm-s + * exactly once here, so a recovered legacy write is indistinguishable from a + * migrated legacy row and can never be mixed unscaled with new rows. */ fun decode(payload: String): PendingChildWrite? { val envelope = runCatching { json.decodeFromString(PendingChildWriteEnvelopeDto.serializer(), payload) }.getOrNull() ?: return null - if (envelope.v != CURRENT_VERSION) return null - return runCatching { + val base = runCatching { PendingChildWrite( session = envelope.session.toDomain(), metrics = envelope.metrics.map { it.toDomain() }, completedSet = envelope.completedSet?.toDomain(), repMetrics = envelope.repMetrics.map { it.toDomain() }, repBiomechanics = envelope.repBiomechanics.map { it.toDomain() }, + metricUnitVersion = envelope.metricUnitVersion, ) - }.getOrNull() + }.getOrNull() ?: return null + return when (envelope.v) { + CURRENT_VERSION -> base.takeIf { envelope.metricUnitVersion == METRIC_UNIT_VERSION_MM } + LEGACY_VERSION -> base.takeIf { envelope.metricUnitVersion == METRIC_UNIT_VERSION_LEGACY } + ?.scaledFromLegacyMetricUnits() + else -> null + } } } +/** + * Issue #1400 F1: scales a legacy (cm / cm-s) pending child write to the mm / mm-s + * contract exactly once — the same field families migration 65 scales, so a replayed + * legacy write lands exactly like a migrated legacy row. Loads, percentages and counts + * are untouched; [PendingChildWrite.metricUnitVersion] becomes [METRIC_UNIT_VERSION_MM]. + */ +internal fun PendingChildWrite.scaledFromLegacyMetricUnits(): PendingChildWrite = copy( + metricUnitVersion = METRIC_UNIT_VERSION_MM, + session = session.copy(avgMcvMmS = session.avgMcvMmS?.let { it * 10f }), + metrics = metrics.map { + it.copy( + positionA = it.positionA * 10f, + positionB = it.positionB * 10f, + velocityA = it.velocityA * 10.0, + velocityB = it.velocityB * 10.0, + ) + }, + repMetrics = repMetrics.map { + it.copy( + peakVelocity = it.peakVelocity * 10f, + avgVelocityConcentric = it.avgVelocityConcentric * 10f, + avgVelocityEccentric = it.avgVelocityEccentric * 10f, + rangeOfMotionMm = it.rangeOfMotionMm * 10f, + peakPowerWatts = it.peakPowerWatts * 10f, + avgPowerWatts = it.avgPowerWatts * 10f, + // The per-sample curves are unit-bearing like the scalars (positions mm, + // velocities mm/s after scaling); load arrays and timestamps are untouched. + concentricPositions = it.concentricPositions.map { v -> v * 10f }.toFloatArray(), + eccentricPositions = it.eccentricPositions.map { v -> v * 10f }.toFloatArray(), + concentricVelocities = it.concentricVelocities.map { v -> v * 10f }.toFloatArray(), + eccentricVelocities = it.eccentricVelocities.map { v -> v * 10f }.toFloatArray(), + ) + }, + repBiomechanics = repBiomechanics.map { + it.copy( + velocity = it.velocity.copy( + meanConcentricVelocityMmS = it.velocity.meanConcentricVelocityMmS * 10f, + peakVelocityMmS = it.velocity.peakVelocityMmS * 10f, + ), + ) + }, +) + /** * The immutable persistence input of one completed-set write. This is the replay unit of * the finalization journal: [com.devil.phoenixproject.data.repository.WorkoutRepository @@ -89,11 +149,15 @@ data class PendingChildWrite( val completedSet: CompletedSet?, val repMetrics: List, val repBiomechanics: List, + /** Issue #1400: explicit metric-unit contract of this write's unit-bearing values. */ + val metricUnitVersion: Int = METRIC_UNIT_VERSION_MM, ) @Serializable internal data class PendingChildWriteEnvelopeDto( val v: Int, + /** Absent on v1 payloads, which predate the issue #1400 unit fix (cm / cm-s). */ + val metricUnitVersion: Int = METRIC_UNIT_VERSION_LEGACY, val session: PersistedSessionDto, val metrics: List = emptyList(), val completedSet: PersistedCompletedSetDto? = null, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt index f1c89bccb..67f5a23bc 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt @@ -1525,6 +1525,46 @@ WHERE gs.rowid = ( "UPDATE WorkoutSession SET totalVelocityLossPercent = 0 WHERE totalVelocityLossPercent < 0", ) + // Migration 65: Issue #1400 F1 metric unit correction (cm/cm-s -> mm/mm-s). + // Row-guarded by metric_unit_version (1 = legacy scale, 2 = mm/mm-s) so a replayed + // statement matches zero rows instead of double-scaling. Invalidation DELETEs are + // idempotent. No data UPDATEs live in schema healing; this is the only scaler. + 65 -> listOf( + """ + CREATE TABLE IF NOT EXISTS PhaseStatistics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sessionId TEXT NOT NULL, + concentricKgAvg REAL NOT NULL, + concentricKgMax REAL NOT NULL, + concentricVelAvg REAL NOT NULL, + concentricVelMax REAL NOT NULL, + concentricWattAvg REAL NOT NULL, + concentricWattMax REAL NOT NULL, + eccentricKgAvg REAL NOT NULL, + eccentricKgMax REAL NOT NULL, + eccentricVelAvg REAL NOT NULL, + eccentricVelMax REAL NOT NULL, + eccentricWattAvg REAL NOT NULL, + eccentricWattMax REAL NOT NULL, + timestamp INTEGER NOT NULL, + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), + FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE + ) + """.trimIndent(), + "ALTER TABLE MetricSample ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + "ALTER TABLE RepMetric ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + "ALTER TABLE RepBiomechanics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + "ALTER TABLE WorkoutSession ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + "ALTER TABLE PhaseStatistics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + "UPDATE MetricSample SET position = position * 10, positionB = positionB * 10, velocity = velocity * 10, velocityB = velocityB * 10, power = power * 10, metric_unit_version = 2 WHERE metric_unit_version = 1", + "UPDATE RepMetric SET peakVelocity = peakVelocity * 10, avgVelocityConcentric = avgVelocityConcentric * 10, avgVelocityEccentric = avgVelocityEccentric * 10, rangeOfMotionMm = rangeOfMotionMm * 10, peakPowerWatts = peakPowerWatts * 10, avgPowerWatts = avgPowerWatts * 10, metric_unit_version = 2 WHERE metric_unit_version = 1", + "UPDATE RepBiomechanics SET mcvMmS = mcvMmS * 10, peakVelocityMmS = peakVelocityMmS * 10, metric_unit_version = 2 WHERE metric_unit_version = 1", + "UPDATE WorkoutSession SET avgMcvMmS = avgMcvMmS * 10, metric_unit_version = 2 WHERE metric_unit_version = 1", + "UPDATE PhaseStatistics SET concentricVelAvg = concentricVelAvg * 10, concentricVelMax = concentricVelMax * 10, concentricWattAvg = concentricWattAvg * 10, concentricWattMax = concentricWattMax * 10, eccentricVelAvg = eccentricVelAvg * 10, eccentricVelMax = eccentricVelMax * 10, eccentricWattAvg = eccentricWattAvg * 10, eccentricWattMax = eccentricWattMax * 10, metric_unit_version = 2 WHERE metric_unit_version = 1", + "DELETE FROM ExerciseMvt", + "DELETE FROM VelocityOneRepMaxEstimate", + ) + else -> emptyList() } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt index 530cd288d..f209e9fba 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt @@ -663,6 +663,7 @@ internal val manifestTables: List = listOf( eccentricWattAvg REAL NOT NULL, eccentricWattMax REAL NOT NULL, timestamp INTEGER NOT NULL, + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ) """.trimIndent(), @@ -732,6 +733,7 @@ internal val manifestTables: List = listOf( avgPowerWatts REAL NOT NULL, updatedAt INTEGER, serverId TEXT, + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ) """.trimIndent(), @@ -762,6 +764,7 @@ internal val manifestTables: List = listOf( avgLoadB REAL NOT NULL, timestamp INTEGER NOT NULL, aggregateEligible INTEGER NOT NULL DEFAULT 1 CHECK(aggregateEligible IN (0, 1)), + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ) """.trimIndent(), @@ -1162,7 +1165,8 @@ internal val manifestTables: List = listOf( hrr300Bpm INTEGER, maxTorsoPitchDeg REAL, maxTorsoRollDeg REAL, - routineModifierApplied INTEGER NOT NULL DEFAULT 1 CHECK(routineModifierApplied IN (0, 1)) + routineModifierApplied INTEGER NOT NULL DEFAULT 1 CHECK(routineModifierApplied IN (0, 1)), + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)) ) """.trimIndent(), ), @@ -1191,6 +1195,7 @@ internal val manifestTables: List = listOf( chestAccXMg INTEGER, chestAccYMg INTEGER, chestAccZMg INTEGER, + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ) """.trimIndent(), @@ -2144,6 +2149,36 @@ internal val manifestColumns: List = listOf( "aggregateEligible", "ALTER TABLE RepBiomechanics ADD COLUMN aggregateEligible INTEGER NOT NULL DEFAULT 1 CHECK(aggregateEligible IN (0, 1))", ), + + // ── Metric unit marker (1 column per scaled table, migration 65) ─── + // Migration 65: Issue #1400 F1 unit correction. 1 = legacy cm/cm-s scale, + // 2 = mm/mm-s. Healing adds the marker only and never scales data (no data + // UPDATEs in schema healing); migration 65 is the only scaler. + SchemaHealOperation( + "MetricSample", + "metric_unit_version", + "ALTER TABLE MetricSample ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + ), + SchemaHealOperation( + "RepMetric", + "metric_unit_version", + "ALTER TABLE RepMetric ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + ), + SchemaHealOperation( + "RepBiomechanics", + "metric_unit_version", + "ALTER TABLE RepBiomechanics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + ), + SchemaHealOperation( + "WorkoutSession", + "metric_unit_version", + "ALTER TABLE WorkoutSession ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + ), + SchemaHealOperation( + "PhaseStatistics", + "metric_unit_version", + "ALTER TABLE PhaseStatistics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2))", + ), ) // ============================================================ diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightSyncRepository.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightSyncRepository.kt index 7bc22dbb0..7cbee2fb3 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightSyncRepository.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightSyncRepository.kt @@ -1532,6 +1532,7 @@ class SqlDelightSyncRepository( maxTorsoPitchDeg: Double?, maxTorsoRollDeg: Double?, routineModifierApplied: Long, + metricUnitVersion: Long, ): WorkoutSession = WorkoutSession( id = id, timestamp = timestamp, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt index cf5712f1d..b1f3df76b 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt @@ -142,6 +142,7 @@ class SqlDelightWorkoutRepository( maxTorsoPitchDeg: Double?, maxTorsoRollDeg: Double?, routineModifierApplied: Long, + metricUnitVersion: Long, ): WorkoutSession = WorkoutSession( id = id, timestamp = timestamp, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt index c2444b51a..948a6cc95 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt @@ -406,8 +406,8 @@ data class WorkoutParameters( /** * Real-time workout metric data from the device * - * Position values are in millimeters (mm), range -1000.0 to +1000.0 - * Raw BLE values are scaled by dividing by 10.0f (Issue #197) + * Position values are in millimeters (mm), velocity in mm/s. Raw firmware values + * are mm / mm-s (issue #1400 RCA §5a); the legacy /10 ingestion scaling is gone. */ data class WorkoutMetric( val timestamp: Long = currentTimeMillis(), diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetector.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetector.kt index 0b8b6afb9..fcabcb90c 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetector.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetector.kt @@ -31,7 +31,7 @@ class RepBoundaryDetector { private const val MIN_SAMPLES = 15 /** Minimum position difference to consider as a valley (in mm) */ - private const val VALLEY_THRESHOLD_MM = 10f + private const val VALLEY_THRESHOLD_MM = 100f /** Moving average window size for smoothing */ private const val SMOOTHING_WINDOW = 5 diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachine.kt index 32de9d2b2..93310c600 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachine.kt @@ -59,7 +59,7 @@ class RepCounterFromMachine { private var phasePeakPosition: Float = 0f // Peak position during current rep (for eccentric progress) private var positionHistoryForDirection = mutableListOf() // Rolling window for smoothing private val DIRECTION_WINDOW_SIZE = 3 - private val DIRECTION_THRESHOLD_MM = 5f // Minimum movement to detect direction change (mm) + private val DIRECTION_THRESHOLD_MM = 50f // Minimum movement to detect direction change (mm) // Track directional counters for position calibration AND visual feedback // Issue #210 FIX: Initialize to 0 instead of null so first rep notification @@ -197,7 +197,7 @@ class RepCounterFromMachine { */ fun seedRomBoundaries(rangeTop: Float, rangeBottom: Float) { if (rangeTop <= 0f || rangeBottom < 0f) return - if (rangeTop == 300.0f && rangeBottom == 0.0f) return // Default/unset values + if (rangeTop == 3000.0f && rangeBottom == 0.0f) return // Default/unset values (3 m rope in mm) // Only seed if not already calibrated from actual reps if (maxRepPosA == null && topPositionsA.isEmpty()) { @@ -768,7 +768,7 @@ class RepCounterFromMachine { } // Progress: 0.0 at bottom, 1.0 at top val range = phasePeakPosition - phaseStartPosition - phaseProgress = if (range > 10f) { + phaseProgress = if (range > 100f) { ((currentPos - phaseStartPosition) / range).coerceIn(0f, 1f) } else { 0f @@ -779,7 +779,7 @@ class RepCounterFromMachine { // Progress: 0.0 at top, 1.0 at bottom val minPos = minRepPosA ?: minRepPosB ?: phaseStartPosition val range = phasePeakPosition - minPos - phaseProgress = if (range > 10f) { + phaseProgress = if (range > 100f) { ((phasePeakPosition - currentPos) / range).coerceIn(0f, 1f) } else { 0f @@ -808,7 +808,7 @@ class RepCounterFromMachine { lastRepBottomB = lastRepBottomB, ) - fun hasMeaningfulRange(minRangeThreshold: Float = 50f): Boolean { + fun hasMeaningfulRange(minRangeThreshold: Float = 500f): Boolean { val minA = minRepPosA val maxA = maxRepPosA val minB = minRepPosB @@ -847,7 +847,7 @@ data class RepRanges( * Check if cable A is active (has built meaningful range of motion). * Used to determine whether to show cable position indicators. */ - fun isCableAActive(minRangeThreshold: Float = 50f): Boolean { + fun isCableAActive(minRangeThreshold: Float = 500f): Boolean { return !(minPosA == null || maxPosA == null) && (maxPosA - minPosA) > minRangeThreshold } @@ -855,7 +855,7 @@ data class RepRanges( * Check if cable B is active (has built meaningful range of motion). * Used to determine whether to show cable position indicators. */ - fun isCableBActive(minRangeThreshold: Float = 50f): Boolean { + fun isCableBActive(minRangeThreshold: Float = 500f): Boolean { return !(minPosB == null || maxPosB == null) && (maxPosB - minPosB) > minRangeThreshold } @@ -871,7 +871,7 @@ data class RepRanges( * @param minRangeThreshold Minimum ROM range required before that cable can be in the danger zone * @return true if either cable with meaningful range is in danger zone */ - fun isInDangerZone(posA: Float, posB: Float, minRangeThreshold: Float = 50f): Boolean { + fun isInDangerZone(posA: Float, posB: Float, minRangeThreshold: Float = 500f): Boolean { return isCableAInDangerZone(posA, minRangeThreshold) || isCableBInDangerZone(posB, minRangeThreshold) } @@ -879,14 +879,14 @@ data class RepRanges( /** * True when cable A has built a meaningful range and [posA] is within 5% of its minimum. */ - fun isCableAInDangerZone(posA: Float, minRangeThreshold: Float = 50f): Boolean { + fun isCableAInDangerZone(posA: Float, minRangeThreshold: Float = 500f): Boolean { return isCableInDangerZone(posA, minPosA, maxPosA, minRangeThreshold) } /** * True when cable B has built a meaningful range and [posB] is within 5% of its minimum. */ - fun isCableBInDangerZone(posB: Float, minRangeThreshold: Float = 50f): Boolean { + fun isCableBInDangerZone(posB: Float, minRangeThreshold: Float = 500f): Boolean { return isCableInDangerZone(posB, minPosB, maxPosB, minRangeThreshold) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt index f2826f4b9..7a5b27569 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt @@ -7001,7 +7001,7 @@ class ActiveSessionEngine( val thresholdA = minA + (rangeA * 0.05f) val cableAInDanger = metric.positionA <= thresholdA val cableAReleased = metric.positionA < WorkoutCoordinator.HANDLE_REST_THRESHOLD || - (metric.positionA - minA) < 10 + (metric.positionA - minA) < 100 if (cableAInDanger && cableAReleased) { cableAppearsReleased = true } @@ -7017,7 +7017,7 @@ class ActiveSessionEngine( val thresholdB = minB + (rangeB * 0.05f) val cableBInDanger = metric.positionB <= thresholdB val cableBReleased = metric.positionB < WorkoutCoordinator.HANDLE_REST_THRESHOLD || - (metric.positionB - minB) < 10 + (metric.positionB - minB) < 100 if (cableBInDanger && cableBReleased) { cableAppearsReleased = true } @@ -9820,6 +9820,7 @@ class ActiveSessionEngine( completedSet = snapshot.completedSet, repMetrics = snapshot.repMetrics, repBiomechanics = snapshot.biomechanicsRepResults, + metricUnitVersion = snapshot.metricUnitVersion, ), ) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt index 8c0d47597..5c7924f63 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt @@ -126,21 +126,21 @@ class WorkoutCoordinator( /** * Two-tier velocity hysteresis for stall detection (Issue #204, #216) * Hysteresis prevents the stall timer toggling near the threshold: - * - Below LOW (<2.5): start/continue stall timer (user is stopped) - * - Above HIGH (>10): reset stall timer (user is clearly moving) - * - Between LOW and HIGH (>=2.5 and <=10): maintain current state (hysteresis band) + * - Below LOW (<25): start/continue stall timer (user is stopped) + * - Above HIGH (>100): reset stall timer (user is clearly moving) + * - Between LOW and HIGH (>=25 and <=100): maintain current state (hysteresis band) */ - const val STALL_VELOCITY_LOW = 2.5 // Below this = definitely stalled (mm/s) - const val STALL_VELOCITY_HIGH = 10.0 // Above this = definitely moving (mm/s) + const val STALL_VELOCITY_LOW = 25.0 // Below this = definitely stalled (mm/s) + const val STALL_VELOCITY_HIGH = 100.0 // Above this = definitely moving (mm/s) /** Minimum position to consider handles "in use" for stall detection (mm) */ - const val STALL_MIN_POSITION = 10.0 + const val STALL_MIN_POSITION = 100.0 /** Position threshold to consider handle at rest (aligned with BLE handle detector). */ - const val HANDLE_REST_THRESHOLD = 5.0 + const val HANDLE_REST_THRESHOLD = 50.0 /** Minimum position range to consider "meaningful" for auto-stop detection (in mm) */ - const val MIN_RANGE_THRESHOLD = 50f + const val MIN_RANGE_THRESHOLD = 500f /** Issue #204: Startup grace period for AMRAP exercises (ms) * Prevents auto-stop from triggering before user has time to grab handles diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt index 29c56da4e..37ae48343 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt @@ -18,6 +18,7 @@ import com.devil.phoenixproject.domain.model.SingleExerciseDefaultsDocument import com.devil.phoenixproject.domain.model.WorkoutMetric import com.devil.phoenixproject.domain.model.WorkoutSession import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.util.METRIC_UNIT_VERSION_MM import com.devil.phoenixproject.util.withPlatformLock import kotlinx.atomicfu.atomic @@ -388,6 +389,13 @@ internal data class WorkoutExitSnapshot( val cycleId: String?, val cycleDayNumber: Int?, val postSaveInput: PostSaveWorkoutInput, + /** + * Issue #1400: explicit metric-unit contract of this snapshot's unit-bearing values + * (rep velocities, ROM, power). The persistent crash form ([PendingChildWrite] via + * CompletionJournalCodec) carries the same marker, so in-flight state recovered after + * the unit upgrade is scaled exactly once or rejected, never mixed with new rows. + */ + val metricUnitVersion: Int = METRIC_UNIT_VERSION_MM, ) internal data class WorkoutExecutionContext( diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt index e60e13233..9de3ba4b3 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt @@ -720,7 +720,48 @@ fun backupPrivacySummary(includesRawTelemetry: Boolean): String = * Highest backup schema version this build can produce. * Bump whenever BackupContent gains/loses entities or a backup field type changes. */ -const val CURRENT_BACKUP_VERSION: Int = 7 +const val CURRENT_BACKUP_VERSION: Int = 8 + +/** + * Issue #1400 F1: the first backup envelope version whose metric values are in the + * corrected mm / mm-s scale. Backups at version 7 or older carry cm / cm-s values in + * the mm-labelled fields, so an import of those must scale the unit-bearing fields + * exactly once (metric_unit_version = 2 on the restored rows is the durable marker). + */ +const val FIRST_MM_SCALE_BACKUP_VERSION: Int = 8 + +/** x10 for pre-[FIRST_MM_SCALE_BACKUP_VERSION] envelopes, 1 otherwise. */ +fun legacyMetricUnitScaleFor(backupVersion: Int): Float = + if (backupVersion < FIRST_MM_SCALE_BACKUP_VERSION) 10f else 1f + +/** + * Scales the unit-bearing [MetricSampleBackup] fields to the current mm / mm-s contract + * when [backupVersion] predates [FIRST_MM_SCALE_BACKUP_VERSION]. Loads, heart rate and + * percentages are untouched. Pure: applying it twice with the same envelope version + * yields the same result (the envelope version is the scale marker). + */ +fun MetricSampleBackup.scaledToCurrentMetricUnits(backupVersion: Int): MetricSampleBackup { + val scale = legacyMetricUnitScaleFor(backupVersion) + if (scale == 1f) return this + return copy( + position = position?.let { it * scale }, + positionB = positionB?.let { it * scale }, + velocity = velocity?.let { it * scale }, + velocityB = velocityB?.let { it * scale }, + power = power?.let { it * scale }, + ) +} + +/** + * Scales the unit-bearing [WorkoutSessionBackup] fields (session average MCV) to the + * current mm / mm-s contract for pre-[FIRST_MM_SCALE_BACKUP_VERSION] envelopes. + * Loads, volumes and velocity-loss percentages are untouched. + */ +fun WorkoutSessionBackup.scaledToCurrentMetricUnits(backupVersion: Int): WorkoutSessionBackup { + val scale = legacyMetricUnitScaleFor(backupVersion) + if (scale == 1f) return this + return copy(avgMcvMmS = avgMcvMmS?.let { it * scale }) +} /** * Profile-scoped preference payload. Raw JSON sections intentionally isolate malformed or diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BleConstants.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BleConstants.kt index 2aee17207..d3fabc60a 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BleConstants.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BleConstants.kt @@ -128,26 +128,28 @@ object BleConstants { // ------------------------------------------------------------------------- object Thresholds { // Handle detection thresholds (from parent repo - proven working) - // Position values are in mm (raw / 10.0f), so thresholds are in mm - const val HANDLE_GRABBED_THRESHOLD = 8.0 // Position > 8.0mm = handles grabbed - const val HANDLE_REST_THRESHOLD = 5.0 // Position < 5.0mm = handles at rest + // Position values are in mm (raw firmware = mm since issue #1400), so thresholds are in mm. + // The pre-#1400 values were tuned against cm-scaled data and are scaled x10 here so + // control behavior is numerically identical on the corrected scale. + const val HANDLE_GRABBED_THRESHOLD = 80.0 // Position > 80.0mm = handles grabbed + const val HANDLE_REST_THRESHOLD = 50.0 // Position < 50.0mm = handles at rest - // Velocity is in mm/s (calculated from mm positions) - const val VELOCITY_THRESHOLD = 50.0 // Velocity > 50 mm/s = significant movement - const val AUTO_START_VELOCITY_THRESHOLD = 20.0 // Lower threshold for auto-start grab detection + // Velocity is in mm/s (raw firmware velocity since issue #1400) + const val VELOCITY_THRESHOLD = 500.0 // Velocity > 500 mm/s = significant movement + const val AUTO_START_VELOCITY_THRESHOLD = 200.0 // Lower threshold for auto-start grab detection // Velocity smoothing (Issue #204, #214) // EMA alpha: 0.3 = balanced smoothing (faster response during direction changes) const val VELOCITY_SMOOTHING_ALPHA = 0.3 // Sample validation - const val MIN_POSITION = -1000 // Valid position range - const val MAX_POSITION = 1000 // Valid position range - const val POSITION_JUMP_THRESHOLD = 20.0f // Max allowed position change between samples (mm) + const val MIN_POSITION = -10000 // Valid position range + const val MAX_POSITION = 10000 // Valid position range + const val POSITION_JUMP_THRESHOLD = 200.0f // Max allowed position change between samples (mm) // Handle state hysteresis - Issue #176: Dynamic baseline threshold for overhead pulley setups - const val GRAB_DELTA_THRESHOLD = 10.0 // Position change (mm) to detect grab - const val RELEASE_DELTA_THRESHOLD = 5.0 // Position must return within 5mm of baseline + const val GRAB_DELTA_THRESHOLD = 100.0 // Position change (mm) to detect grab + const val RELEASE_DELTA_THRESHOLD = 50.0 // Position must return within 50mm of baseline } // ------------------------------------------------------------------------- diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt index c65ad7e4f..dcadcf116 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt @@ -1636,7 +1636,7 @@ abstract class BaseDataBackupManager( val rawJson = nav.nextValueAsString() val session = tryImport("session-parse", null) { json.decodeFromString(rawJson) - } ?: continue + }?.scaledToCurrentMetricUnits(backupVersion) ?: continue if (backupVersion >= 6 && session.profileId != null && !profileParentAvailable(session.profileId) @@ -1854,7 +1854,7 @@ abstract class BaseDataBackupManager( json.decodeFromString(rawJson) } if (metric != null) { - restoreMetric(metric) + restoreMetric(metric.scaledToCurrentMetricUnits(backupVersion)) batchCount++ } totalMetricsSeen++ @@ -1880,7 +1880,7 @@ abstract class BaseDataBackupManager( json.decodeFromString(rawJson) } if (metric != null) { - restoreMetric(metric) + restoreMetric(metric.scaledToCurrentMetricUnits(backupVersion)) batchCount++ } totalMetricsSeen++ diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/MetricUnitVersions.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/MetricUnitVersions.kt new file mode 100644 index 000000000..0717e182c --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/MetricUnitVersions.kt @@ -0,0 +1,13 @@ +package com.devil.phoenixproject.util + +/** + * Issue #1400 F1 metric-unit contract versions for the per-row `metric_unit_version` + * marker and for versioned persisted in-flight state (completion journal, exit snapshot). + * + * - [METRIC_UNIT_VERSION_LEGACY]: values carry the pre-#1400 cm / cm-s scale while + * being labelled mm / mm-s. + * - [METRIC_UNIT_VERSION_MM]: values are true mm / mm-s (raw firmware units). + */ +const val METRIC_UNIT_VERSION_LEGACY: Int = 1 + +const val METRIC_UNIT_VERSION_MM: Int = 2 diff --git a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq index 92d1dd078..8b390f618 100644 --- a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq +++ b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq @@ -135,7 +135,9 @@ CREATE TABLE WorkoutSession ( maxTorsoRollDeg REAL, -- Legacy or imported sessions are unknown until a local workout explicitly records -- whether a one-shot routine modifier was applied. Fail closed for 1RM inputs. - routineModifierApplied INTEGER NOT NULL DEFAULT 1 CHECK(routineModifierApplied IN (0, 1)) + routineModifierApplied INTEGER NOT NULL DEFAULT 1 CHECK(routineModifierApplied IN (0, 1)), + -- Issue #1400 (migration 65): 1 = legacy cm/cm-s scale, 2 = mm/mm-s. Insert paths write 2. + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)) ); CREATE INDEX idx_workout_session_timestamp ON WorkoutSession(timestamp); @@ -173,6 +175,8 @@ CREATE TABLE MetricSample ( chestAccXMg INTEGER, chestAccYMg INTEGER, chestAccZMg INTEGER, + -- Issue #1400 (migration 65): 1 = legacy cm/cm-s scale, 2 = mm/mm-s. Insert paths write 2. + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ); @@ -403,6 +407,8 @@ CREATE TABLE PhaseStatistics ( eccentricWattAvg REAL NOT NULL, eccentricWattMax REAL NOT NULL, timestamp INTEGER NOT NULL, + -- Issue #1400 (migration 65): 1 = legacy cm/cm-s scale, 2 = mm/mm-s. Insert paths write 2. + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ); @@ -445,6 +451,8 @@ CREATE TABLE RepMetric ( avgPowerWatts REAL NOT NULL, updatedAt INTEGER, serverId TEXT, + -- Issue #1400 (migration 65): 1 = legacy cm/cm-s scale, 2 = mm/mm-s. Insert paths write 2. + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ); @@ -479,6 +487,8 @@ CREATE TABLE RepBiomechanics ( timestamp INTEGER NOT NULL, -- Issue #1400 (migration 64): 0 = kept out of set-level velocity aggregates aggregateEligible INTEGER NOT NULL DEFAULT 1 CHECK(aggregateEligible IN (0, 1)), + -- Issue #1400 (migration 65): 1 = legacy cm/cm-s scale, 2 = mm/mm-s. Insert paths write 2. + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE ); @@ -1088,9 +1098,10 @@ INSERT INTO WorkoutSession ( avgMcvMmS, avgAsymmetryPercent, totalVelocityLossPercent, dominantSide, strengthProfile, formScore, profile_id, - display_multiplier, externalAddedLoadKg, counterweightKg, rackItemsJson + display_multiplier, externalAddedLoadKg, counterweightKg, rackItemsJson, + metric_unit_version ) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); updateSessionRoutineModifierApplied: UPDATE WorkoutSession SET routineModifierApplied = :routineModifierApplied WHERE id = :id; @@ -1113,8 +1124,8 @@ INSERT OR IGNORE INTO WorkoutSession ( updatedAt, profile_id, display_multiplier, externalAddedLoadKg, counterweightKg, rackItemsJson -) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); -- First materialization of a portal exercise-row projection. Existing rows -- are never replaced: the repository uses updatePortalSessionProjection for @@ -1136,8 +1147,8 @@ INSERT OR IGNORE INTO WorkoutSession ( profile_id, display_multiplier, externalAddedLoadKg, counterweightKg, rackItemsJson, portalOrigin, local_sync_generation, synced_sync_generation -) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0); +, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0, 2); updatePortalSessionProjection: UPDATE WorkoutSession SET @@ -1230,27 +1241,27 @@ selectMetricById: SELECT * FROM MetricSample WHERE id = :id; insertMetric: -INSERT INTO MetricSample (sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power, status) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +INSERT INTO MetricSample (sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power, status, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); insertMetricWithPolar: INSERT INTO MetricSample ( sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power, status, heartRateBpm, rrIntervalMs, torsoPitchDeg, torsoRollDeg, dynamicAccMg, chestAccXMg, chestAccYMg, chestAccZMg -) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); insertMetricRestoreIfAbsent: INSERT OR IGNORE INTO MetricSample( id, sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power, status, heartRateBpm, rrIntervalMs, torsoPitchDeg, torsoRollDeg, dynamicAccMg, chestAccXMg, chestAccYMg, chestAccZMg -) +, metric_unit_version) VALUES ( :id, :sessionId, :timestamp, :position, :positionB, :velocity, :velocityB, :load, :loadB, :power, :status, :heartRateBpm, :rrIntervalMs, :torsoPitchDeg, :torsoRollDeg, :dynamicAccMg, :chestAccXMg, :chestAccYMg, :chestAccZMg -); +, 2); deleteMetricsBySession: DELETE FROM MetricSample WHERE sessionId = ?; @@ -1678,8 +1689,8 @@ WHERE id = ?; -- ==================== PHASE STATISTICS QUERIES ==================== insertPhaseStatistics: -INSERT INTO PhaseStatistics (sessionId, concentricKgAvg, concentricKgMax, concentricVelAvg, concentricVelMax, concentricWattAvg, concentricWattMax, eccentricKgAvg, eccentricKgMax, eccentricVelAvg, eccentricVelMax, eccentricWattAvg, eccentricWattMax, timestamp) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +INSERT INTO PhaseStatistics (sessionId, concentricKgAvg, concentricKgMax, concentricVelAvg, concentricVelMax, concentricWattAvg, concentricWattMax, eccentricKgAvg, eccentricKgMax, eccentricVelAvg, eccentricVelMax, eccentricWattAvg, eccentricWattMax, timestamp, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); selectPhaseStatsBySessionIds: SELECT * FROM PhaseStatistics WHERE sessionId IN ?; @@ -1700,8 +1711,8 @@ INSERT INTO RepMetric ( avgForceEccentricA, avgForceEccentricB, peakVelocity, avgVelocityConcentric, avgVelocityEccentric, rangeOfMotionMm, peakPowerWatts, avgPowerWatts, updatedAt, serverId -) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); selectRepMetricsBySession: SELECT * FROM RepMetric WHERE sessionId = ? ORDER BY repNumber ASC; @@ -1733,7 +1744,7 @@ INSERT OR REPLACE INTO RepBiomechanics ( velocityLossPercent, estimatedRepsRemaining, shouldStopSet, normalizedForceN, normalizedPositionPct, stickingPointPct, strengthProfile, asymmetryPercent, dominantSide, avgLoadA, avgLoadB, timestamp, aggregateEligible -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); +, metric_unit_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2); deleteRepBiomechanicsBySession: DELETE FROM RepBiomechanics WHERE sessionId = ?; @@ -4201,8 +4212,8 @@ INSERT OR IGNORE INTO WorkoutSession ( profile_id, display_multiplier, externalAddedLoadKg, counterweightKg, rackItemsJson, portalOrigin, local_sync_generation, synced_sync_generation -) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0); +, metric_unit_version) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0, 2); updateLegacyPortalSessionProjection: UPDATE WorkoutSession SET diff --git a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/65.sqm b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/65.sqm new file mode 100644 index 000000000..cc38a691e --- /dev/null +++ b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/65.sqm @@ -0,0 +1,59 @@ +-- Migration 65: Issue #1400 F1 metric unit correction (cm/cm-s -> mm/mm-s). +-- +-- The pre-#1400 pipeline divided raw firmware position/velocity by 10 at ingestion, +-- so every persisted position/velocity/power value is 1/10 of its labelled mm unit. +-- This migration scales the persisted metric fields x10 exactly once. +-- +-- Replay safety (arch constraint 3): applyMigrationResilient and the iOS/tvOS fallback +-- replay a step's statements one at a time after a partial failure, so every scaling +-- statement is row-guarded by the durable per-row marker `metric_unit_version` +-- (1 = legacy cm/cm-s scale, 2 = mm/mm-s). A re-run matches zero rows and is a no-op, +-- while rows scaled by a partially applied run are never scaled twice. +-- Loads, percentages, asymmetry and counts are intentionally NOT touched. +-- There are no data UPDATEs in schema healing; this migration is the only scaler. +-- +-- PhaseStatistics is created here IF NOT EXISTS (the category-B idempotent pattern) so +-- the step is self-contained: real upgrades find the populated legacy table and scale it, +-- while synthetic/schema-skew databases get the full current shape without a failed ALTER. +-- +-- Mirrors 65.sqm exactly in MigrationStatements.getMigrationStatements(65). + +CREATE TABLE IF NOT EXISTS PhaseStatistics ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sessionId TEXT NOT NULL, + concentricKgAvg REAL NOT NULL, + concentricKgMax REAL NOT NULL, + concentricVelAvg REAL NOT NULL, + concentricVelMax REAL NOT NULL, + concentricWattAvg REAL NOT NULL, + concentricWattMax REAL NOT NULL, + eccentricKgAvg REAL NOT NULL, + eccentricKgMax REAL NOT NULL, + eccentricVelAvg REAL NOT NULL, + eccentricVelMax REAL NOT NULL, + eccentricWattAvg REAL NOT NULL, + eccentricWattMax REAL NOT NULL, + timestamp INTEGER NOT NULL, + metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)), + FOREIGN KEY (sessionId) REFERENCES WorkoutSession(id) ON DELETE CASCADE +); + +ALTER TABLE MetricSample ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)); +ALTER TABLE RepMetric ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)); +ALTER TABLE RepBiomechanics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)); +ALTER TABLE WorkoutSession ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)); +ALTER TABLE PhaseStatistics ADD COLUMN metric_unit_version INTEGER NOT NULL DEFAULT 1 CHECK(metric_unit_version IN (1, 2)); + +UPDATE MetricSample SET position = position * 10, positionB = positionB * 10, velocity = velocity * 10, velocityB = velocityB * 10, power = power * 10, metric_unit_version = 2 WHERE metric_unit_version = 1; +UPDATE RepMetric SET peakVelocity = peakVelocity * 10, avgVelocityConcentric = avgVelocityConcentric * 10, avgVelocityEccentric = avgVelocityEccentric * 10, rangeOfMotionMm = rangeOfMotionMm * 10, peakPowerWatts = peakPowerWatts * 10, avgPowerWatts = avgPowerWatts * 10, metric_unit_version = 2 WHERE metric_unit_version = 1; +UPDATE RepBiomechanics SET mcvMmS = mcvMmS * 10, peakVelocityMmS = peakVelocityMmS * 10, metric_unit_version = 2 WHERE metric_unit_version = 1; +UPDATE WorkoutSession SET avgMcvMmS = avgMcvMmS * 10, metric_unit_version = 2 WHERE metric_unit_version = 1; +UPDATE PhaseStatistics SET concentricVelAvg = concentricVelAvg * 10, concentricVelMax = concentricVelMax * 10, concentricWattAvg = concentricWattAvg * 10, concentricWattMax = concentricWattMax * 10, eccentricVelAvg = eccentricVelAvg * 10, eccentricVelMax = eccentricVelMax * 10, eccentricWattAvg = eccentricWattAvg * 10, eccentricWattMax = eccentricWattMax * 10, metric_unit_version = 2 WHERE metric_unit_version = 1; + +-- Derived estimates computed on the old scale are invalidated, not rescaled (arch +-- constraint 5): learned personal MVT samples and stored velocity-1RM estimates were +-- derived from 1/10-scale velocities. They rebuild from new-scale sets automatically +-- (per-set onPostSaveComputed hook). RPG attributes and POWER_CEILING are physical +-- watts and are unchanged. DELETE is idempotent under replay. +DELETE FROM ExerciseMvt; +DELETE FROM VelocityOneRepMaxEstimate; diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400ControlEquivalenceReplayTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400ControlEquivalenceReplayTest.kt new file mode 100644 index 000000000..bdaa40247 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400ControlEquivalenceReplayTest.kt @@ -0,0 +1,415 @@ +package com.devil.phoenixproject + +import com.devil.phoenixproject.data.ble.MonitorDataProcessor +import com.devil.phoenixproject.data.ble.parseMonitorPacket +import com.devil.phoenixproject.data.ble.parseRepPacket +import com.devil.phoenixproject.data.repository.HandleState +import com.devil.phoenixproject.domain.replay.RepBoundaryDetector +import com.devil.phoenixproject.domain.usecase.RepCounterFromMachine +import kotlin.math.abs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Issue #1400 F1 AC2: control-equivalence replay. The same synthetic raw monitor / + * rep stream is replayed through the old pipeline (legacy /10 ingestion with the + * pre-#1400 cm-scale constants, mirrored below) and the new pipeline (raw mm / mm-s + * ingestion with the x10 constants). Handle-state transitions, grab/auto-start + * timing, filtered-sample indices, rep valleys, rep counts, ROM seeding and Just + * Lift danger-zone decisions must be identical. + * + * Stream values are multiples of 10 raw units so raw/10 is exact in Float and the + * two pipelines differ only by an exact factor of 10 — discrete outcomes are then + * compared exactly, continuous seeded values by the exact x10 relation. + */ +class Issue1400ControlEquivalenceReplayTest { + + private class Clock { + var now: Long = 1_000_000L + fun advance(ms: Long) { + now += ms + } + } + + // ==================== legacy pipeline mirror (pre-#1400 semantics) ==================== + + /** Pre-#1400 MonitorDataProcessor semantics: pos = raw/10 (cm), vel = raw/10 (cm/s). */ + private class LegacyMonitorProcessor(private val clock: Clock) { + private var lastGoodPosA = 0.0f + private var lastGoodPosB = 0.0f + private var lastPositionA = 0.0f + private var lastPositionB = 0.0f + private var lastTimestamp = 0L + private var smoothedA = 0.0 + private var smoothedB = 0.0 + private var firstVelocity = true + private var lastFiltered = false + + fun process(posARaw: Int, velARaw: Int): FloatArray? { + var posA = posARaw / 10.0f + if (posA !in -1000f..1000f) posA = lastGoodPosA else lastGoodPosA = posA + val previousPosA = lastPositionA + lastPositionA = posA + val t = clock.now + val jump = abs(posA - previousPosA) + if (lastTimestamp > 0L && jump > 20.0f) { + lastFiltered = true + return null + } + val rawVelocityA = velARaw / 10.0 + if (lastFiltered) { + lastFiltered = false + } else if (firstVelocity) { + smoothedA = rawVelocityA + firstVelocity = false + } else { + smoothedA = 0.3 * rawVelocityA + 0.7 * smoothedA + } + lastTimestamp = t + return floatArrayOf(posA, smoothedA.toFloat()) + } + } + + /** Pre-#1400 HandleStateDetector.analyzeHandleState semantics with the old constants. */ + private class LegacyHandleStateDetector(private val clock: Clock) { + private var state = HandleState.WaitingForRest + private var pendingGrabbedStart: Long? = null + private var pendingReleasedStart: Long? = null + private var activeHandlesMask = 0 + private var waitingForRestStart: Long? = null + private var restBaselinePosA: Double? = null + + fun state(): HandleState = state + + fun process(posA: Float, velocityA: Double) { + val pos = posA.toDouble() + val grabbed = if (restBaselinePosA != null) { + (pos - restBaselinePosA!!) > 10.0 + } else { + pos > 8.0 + } + // Auto-start mode uses the lower velocity threshold (old scale: 20 cm/s). + val moving = abs(velocityA) > 20.0 + val nextState = when (state) { + HandleState.WaitingForRest -> { + if (pos < 5.0) { + waitingForRestStart = null + restBaselinePosA = pos + HandleState.Released + } else { + val start = waitingForRestStart + if (start == null) { + waitingForRestStart = clock.now + HandleState.WaitingForRest + } else if (clock.now - start > 3000L) { + restBaselinePosA = if (pos > 8.0) 0.0 else pos + waitingForRestStart = null + HandleState.Released + } else { + HandleState.WaitingForRest + } + } + } + HandleState.Released, HandleState.Moving -> { + val active = grabbed && moving + when { + active -> { + val start = pendingGrabbedStart + if (start == null) { + pendingGrabbedStart = clock.now + state + } else if (clock.now - start >= 200L) { + activeHandlesMask = 1 + pendingGrabbedStart = null + HandleState.Grabbed + } else { + state + } + } + grabbed -> { + pendingGrabbedStart = null + HandleState.Moving + } + else -> { + pendingGrabbedStart = null + HandleState.Released + } + } + } + HandleState.Grabbed -> { + val released = if (restBaselinePosA != null) { + (pos - restBaselinePosA!!) < 5.0 + } else { + pos < 5.0 + } + val isReleased = when (activeHandlesMask) { + 1 -> released + else -> released + } + if (isReleased) { + val start = pendingReleasedStart + if (start == null) { + pendingReleasedStart = clock.now + HandleState.Grabbed + } else if (clock.now - start >= 200L) { + pendingReleasedStart = null + activeHandlesMask = 0 + HandleState.Released + } else { + HandleState.Grabbed + } + } else { + pendingReleasedStart = null + HandleState.Grabbed + } + } + } + state = nextState + } + } + + /** Pre-#1400 RepBoundaryDetector semantics (valley prominence 10f on cm-scale positions). */ + private object LegacyRepBoundaryDetector { + private const val VALLEY_THRESHOLD = 10f + + fun valleyIndices(positions: FloatArray): List { + val smoothed = FloatArray(positions.size) { i -> + val start = maxOf(0, i - 2) + val end = minOf(positions.size - 1, i + 2) + var sum = 0f + for (j in start..end) sum += positions[j] + sum / (end - start + 1) + } + val valleys = mutableListOf() + for (i in 2 until smoothed.size - 2) { + val current = smoothed[i] + var isMinimum = true + var maxInWindow = current + for (j in -2..2) { + val value = smoothed[i + j] + if (value < current) { + isMinimum = false + break + } + if (value > maxInWindow) maxInWindow = value + } + if (isMinimum && maxInWindow - current >= VALLEY_THRESHOLD) { + if (valleys.isEmpty() || i - valleys.last() >= 8) valleys.add(i) + } + } + if (smoothed.size > 10) { + val firstFew = smoothed.take(5).minOrNull() ?: smoothed[0] + val restAvg = smoothed.drop(5).take(10).average().toFloat() + if (firstFew < restAvg - VALLEY_THRESHOLD) { + val minIndex = (0 until minOf(5, smoothed.size)).minByOrNull { smoothed[it] } ?: 0 + if (valleys.isEmpty() || valleys.first() - minIndex >= 8) valleys.add(0, minIndex) + } + } + if (smoothed.size > 10) { + val lastFewMin = smoothed.takeLast(5).minOrNull() ?: smoothed.last() + val beforeLastAvg = smoothed.dropLast(5).takeLast(10).average().toFloat() + if (lastFewMin < beforeLastAvg - VALLEY_THRESHOLD) { + val baseIndex = smoothed.size - 5 + val minOffset = (0 until 5).minByOrNull { smoothed[baseIndex + it] } ?: 4 + val minIndex = baseIndex + minOffset + if (valleys.isEmpty() || minIndex - valleys.last() >= 8) valleys.add(minIndex) + } + } + return valleys.sorted() + } + } + + // ==================== tests ==================== + + @Test + fun `handle states grab timing and filtered samples are identical across pipelines`() { + val oldClock = Clock() + val newClock = Clock() + val legacy = LegacyMonitorProcessor(oldClock) + val legacyDetector = LegacyHandleStateDetector(oldClock) + val processor = MonitorDataProcessor(timeProvider = { newClock.now }) + val detector = com.devil.phoenixproject.data.ble.HandleStateDetector(timeProvider = { newClock.now }) + detector.enable(autoStart = true) + + val oldStates = mutableListOf>() + val newStates = mutableListOf>() + val oldFiltered = mutableListOf() + val newFiltered = mutableListOf() + + stream().forEachIndexed { index, sample -> + val (posARaw, velARaw, deltaMs) = sample + oldClock.advance(deltaMs) + newClock.advance(deltaMs) + + val oldMetric = legacy.process(posARaw, velARaw) + if (oldMetric == null) { + oldFiltered.add(index) + } else { + legacyDetector.process(oldMetric[0], oldMetric[1].toDouble()) + } + oldStates.add(index to legacyDetector.state()) + + val parsed = parseMonitorPacket(packetBytes(posARaw, velARaw))!! + val newMetric = processor.process(parsed) + if (newMetric == null) { + newFiltered.add(index) + } else { + detector.processMetric(newMetric) + } + newStates.add(index to detector.handleState.value) + } + + assertEquals(oldFiltered, newFiltered, "jump/range filtered sample indices must be identical") + assertEquals(oldStates, newStates, "handle-state transitions per sample must be identical") + assertTrue(oldStates.any { it.second == HandleState.Grabbed }, "the stream must exercise the grab path") + assertTrue(oldStates.any { it.second == HandleState.Released }, "the stream must exercise the release path") + } + + @Test + fun `rep valleys and rep counts are identical across pipelines`() { + // Two slow reps worth of raw position samples (raw units, multiples of 10). + val wave = (0..60).map { i -> + val phase = i / 30.0 + val raw = ((kotlin.math.sin(phase * 2 * kotlin.math.PI) * 300.0).toInt() / 10) * 10 + raw + } + val oldPositions = FloatArray(wave.size) { wave[it] / 10.0f } + val newPositions = FloatArray(wave.size) { wave[it].toFloat() } + + val oldValleys = LegacyRepBoundaryDetector.valleyIndices(oldPositions) + val newStarts = RepBoundaryDetector().detectBoundaries(newPositions).map { it.startIndex } + // Boundaries pair up consecutive valleys, so the last valley has no boundary of its own. + assertEquals(oldValleys.dropLast(1), newStarts, "valley indices must be identical") + assertEquals(oldValleys.size, newStarts.size + 1, "valley counts must be identical") + + // Rep counts come from the machine counters (scale-free); both parse paths must + // deliver identical count progressions on the same notification stream. + val oldCounter = RepCounterFromMachine() + val newCounter = RepCounterFromMachine() + oldCounter.configure(warmupTarget = 0, workingTarget = 0, isJustLift = false, stopAtTop = false) + newCounter.configure(warmupTarget = 0, workingTarget = 0, isJustLift = false, stopAtTop = false) + val oldEvents = mutableListOf() + val newEvents = mutableListOf() + oldCounter.onRepEvent = { oldEvents.add(it.workingCount) } + newCounter.onRepEvent = { newEvents.add(it.workingCount) } + for (up in 1..5) { + val wireTop = 65.0f + val newNotification = parseRepPacket(repPacketBytes(up, up, floatBits(wireTop), floatBits(5.0f)), false, up.toLong())!! + // Old pipeline used the unscaled wire floats; new pipeline scales x10 at parse. + oldCounter.process( + repsRomCount = 0, repsSetCount = up, up = up, down = up, + posA = wireTop, posB = 0f, + ) + newCounter.process( + repsRomCount = 0, repsSetCount = up, up = up, down = up, + posA = newNotification.rangeTop, posB = 0f, + ) + assertEquals(wireTop * 10f, newNotification.rangeTop, "parsed ROM bounds scale x10") + } + assertEquals(oldEvents, newEvents, "rep count progressions must be identical") + assertTrue(newEvents.isNotEmpty(), "the stream must produce working reps") + } + + @Test + fun `ROM seeding and Just Lift danger zone are identical across pipelines`() { + // Rep-packet ROM seeding: wire 65.0/5.0 seeds 65.0/5.0 cm on the old pipeline and + // 650/50 mm on the new one; the seeds differ by exactly x10 and the 300f rope + // sentinel is rejected by both (300f old, 3000f new). + val oldCounter = RepCounterFromMachine() + val newCounter = RepCounterFromMachine() + val wireTop = 65.0f + val wireBottom = 5.0f + val newNotification = parseRepPacket(repPacketBytes(1, 1, floatBits(wireTop), floatBits(wireBottom)), false, 1L)!! + // Old pipeline: wire floats used unscaled against cm positions. New pipeline: + // x10 at parse so seeds match the mm position scale. + assertEquals(wireTop * 10f, newNotification.rangeTop, "parsed ROM bounds scale x10") + oldCounter.seedRomBoundaries(wireTop, wireBottom) + newCounter.seedRomBoundaries(newNotification.rangeTop, newNotification.rangeBottom) + val oldRanges = oldCounter.getRepRanges() + val newRanges = newCounter.getRepRanges() + assertEquals(oldRanges.maxPosA!! * 10f, newRanges.maxPosA!!, "ROM seed must scale x10") + assertEquals(oldRanges.minPosA!! * 10f, newRanges.minPosA!!, "ROM seed must scale x10") + + // The 3 m rope sentinel is rejected on both pipelines: the legacy rule compares + // the unscaled wire floats (300f/0f), the new counter compares the parsed mm + // values (3000f/0f). The sentinel check is parse-scaled consistently. + val sentinelWireTop = 300.0f + val sentinelWireBottom = 0.0f + val legacySentinelRejects = sentinelWireTop == 300.0f && sentinelWireBottom == 0.0f + assertTrue(legacySentinelRejects, "legacy sentinel rule rejects the 300f/0f wire pair") + val sentinel = parseRepPacket(repPacketBytes(1, 1, floatBits(sentinelWireTop), floatBits(sentinelWireBottom)), false, 1L)!! + assertEquals(3000.0f, sentinel.rangeTop, "the rope sentinel must parse to the mm sentinel") + val newSentinel = RepCounterFromMachine() + newSentinel.seedRomBoundaries(sentinel.rangeTop, sentinel.rangeBottom) + assertEquals(null, newSentinel.getRepRanges().maxPosA, "new sentinel must not seed") + + // Just Lift: continuous range tracking and the danger-zone predicate must decide + // identically on the same physical stream (cm thresholds vs x10 mm thresholds). + for (posRaw in listOf(0, 200, 600, 400, 100, 60)) { + oldCounter.updatePositionRangesContinuously(posRaw / 10f, posRaw / 10f) + newCounter.updatePositionRangesContinuously(posRaw.toFloat(), posRaw.toFloat()) + } + for (posRaw in listOf(60, 100, 300, 550, 60, 10)) { + val oldDanger = oldCounter.getRepRanges().isInDangerZone(posRaw / 10f, posRaw / 10f, 50f) + val newDanger = newCounter.getRepRanges().isInDangerZone(posRaw.toFloat(), posRaw.toFloat(), 500f) + assertEquals(oldDanger, newDanger, "Just Lift danger-zone decision must be identical at raw=$posRaw") + } + } + + // ==================== stream + helpers ==================== + + /** (posARaw, velARaw, deltaMsSincePrevious) — rest, grab ramp, sustained dwell, jump, release ramp. */ + private fun stream(): List> = listOf( + Triple(0, 0, 20), + Triple(0, 0, 20), + Triple(10, 0, 20), + Triple(200, 300, 20), // extended but slow -> Moving (EMA lags below the grab threshold) + Triple(240, 800, 20), // high velocity -> grab pending + Triple(280, 700, 220), // dwell elapsed -> GRAB CONFIRMED + Triple(300, 600, 220), // still grabbed + Triple(310, 500, 20), + Triple(560, 500, 20), // +250 raw jump -> filtered + Triple(560, 400, 20), // re-accepted + Triple(550, 300, 20), + Triple(350, 100, 20), // release ramp (each step exactly 200 raw = the jump threshold) + Triple(150, 0, 20), + Triple(30, 0, 20), // released (baseline-relative delta < release threshold) + Triple(30, 0, 220), // dwell elapsed -> RELEASE CONFIRMED + Triple(5, 0, 20), + ) + + private fun packetBytes(posARaw: Int, velARaw: Int): ByteArray { + val data = ByteArray(26) + putUInt16LE(data, 4, posARaw and 0xFFFF) + putUInt16LE(data, 6, velARaw and 0xFFFF) + putUInt16LE(data, 8, 2000) + putUInt16LE(data, 10, 0) + putUInt16LE(data, 12, 0) + putUInt16LE(data, 14, 0) + return data + } + + private fun repPacketBytes(up: Int, down: Int, rangeTopBits: Int, rangeBottomBits: Int): ByteArray { + val data = ByteArray(24) + putUInt32LE(data, 0, up) + putUInt32LE(data, 4, down) + putUInt32LE(data, 8, rangeTopBits) + putUInt32LE(data, 12, rangeBottomBits) + return data + } + + private fun floatBits(value: Float): Int = value.toRawBits() + + private fun putUInt16LE(data: ByteArray, offset: Int, value: Int) { + data[offset] = (value and 0xFF).toByte() + data[offset + 1] = ((value shr 8) and 0xFF).toByte() + } + + private fun putUInt32LE(data: ByteArray, offset: Int, value: Int) { + data[offset] = (value and 0xFF).toByte() + data[offset + 1] = ((value shr 8) and 0xFF).toByte() + data[offset + 2] = ((value shr 16) and 0xFF).toByte() + data[offset + 3] = ((value shr 24) and 0xFF).toByte() + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400MetricUnitContractTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400MetricUnitContractTest.kt new file mode 100644 index 000000000..bee3ffa87 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/Issue1400MetricUnitContractTest.kt @@ -0,0 +1,194 @@ +package com.devil.phoenixproject + +import com.devil.phoenixproject.data.ble.MonitorDataProcessor +import com.devil.phoenixproject.data.ble.MonitorPacket +import com.devil.phoenixproject.data.ble.parseMonitorPacket +import com.devil.phoenixproject.data.ble.parseRepPacket +import com.devil.phoenixproject.domain.assessment.AssessmentEngine +import com.devil.phoenixproject.domain.model.BiomechanicsVelocityZone +import com.devil.phoenixproject.domain.onerepmax.VelocityOneRepMaxEstimator +import com.devil.phoenixproject.domain.onerepmax.WorkoutVelocityPoint +import com.devil.phoenixproject.domain.usecase.RepCounterFromMachine +import com.devil.phoenixproject.util.CURRENT_BACKUP_VERSION +import com.devil.phoenixproject.util.FIRST_MM_SCALE_BACKUP_VERSION +import com.devil.phoenixproject.util.MetricSampleBackup +import com.devil.phoenixproject.util.WorkoutSessionBackup +import com.devil.phoenixproject.util.legacyMetricUnitScaleFor +import com.devil.phoenixproject.util.scaledToCurrentMetricUnits +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Issue #1400 F1 acceptance criteria for the metric-unit contract: raw firmware + * position is mm and raw firmware velocity is mm/s (RCA section 5a). The legacy + * /10 ingestion scaling is gone, so raw values pass through at face value and the + * mm-labelled consumers are correct by construction. + */ +class Issue1400MetricUnitContractTest { + + // ========== AC1: parser and processor units ========== + + @Test + fun `parser raw position 300 becomes 300f mm`() { + val packet = monitorPacketBytes(posARaw = 300, posBRaw = -150) + val parsed = assertNotNull(parseMonitorPacket(packet)) + assertEquals(300f, parsed.posA) + assertEquals(-150f, parsed.posB) + } + + @Test + fun `processor raw velocity 700 seeds 700 mm per s`() { + val processor = MonitorDataProcessor() + val metric = assertNotNull( + processor.process(MonitorPacket(ticks = 1, posA = 300f, posB = 0f, loadA = 20f, loadB = 0f, status = 0, firmwareVelA = 700, firmwareVelB = -250)), + ) + assertEquals(700.0, metric.velocityA, 0.001) + assertEquals(-250.0, metric.velocityB, 0.001) + } + + @Test + fun `rep packet ROM bounds scale to mm at parse and the rope sentinel is 3000f`() { + val wire = repPacketBytes(rangeTopBits = floatBits(300.0f), rangeBottomBits = floatBits(0.0f)) + val parsed = assertNotNull(parseRepPacket(wire, hasOpcodePrefix = false, timestamp = 1L)) + // 300.0f wire = the published 3 m rope sentinel; x10 at parse = 3000 mm. + assertEquals(3000.0f, parsed.rangeTop) + assertEquals(0.0f, parsed.rangeBottom) + + val counter = RepCounterFromMachine() + counter.seedRomBoundaries(parsed.rangeTop, parsed.rangeBottom) + val ranges = counter.getRepRanges() + assertEquals(null, ranges.maxPosA, "the unset sentinel must not seed ROM boundaries") + + val real = assertNotNull(parseRepPacket(repPacketBytes(floatBits(65.0f), floatBits(5.0f)), false, 1L)) + assertEquals(650.0f, real.rangeTop) + assertEquals(50.0f, real.rangeBottom) + val seeded = RepCounterFromMachine() + seeded.seedRomBoundaries(real.rangeTop, real.rangeBottom) + assertEquals(650.0f, seeded.getRepRanges().maxPosA) + assertEquals(50.0f, seeded.getRepRanges().minPosA) + } + + // ========== AC3: zones and velocity-1RM in true mm/s ========== + + @Test + fun `MCV 700 mm per s classifies MODERATE not GRIND`() { + assertEquals(BiomechanicsVelocityZone.MODERATE, BiomechanicsVelocityZone.fromMcv(700f)) + assertEquals(BiomechanicsVelocityZone.GRIND, BiomechanicsVelocityZone.fromMcv(200f)) + } + + @Test + fun `velocity 1RM estimator receives m per s points in the reporter range`() { + // Reporter-shaped magnitudes after the fix: light explosive bench ~700 mm/s, + // RDL ~400 mm/s, heavier bench ~300 mm/s -> 0.3-1.3 m/s fit points (RCA section 5a). + val points = listOf( + WorkoutVelocityPoint(loadPerCableKg = 10f, mcvMmS = 700f, timestampMs = 1, workingReps = 5), + WorkoutVelocityPoint(loadPerCableKg = 20f, mcvMmS = 520f, timestampMs = 2, workingReps = 5), + WorkoutVelocityPoint(loadPerCableKg = 30f, mcvMmS = 300f, timestampMs = 3, workingReps = 5), + ) + for (point in points) { + val mps = point.mcvMmS / 1000f + assertTrue(mps in 0.3f..1.3f, "reporter-shaped MCV ${point.mcvMmS} mm/s must fit 0.3-1.3 m/s, was $mps") + } + val result = VelocityOneRepMaxEstimator(AssessmentEngine()).estimate(points, mvtMs = 0.17f) + assertNotNull(result, "reporter-shaped points must produce a velocity-1RM estimate") + assertTrue(result.estimatedPerCableKg > 0f) + } + + // ========== AC4: backup v8 scales v7-and-older exactly once ========== + + @Test + fun `backup v7 import scales unit fields exactly once and v8 does not`() { + val legacy = MetricSampleBackup( + sessionId = "s", + timestamp = 1, + position = 35f, + positionB = 36f, + velocity = 70f, + velocityB = 71f, + load = 20.5f, + power = 1400f, + ) + val scaled = legacy.scaledToCurrentMetricUnits(backupVersion = 7) + assertEquals(350f, scaled.position) + assertEquals(360f, scaled.positionB) + assertEquals(700f, scaled.velocity) + assertEquals(710f, scaled.velocityB) + assertEquals(14000f, scaled.power) + assertEquals(20.5f, scaled.load, "loads must not scale") + + // Exactly-once is enforced by the envelope-version dispatch below plus the row + // marker on the DB side (restored rows are written at metric_unit_version = 2, so + // migration 65's WHERE metric_unit_version = 1 scaler can never touch them again); + // this function itself is pure in the envelope version, not idempotent on output. + + val modern = legacy.scaledToCurrentMetricUnits(backupVersion = FIRST_MM_SCALE_BACKUP_VERSION) + assertEquals(legacy, modern, "v8 imports must not scale") + assertEquals(1f, legacyMetricUnitScaleFor(8)) + assertEquals(10f, legacyMetricUnitScaleFor(7)) + assertEquals(10f, legacyMetricUnitScaleFor(1)) + assertEquals(8, CURRENT_BACKUP_VERSION) + } + + @Test + fun `backup v7 session import scales avg MCV only`() { + val session = WorkoutSessionBackup( + id = "s", + timestamp = 1, + mode = "OldSchool", + targetReps = 5, + weightPerCableKg = 20f, + progressionKg = 0f, + duration = 1, + totalReps = 5, + warmupReps = 0, + workingReps = 5, + isJustLift = false, + stopAtTop = false, + avgMcvMmS = 45f, + totalVelocityLossPercent = 25f, + heaviestLiftKg = 20f, + ) + val scaled = session.scaledToCurrentMetricUnits(backupVersion = 7) + assertEquals(450f, scaled.avgMcvMmS) + assertEquals(25f, scaled.totalVelocityLossPercent, "percentages must not scale") + assertEquals(20f, scaled.heaviestLiftKg, "loads must not scale") + } + + // ========== helpers ========== + + private fun monitorPacketBytes(posARaw: Int, posBRaw: Int): ByteArray { + val data = ByteArray(26) + putUInt16LE(data, 4, posARaw and 0xFFFF) + putUInt16LE(data, 6, 700 and 0xFFFF) + putUInt16LE(data, 8, 2000) // loadA 20.00 kg + putUInt16LE(data, 10, posBRaw and 0xFFFF) + putUInt16LE(data, 12, 0) + putUInt16LE(data, 14, 0) + return data + } + + private fun repPacketBytes(rangeTopBits: Int, rangeBottomBits: Int): ByteArray { + val data = ByteArray(24) + putUInt32LE(data, 0, 1) // up + putUInt32LE(data, 4, 1) // down + putUInt32LE(data, 8, rangeTopBits) + putUInt32LE(data, 12, rangeBottomBits) + return data + } + + private fun floatBits(value: Float): Int = value.toRawBits() + + private fun putUInt16LE(data: ByteArray, offset: Int, value: Int) { + data[offset] = (value and 0xFF).toByte() + data[offset + 1] = ((value shr 8) and 0xFF).toByte() + } + + private fun putUInt32LE(data: ByteArray, offset: Int, value: Int) { + data[offset] = (value and 0xFF).toByte() + data[offset + 1] = ((value shr 8) and 0xFF).toByte() + data[offset + 2] = ((value shr 16) and 0xFF).toByte() + data[offset + 3] = ((value shr 24) and 0xFF).toByte() + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/BlePacketCaptureTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/BlePacketCaptureTest.kt index 0bc0fa773..897d77770 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/BlePacketCaptureTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/BlePacketCaptureTest.kt @@ -11,7 +11,7 @@ class BlePacketCaptureTest { val data = ByteArray(26) putUInt16LE(data, 0, 0x1234) putUInt16LE(data, 2, 0x0001) - putInt16LE(data, 4, 1234) // posA 123.4 mm + putInt16LE(data, 4, 1234) // posA 1234 mm (raw int16 is mm, issue #1400) putInt16LE(data, 6, 7) // velA putUInt16LE(data, 8, 5000) // loadA 50.0 kg putInt16LE(data, 10, 2000) // posB 200.0 mm @@ -30,8 +30,8 @@ class BlePacketCaptureTest { val packet = parseMonitorPacket(data) assertTrue(packet != null) - assertEquals(123.4f, packet.posA, 0.01f) - assertEquals(200.0f, packet.posB, 0.01f) + assertEquals(1234f, packet.posA, 0.01f) + assertEquals(2000f, packet.posB, 0.01f) assertEquals(50.0f, packet.loadA, 0.01f) assertEquals(25.0f, packet.loadB, 0.01f) assertEquals( diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetectorTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetectorTest.kt index 967648c6e..76511efdb 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetectorTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/HandleStateDetectorTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertTrue class HandleStateDetectorTest { private var fakeTime = 0L - private fun createDetector(): HandleStateDetector = HandleStateDetector(timeProvider = { fakeTime }) /** @@ -45,8 +44,8 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) assertEquals(HandleState.WaitingForRest, detector.handleState.value) - // Both handles below rest threshold (5mm) - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + // Both handles below rest threshold (50mm) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -54,9 +53,8 @@ class HandleStateDetectorTest { fun `WaitingForRest stays when handles above rest threshold`() { val detector = createDetector() detector.enable(autoStart = true) - // Both handles above rest threshold - detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) + detector.processMetric(metric(posA = 100.0f, posB = 100.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) } @@ -67,17 +65,17 @@ class HandleStateDetectorTest { fakeTime = 0L // Handles above rest threshold - starts timeout - detector.processMetric(metric(posA = 6.0f, posB = 6.0f)) + detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) // 2999ms later - still waiting fakeTime = 2999L - detector.processMetric(metric(posA = 6.0f, posB = 6.0f)) + detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) // 3001ms - timeout fires, uses real baseline (not grabbed) fakeTime = 3001L - detector.processMetric(metric(posA = 6.0f, posB = 6.0f)) + detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -87,24 +85,24 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) fakeTime = 0L - // Handles above GRABBED threshold (8mm) - starts timeout - detector.processMetric(metric(posA = 20.0f, posB = 20.0f)) + // Handles above GRABBED threshold (80mm) - starts timeout + detector.processMetric(metric(posA = 200.0f, posB = 200.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) // Timeout fires fakeTime = 3001L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f)) assertEquals(HandleState.Released, detector.handleState.value) - // After virtual baseline (0.0), position 20mm is well above grab delta threshold (10mm) + // After virtual baseline (0.0), position 200mm is well above grab delta threshold (100mm) // So next metric with velocity should start the grab dwell fakeTime = 3100L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) // Should still be Released (dwell not started or just started) // After 200ms dwell fakeTime = 3300L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -113,24 +111,23 @@ class HandleStateDetectorTest { val detector = createDetector() detector.enable(autoStart = true) fakeTime = 0L - - // Handles above rest (5mm) but below grabbed threshold (8mm) -- elevated rest - detector.processMetric(metric(posA = 6.0f, posB = 6.0f)) + // Handles above rest (50mm) but below grabbed threshold (80mm) -- elevated rest + detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) - // Timeout fires - real baseline captured at 6.0 + // Timeout fires - real baseline captured at 60.0 fakeTime = 3001L - detector.processMetric(metric(posA = 6.0f, posB = 6.0f)) + detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) assertEquals(HandleState.Released, detector.handleState.value) - // Position at 17mm: delta from baseline 6.0 = 11mm > GRAB_DELTA_THRESHOLD (10mm) + // Position at 170mm: delta from baseline 60.0 = 110mm > GRAB_DELTA_THRESHOLD (100mm) // With velocity, should start grab dwell fakeTime = 3100L - detector.processMetric(metric(posA = 17.0f, posB = 17.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 170.0f, posB = 170.0f, velA = 1000.0, velB = 1000.0)) // After 200ms dwell fakeTime = 3300L - detector.processMetric(metric(posA = 17.0f, posB = 17.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 170.0f, posB = 170.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -140,22 +137,22 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // First grab signal - starts dwell timer fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Released, detector.handleState.value) // Still dwelling // 199ms later - not yet fakeTime = 1199L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Released, detector.handleState.value) // 200ms - dwell complete fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -165,12 +162,12 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Position extended but zero velocity -> Moving fakeTime = 100L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 0.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 0.0, velB = 0.0)) assertEquals(HandleState.Moving, detector.handleState.value) } @@ -180,12 +177,12 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Handles still at rest (below grab threshold) fakeTime = 100L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -195,19 +192,19 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Moving - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 100L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 0.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 0.0, velB = 0.0)) assertEquals(HandleState.Moving, detector.handleState.value) // Now add velocity - starts grab dwell fakeTime = 200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Moving, detector.handleState.value) // Still dwelling // 200ms later - grab confirmed fakeTime = 400L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -217,14 +214,14 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Moving - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 100L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 0.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 0.0, velB = 0.0)) assertEquals(HandleState.Moving, detector.handleState.value) // Handles return to rest fakeTime = 200L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -234,26 +231,26 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Grabbed - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Start release - handles back at rest fakeTime = 2000L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Still dwelling // 199ms - not yet fakeTime = 2199L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // 200ms - release confirmed fakeTime = 2200L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -263,16 +260,16 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Grabbed - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Handles still extended fakeTime = 2000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 50.0, velB = 50.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 500.0, velB = 500.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -286,32 +283,32 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Start grab dwell fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) // 150ms later - still dwelling fakeTime = 1150L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Released, detector.handleState.value) // Handles drop back to rest - resets dwell fakeTime = 1160L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // New grab attempt - should need full 200ms again fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) // Only 0ms into new dwell assertEquals(HandleState.Released, detector.handleState.value) // 200ms from the NEW dwell start (1200 + 200 = 1400) fakeTime = 1400L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -321,35 +318,35 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Grabbed - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Start release dwell fakeTime = 2000L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // 150ms - still dwelling fakeTime = 2150L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Handles move away from rest - resets release dwell fakeTime = 2160L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 50.0, velB = 50.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 500.0, velB = 500.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // New release attempt - needs full 200ms again fakeTime = 2200L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Just started new dwell fakeTime = 2400L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // 200ms from 2200 } @@ -359,21 +356,21 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) // Start grab at t=1000 fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Released, detector.handleState.value) // At exactly 199ms (< 200ms dwell) -- should NOT transition fakeTime = 1199L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Released, detector.handleState.value) // At exactly 200ms (>= 200ms dwell) -- SHOULD transition fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -387,15 +384,15 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) // Only handle A grabbed and moving fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 1.5f, velA = 100.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 15.0f, velA = 1000.0, velB = 0.0)) // 200ms dwell fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 1.5f, velA = 100.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 15.0f, velA = 1000.0, velB = 0.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -405,15 +402,15 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) // Only handle B grabbed and moving fakeTime = 1000L - detector.processMetric(metric(posA = 1.5f, posB = 20.0f, velA = 0.0, velB = 100.0)) + detector.processMetric(metric(posA = 15.0f, posB = 200.0f, velA = 0.0, velB = 1000.0)) // 200ms dwell fakeTime = 1200L - detector.processMetric(metric(posA = 1.5f, posB = 20.0f, velA = 0.0, velB = 100.0)) + detector.processMetric(metric(posA = 15.0f, posB = 200.0f, velA = 0.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -423,26 +420,26 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Grabbed (only handle A active) - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 1.5f, velA = 100.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 15.0f, velA = 1000.0, velB = 0.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 1.5f, velA = 100.0, velB = 0.0)) + detector.processMetric(metric(posA = 200.0f, posB = 15.0f, velA = 1000.0, velB = 0.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Handle B at rest (was never active) -- should NOT trigger release fakeTime = 2000L - detector.processMetric(metric(posA = 20.0f, posB = 0.0f)) + detector.processMetric(metric(posA = 200.0f, posB = 0.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Handle A returns to rest -- SHOULD start release dwell fakeTime = 2100L - detector.processMetric(metric(posA = 2.0f, posB = 0.0f)) + detector.processMetric(metric(posA = 20.0f, posB = 0.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Dwelling // 200ms later -- release confirmed fakeTime = 2300L - detector.processMetric(metric(posA = 2.0f, posB = 0.0f)) + detector.processMetric(metric(posA = 20.0f, posB = 0.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -452,26 +449,26 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Go to Released -> Grabbed (both handles active) - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Only A released, B still extended -- should NOT release fakeTime = 2000L - detector.processMetric(metric(posA = 2.0f, posB = 20.0f)) + detector.processMetric(metric(posA = 20.0f, posB = 200.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Both released fakeTime = 2100L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Dwelling // 200ms later fakeTime = 2300L - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -485,26 +482,26 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Handles at rest with non-zero position -> captures baseline - detector.processMetric(metric(posA = 3.0f, posB = 4.0f)) + detector.processMetric(metric(posA = 30.0f, posB = 40.0f)) assertEquals(HandleState.Released, detector.handleState.value) - // Now position must be 3.0 + GRAB_DELTA_THRESHOLD (10mm) = 13mm to trigger grab - // Position at 12mm -> delta = 9mm < 10mm -> NOT grabbed + // Now position must be 30.0 + GRAB_DELTA_THRESHOLD (100mm) = 130mm to trigger grab + // Position at 120mm -> delta = 90mm < 100mm -> NOT grabbed fakeTime = 100L - detector.processMetric(metric(posA = 12.0f, posB = 12.0f, velA = 100.0, velB = 100.0)) - // Not grabbed because delta from baseline is only 9mm (12-3) and 8mm (12-4) + detector.processMetric(metric(posA = 120.0f, posB = 120.0f, velA = 1000.0, velB = 1000.0)) + // Not grabbed because delta from baseline is only 90mm (120-30) and 80mm (120-40) // Should be Moving (position extended but doesn't meet grab delta + velocity) - // Actually let's check: handleAGrabbed = (12 - 3) = 9 < 10 = false for A + // Actually let's check: handleAGrabbed = (120 - 30) = 90 < 100 = false for A // So neither handle is grabbed, which means back to rest: Released assertEquals(HandleState.Released, detector.handleState.value) - // Position at 14mm -> delta from baseline 3 = 11mm > 10mm -> grabbed + // Position at 140mm -> delta from baseline 30 = 110mm > 100mm -> grabbed fakeTime = 200L - detector.processMetric(metric(posA = 14.0f, posB = 15.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 140.0f, posB = 150.0f, velA = 1000.0, velB = 1000.0)) // 200ms dwell fakeTime = 400L - detector.processMetric(metric(posA = 14.0f, posB = 15.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 140.0f, posB = 150.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -513,14 +510,14 @@ class HandleStateDetectorTest { val detector = createDetector() detector.enable(autoStart = true) - // Baseline captured at 3.0, 4.0 - detector.processMetric(metric(posA = 3.0f, posB = 4.0f)) + // Baseline captured at 30.0, 40.0 + detector.processMetric(metric(posA = 30.0f, posB = 40.0f)) assertEquals(HandleState.Released, detector.handleState.value) - // Absolute position 9mm > HANDLE_GRABBED_THRESHOLD (8mm) -- but baseline-relative: - // delta = 9 - 3 = 6mm which is < GRAB_DELTA_THRESHOLD (10mm) -- NOT grabbed + // Absolute position 90mm > HANDLE_GRABBED_THRESHOLD (80mm) -- but baseline-relative: + // delta = 90 - 30 = 60mm which is < GRAB_DELTA_THRESHOLD (100mm) -- NOT grabbed fakeTime = 100L - detector.processMetric(metric(posA = 9.0f, posB = 9.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 90.0f, posB = 90.0f, velA = 1000.0, velB = 1000.0)) // Since neither is grab-detected via delta, this is "back to rest" => Released assertEquals(HandleState.Released, detector.handleState.value) } @@ -530,35 +527,34 @@ class HandleStateDetectorTest { val detector = createDetector() detector.enable(autoStart = true) - // Rest baseline at 3.0 - detector.processMetric(metric(posA = 3.0f, posB = 3.0f)) + // Rest baseline at 30.0 + detector.processMetric(metric(posA = 30.0f, posB = 30.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Grab with large delta fakeTime = 1000L - detector.processMetric(metric(posA = 30.0f, posB = 30.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 300.0f, posB = 300.0f, velA = 1000.0, velB = 1000.0)) fakeTime = 1200L - detector.processMetric(metric(posA = 30.0f, posB = 30.0f, velA = 100.0, velB = 100.0)) + detector.processMetric(metric(posA = 300.0f, posB = 300.0f, velA = 1000.0, velB = 1000.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) - // Release: position returns to within RELEASE_DELTA_THRESHOLD (5mm) of baseline (3.0) - // Position 7.0: delta = 7 - 3 = 4mm < 5mm -> released + // Release: position returns to within RELEASE_DELTA_THRESHOLD (50mm) of baseline (30.0) + // Position 70.0: delta = 70 - 30 = 40mm < 50mm -> released fakeTime = 2000L - detector.processMetric(metric(posA = 7.0f, posB = 7.0f)) + detector.processMetric(metric(posA = 70.0f, posB = 70.0f)) assertEquals(HandleState.Grabbed, detector.handleState.value) // Dwelling fakeTime = 2200L - detector.processMetric(metric(posA = 7.0f, posB = 7.0f)) + detector.processMetric(metric(posA = 70.0f, posB = 70.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @Test fun `baseline reset on enable`() { val detector = createDetector() - // First session - set baseline detector.enable(autoStart = true) - detector.processMetric(metric(posA = 3.0f, posB = 3.0f)) + detector.processMetric(metric(posA = 30.0f, posB = 30.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Re-enable - should reset everything including baseline @@ -566,7 +562,7 @@ class HandleStateDetectorTest { assertEquals(HandleState.WaitingForRest, detector.handleState.value) // New baseline should be captured fresh - detector.processMetric(metric(posA = 1.0f, posB = 1.0f)) + detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -574,9 +570,8 @@ class HandleStateDetectorTest { fun `baseline reset on disable`() { val detector = createDetector() detector.enable(autoStart = true) - // Set baseline - detector.processMetric(metric(posA = 3.0f, posB = 3.0f)) + detector.processMetric(metric(posA = 30.0f, posB = 30.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Disable clears everything @@ -587,7 +582,7 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // New baseline captured - detector.processMetric(metric(posA = 1.0f, posB = 1.0f)) + detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -595,9 +590,8 @@ class HandleStateDetectorTest { fun `baseline reset on reset`() { val detector = createDetector() detector.enable(autoStart = true) - // Set baseline - detector.processMetric(metric(posA = 3.0f, posB = 3.0f)) + detector.processMetric(metric(posA = 30.0f, posB = 30.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Reset returns to WaitingForRest @@ -605,7 +599,7 @@ class HandleStateDetectorTest { assertEquals(HandleState.WaitingForRest, detector.handleState.value) // New baseline captured - detector.processMetric(metric(posA = 1.0f, posB = 1.0f)) + detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -613,9 +607,8 @@ class HandleStateDetectorTest { fun `baseline reset on enableJustLiftWaiting`() { val detector = createDetector() detector.enable(autoStart = true) - // Set baseline - detector.processMetric(metric(posA = 3.0f, posB = 3.0f)) + detector.processMetric(metric(posA = 30.0f, posB = 30.0f)) assertEquals(HandleState.Released, detector.handleState.value) // enableJustLiftWaiting resets everything @@ -623,7 +616,7 @@ class HandleStateDetectorTest { assertEquals(HandleState.WaitingForRest, detector.handleState.value) // New baseline captured - detector.processMetric(metric(posA = 1.0f, posB = 1.0f)) + detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) assertEquals(HandleState.Released, detector.handleState.value) } @@ -638,15 +631,15 @@ class HandleStateDetectorTest { assertTrue(detector.isAutoStartMode) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) - // Velocity 25 mm/s > AUTO_START_VELOCITY_THRESHOLD (20) -> should detect grab + // Velocity 250 mm/s > AUTO_START_VELOCITY_THRESHOLD (200) -> should detect grab fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 25.0, velB = 25.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 250.0, velB = 250.0)) // 200ms dwell fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 25.0, velB = 25.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 250.0, velB = 250.0)) assertEquals(HandleState.Grabbed, detector.handleState.value) } @@ -657,15 +650,15 @@ class HandleStateDetectorTest { assertFalse(detector.isAutoStartMode) // Go to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) - // Velocity 25 mm/s < VELOCITY_THRESHOLD (50) -> should NOT detect grab + // Velocity 250 mm/s < VELOCITY_THRESHOLD (500) -> should NOT detect grab fakeTime = 1000L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 25.0, velB = 25.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 250.0, velB = 250.0)) // 200ms later - still no grab because velocity too low fakeTime = 1200L - detector.processMetric(metric(posA = 20.0f, posB = 20.0f, velA = 25.0, velB = 25.0)) + detector.processMetric(metric(posA = 200.0f, posB = 200.0f, velA = 250.0, velB = 250.0)) // With no velocity above threshold, position above threshold -> Moving assertEquals(HandleState.Moving, detector.handleState.value) } @@ -682,18 +675,18 @@ class HandleStateDetectorTest { // Initial: both false assertEquals(HandleDetection(false, false), detector.handleDetection.value) - // Left handle extended > 50mm - detector.processMetric(metric(posA = 60.0f, posB = 10.0f)) + // Left handle extended > 500mm + detector.processMetric(metric(posA = 600.0f, posB = 100.0f)) assertEquals(HandleDetection(true, false), detector.handleDetection.value) // Both extended fakeTime = 100L - detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) + detector.processMetric(metric(posA = 600.0f, posB = 600.0f)) assertEquals(HandleDetection(true, true), detector.handleDetection.value) // Both back fakeTime = 200L - detector.processMetric(metric(posA = 10.0f, posB = 10.0f)) + detector.processMetric(metric(posA = 100.0f, posB = 100.0f)) assertEquals(HandleDetection(false, false), detector.handleDetection.value) } @@ -703,7 +696,7 @@ class HandleStateDetectorTest { // Not enabled - processMetric should be no-op assertFalse(detector.isEnabled) - detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) + detector.processMetric(metric(posA = 600.0f, posB = 600.0f)) assertEquals(HandleDetection(false, false), detector.handleDetection.value) } @@ -744,7 +737,7 @@ class HandleStateDetectorTest { detector.enable(autoStart = true) // Advance to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // Reset @@ -761,7 +754,7 @@ class HandleStateDetectorTest { assertFalse(detector.isAutoStartMode) // Advance to Released - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.Released, detector.handleState.value) // enableJustLiftWaiting @@ -782,11 +775,11 @@ class HandleStateDetectorTest { assertEquals(HandleState.WaitingForRest, detector.handleState.value) // Should not change state - detector.processMetric(metric(posA = 2.0f, posB = 1.5f)) + detector.processMetric(metric(posA = 20.0f, posB = 15.0f)) assertEquals(HandleState.WaitingForRest, detector.handleState.value) // Should not change handle detection - detector.processMetric(metric(posA = 60.0f, posB = 60.0f)) + detector.processMetric(metric(posA = 600.0f, posB = 600.0f)) assertEquals(HandleDetection(false, false), detector.handleDetection.value) } @@ -794,15 +787,14 @@ class HandleStateDetectorTest { fun `position diagnostics track min and max`() { val detector = createDetector() detector.enable(autoStart = true) - - detector.processMetric(metric(posA = 10.0f, posB = 5.0f)) - assertEquals(5.0, detector.minPositionSeen) - assertEquals(10.0, detector.maxPositionSeen) + detector.processMetric(metric(posA = 100.0f, posB = 50.0f)) + assertEquals(50.0, detector.minPositionSeen) + assertEquals(100.0, detector.maxPositionSeen) fakeTime = 100L - detector.processMetric(metric(posA = 2.0f, posB = 20.0f)) - assertEquals(2.0, detector.minPositionSeen) - assertEquals(20.0, detector.maxPositionSeen) + detector.processMetric(metric(posA = 20.0f, posB = 200.0f)) + assertEquals(20.0, detector.minPositionSeen) + assertEquals(200.0, detector.maxPositionSeen) } @Test @@ -817,9 +809,9 @@ class HandleStateDetectorTest { detector.enable(autoStart = false) assertFalse(detector.hasObservedPositionRange()) - detector.processMetric(metric(posA = -30.0f, posB = -8.0f)) - assertEquals(-30.0, detector.minPositionSeen) - assertEquals(-8.0, detector.maxPositionSeen) + detector.processMetric(metric(posA = -300.0f, posB = -80.0f)) + assertEquals(-300.0, detector.minPositionSeen) + assertEquals(-80.0, detector.maxPositionSeen) assertTrue(detector.hasObservedPositionRange()) detector.reset() diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessorTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessorTest.kt index efaf98b93..08945d369 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessorTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/MonitorDataProcessorTest.kt @@ -23,11 +23,11 @@ class MonitorDataProcessorTest { /** * Helper to build a MonitorPacket with sensible defaults. - * Positions at 10mm (well within valid range), loads at 5kg. + * Positions at 100mm (well within valid range), loads at 5kg. */ private fun packet( - posA: Float = 10.0f, - posB: Float = 10.0f, + posA: Float = 100.0f, + posB: Float = 100.0f, loadA: Float = 5.0f, loadB: Float = 5.0f, ticks: Long = 0L, @@ -55,10 +55,10 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - val result = processor.process(packet(posA = 100.0f, posB = 200.0f)) + val result = processor.process(packet(posA = 1000.0f, posB = 2000.0f)) assertNotNull(result) - assertEquals(100.0f, result.positionA) - assertEquals(200.0f, result.positionB) + assertEquals(1000.0f, result.positionA) + assertEquals(2000.0f, result.positionB) } @Test @@ -67,15 +67,15 @@ class MonitorDataProcessorTest { fakeTime = 1000L // First sample: establish last-good values - val m1 = processor.process(packet(posA = 50.0f, posB = 60.0f)) + val m1 = processor.process(packet(posA = 500.0f, posB = 600.0f)) assertNotNull(m1) fakeTime = 1020L - // Second sample: posA out of range (>1000), should use last-good (50.0) - val m2 = processor.process(packet(posA = 1500.0f, posB = 65.0f)) + // Second sample: posA out of range (>10000), should use last-good (500.0) + val m2 = processor.process(packet(posA = 15000.0f, posB = 650.0f)) assertNotNull(m2) - assertEquals(50.0f, m2.positionA, "posA should fall back to last-good value") - assertEquals(65.0f, m2.positionB, "posB should pass through unchanged") + assertEquals(500.0f, m2.positionA, "posA should fall back to last-good value") + assertEquals(650.0f, m2.positionB, "posB should pass through unchanged") } @Test @@ -84,15 +84,15 @@ class MonitorDataProcessorTest { fakeTime = 1000L // Establish last-good - val m1 = processor.process(packet(posA = 50.0f, posB = 60.0f)) + val m1 = processor.process(packet(posA = 500.0f, posB = 600.0f)) assertNotNull(m1) fakeTime = 1020L // posB out of range - val m2 = processor.process(packet(posA = 55.0f, posB = -1500.0f)) + val m2 = processor.process(packet(posA = 550.0f, posB = -15000.0f)) assertNotNull(m2) - assertEquals(55.0f, m2.positionA) - assertEquals(60.0f, m2.positionB, "posB should fall back to last-good value") + assertEquals(550.0f, m2.positionA) + assertEquals(600.0f, m2.positionB, "posB should fall back to last-good value") } @Test @@ -101,15 +101,15 @@ class MonitorDataProcessorTest { fakeTime = 1000L // Establish last-good - val m1 = processor.process(packet(posA = 50.0f, posB = 60.0f)) + val m1 = processor.process(packet(posA = 500.0f, posB = 600.0f)) assertNotNull(m1) fakeTime = 1020L // Both out of range - val m2 = processor.process(packet(posA = 2000.0f, posB = -2000.0f)) + val m2 = processor.process(packet(posA = 20000.0f, posB = -20000.0f)) assertNotNull(m2) - assertEquals(50.0f, m2.positionA, "posA should fall back to last-good") - assertEquals(60.0f, m2.positionB, "posB should fall back to last-good") + assertEquals(500.0f, m2.positionA, "posA should fall back to last-good") + assertEquals(600.0f, m2.positionB, "posB should fall back to last-good") } @Test @@ -118,7 +118,7 @@ class MonitorDataProcessorTest { fakeTime = 1000L val result = processor.process( - packet(posA = BleConstants.Thresholds.MIN_POSITION.toFloat(), posB = 10.0f), + packet(posA = BleConstants.Thresholds.MIN_POSITION.toFloat(), posB = 100.0f), ) assertNotNull(result) assertEquals(BleConstants.Thresholds.MIN_POSITION.toFloat(), result.positionA) @@ -130,7 +130,7 @@ class MonitorDataProcessorTest { fakeTime = 1000L val result = processor.process( - packet(posA = BleConstants.Thresholds.MAX_POSITION.toFloat(), posB = 10.0f), + packet(posA = BleConstants.Thresholds.MAX_POSITION.toFloat(), posB = 100.0f), ) assertNotNull(result) assertEquals(BleConstants.Thresholds.MAX_POSITION.toFloat(), result.positionA) @@ -179,13 +179,13 @@ class MonitorDataProcessorTest { fakeTime = 1000L // First sample establishes baseline - val m1 = processor.process(packet(posA = 100.0f, posB = 100.0f)) + val m1 = processor.process(packet(posA = 1000.0f, posB = 1000.0f)) assertNotNull(m1) fakeTime = 1020L - // Jump of 25mm > POSITION_JUMP_THRESHOLD (20mm) - val m2 = processor.process(packet(posA = 125.0f, posB = 100.0f)) - assertNull(m2, "Position jump >20mm should reject sample") + // Jump of 250mm > POSITION_JUMP_THRESHOLD (200mm) + val m2 = processor.process(packet(posA = 1250.0f, posB = 1000.0f)) + assertNull(m2, "Position jump >200mm should reject sample") } @Test @@ -194,13 +194,13 @@ class MonitorDataProcessorTest { fakeTime = 1000L // First sample establishes baseline - val m1 = processor.process(packet(posA = 100.0f, posB = 100.0f)) + val m1 = processor.process(packet(posA = 1000.0f, posB = 1000.0f)) assertNotNull(m1) fakeTime = 1020L - // Jump of 15mm < POSITION_JUMP_THRESHOLD (20mm) - val m2 = processor.process(packet(posA = 115.0f, posB = 110.0f)) - assertNotNull(m2, "Position jump <20mm should pass") + // Jump of 150mm < POSITION_JUMP_THRESHOLD (200mm) + val m2 = processor.process(packet(posA = 1150.0f, posB = 1100.0f)) + assertNotNull(m2, "Position jump <200mm should pass") } @Test @@ -208,20 +208,20 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - // Normal sample establishes baseline at 100mm - val m1 = processor.process(packet(posA = 100.0f, posB = 100.0f)) + // Normal sample establishes baseline at 1000mm + val m1 = processor.process(packet(posA = 1000.0f, posB = 1000.0f)) assertNotNull(m1) fakeTime = 1020L - // Spike: +50mm jump (> 20mm threshold) -> filtered - val m2 = processor.process(packet(posA = 150.0f, posB = 100.0f)) + // Spike: +500mm jump (> 200mm threshold) -> filtered + val m2 = processor.process(packet(posA = 1500.0f, posB = 1000.0f)) assertNull(m2, "Spike should be filtered") fakeTime = 1040L - // Next sample at 150mm: delta from spike (150) = 0mm -> PASSES - // This proves the fix: lastPositionA was updated to 150 (the spike value) + // Next sample at 1500mm: delta from spike (1500) = 0mm -> PASSES + // This proves the fix: lastPositionA was updated to 1500 (the spike value) // so delta from the spike to the same value is 0 - val m3 = processor.process(packet(posA = 150.0f, posB = 100.0f)) + val m3 = processor.process(packet(posA = 1500.0f, posB = 1000.0f)) assertNotNull(m3, "Issue #210: Same position as spike should pass (delta=0, no cascade)") } @@ -230,24 +230,24 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - // Establish baseline at 100mm - val m1 = processor.process(packet(posA = 100.0f, posB = 100.0f)) + // Establish baseline at 1000mm + val m1 = processor.process(packet(posA = 1000.0f, posB = 1000.0f)) assertNotNull(m1) fakeTime = 1020L - // Spike to 150mm -> filtered (delta = 50 > 20) - val m2 = processor.process(packet(posA = 150.0f, posB = 100.0f)) + // Spike to 1500mm -> filtered (delta = 500 > 200) + val m2 = processor.process(packet(posA = 1500.0f, posB = 1000.0f)) assertNull(m2) fakeTime = 1040L - // Normal at 102mm: delta from SPIKE value (150) = 48mm -> also filtered + // Normal at 1020mm: delta from SPIKE value (1500) = 480mm -> also filtered // This is correct: the tracking position is the spike value, not pre-spike - val m3 = processor.process(packet(posA = 102.0f, posB = 100.0f)) - assertNull(m3, "Delta from spike (150 -> 102 = 48mm) should still be filtered") + val m3 = processor.process(packet(posA = 1020.0f, posB = 1000.0f)) + assertNull(m3, "Delta from spike (1500 -> 1020 = 480mm) should still be filtered") fakeTime = 1060L - // Same position again: delta from 102 = 0 -> passes - val m4 = processor.process(packet(posA = 102.0f, posB = 100.0f)) + // Same position again: delta from 1020 = 0 -> passes + val m4 = processor.process(packet(posA = 1020.0f, posB = 1000.0f)) assertNotNull(m4, "Issue #210: Second attempt at same position should pass (delta=0)") } @@ -258,7 +258,7 @@ class MonitorDataProcessorTest { // First sample ever: no lastTimestamp (==0), so jump filter should NOT apply // Even with a "big" position, it should pass because there's no previous reference - val result = processor.process(packet(posA = 500.0f, posB = 500.0f)) + val result = processor.process(packet(posA = 5000.0f, posB = 5000.0f)) assertNotNull(result, "First sample should always pass jump filter (no previous reference)") } @@ -269,12 +269,12 @@ class MonitorDataProcessorTest { fakeTime = 1000L // First sample - val m1 = processor.process(packet(posA = 100.0f, posB = 100.0f)) + val m1 = processor.process(packet(posA = 1000.0f, posB = 1000.0f)) assertNotNull(m1) fakeTime = 1020L // Huge jump, but strict validation disabled -> should pass - val m2 = processor.process(packet(posA = 500.0f, posB = 500.0f)) + val m2 = processor.process(packet(posA = 5000.0f, posB = 5000.0f)) assertNotNull(m2, "Jump should pass when strictValidationEnabled is false") } @@ -291,12 +291,12 @@ class MonitorDataProcessorTest { // and seeds EMA directly with firmware velocity. With firmware velocity the very // first call is the seed point (unlike client-side delta which required 2 samples). val result = processor.process( - packet(posA = 100.0f, posB = 100.0f, firmwareVelA = 100), + packet(posA = 1000.0f, posB = 1000.0f, firmwareVelA = 100), ) assertNotNull(result) // Velocity should be exactly the raw firmware value (seeded, not smoothed toward 0) - val expectedVelocity = 10.0 // firmwareVelA=100 / 10.0 = 10 mm/s + val expectedVelocity = 100.0 // firmwareVelA=100 used as-is = 100 mm/s assertEquals( expectedVelocity, result.velocityA, @@ -313,22 +313,22 @@ class MonitorDataProcessorTest { // Establish initial position processor.process(packet(posA = 0.0f, posB = 0.0f)) - // Feed constant firmware velocity: 1000 raw units = 100 mm/s - // Position moves 10mm every 100ms (within jump threshold) to pass validation + // Feed constant firmware velocity: 1000 raw units = 1000 mm/s + // Position moves 100mm every 100ms (within jump threshold) to pass validation var lastVelocity = 0.0 for (i in 1..20) { fakeTime = (i * 100).toLong() - val posA = (i * 10).toFloat() + val posA = (i * 100).toFloat() val result = processor.process(packet(posA = posA, posB = 0.0f, firmwareVelA = 1000)) if (result != null) { lastVelocity = result.velocityA } } - // After 20 samples at constant firmware velocity, EMA should be very close to 100 mm/s - val expectedVelocity = 100.0 + // After 20 samples at constant firmware velocity, EMA should be very close to 1000 mm/s + val expectedVelocity = 1000.0 assertTrue( - abs(lastVelocity - expectedVelocity) < 5.0, + abs(lastVelocity - expectedVelocity) < 50.0, "After 20 samples at constant velocity, EMA should converge. Got $lastVelocity, expected ~$expectedVelocity", ) } @@ -339,23 +339,23 @@ class MonitorDataProcessorTest { fakeTime = 1000L // Establish baseline - processor.process(packet(posA = 100.0f, posB = 100.0f)) + processor.process(packet(posA = 1000.0f, posB = 1000.0f)) fakeTime = 2000L - // Normal movement: 110mm, velocity = 10 mm/s - val m2 = processor.process(packet(posA = 110.0f, posB = 100.0f)) + // Normal movement: 1100mm, velocity = 100 mm/s + val m2 = processor.process(packet(posA = 1100.0f, posB = 1000.0f)) assertNotNull(m2) val velocityBeforeFilter = m2.velocityA fakeTime = 3000L - // Spike to 200mm -> filtered - val m3 = processor.process(packet(posA = 200.0f, posB = 100.0f)) + // Spike to 2000mm -> filtered + val m3 = processor.process(packet(posA = 2000.0f, posB = 1000.0f)) assertNull(m3) fakeTime = 4000L - // Same position as spike (200mm) -> passes + // Same position as spike (2000mm) -> passes // But velocity should NOT be updated from the spike's bad reference - val m4 = processor.process(packet(posA = 200.0f, posB = 100.0f)) + val m4 = processor.process(packet(posA = 2000.0f, posB = 1000.0f)) assertNotNull(m4) // Velocity should equal the value before filter (skip happened) assertEquals( @@ -371,30 +371,30 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - // First sample seeds EMA with firmware velocity 200 raw = 20.0 mm/s + // First sample seeds EMA with firmware velocity 200 raw = 200.0 mm/s val result = processor.process( - packet(posA = 100.0f, posB = 100.0f, firmwareVelA = 200), + packet(posA = 1000.0f, posB = 1000.0f, firmwareVelA = 200), ) assertNotNull(result) - // Firmware velocity is converted: raw / 10.0 = mm/s + // Firmware velocity is used as-is: raw = mm/s (no division) assertEquals( - 20.0, + 200.0, result.velocityA, 0.01, - "Velocity should come from firmware: 200 raw / 10.0 = 20 mm/s", + "Velocity should come from firmware: 200 raw as-is = 200 mm/s", ) fakeTime = 1500L // Second sample with different firmware velocity: EMA smooths toward it val result2 = processor.process( - packet(posA = 110.0f, posB = 100.0f, firmwareVelA = 400), + packet(posA = 1100.0f, posB = 1000.0f, firmwareVelA = 400), ) assertNotNull(result2) - // EMA: 0.3 * 40.0 + 0.7 * 20.0 = 12.0 + 14.0 = 26.0 + // EMA: 0.3 * 400.0 + 0.7 * 200.0 = 120.0 + 140.0 = 260.0 assertEquals( - 26.0, + 260.0, result2.velocityA, 0.01, "Second sample should EMA-smooth toward new firmware velocity", @@ -407,10 +407,10 @@ class MonitorDataProcessorTest { fakeTime = 1000L // First sample - processor.process(packet(posA = 100.0f, posB = 100.0f)) + processor.process(packet(posA = 1000.0f, posB = 1000.0f)) // Same timestamp, small position change (within jump threshold) - val result = processor.process(packet(posA = 110.0f, posB = 100.0f)) + val result = processor.process(packet(posA = 1100.0f, posB = 1000.0f)) assertNotNull(result) assertEquals( @@ -449,7 +449,6 @@ class MonitorDataProcessorTest { fun `deload event debounced within 2 seconds`() { val processor = createProcessor() fakeTime = 5000L - // First deload processor.process(packet(status = SampleStatus.DELOAD_OCCURRED)) assertEquals(1, deloadCallCount) @@ -464,7 +463,6 @@ class MonitorDataProcessorTest { fun `deload event fires again after 2 second cooldown`() { val processor = createProcessor() fakeTime = 5000L - // First deload processor.process(packet(status = SampleStatus.DELOAD_OCCURRED)) assertEquals(1, deloadCallCount) @@ -479,7 +477,6 @@ class MonitorDataProcessorTest { fun `ROM_OUTSIDE_HIGH triggers onRomViolation callback`() { val processor = createProcessor() fakeTime = 1000L - processor.process(packet(status = SampleStatus.ROM_OUTSIDE_HIGH)) assertEquals(1, romViolations.size) assertEquals(MonitorDataProcessor.RomViolationType.OUTSIDE_HIGH, romViolations[0]) @@ -489,7 +486,6 @@ class MonitorDataProcessorTest { fun `ROM_OUTSIDE_LOW triggers onRomViolation callback`() { val processor = createProcessor() fakeTime = 1000L - processor.process(packet(status = SampleStatus.ROM_OUTSIDE_LOW)) assertEquals(1, romViolations.size) assertEquals(MonitorDataProcessor.RomViolationType.OUTSIDE_LOW, romViolations[0]) @@ -505,16 +501,16 @@ class MonitorDataProcessorTest { fakeTime = 1000L // Process some samples to establish state - processor.process(packet(posA = 100.0f, posB = 100.0f)) + processor.process(packet(posA = 1000.0f, posB = 1000.0f)) fakeTime = 1020L - processor.process(packet(posA = 110.0f, posB = 110.0f)) + processor.process(packet(posA = 1100.0f, posB = 1100.0f)) // Reset processor.resetForNewSession() // After reset, next process should act as first sample (no jump filter, no velocity) fakeTime = 5000L - val result = processor.process(packet(posA = 500.0f, posB = 500.0f)) + val result = processor.process(packet(posA = 5000.0f, posB = 5000.0f)) assertNotNull(result, "After reset, first sample should pass (no jump filter reference)") } @@ -523,12 +519,12 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - // Build up velocity EMA with high firmware velocity (500 mm/s) + // Build up velocity EMA with high firmware velocity (5000 mm/s) val preReset = processor.process( packet(posA = 0.0f, posB = 0.0f, firmwareVelA = 5000), ) assertNotNull(preReset) - assertEquals(500.0, preReset.velocityA, 0.01, "Pre-reset EMA should be seeded at 500") + assertEquals(5000.0, preReset.velocityA, 0.01, "Pre-reset EMA should be seeded at 5000") // Reset clears EMA and sets isFirstVelocitySample = true processor.resetForNewSession() @@ -536,12 +532,12 @@ class MonitorDataProcessorTest { // After reset, first sample re-seeds EMA fresh with firmware velocity fakeTime = 3000L val result = processor.process( - packet(posA = 200.0f, posB = 0.0f, firmwareVelA = 100), + packet(posA = 2000.0f, posB = 0.0f, firmwareVelA = 100), ) assertNotNull(result) - // Velocity = firmwareVelA=100 / 10.0 = 10 mm/s (seeded fresh, not contaminated by pre-reset 500) + // Velocity = firmwareVelA=100 used as-is = 100 mm/s (seeded fresh, not contaminated by pre-reset 5000) assertEquals( - 10.0, + 100.0, result.velocityA, 0.01, "After reset, EMA should be re-seeded with first raw firmware velocity", @@ -572,17 +568,17 @@ class MonitorDataProcessorTest { val processor = createProcessor() fakeTime = 1000L - // Establish last-good at 50, 60 - processor.process(packet(posA = 50.0f, posB = 60.0f)) + // Establish last-good at 500, 600 + processor.process(packet(posA = 500.0f, posB = 600.0f)) // Reset processor.resetForNewSession() fakeTime = 5000L - // Process with out-of-range position -> should use preserved last-good (50, 60) - val result = processor.process(packet(posA = 2000.0f, posB = -2000.0f)) + // Process with out-of-range position -> should use preserved last-good (500, 600) + val result = processor.process(packet(posA = 20000.0f, posB = -20000.0f)) assertNotNull(result) - assertEquals(50.0f, result.positionA, "lastGoodPosA should be preserved across reset") - assertEquals(60.0f, result.positionB, "lastGoodPosB should be preserved across reset") + assertEquals(500.0f, result.positionA, "lastGoodPosA should be preserved across reset") + assertEquals(600.0f, result.positionB, "lastGoodPosB should be preserved across reset") } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/ProtocolParserTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/ProtocolParserTest.kt index c05abf3d9..b0ccbaa26 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/ProtocolParserTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/ble/ProtocolParserTest.kt @@ -200,7 +200,7 @@ class ProtocolParserTest { assertFalse(result.isLegacyFormat) assertEquals(10, result.topCounter) assertEquals(8, result.completeCounter) - assertEquals(300.0f, result.rangeTop) + assertEquals(3000.0f, result.rangeTop) // wire 300.0f scaled x10 to mm at parse (issue #1400) assertEquals(0.0f, result.rangeBottom) assertEquals(3, result.repsRomCount) assertEquals(5, result.repsRomTotal) @@ -239,7 +239,7 @@ class ProtocolParserTest { assertFalse(result.isLegacyFormat) assertEquals(5, result.topCounter) assertEquals(4, result.completeCounter) - assertEquals(1.0f, result.rangeTop) + assertEquals(10.0f, result.rangeTop) // wire 1.0f scaled x10 to mm at parse (issue #1400) assertEquals(1, result.repsRomCount) assertEquals(3, result.repsSetCount) } @@ -256,7 +256,7 @@ class ProtocolParserTest { fun `parseMonitorPacket parses position correctly`() { // 16-byte packet with positions // posA at offset 4-5 (signed), posB at offset 10-11 (signed) - // posA raw = 1234 -> 123.4mm, posB raw = -567 -> -56.7mm + // posA raw = 1234 -> 1234mm, posB raw = -567 -> -567mm (raw int16 is mm, issue #1400) val data = ByteArray(16) // posA = 1234 = 0x04D2 LE data[4] = 0xD2.toByte() @@ -268,8 +268,8 @@ class ProtocolParserTest { val result = parseMonitorPacket(data) assertNotNull(result) - assertEquals(123.4f, result.posA, 0.01f) - assertEquals(-56.7f, result.posB, 0.01f) + assertEquals(1234f, result.posA, 0.01f) + assertEquals(-567f, result.posB, 0.01f) } @Test diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/integration/intervals/Issue1400CompletionJournalUnitVersionTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/integration/intervals/Issue1400CompletionJournalUnitVersionTest.kt new file mode 100644 index 000000000..3fac32646 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/integration/intervals/Issue1400CompletionJournalUnitVersionTest.kt @@ -0,0 +1,184 @@ +package com.devil.phoenixproject.data.integration.intervals + +import com.devil.phoenixproject.domain.model.AsymmetryResult +import com.devil.phoenixproject.domain.model.BiomechanicsRepResult +import com.devil.phoenixproject.domain.model.BiomechanicsVelocityZone +import com.devil.phoenixproject.domain.model.ForceCurveResult +import com.devil.phoenixproject.domain.model.RepMetricData +import com.devil.phoenixproject.domain.model.StrengthProfile +import com.devil.phoenixproject.domain.model.VelocityResult +import com.devil.phoenixproject.domain.model.WorkoutMetric +import com.devil.phoenixproject.domain.model.WorkoutSession +import com.devil.phoenixproject.util.METRIC_UNIT_VERSION_LEGACY +import com.devil.phoenixproject.util.METRIC_UNIT_VERSION_MM +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Issue #1400 F1: the completion journal is explicitly metric-unit versioned. A v1 + * payload (pre-unit-fix, cm / cm-s) decodes scaled to mm / mm-s exactly once — the + * same field families migration 65 scales — and a v2 payload round-trips unchanged. + */ +class Issue1400CompletionJournalUnitVersionTest { + + @Test + fun `v2 payload round-trips at the mm metric unit version`() { + val write = legacyWrite().scaledFromLegacyMetricUnits() + val decoded = assertNotNull(CompletionJournalCodec.decode(CompletionJournalCodec.encode(write))) + assertEquals(METRIC_UNIT_VERSION_MM, decoded.metricUnitVersion) + assertEquals(450f, decoded.session.avgMcvMmS) + assertEquals(350f, decoded.metrics.single().positionA) + assertEquals(700.0, decoded.metrics.single().velocityA, 0.001) + assertEquals(700f, decoded.repMetrics.single().peakVelocity) + assertEquals(350f, decoded.repMetrics.single().rangeOfMotionMm) + assertEquals(700f, decoded.repBiomechanics.single().velocity.meanConcentricVelocityMmS) + } + + @Test + fun `v1 payload scales unit fields exactly once on decode`() { + // A pre-#1400 writer encoded with v=1 and no metricUnitVersion field. + val legacy = legacyWrite() + val payload = CompletionJournalCodec.encode(legacy) + assertEquals(METRIC_UNIT_VERSION_LEGACY, legacy.metricUnitVersion) + + val decoded = assertNotNull(CompletionJournalCodec.decode(payload)) + assertEquals(METRIC_UNIT_VERSION_MM, decoded.metricUnitVersion) + + // Same field families as migration 65: x10 exactly once. + assertEquals(450f, decoded.session.avgMcvMmS) + val metric = decoded.metrics.single() + assertEquals(350f, metric.positionA) + assertEquals(360f, metric.positionB) + assertEquals(700.0, metric.velocityA, 0.001) + assertEquals(710.0, metric.velocityB, 0.001) + val rep = decoded.repMetrics.single() + assertEquals(700f, rep.peakVelocity) + assertEquals(600f, rep.avgVelocityConcentric) + assertEquals(500f, rep.avgVelocityEccentric) + assertEquals(350f, rep.rangeOfMotionMm) + assertEquals(14000f, rep.peakPowerWatts) + assertEquals(12000f, rep.avgPowerWatts) + // The per-sample curves scale with the scalars (same field families as migration 65's + // Kotlin-side journal recovery); load curves stay untouched. + assertEquals(350f, rep.concentricPositions.single()) + assertEquals(100f, rep.eccentricPositions.single()) + assertEquals(700f, rep.concentricVelocities.single()) + assertEquals(600f, rep.eccentricVelocities.single()) + assertEquals(20.5f, rep.concentricLoadsA.single()) + val biomech = decoded.repBiomechanics.single() + assertEquals(700f, biomech.velocity.meanConcentricVelocityMmS) + assertEquals(800f, biomech.velocity.peakVelocityMmS) + + // Loads, percentages and counts are untouched. + assertEquals(20.5f, metric.loadA) + assertEquals(20.5f, decoded.repMetrics.single().peakForceA) + assertEquals(25f, biomech.velocity.velocityLossPercent) + + // Scaling is applied exactly once: re-encoding the decoded (mm) write and + // decoding again must not scale again. + val reEncoded = CompletionJournalCodec.encode(decoded) + val decodedAgain = assertNotNull(CompletionJournalCodec.decode(reEncoded)) + assertEquals(decoded.session.avgMcvMmS, decodedAgain.session.avgMcvMmS) + assertEquals(decoded.metrics.single().positionA, decodedAgain.metrics.single().positionA) + } + + @Test + fun `unknown journal versions are rejected`() { + val payload = CompletionJournalCodec.encode(legacyWrite()).replace("\"v\":1", "\"v\":99") + assertNull(CompletionJournalCodec.decode(payload)) + } + + // ==================== fixtures ==================== + + private fun legacyWrite() = PendingChildWrite( + session = WorkoutSession( + id = "s-1", + timestamp = 1_700_000_000_000L, + mode = "Old School", + reps = 5, + weightPerCableKg = 20f, + duration = 60_000L, + totalReps = 5, + warmupReps = 0, + workingReps = 5, + avgMcvMmS = 45f, + ), + metrics = listOf( + WorkoutMetric( + timestamp = 1_700_000_010_000L, + loadA = 20.5f, + loadB = 21f, + positionA = 35f, + positionB = 36f, + velocityA = 70.0, + velocityB = 71.0, + ), + ), + completedSet = null, + repMetrics = listOf(repMetric()), + repBiomechanics = listOf(repBiomechanics()), + metricUnitVersion = METRIC_UNIT_VERSION_LEGACY, + ) + + private fun repMetric() = RepMetricData( + repNumber = 1, + isWarmup = false, + startTimestamp = 1L, + endTimestamp = 2L, + durationMs = 1L, + concentricDurationMs = 1L, + concentricPositions = floatArrayOf(35f), + concentricLoadsA = floatArrayOf(20.5f), + concentricLoadsB = floatArrayOf(21f), + concentricVelocities = floatArrayOf(70f), + concentricTimestamps = longArrayOf(0L), + eccentricDurationMs = 1L, + eccentricPositions = floatArrayOf(10f), + eccentricLoadsA = floatArrayOf(20.5f), + eccentricLoadsB = floatArrayOf(21f), + eccentricVelocities = floatArrayOf(60f), + eccentricTimestamps = longArrayOf(1L), + peakForceA = 20.5f, + peakForceB = 21f, + avgForceConcentricA = 20f, + avgForceConcentricB = 21f, + avgForceEccentricA = 20f, + avgForceEccentricB = 21f, + peakVelocity = 70f, + avgVelocityConcentric = 60f, + avgVelocityEccentric = 50f, + rangeOfMotionMm = 35f, + peakPowerWatts = 1400f, + avgPowerWatts = 1200f, + ) + + private fun repBiomechanics() = BiomechanicsRepResult( + velocity = VelocityResult( + meanConcentricVelocityMmS = 70f, + peakVelocityMmS = 80f, + zone = BiomechanicsVelocityZone.GRIND, + velocityLossPercent = 25f, + estimatedRepsRemaining = 3, + shouldStopSet = false, + repNumber = 1, + ), + forceCurve = ForceCurveResult( + normalizedForceN = floatArrayOf(1f), + normalizedPositionPct = floatArrayOf(0f), + stickingPointPct = null, + strengthProfile = StrengthProfile.FLAT, + repNumber = 1, + ), + asymmetry = AsymmetryResult( + asymmetryPercent = 1f, + dominantSide = "A", + avgLoadA = 20f, + avgLoadB = 21f, + repNumber = 1, + ), + repNumber = 1, + timestamp = 2L, + ) +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetectorTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetectorTest.kt index 30076137f..6003c595c 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetectorTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/replay/RepBoundaryDetectorTest.kt @@ -54,8 +54,8 @@ class RepBoundaryDetectorTest { // Single rep: valley at 100mm, peak at 300mm, valley at 100mm // 20 samples total val positions = buildSingleRepPositions( - valleyMm = 100f, - peakMm = 300f, + valleyMm = 1000f, + peakMm = 3000f, sampleCount = 20, ) @@ -78,8 +78,8 @@ class RepBoundaryDetectorTest { // 3 reps: each with valley at 100mm, peak at 300mm val positions = buildMultiRepPositions( repCount = 3, - valleyMm = 100f, - peakMm = 300f, + valleyMm = 1000f, + peakMm = 3000f, samplesPerRep = 20, ) @@ -110,8 +110,8 @@ class RepBoundaryDetectorTest { // Data starts at a valley (low position) val positions = buildMultiRepPositions( repCount = 2, - valleyMm = 50f, // Starts at low position - peakMm = 250f, + valleyMm = 500f, // Starts at low position + peakMm = 2500f, samplesPerRep = 20, ) @@ -126,8 +126,8 @@ class RepBoundaryDetectorTest { // Build data that ends at a valley val positions = buildMultiRepPositions( repCount = 2, - valleyMm = 50f, - peakMm = 250f, + valleyMm = 500f, + peakMm = 2500f, samplesPerRep = 20, ) @@ -148,8 +148,8 @@ class RepBoundaryDetectorTest { @Test fun `detectBoundaries identifies peak position for phase split`() { val positions = buildSingleRepPositions( - valleyMm = 100f, - peakMm = 300f, + valleyMm = 1000f, + peakMm = 3000f, sampleCount = 20, ) @@ -176,8 +176,8 @@ class RepBoundaryDetectorTest { @Test fun `concentricIndices and eccentricIndices partition rep correctly`() { val positions = buildSingleRepPositions( - valleyMm = 100f, - peakMm = 300f, + valleyMm = 1000f, + peakMm = 3000f, sampleCount = 20, ) @@ -206,7 +206,7 @@ class RepBoundaryDetectorTest { val concentricPositions = rep.concentricIndices.map { positions[it] } for (i in 1 until concentricPositions.size) { assertTrue( - concentricPositions[i] >= concentricPositions[i - 1] - 5f, // Allow small smoothing variance + concentricPositions[i] >= concentricPositions[i - 1] - 50f, // Allow small smoothing variance "Concentric phase should have generally increasing positions", ) } @@ -215,7 +215,7 @@ class RepBoundaryDetectorTest { val eccentricPositions = rep.eccentricIndices.map { positions[it] } for (i in 1 until eccentricPositions.size) { assertTrue( - eccentricPositions[i] <= eccentricPositions[i - 1] + 5f, // Allow small smoothing variance + eccentricPositions[i] <= eccentricPositions[i - 1] + 50f, // Allow small smoothing variance "Eccentric phase should have generally decreasing positions", ) } @@ -230,14 +230,14 @@ class RepBoundaryDetectorTest { // Build clean data first val cleanPositions = buildMultiRepPositions( repCount = 3, - valleyMm = 100f, - peakMm = 300f, + valleyMm = 1000f, + peakMm = 3000f, samplesPerRep = 20, ) - // Add noise (+/- 3mm random variation) + // Add noise (+/- 30mm random variation) val noisyPositions = FloatArray(cleanPositions.size) { i -> - cleanPositions[i] + (Random.nextFloat() - 0.5f) * 6f + cleanPositions[i] + (Random.nextFloat() - 0.5f) * 60f } val result = detector.detectBoundaries(noisyPositions) @@ -256,22 +256,22 @@ class RepBoundaryDetectorTest { // because it's too close to the real valleys val positions = FloatArray(30) { i -> when { - i < 5 -> 100f + i < 5 -> 1000f // Start valley - i < 10 -> 100f + (i - 5) * 40f + i < 10 -> 1000f + (i - 5) * 400f // Rising - i == 12 -> 280f + i == 12 -> 2800f // Small dip (should be ignored) - i < 15 -> 300f + i < 15 -> 3000f // Peak - i < 25 -> 300f - (i - 15) * 20f + i < 25 -> 3000f - (i - 15) * 200f // Falling - else -> 100f // End valley + else -> 1000f // End valley } } @@ -286,18 +286,18 @@ class RepBoundaryDetectorTest { // Create data with valleys only 5 samples apart (less than minimum 8) val positions = FloatArray(40) { i -> when { - i < 3 -> 100f + i < 3 -> 1000f - i < 5 -> 200f + i < 5 -> 2000f - i < 8 -> 100f + i < 8 -> 1000f // Valley at ~6, too close to start - i < 20 -> 100f + ((i - 8) * 20f).coerceAtMost(200f) + i < 20 -> 1000f + ((i - 8) * 200f).coerceAtMost(2000f) - i < 30 -> 300f - ((i - 20) * 20f).coerceAtLeast(0f) + i < 30 -> 3000f - ((i - 20) * 200f).coerceAtLeast(0f) - else -> 100f + else -> 1000f } } @@ -314,7 +314,7 @@ class RepBoundaryDetectorTest { @Test fun `detectBoundaries handles flat data gracefully`() { // All positions are the same - no valleys or peaks - val positions = FloatArray(30) { 150f } + val positions = FloatArray(30) { 1500f } val result = detector.detectBoundaries(positions) @@ -325,7 +325,7 @@ class RepBoundaryDetectorTest { fun `detectBoundaries handles single incomplete rep`() { // Data that goes valley -> peak but never returns to valley val positions = FloatArray(15) { i -> - 100f + i * 15f // Steadily increasing, no return + 1000f + i * 150f // Steadily increasing, no return } val result = detector.detectBoundaries(positions) diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachineTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachineTest.kt index cb6fbf909..b68e64f09 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachineTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/RepCounterFromMachineTest.kt @@ -956,20 +956,20 @@ class RepRangesTest { // This tests the Just Lift autostop scenario where handles are placed down // Position goes to ~0 after user has established a meaningful ROM range val ranges = RepRanges( - minPosA = 30f, // Typical overhead pulley rest position - maxPosA = 230f, // Extended position after reps - minPosB = 30f, - maxPosB = 230f, + minPosA = 300f, // Typical overhead pulley rest position + maxPosA = 2300f, // Extended position after reps + minPosB = 300f, + maxPosB = 2300f, ) - // Range = 200mm, threshold = 30 + (200 * 0.05) = 40mm + // Range = 2000mm, threshold = 300 + (2000 * 0.05) = 400mm // Position at 0 or very low should trigger danger zone for autostop assertTrue(ranges.isInDangerZone(posA = 0f, posB = 0f)) - assertTrue(ranges.isInDangerZone(posA = 5f, posB = 5f)) - assertTrue(ranges.isInDangerZone(posA = 35f, posB = 35f)) // Just above min but below threshold + assertTrue(ranges.isInDangerZone(posA = 50f, posB = 50f)) + assertTrue(ranges.isInDangerZone(posA = 350f, posB = 350f)) // Just above min but below threshold - // Position at 50 should NOT trigger (above threshold of 40) - assertFalse(ranges.isInDangerZone(posA = 50f, posB = 50f)) + // Position at 500 should NOT trigger (above threshold of 400) + assertFalse(ranges.isInDangerZone(posA = 500f, posB = 500f)) } @Test @@ -1014,14 +1014,14 @@ class RepRangesTest { val onlyB = RepRanges( minPosA = null, maxPosA = null, - minPosB = 30f, - maxPosB = 230f, + minPosB = 300f, + maxPosB = 2300f, ) assertFalse(onlyB.isCableAInDangerZone(0f)) assertTrue(onlyB.isCableBInDangerZone(0f)) - assertFalse(onlyB.isCableBInDangerZone(0f, minRangeThreshold = 250f)) - assertTrue(onlyB.isCableBInDangerZone(35f)) - assertTrue(onlyB.isInDangerZone(posA = 0f, posB = 35f)) - assertFalse(onlyB.isInDangerZone(posA = 0f, posB = 50f)) + assertFalse(onlyB.isCableBInDangerZone(0f, minRangeThreshold = 2500f)) + assertTrue(onlyB.isCableBInDangerZone(350f)) + assertTrue(onlyB.isInDangerZone(posA = 0f, posB = 350f)) + assertFalse(onlyB.isInDangerZone(posA = 0f, posB = 500f)) } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt index ef9c87a3a..ff1ac9ada 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt @@ -108,7 +108,8 @@ class ExerciseMediaWiringTest { // T6: Phase 1 adds NO migration. Two guards, both history-aware (SD14): // (a) the migration set must not grow past the implementation base's latest - // (64.sqm at 6f95247) — bump this ratchet only when a real migration lands; + // (64.sqm at 6f95247) — bump this ratchet only when a real migration lands + // (65: issue #1400 metric-unit x10); // (b) the only migration allowed to mention ExerciseImage is 43.sqm, the // historical migration that CREATED the table; nothing may ALTER/DROP it. @Test @@ -123,7 +124,7 @@ class ExerciseMediaWiringTest { if (src.contains("ExerciseImage")) mentions.add("$n.sqm") } assertTrue( - maxSeen <= 64, + maxSeen <= 65, "Phase 1 adds no schema migration — found $maxSeen.sqm beyond the base 64.sqm (T6/AC13).", ) assertTrue( diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt index 0c2a8b3c5..56559f245 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt @@ -376,7 +376,7 @@ class BackupSerializationTest { val jsonString = json.encodeToString(backupData) - assertEquals(7, CURRENT_BACKUP_VERSION) + assertEquals(8, CURRENT_BACKUP_VERSION) assertTrue(jsonString.contains("\"profilePreferences\"")) assertFalse(jsonString.contains("equipmentRackItems")) listOf( diff --git a/shared/src/iosSimulatorArm64Main/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepository.kt b/shared/src/iosSimulatorArm64Main/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepository.kt index 7aca31bbc..644c16d33 100644 --- a/shared/src/iosSimulatorArm64Main/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepository.kt +++ b/shared/src/iosSimulatorArm64Main/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepository.kt @@ -1460,11 +1460,14 @@ class PhantomBleRepository( timestamp = now, loadA = load + wave.coerceAtLeast(0f) * config.loadScale, loadB = load + (-wave).coerceAtLeast(0f) * config.loadScale, - positionA = wave * 650f * config.positionScale, - positionB = wave * 640f * config.positionScale, + // Issue #1400: post-parse metric space is mm / mm/s. The wave + // amplitudes are scaled x10 from the old cm/cm-s emission so the + // simulated motion is identical against the x10 control constants. + positionA = wave * 6500f * config.positionScale, + positionB = wave * 6400f * config.positionScale, ticks = ticks++, - velocityA = wave * 250.0 * config.velocityScale, - velocityB = wave * 245.0 * config.velocityScale, + velocityA = wave * 2500.0 * config.velocityScale, + velocityB = wave * 2450.0 * config.velocityScale, status = 0, ) _metricsFlow.tryEmit(metric) @@ -1645,7 +1648,8 @@ class PhantomBleRepository( repsSetCount = target?.let { minOf(workingCount, it) } ?: workingCount, // The machine reports an unlimited command (0xFF) as target 252. repsSetTotal = target ?: 252, - rangeTop = 650f, + // Issue #1400: parsed rep-packet ROM bounds are mm (x10 at parse). + rangeTop = 6500f, rangeBottom = 0f, rawData = byteArrayOf(), // Synthetic event, not captured BLE bytes. timestamp = Clock.System.now().toEpochMilliseconds(), @@ -1710,8 +1714,9 @@ class PhantomBleRepository( repsRomTotal = params.warmupReps, repsSetCount = rep.coerceAtMost(target), repsSetTotal = target, - rangeTop = 650f, - rangeBottom = -650f, + // Issue #1400: parsed rep-packet ROM bounds are mm (x10 at parse). + rangeTop = 6500f, + rangeBottom = -6500f, rawData = rawData, timestamp = timestamp, ), diff --git a/shared/src/iosSimulatorArm64Test/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepositoryTest.kt b/shared/src/iosSimulatorArm64Test/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepositoryTest.kt index d3f894a4e..089209b0a 100644 --- a/shared/src/iosSimulatorArm64Test/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepositoryTest.kt +++ b/shared/src/iosSimulatorArm64Test/kotlin/com/devil/phoenixproject/data/repository/PhantomBleRepositoryTest.kt @@ -2142,11 +2142,11 @@ class PhantomBleRepositoryTest { val repository = PhantomBleRepository(ConnectionLogRepository()) val raw = monitorPacket( ticks = 42, - posA = 1250, // 125.0mm - velA = 320, // 32.0mm/s + posA = 1250, // 1250.0mm (raw mm, issue #1400) + velA = 320, // 320.0mm/s (raw mm/s, issue #1400) loadA = 1234, // 12.34kg - posB = -750, // -75.0mm - velB = -250, // -25.0mm/s + posB = -750, // -750.0mm (raw mm, issue #1400) + velB = -250, // -250.0mm/s (raw mm/s, issue #1400) loadB = 567, // 5.67kg ) @@ -2158,10 +2158,10 @@ class PhantomBleRepositoryTest { assertEquals(42, metric.ticks) assertEquals(12.34f, metric.loadA) assertEquals(5.67f, metric.loadB) - assertEquals(125.0f, metric.positionA) - assertEquals(-75.0f, metric.positionB) - assertEquals(32.0, metric.velocityA) - assertEquals(-25.0, metric.velocityB) + assertEquals(1250.0f, metric.positionA) + assertEquals(-750.0f, metric.positionB) + assertEquals(320.0, metric.velocityA) + assertEquals(-250.0, metric.velocityB) cancelAndIgnoreRemainingEvents() } } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt index 12a834b95..fcf8fdf8b 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt @@ -208,9 +208,9 @@ fun WorkoutHud( // PERIPHERAL VISION BARS (Pinned to edges, overlaying the pager) // Detect activity quickly (movement/load), then latch per-cable for the set to avoid flicker. - val activePositionThresholdMm = 50f // Match handle detection threshold - val activeVelocityThresholdMms = 20.0 // Match auto-start velocity threshold - val activeRangeThresholdMm = 20f // Lower than ROM threshold for early visibility + val activePositionThresholdMm = 500f // Match handle detection threshold + val activeVelocityThresholdMms = 200.0 // Match auto-start velocity threshold + val activeRangeThresholdMm = 200f // Lower than ROM threshold for early visibility val activeLoadDeltaKg = 1.0f // Above baseline to treat as engaged val cableAHasRange = repRanges?.isCableAActive(activeRangeThresholdMm) == true