@mentra/bluetooth-sdk 3.3.0 → 3.4.0-beta.1237
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +61 -0
- package/README.md +80 -11
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +85 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +154 -110
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
- package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +201 -1
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +43 -5
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +2 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +3 -0
- package/build/generated/changelogCatalog.d.ts.map +1 -1
- package/build/generated/changelogCatalog.js +4 -0
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +6 -6
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +9 -0
- package/build/index.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +76 -12
- package/ios/MentraBluetoothSDK.podspec +4 -0
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +2 -2
- package/ios/Source/Bridge.swift +11 -3
- package/ios/Source/DeviceManager.swift +131 -18
- package/ios/Source/DeviceStore.swift +27 -0
- package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +40 -5
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/errors/BluetoothSdkError.swift +5 -1
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +9 -6
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
- package/ios/Source/sgcs/MentraLive.swift +1270 -189
- package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
- package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
- package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
- package/ios/Source/sgcs/Nimo.swift +10 -3
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
- package/ios/Source/sgcs/SGCManager.swift +13 -0
- package/ios/Source/sgcs/Simulated.swift +2 -0
- package/ios/Source/status/DeviceStatus.swift +35 -0
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/types/DeviceModels.swift +8 -1
- package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/BesCrashReportTests.swift +142 -0
- package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
- package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
- package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
- package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
- package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
- package/package.json +3 -2
- package/plugin/build/withAndroid.js +9 -11
- package/plugin/build/withKotlinVersion.d.ts +2 -0
- package/plugin/build/withKotlinVersion.js +46 -0
- package/src/BluetoothSdk.types.ts +201 -1
- package/src/_private/BluetoothSdkModule.ts +47 -5
- package/src/generated/changelogCatalog.ts +4 -0
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +22 -0
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
package com.mentra.bluetoothsdk.stt
|
|
2
|
-
|
|
3
|
-
import android.content.Context
|
|
4
|
-
import com.mentra.bluetoothsdk.utils.NativeLog as Log
|
|
5
|
-
import com.konovalov.vad.silero.Vad
|
|
6
|
-
import com.konovalov.vad.silero.VadSilero
|
|
7
|
-
import com.konovalov.vad.silero.config.FrameSize
|
|
8
|
-
import com.konovalov.vad.silero.config.Mode
|
|
9
|
-
import com.konovalov.vad.silero.config.SampleRate
|
|
10
|
-
import java.nio.ByteBuffer
|
|
11
|
-
import java.nio.ByteOrder
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* VadGateSpeechPolicy handles Voice Activity Detection using Silero VAD.
|
|
15
|
-
*
|
|
16
|
-
* Features:
|
|
17
|
-
* - Dynamic VAD check throttling (adjusts frequency based on silence duration)
|
|
18
|
-
* - 8-second silence timeout before declaring "not speaking"
|
|
19
|
-
* - Bypass modes for debugging and PCM streaming
|
|
20
|
-
* - 512-sample frame size (matches Sherpa-ONNX requirements)
|
|
21
|
-
*
|
|
22
|
-
* Ported from android_core VadGateSpeechPolicy.java
|
|
23
|
-
*/
|
|
24
|
-
class VadGateSpeechPolicy(private val context: Context) {
|
|
25
|
-
companion object {
|
|
26
|
-
private const val TAG = "VadGateSpeechPolicy"
|
|
27
|
-
|
|
28
|
-
// Total required silence duration
|
|
29
|
-
private const val REQUIRED_SILENCE_DURATION_MS = 8000L
|
|
30
|
-
|
|
31
|
-
// Dynamic VAD check intervals
|
|
32
|
-
private const val INITIAL_SILENCE_VAD_INTERVAL_MS = 50L // Check frequently at first
|
|
33
|
-
private const val MEDIUM_SILENCE_VAD_INTERVAL_MS = 100L // Medium frequency after some time
|
|
34
|
-
private const val LONG_SILENCE_VAD_INTERVAL_MS =
|
|
35
|
-
200L // Less frequent after extended silence
|
|
36
|
-
|
|
37
|
-
// Thresholds for switching intervals
|
|
38
|
-
private const val MEDIUM_SILENCE_THRESHOLD_MS =
|
|
39
|
-
20000L // Switch to medium interval after 20s
|
|
40
|
-
private const val LONG_SILENCE_THRESHOLD_MS = 60000L // Switch to long interval after 60s
|
|
41
|
-
|
|
42
|
-
private const val FRAME_SIZE = 512
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
private var vad: VadSilero? = null
|
|
46
|
-
private var isCurrentlySpeech = false
|
|
47
|
-
private var bypassVadForDebugging = false
|
|
48
|
-
private var bypassVadForPCM = false
|
|
49
|
-
|
|
50
|
-
/** Notified whenever the speech/silence state actually flips. */
|
|
51
|
-
var onSpeechStateChanged: ((Boolean) -> Unit)? = null
|
|
52
|
-
|
|
53
|
-
// Timestamp of the last detected speech
|
|
54
|
-
private var lastSpeechDetectedTime = 0L
|
|
55
|
-
// Throttle timer for silence VAD checks
|
|
56
|
-
private var lastVadCheckTime = 0L
|
|
57
|
-
|
|
58
|
-
/** Initialize the Silero VAD model */
|
|
59
|
-
fun init(blockSizeSamples: Int) {
|
|
60
|
-
startVad()
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
private fun startVad() {
|
|
64
|
-
try {
|
|
65
|
-
// Set internal silence duration very low; external logic manages the full required
|
|
66
|
-
// silence duration
|
|
67
|
-
vad =
|
|
68
|
-
Vad.builder()
|
|
69
|
-
.setContext(context)
|
|
70
|
-
.setSampleRate(SampleRate.SAMPLE_RATE_16K)
|
|
71
|
-
.setFrameSize(FrameSize.FRAME_SIZE_512)
|
|
72
|
-
.setMode(Mode.NORMAL)
|
|
73
|
-
.setSilenceDurationMs(50)
|
|
74
|
-
.setSpeechDurationMs(50)
|
|
75
|
-
.build()
|
|
76
|
-
|
|
77
|
-
Log.d(TAG, "VAD initialized successfully")
|
|
78
|
-
} catch (e: Exception) {
|
|
79
|
-
Log.e(TAG, "Failed to initialize VAD", e)
|
|
80
|
-
vad = null
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** Check if audio should be passed to the recognizer based on VAD state */
|
|
85
|
-
fun shouldPassAudioToRecognizer(): Boolean {
|
|
86
|
-
// CRITICAL: Handle VAD null case
|
|
87
|
-
if (vad == null) {
|
|
88
|
-
return bypassVadForDebugging || bypassVadForPCM || true
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
return bypassVadForDebugging || bypassVadForPCM || isCurrentlySpeech
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/** Process audio bytes through VAD to detect speech */
|
|
95
|
-
fun processAudioBytes(bytes: ByteArray, offset: Int, length: Int) {
|
|
96
|
-
val now = System.currentTimeMillis()
|
|
97
|
-
|
|
98
|
-
// If in speech state and it hasn't been 8 seconds since the last speech was detected, skip
|
|
99
|
-
// processing
|
|
100
|
-
if (isCurrentlySpeech && (now - lastSpeechDetectedTime < REQUIRED_SILENCE_DURATION_MS)) {
|
|
101
|
-
return
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// Calculate silence duration
|
|
105
|
-
val silenceDuration = now - lastSpeechDetectedTime
|
|
106
|
-
|
|
107
|
-
// Determine which VAD interval to use based on silence duration
|
|
108
|
-
val currentVadInterval =
|
|
109
|
-
when {
|
|
110
|
-
silenceDuration < MEDIUM_SILENCE_THRESHOLD_MS -> INITIAL_SILENCE_VAD_INTERVAL_MS
|
|
111
|
-
silenceDuration < LONG_SILENCE_THRESHOLD_MS -> MEDIUM_SILENCE_VAD_INTERVAL_MS
|
|
112
|
-
else -> LONG_SILENCE_VAD_INTERVAL_MS
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// During silence, throttle VAD checks based on the dynamic interval
|
|
116
|
-
if (!isCurrentlySpeech && (now - lastVadCheckTime < currentVadInterval)) {
|
|
117
|
-
return
|
|
118
|
-
}
|
|
119
|
-
lastVadCheckTime = now
|
|
120
|
-
|
|
121
|
-
val audioBytesFull = bytesToShort(bytes)
|
|
122
|
-
val totalSamples = audioBytesFull.size
|
|
123
|
-
|
|
124
|
-
if (totalSamples % FRAME_SIZE != 0) {
|
|
125
|
-
Log.e(
|
|
126
|
-
TAG,
|
|
127
|
-
"Invalid audio frame size: $totalSamples samples. Needs to be multiple of $FRAME_SIZE."
|
|
128
|
-
)
|
|
129
|
-
return
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
val currentVad =
|
|
133
|
-
vad
|
|
134
|
-
?: run {
|
|
135
|
-
Log.w(TAG, "VAD not initialized, skipping audio processing")
|
|
136
|
-
return
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
var previousSpeechState = isCurrentlySpeech
|
|
140
|
-
|
|
141
|
-
// Process each 512-sample frame
|
|
142
|
-
val numFrames = totalSamples / FRAME_SIZE
|
|
143
|
-
for (i in 0 until numFrames) {
|
|
144
|
-
val currentTime = System.currentTimeMillis()
|
|
145
|
-
val startIdx = i * FRAME_SIZE
|
|
146
|
-
val audioFrame = audioBytesFull.copyOfRange(startIdx, startIdx + FRAME_SIZE)
|
|
147
|
-
val detectedSpeech = currentVad.isSpeech(audioFrame)
|
|
148
|
-
|
|
149
|
-
if (detectedSpeech) {
|
|
150
|
-
isCurrentlySpeech = true
|
|
151
|
-
// Update the last speech detection timestamp
|
|
152
|
-
lastSpeechDetectedTime = currentTime
|
|
153
|
-
} else {
|
|
154
|
-
// If no speech detected, and 8 seconds have elapsed since the last speech, mark as
|
|
155
|
-
// silence
|
|
156
|
-
if (currentTime - lastSpeechDetectedTime >= REQUIRED_SILENCE_DURATION_MS) {
|
|
157
|
-
isCurrentlySpeech = false
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
if (isCurrentlySpeech != previousSpeechState) {
|
|
162
|
-
Log.d(
|
|
163
|
-
TAG,
|
|
164
|
-
"Speech detection changed to: ${if (isCurrentlySpeech) "SPEECH" else "SILENCE"}"
|
|
165
|
-
)
|
|
166
|
-
previousSpeechState = isCurrentlySpeech
|
|
167
|
-
onSpeechStateChanged?.invoke(isCurrentlySpeech)
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** Convert byte array (PCM16LE) to short array */
|
|
173
|
-
private fun bytesToShort(bytes: ByteArray): ShortArray {
|
|
174
|
-
val shorts = ShortArray(bytes.size / 2)
|
|
175
|
-
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts)
|
|
176
|
-
return shorts
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/** Stop VAD and release resources */
|
|
180
|
-
fun stop() {
|
|
181
|
-
try {
|
|
182
|
-
vad?.close()
|
|
183
|
-
vad = null
|
|
184
|
-
Log.d(TAG, "VAD stopped and resources released")
|
|
185
|
-
} catch (e: Exception) {
|
|
186
|
-
Log.e(TAG, "Error stopping VAD", e)
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/** Reset VAD state */
|
|
191
|
-
fun reset() {
|
|
192
|
-
val wasSpeaking = isCurrentlySpeech
|
|
193
|
-
isCurrentlySpeech = false
|
|
194
|
-
lastSpeechDetectedTime = 0
|
|
195
|
-
lastVadCheckTime = 0
|
|
196
|
-
if (wasSpeaking) onSpeechStateChanged?.invoke(false)
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
/** Change bypass VAD for debugging state */
|
|
200
|
-
fun changeBypassVadForDebugging(bypass: Boolean) {
|
|
201
|
-
bypassVadForDebugging = bypass
|
|
202
|
-
Log.d(TAG, "Bypass VAD for debugging: $bypass")
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** Change bypass VAD for PCM streaming state */
|
|
206
|
-
fun changeBypassVadForPCM(bypass: Boolean) {
|
|
207
|
-
Log.d(TAG, "VAD PCM Bypass State Change: $bypassVadForPCM -> $bypass")
|
|
208
|
-
bypassVadForPCM = bypass
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** Handle microphone state changes */
|
|
212
|
-
fun microphoneStateChanged(state: Boolean) {
|
|
213
|
-
if (!state) {
|
|
214
|
-
// Microphone turned off: force immediate silence
|
|
215
|
-
val wasSpeaking = isCurrentlySpeech
|
|
216
|
-
isCurrentlySpeech = false
|
|
217
|
-
lastSpeechDetectedTime = 0
|
|
218
|
-
lastVadCheckTime = 0
|
|
219
|
-
|
|
220
|
-
// Optionally flush the VAD's internal state by processing a silent frame
|
|
221
|
-
vad?.let { vadInstance ->
|
|
222
|
-
val silentFrame = ShortArray(FRAME_SIZE)
|
|
223
|
-
vadInstance.isSpeech(silentFrame)
|
|
224
|
-
}
|
|
225
|
-
Log.d(TAG, "Microphone turned off; forced state to SILENCE.")
|
|
226
|
-
if (wasSpeaking) onSpeechStateChanged?.invoke(false)
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
package com.mentra.bluetoothsdk.sgcs
|
|
2
|
-
|
|
3
|
-
import android.content.Context
|
|
4
|
-
import android.os.Handler
|
|
5
|
-
|
|
6
|
-
/** No diagnostic receiver, commands, or screen capture in release builds. */
|
|
7
|
-
@Suppress("UNUSED_PARAMETER")
|
|
8
|
-
internal class NimoDiagnostics(
|
|
9
|
-
context: Context,
|
|
10
|
-
handler: Handler,
|
|
11
|
-
send: (ByteArray, () -> Unit) -> Boolean,
|
|
12
|
-
requestCanvasHold: ((() -> Unit) -> Unit) = { _ -> },
|
|
13
|
-
releaseCanvasHold: (resume: Boolean) -> Unit = { _ -> },
|
|
14
|
-
) {
|
|
15
|
-
fun connected(maxWriteBytes: Int) {}
|
|
16
|
-
fun disconnected() {}
|
|
17
|
-
fun close() {}
|
|
18
|
-
fun onPacket(packet: ByteArray): Boolean = false
|
|
19
|
-
fun cancelHeldCapture(reason: String, resumeCanvas: Boolean = false) {}
|
|
20
|
-
}
|
|
@@ -1,287 +0,0 @@
|
|
|
1
|
-
package com.mentra.bluetoothsdk.sgcs
|
|
2
|
-
|
|
3
|
-
import android.content.Context
|
|
4
|
-
import android.os.Handler
|
|
5
|
-
import android.os.Looper
|
|
6
|
-
import androidx.test.core.app.ApplicationProvider
|
|
7
|
-
import java.io.File
|
|
8
|
-
import java.util.concurrent.TimeUnit
|
|
9
|
-
import org.json.JSONObject
|
|
10
|
-
import org.junit.After
|
|
11
|
-
import org.junit.Assert.*
|
|
12
|
-
import org.junit.Before
|
|
13
|
-
import org.junit.Test
|
|
14
|
-
import org.junit.runner.RunWith
|
|
15
|
-
import org.robolectric.RobolectricTestRunner
|
|
16
|
-
import org.robolectric.Shadows
|
|
17
|
-
import org.robolectric.annotation.Config
|
|
18
|
-
import org.robolectric.annotation.LooperMode
|
|
19
|
-
|
|
20
|
-
@RunWith(RobolectricTestRunner::class)
|
|
21
|
-
@Config(sdk = [33])
|
|
22
|
-
@LooperMode(LooperMode.Mode.PAUSED)
|
|
23
|
-
class NimoDiagnosticsTest {
|
|
24
|
-
private data class Write(val packet: ByteArray, val completed: () -> Unit)
|
|
25
|
-
private val writes = mutableListOf<Write>()
|
|
26
|
-
private var heldReady: (() -> Unit)? = null
|
|
27
|
-
private val holdReleases = mutableListOf<Boolean>()
|
|
28
|
-
private lateinit var diagnostics: NimoDiagnostics
|
|
29
|
-
private lateinit var root: File
|
|
30
|
-
private lateinit var previousDirectories: Set<String>
|
|
31
|
-
|
|
32
|
-
@Before fun setup() {
|
|
33
|
-
val context = ApplicationProvider.getApplicationContext<Context>()
|
|
34
|
-
root = File(context.filesDir, "nimo-framebuffer")
|
|
35
|
-
previousDirectories = root.listFiles()?.map { it.name }?.toSet() ?: emptySet()
|
|
36
|
-
diagnostics = NimoDiagnostics(
|
|
37
|
-
context,
|
|
38
|
-
Handler(Looper.getMainLooper()),
|
|
39
|
-
{ frame, complete -> writes.add(Write(frame.copyOf(), complete)); true },
|
|
40
|
-
{ ready -> heldReady = ready },
|
|
41
|
-
{ resume -> holdReleases += resume },
|
|
42
|
-
)
|
|
43
|
-
diagnostics.connected(512)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
@After fun dispose() { diagnostics.close() }
|
|
47
|
-
|
|
48
|
-
@Test fun probePreservesNotReadyAndAcceptsResponsesBeforeWriteCallbacks() {
|
|
49
|
-
start("probe")
|
|
50
|
-
driveToPageGate()
|
|
51
|
-
assertTrue(diagnostics.onPacket(fbpReply(writes[3].packet, ByteArray(240))))
|
|
52
|
-
val result = receipt()
|
|
53
|
-
assertTrue(result.getBoolean("probe_ok"))
|
|
54
|
-
assertFalse(result.getBoolean("ok"))
|
|
55
|
-
assertTrue(result.isNull("error"))
|
|
56
|
-
assertEquals(0, result.getJSONObject("readiness").getInt("ready"))
|
|
57
|
-
assertEquals(1, result.getJSONObject("readiness").getInt("tws"))
|
|
58
|
-
assertEquals(NimoFramebufferProtocol.EXPECTED_VERSION, result.getString("runtime_version"))
|
|
59
|
-
assertEquals(8, result.getInt("wire_events"))
|
|
60
|
-
assertEquals(8, File(captureDirectory(), "wire.jsonl").readLines().size)
|
|
61
|
-
writes.toList().forEach { it.completed() }
|
|
62
|
-
idle(4_000)
|
|
63
|
-
assertEquals(4, writes.size)
|
|
64
|
-
assertTrue(receipt().getBoolean("probe_ok"))
|
|
65
|
-
assertTrue(writes.all { it.packet[8] == 2.toByte() && (it.packet[9].toInt() and 255) in listOf(0x0B, 0x19, 0x15) })
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
@Test fun duplicateTriggerDoesNotStartAnotherRead() {
|
|
69
|
-
start("capture")
|
|
70
|
-
start("probe")
|
|
71
|
-
assertEquals(1, writes.size)
|
|
72
|
-
assertEquals(1, newDirectories().size)
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
@Test fun disconnectCancelsPendingTimeoutAndIgnoresLateWriteCompletion() {
|
|
76
|
-
start("capture")
|
|
77
|
-
writes.single().completed()
|
|
78
|
-
diagnostics.disconnected()
|
|
79
|
-
val error = receipt().getString("error")
|
|
80
|
-
assertTrue(error.contains("disconnected"))
|
|
81
|
-
diagnostics.connected(512)
|
|
82
|
-
writes.single().completed()
|
|
83
|
-
idle(4_000)
|
|
84
|
-
assertEquals(error, receipt().getString("error"))
|
|
85
|
-
assertEquals(1, writes.size)
|
|
86
|
-
assertFalse(diagnostics.onPacket(versionReply()))
|
|
87
|
-
assertFalse(receipt().getBoolean("ok"))
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
@Test fun timeoutStartsAtWriteCompletionAndDoesNotRetry() {
|
|
91
|
-
start("probe")
|
|
92
|
-
idle(5_000)
|
|
93
|
-
assertFalse(File(captureDirectory(), "session.json").exists())
|
|
94
|
-
writes.single().completed()
|
|
95
|
-
idle(2_900)
|
|
96
|
-
assertFalse(File(captureDirectory(), "session.json").exists())
|
|
97
|
-
idle(200)
|
|
98
|
-
assertTrue(receipt().getString("error").contains("response timeout"))
|
|
99
|
-
assertEquals(1, writes.size)
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
@Test fun captureRejectsCrcBeforeRequestingBulkPages() {
|
|
103
|
-
start("capture")
|
|
104
|
-
driveToPageGate()
|
|
105
|
-
val corrupted = fbpReply(writes[3].packet, ByteArray(240)).also { it[4] = (it[4].toInt() xor 1).toByte() }
|
|
106
|
-
assertTrue(diagnostics.onPacket(corrupted))
|
|
107
|
-
assertFalse(receipt().getBoolean("ok"))
|
|
108
|
-
assertFalse(receipt().getBoolean("probe_ok"))
|
|
109
|
-
assertTrue(receipt().getString("error").contains("CRC mismatch"))
|
|
110
|
-
assertEquals(4, writes.size)
|
|
111
|
-
assertEquals(0, receipt().getJSONArray("banks").length())
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
@Test fun totalDeadlineBoundsAWriteThatNeverCompletes() {
|
|
115
|
-
start("capture")
|
|
116
|
-
idle(600_001)
|
|
117
|
-
assertTrue(receipt().getString("error").contains("10-minute budget"))
|
|
118
|
-
writes.single().completed()
|
|
119
|
-
idle(4_000)
|
|
120
|
-
assertEquals(1, writes.size)
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
@Test fun heldSampleBudgetIncludesCanvasDrainAndStaleReadyCannotStartCapture() {
|
|
124
|
-
start("held-sample")
|
|
125
|
-
assertTrue(writes.isEmpty())
|
|
126
|
-
assertNotNull(heldReady)
|
|
127
|
-
|
|
128
|
-
idle(15_001)
|
|
129
|
-
|
|
130
|
-
assertEquals(listOf(true), holdReleases)
|
|
131
|
-
assertTrue(receipt().getString("error").contains("15-second budget"))
|
|
132
|
-
heldReady?.invoke()
|
|
133
|
-
assertTrue(writes.isEmpty())
|
|
134
|
-
assertEquals(listOf(true), holdReleases)
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
@Test fun disconnectBeforeHeldCaptureIsReadyReleasesWithoutResumingCanvas() {
|
|
138
|
-
start("held-capture")
|
|
139
|
-
|
|
140
|
-
diagnostics.disconnected()
|
|
141
|
-
|
|
142
|
-
assertEquals(listOf(false), holdReleases)
|
|
143
|
-
assertTrue(receipt().getString("error").contains("disconnected"))
|
|
144
|
-
heldReady?.invoke()
|
|
145
|
-
assertTrue(writes.isEmpty())
|
|
146
|
-
assertEquals(listOf(false), holdReleases)
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
@Test fun duplicateHeldCaptureDoesNotReplaceHoldOrDeadline() {
|
|
150
|
-
start("held-sample")
|
|
151
|
-
val firstReady = heldReady
|
|
152
|
-
|
|
153
|
-
start("held-capture")
|
|
154
|
-
|
|
155
|
-
assertSame(firstReady, heldReady)
|
|
156
|
-
assertEquals(1, newDirectories().size)
|
|
157
|
-
idle(15_001)
|
|
158
|
-
assertEquals(listOf(true), holdReleases)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
@Test fun insufficientCapacityFailsWithoutSendingDiagnosticCommands() {
|
|
162
|
-
diagnostics.connected(20)
|
|
163
|
-
start("capture")
|
|
164
|
-
assertEquals(0, writes.size)
|
|
165
|
-
assertTrue(receipt().getString("error").contains("Write capacity"))
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
@Test fun samplePinsPreparedBankAndNeverClaimsStaticPairVerification() {
|
|
169
|
-
assertSample(1)
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
@Test fun sampleAlsoPinsPreparedBankZero() {
|
|
173
|
-
assertSample(0)
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
@Test fun heldSampleStartsOnlyAfterDrainAndReleasesOnSuccess() {
|
|
177
|
-
assertSample(1, "held-sample")
|
|
178
|
-
assertEquals(listOf(true), holdReleases)
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
private fun assertSample(bank: Int, mode: String = "sample") {
|
|
182
|
-
val state = byteArrayOf((1 - bank).toByte(), bank.toByte(), 0, 0)
|
|
183
|
-
start(mode)
|
|
184
|
-
if (mode == "held-sample") {
|
|
185
|
-
assertTrue(writes.isEmpty())
|
|
186
|
-
requireNotNull(heldReady).invoke()
|
|
187
|
-
}
|
|
188
|
-
driveToPageGate()
|
|
189
|
-
diagnostics.onPacket(fbpReply(writes.last().packet, ByteArray(240), state))
|
|
190
|
-
// The gate always probes bank0/page0; the sample follows its prepared selector.
|
|
191
|
-
repeat(315) { page ->
|
|
192
|
-
val request = writes.last().packet
|
|
193
|
-
assertEquals(bank, request[21].toInt())
|
|
194
|
-
assertEquals(page, (request[22].toInt() and 255) or ((request[23].toInt() and 255) shl 8))
|
|
195
|
-
diagnostics.onPacket(fbpReply(request, ByteArray(240) { page.toByte() }, state))
|
|
196
|
-
}
|
|
197
|
-
val result = receipt()
|
|
198
|
-
assertTrue(result.getBoolean("sample_ok"))
|
|
199
|
-
assertFalse(result.getBoolean("ok"))
|
|
200
|
-
assertFalse(result.getBoolean("atomic"))
|
|
201
|
-
assertFalse(result.getBoolean("optical"))
|
|
202
|
-
assertEquals("non_atomic_single_pass", result.getString("evidence_kind"))
|
|
203
|
-
assertEquals(0, result.getInt("static_pairs_verified"))
|
|
204
|
-
assertEquals(1, result.getJSONArray("banks").length())
|
|
205
|
-
assertEquals(319, writes.size)
|
|
206
|
-
assertEquals(638, result.getInt("wire_events"))
|
|
207
|
-
assertFalse(result.getBoolean("pixel_stability_verified"))
|
|
208
|
-
assertEquals(mode, result.getString("mode"))
|
|
209
|
-
assertEquals(75_600, File(captureDirectory(), "bank$bank-pass1.bin").length().toInt())
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
@Test fun sampleRejectsSelectorChangeBetweenGateAndFirstPageWithoutRetrying() {
|
|
213
|
-
start("sample")
|
|
214
|
-
driveToPageGate()
|
|
215
|
-
diagnostics.onPacket(fbpReply(writes.last().packet, ByteArray(240)))
|
|
216
|
-
diagnostics.onPacket(fbpReply(writes.last().packet, ByteArray(240), byteArrayOf(1, 0, 0, 0)))
|
|
217
|
-
val result = receipt()
|
|
218
|
-
assertFalse(result.getBoolean("sample_ok"))
|
|
219
|
-
assertFalse(result.getBoolean("ok"))
|
|
220
|
-
assertTrue(result.getString("error").contains("Sample metadata differs from page gate"))
|
|
221
|
-
assertEquals(5, writes.size)
|
|
222
|
-
assertEquals(0, result.getJSONArray("banks").length())
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
@Test fun sampleTimeoutCannotProduceSuccessOrStartASecondPass() {
|
|
226
|
-
start("sample")
|
|
227
|
-
driveToPageGate()
|
|
228
|
-
diagnostics.onPacket(fbpReply(writes.last().packet, ByteArray(240)))
|
|
229
|
-
writes.last().completed()
|
|
230
|
-
idle(3_001)
|
|
231
|
-
assertFalse(receipt().getBoolean("sample_ok"))
|
|
232
|
-
assertFalse(receipt().getBoolean("ok"))
|
|
233
|
-
assertEquals(5, writes.size)
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
@Test fun fullCaptureStillRequiresFourCompleteReadsAndTwoStaticPairs() {
|
|
237
|
-
start("capture")
|
|
238
|
-
driveToPageGate()
|
|
239
|
-
diagnostics.onPacket(fbpReply(writes.last().packet, ByteArray(240)))
|
|
240
|
-
repeat(4) { pass ->
|
|
241
|
-
repeat(315) { page ->
|
|
242
|
-
val request = writes.last().packet
|
|
243
|
-
assertEquals(pass / 2, request[21].toInt())
|
|
244
|
-
diagnostics.onPacket(fbpReply(request, ByteArray(240) { page.toByte() }))
|
|
245
|
-
}
|
|
246
|
-
if (pass < 3) assertFalse(File(captureDirectory(), "session.json").exists())
|
|
247
|
-
}
|
|
248
|
-
assertTrue(receipt().getBoolean("ok"))
|
|
249
|
-
assertEquals(2, receipt().getInt("static_pairs_verified"))
|
|
250
|
-
assertEquals(4, receipt().getJSONArray("banks").length())
|
|
251
|
-
assertEquals(1264, writes.size)
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
private fun driveToPageGate() {
|
|
255
|
-
assertEquals(1, writes.size)
|
|
256
|
-
assertFalse(diagnostics.onPacket(versionReply()))
|
|
257
|
-
assertEquals(2, writes.size)
|
|
258
|
-
assertFalse(diagnostics.onPacket(frame(0x19, byteArrayOf(0, 0, 1, 0))))
|
|
259
|
-
assertEquals(3, writes.size)
|
|
260
|
-
assertTrue(diagnostics.onPacket(fbpReply(writes[2].packet, "537cf1p1".toByteArray())))
|
|
261
|
-
assertEquals(4, writes.size)
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// Exercise the production coordinator without pretending Robolectric proves Android's
|
|
265
|
-
// signature-permission enforcement for the ADB receiver. That boundary needs a device test.
|
|
266
|
-
private fun start(mode: String) {
|
|
267
|
-
NimoDiagnostics::class.java.getDeclaredMethod("start", String::class.java).apply { isAccessible = true }
|
|
268
|
-
.invoke(diagnostics, mode)
|
|
269
|
-
}
|
|
270
|
-
private fun idle(milliseconds: Long) = Shadows.shadowOf(Looper.getMainLooper()).idleFor(milliseconds, TimeUnit.MILLISECONDS)
|
|
271
|
-
private fun newDirectories() = root.listFiles()?.filter { it.name !in previousDirectories } ?: emptyList()
|
|
272
|
-
private fun captureDirectory() = newDirectories().single()
|
|
273
|
-
private fun receipt() = JSONObject(File(captureDirectory(), "session.json").readText())
|
|
274
|
-
private fun versionReply() = frame(0x0B, byteArrayOf(0) + NimoFramebufferProtocol.EXPECTED_VERSION.toByteArray())
|
|
275
|
-
|
|
276
|
-
private fun fbpReply(request: ByteArray, data: ByteArray, state: ByteArray = byteArrayOf(0, 1, 0, 0)): ByteArray {
|
|
277
|
-
val payload = byteArrayOf(0) + "FBP1".toByteArray() + request.copyOfRange(16, 24) + state + state +
|
|
278
|
-
byteArrayOf(data.size.toByte(), (data.size shr 8).toByte()) + data
|
|
279
|
-
return frame(0x15, payload)
|
|
280
|
-
}
|
|
281
|
-
private fun frame(key: Int, payload: ByteArray): ByteArray {
|
|
282
|
-
val body = byteArrayOf(2, key.toByte(), payload.size.toByte(), (payload.size shr 8).toByte()) + payload
|
|
283
|
-
val crc = NimoCanvasCodec.crc16(body)
|
|
284
|
-
return byteArrayOf(0xBF.toByte(), 0, body.size.toByte(), (body.size shr 8).toByte(),
|
|
285
|
-
crc.toByte(), (crc shr 8).toByte(), 0, 0) + body
|
|
286
|
-
}
|
|
287
|
-
}
|
package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
package com.mentra.bluetoothsdk.sgcs
|
|
2
|
-
|
|
3
|
-
import org.junit.Assert.*
|
|
4
|
-
import org.junit.Test
|
|
5
|
-
|
|
6
|
-
class NimoFramebufferProtocolTest {
|
|
7
|
-
@Test fun hexPreservesEveryByteAndEmptyEvidence() {
|
|
8
|
-
val bytes = ByteArray(256) { it.toByte() }
|
|
9
|
-
assertEquals(bytes.joinToString("") { "%02x".format(it.toInt() and 255) }, NimoFramebufferProtocol.hex(bytes))
|
|
10
|
-
assertEquals("", NimoFramebufferProtocol.hex(byteArrayOf()))
|
|
11
|
-
}
|
|
12
|
-
private val pingRequest = NimoFramebufferProtocol.Request(0x01020304L, 0, 0, 0)
|
|
13
|
-
// Fixed vectors produced independently by the existing Python FBP1 codec.
|
|
14
|
-
private val ping = hex("bf0023008234000002151f0000464250310403020100000000000100000001000008003533376366317031")
|
|
15
|
-
private val page = hex("bf000b0175e500000215070100464250310403020101013a010001000000010000f000") +
|
|
16
|
-
ByteArray(240) { it.toByte() }
|
|
17
|
-
|
|
18
|
-
@Test fun requestAndReplyMatchIndependentGoldenVectors() {
|
|
19
|
-
assertArrayEquals(hex("bf001000227a000002150c00464250310403020100000000"),
|
|
20
|
-
NimoFramebufferProtocol.requestFrame(pingRequest))
|
|
21
|
-
val reply = NimoFramebufferProtocol.reply(ping, pingRequest)
|
|
22
|
-
assertArrayEquals("537cf1p1".toByteArray(), reply.data)
|
|
23
|
-
assertEquals(NimoFramebufferProtocol.State(0, 1, 0, 0), reply.before)
|
|
24
|
-
val expectedPage = NimoFramebufferProtocol.Request(0x01020304L, 1, 1, 314)
|
|
25
|
-
assertArrayEquals(ByteArray(240) { it.toByte() }, NimoFramebufferProtocol.reply(page, expectedPage).data)
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
@Test fun rejectsCrcLengthsDirectionIndexAndCommand() {
|
|
29
|
-
for (offset in listOf(0, 1, 2, 4, 6, 8, 9, 10)) {
|
|
30
|
-
val invalid = ping.copyOf().also { it[offset] = (it[offset].toInt() xor 1).toByte() }
|
|
31
|
-
rejects { NimoFramebufferProtocol.reply(invalid, pingRequest) }
|
|
32
|
-
}
|
|
33
|
-
rejects { NimoFramebufferProtocol.reply(ping + 0, pingRequest) }
|
|
34
|
-
rejects { NimoFramebufferProtocol.reply(ping.copyOf(ping.size - 1), pingRequest) }
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
@Test fun rejectsWrongTagMagicNonceOperationBankAndPage() {
|
|
38
|
-
for (offset in listOf(13, 17, 21, 22, 23, 33, 35)) {
|
|
39
|
-
val invalid = changeAndRecrc(ping, offset, ping[offset].toInt() xor 1)
|
|
40
|
-
rejects { NimoFramebufferProtocol.reply(invalid, pingRequest) }
|
|
41
|
-
}
|
|
42
|
-
rejects { NimoFramebufferProtocol.reply(ping, pingRequest.copy(nonce = 9)) }
|
|
43
|
-
rejects { NimoFramebufferProtocol.reply(ping, pingRequest.copy(op = 1)) }
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
@Test fun rejectsStatusErrorsEvenWithValidCorrelation() {
|
|
47
|
-
for (status in listOf(1, 6, 7, 255)) {
|
|
48
|
-
val payload = ping.copyOfRange(12, 35).also { it[0] = status.toByte(); it[21] = 0; it[22] = 0 }
|
|
49
|
-
rejects { NimoFramebufferProtocol.reply(frame(0x15, payload), pingRequest) }
|
|
50
|
-
}
|
|
51
|
-
rejects { NimoFramebufferProtocol.reply(changeAndRecrc(ping, 12, 6), pingRequest) }
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
@Test fun rejectsMetadataChangedWithinAndAcrossPagesAndOutOfOrder() {
|
|
55
|
-
val request = NimoFramebufferProtocol.Request(0x01020304L, 1, 1, 0)
|
|
56
|
-
val first = NimoFramebufferProtocol.reply(pageAt(0), request)
|
|
57
|
-
val read = NimoFramebufferProtocol.BankRead(request.nonce, request.bank)
|
|
58
|
-
read.add(first)
|
|
59
|
-
rejects { read.add(first) }
|
|
60
|
-
rejects { NimoFramebufferProtocol.BankRead(request.nonce, request.bank).add(first.copy(page = 1)) }
|
|
61
|
-
rejects { NimoFramebufferProtocol.reply(changeAndRecrc(pageAt(0), 29, 1), request) }
|
|
62
|
-
val changed = first.copy(page = 1, before = first.before.copy(dirty = 1), after = first.after.copy(dirty = 1))
|
|
63
|
-
val changedRead = NimoFramebufferProtocol.BankRead(request.nonce, request.bank)
|
|
64
|
-
changedRead.add(first)
|
|
65
|
-
rejects { changedRead.add(changed) }
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
@Test fun bankRequiresEveryPageAndIndependentEqualSecondPass() {
|
|
69
|
-
val first = completeBank(10)
|
|
70
|
-
val second = completeBank(11)
|
|
71
|
-
NimoFramebufferProtocol.verifyPair(first, second)
|
|
72
|
-
assertEquals(75600, first.bytes().size)
|
|
73
|
-
rejects { NimoFramebufferProtocol.verifyPair(first, first) }
|
|
74
|
-
rejects { NimoFramebufferProtocol.verifyPair(first, completeBank(12, changedLastPixel = true)) }
|
|
75
|
-
rejects { NimoFramebufferProtocol.BankRead(20, 1).bytes() }
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
@Test fun requestLimitsPreventArbitraryCommandsOrAddresses() {
|
|
79
|
-
for (request in listOf(pingRequest.copy(nonce = -1), pingRequest.copy(nonce = 0x100000000L),
|
|
80
|
-
pingRequest.copy(op = 2), pingRequest.copy(bank = 2), pingRequest.copy(page = 1),
|
|
81
|
-
pingRequest.copy(op = 1, page = 315))) {
|
|
82
|
-
rejects { NimoFramebufferProtocol.requestFrame(request) }
|
|
83
|
-
}
|
|
84
|
-
rejects { NimoFramebufferProtocol.queryFrame(0x0A) }
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
@Test fun basicResponsesRequireExactVersionAndReadinessShape() {
|
|
88
|
-
val version = byteArrayOf(0) + NimoFramebufferProtocol.EXPECTED_VERSION.toByteArray()
|
|
89
|
-
assertEquals(NimoFramebufferProtocol.EXPECTED_VERSION,
|
|
90
|
-
NimoFramebufferProtocol.version(frame(0x0B, version)))
|
|
91
|
-
rejects { NimoFramebufferProtocol.version(frame(0x0B, version + 0)) }
|
|
92
|
-
rejects { NimoFramebufferProtocol.version(frame(0x0B, version.copyOf().also { it[0] = 7 })) }
|
|
93
|
-
assertEquals(listOf(0, 0, 1, 0), NimoFramebufferProtocol.readiness(frame(0x19, byteArrayOf(0, 0, 1, 0))))
|
|
94
|
-
rejects { NimoFramebufferProtocol.readiness(frame(0x19, byteArrayOf(0, 1, 1))) }
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
private fun completeBank(nonce: Long, changedLastPixel: Boolean = false): NimoFramebufferProtocol.BankRead {
|
|
98
|
-
val read = NimoFramebufferProtocol.BankRead(nonce, 1)
|
|
99
|
-
repeat(315) { index ->
|
|
100
|
-
val original = NimoFramebufferProtocol.reply(pageAt(index),
|
|
101
|
-
NimoFramebufferProtocol.Request(0x01020304L, 1, 1, index))
|
|
102
|
-
val data = original.data.copyOf()
|
|
103
|
-
if (changedLastPixel && index == 314) data[239] = 0
|
|
104
|
-
read.add(original.copy(nonce = nonce, data = data))
|
|
105
|
-
}
|
|
106
|
-
return read
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
private fun pageAt(index: Int): ByteArray {
|
|
110
|
-
val result = page.copyOf()
|
|
111
|
-
result[23] = index.toByte(); result[24] = (index shr 8).toByte()
|
|
112
|
-
return recrc(result)
|
|
113
|
-
}
|
|
114
|
-
private fun changeAndRecrc(value: ByteArray, index: Int, byte: Int) =
|
|
115
|
-
recrc(value.copyOf().also { it[index] = byte.toByte() })
|
|
116
|
-
private fun recrc(value: ByteArray): ByteArray {
|
|
117
|
-
val crc = NimoCanvasCodec.crc16(value.copyOfRange(8, value.size))
|
|
118
|
-
value[4] = crc.toByte(); value[5] = (crc shr 8).toByte()
|
|
119
|
-
return value
|
|
120
|
-
}
|
|
121
|
-
private fun frame(key: Int, payload: ByteArray): ByteArray {
|
|
122
|
-
val body = byteArrayOf(2, key.toByte(), payload.size.toByte(), (payload.size shr 8).toByte()) + payload
|
|
123
|
-
return recrc(byteArrayOf(0xBF.toByte(), 0, body.size.toByte(), (body.size shr 8).toByte(), 0, 0, 0, 0) + body)
|
|
124
|
-
}
|
|
125
|
-
private fun rejects(block: () -> Unit) { assertThrows(IllegalArgumentException::class.java, block) }
|
|
126
|
-
private fun hex(value: String) = value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
|
127
|
-
}
|