@mentra/bluetooth-sdk 3.2.1 → 3.3.0-beta.1001

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.
Files changed (108) hide show
  1. package/README.md +99 -6
  2. package/android/build.gradle +15 -0
  3. package/android/lc3Lib/build.gradle +6 -1
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +1 -1
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +6 -2
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +9 -1
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +231 -36
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +160 -20
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +3 -1
  25. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
  26. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
  30. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +20 -7
  39. package/build/BluetoothSdk.types.d.ts +9 -1
  40. package/build/BluetoothSdk.types.d.ts.map +1 -1
  41. package/build/BluetoothSdk.types.js.map +1 -1
  42. package/build/_private/BluetoothSdkModule.d.ts +2 -1
  43. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  44. package/build/_private/BluetoothSdkModule.js +2 -1
  45. package/build/_private/BluetoothSdkModule.js.map +1 -1
  46. package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
  47. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  48. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  49. package/build/_private/nativeLogConsole.d.ts +19 -0
  50. package/build/_private/nativeLogConsole.d.ts.map +1 -1
  51. package/build/_private/nativeLogConsole.js +12 -0
  52. package/build/_private/nativeLogConsole.js.map +1 -1
  53. package/build/generated/changelogCatalog.d.ts +4 -1
  54. package/build/generated/changelogCatalog.d.ts.map +1 -1
  55. package/build/generated/changelogCatalog.js +5 -1
  56. package/build/generated/changelogCatalog.js.map +1 -1
  57. package/build/generated/releaseMetadata.js +6 -6
  58. package/build/generated/releaseMetadata.js.map +1 -1
  59. package/build/index.d.ts +1 -1
  60. package/build/index.d.ts.map +1 -1
  61. package/build/index.js +1 -0
  62. package/build/index.js.map +1 -1
  63. package/build/ota-transport/index.d.ts +4 -0
  64. package/build/ota-transport/index.d.ts.map +1 -1
  65. package/build/ota-transport/index.js +2 -0
  66. package/build/ota-transport/index.js.map +1 -1
  67. package/ios/BluetoothSdkModule.swift +16 -4
  68. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  69. package/ios/Source/DeviceManager.swift +10 -3
  70. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  71. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  72. package/ios/Source/MentraBluetoothSDK.swift +306 -54
  73. package/ios/Source/TouchGesture.swift +13 -0
  74. package/ios/Source/events/BluetoothEvents.swift +4 -0
  75. package/ios/Source/internal/BluetoothAvailability.swift +6 -0
  76. package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
  77. package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
  78. package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
  79. package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
  80. package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
  81. package/ios/Source/sgcs/MentraLive.swift +167 -64
  82. package/ios/Source/sgcs/NimoCanvasCodec.swift +4 -1
  83. package/ios/Source/sgcs/SGCManager.swift +1 -1
  84. package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
  85. package/ios/Source/utils/G1Text.swift +2 -24
  86. package/ios/Source/utils/G1TextSanitizer.swift +27 -0
  87. package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
  88. package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
  89. package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
  90. package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
  91. package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
  92. package/ios/Tests/G1TextSanitizerTests.swift +32 -0
  93. package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
  94. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  95. package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
  96. package/ios/Tests/NimoCanvasCodecTests.swift +17 -4
  97. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  98. package/ios/Tests/VersionInfoCommandTests.swift +142 -1
  99. package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
  100. package/package.json +2 -2
  101. package/src/BluetoothSdk.types.ts +16 -0
  102. package/src/_private/BluetoothSdkModule.ts +4 -1
  103. package/src/_private/MentraLocalNetworkModule.ts +28 -0
  104. package/src/_private/nativeLogConsole.ts +19 -0
  105. package/src/generated/changelogCatalog.ts +5 -1
  106. package/src/generated/releaseMetadata.ts +6 -6
  107. package/src/index.ts +2 -0
  108. package/src/ota-transport/index.ts +10 -1
@@ -0,0 +1,124 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import androidx.test.core.app.ApplicationProvider
4
+ import android.content.Context
5
+ import org.assertj.core.api.Assertions.assertThat
6
+ import org.json.JSONObject
7
+ import org.junit.Test
8
+ import org.junit.runner.RunWith
9
+ import org.robolectric.RobolectricTestRunner
10
+ import org.robolectric.annotation.Config
11
+
12
+ @RunWith(RobolectricTestRunner::class)
13
+ @Config(sdk = [33])
14
+ class BluetoothSdkUpdateCheckTest {
15
+ private val context: Context = ApplicationProvider.getApplicationContext()
16
+
17
+ private fun result(status: String, latest: String? = "3.2.1", minimum: String? = null) =
18
+ BluetoothSdkUpdateCheckResult(status, "latest", latest, minimum)
19
+
20
+ @Test
21
+ fun `parses the Core response, treating null and blank versions as unknown`() {
22
+ val parsed =
23
+ BluetoothSdkUpdateCheckResult.parse(
24
+ """{"status":"update_available","channel":"dev","latestVersion":"3.3.0-dev.821","minimumSupportedVersion":null}""",
25
+ )!!
26
+ assertThat(parsed).isEqualTo(BluetoothSdkUpdateCheckResult("update_available", "dev", "3.3.0-dev.821", null))
27
+ assertThat(BluetoothSdkUpdateCheckResult.parse("""{"status":"current","latestVersion":""}""")!!.latestVersion).isNull()
28
+ assertThat(BluetoothSdkUpdateCheckResult.parse("<html>502</html>")).isNull()
29
+ }
30
+
31
+ @Test
32
+ fun `the banner names the installed and latest versions and the surface's update command`() {
33
+ val reactNative = BluetoothSdkUpdateNotice.banner("3.1.0", result("update_available"), "react_native")!!
34
+ assertThat(reactNative)
35
+ .contains("MENTRA BLUETOOTH SDK UPDATE AVAILABLE")
36
+ .contains("Installed: 3.1.0")
37
+ .contains("Latest: 3.2.1")
38
+ .contains("bun add @mentra/bluetooth-sdk@3.2.1")
39
+ .doesNotContain("NO LONGER SUPPORTED")
40
+ assertThat(BluetoothSdkUpdateNotice.banner("3.1.0", result("update_available"), "android")!!)
41
+ .contains("com.mentraglass:bluetooth-sdk:3.2.1")
42
+ assertThat(BluetoothSdkUpdateNotice.banner("3.1.0", result("update_available"), "ios")!!)
43
+ .contains("MentraBluetoothSDK Swift package at 3.2.1")
44
+ }
45
+
46
+ @Test
47
+ fun `an unsupported version gets the stronger banner`() {
48
+ val banner = BluetoothSdkUpdateNotice.banner("3.0.5", result("unsupported", minimum = "3.1.0"), "android")!!
49
+ assertThat(banner)
50
+ .contains("MENTRA BLUETOOTH SDK 3.0.5 IS NO LONGER SUPPORTED")
51
+ .contains("known issues")
52
+ }
53
+
54
+ @Test
55
+ fun `no banner when current, unknown, or no latest version to point at`() {
56
+ assertThat(BluetoothSdkUpdateNotice.banner("3.2.1", result("current"), "android")).isNull()
57
+ assertThat(BluetoothSdkUpdateNotice.banner("3.2.1", result("unknown", latest = null), "android")).isNull()
58
+ assertThat(BluetoothSdkUpdateNotice.banner("3.2.1", result("update_available", latest = null), "android")).isNull()
59
+ }
60
+
61
+ @Test
62
+ fun `the request identifies the install, app and SDK`() {
63
+ val body = BluetoothSdkUpdateCheck(context, "react_native", sdkVersion = "3.1.0", transport = { null }) { _, _ -> }.requestBody()
64
+ assertThat(body.getString("install_id")).isEqualTo(BluetoothSdkInstallId.get(context)).startsWith("mentra-bt-sdk-")
65
+ assertThat(body.getString("app_identifier")).isEqualTo(context.packageName)
66
+ assertThat(body.getString("sdk_version")).isEqualTo("3.1.0")
67
+ assertThat(body.getString("sdk_platform")).isEqualTo("android")
68
+ assertThat(body.getString("sdk_surface")).isEqualTo("react_native")
69
+ assertThat(body.has("app_build_type")).isTrue()
70
+ }
71
+
72
+ @Test
73
+ fun `an out-of-date SDK prints the banner once at start and stops on close`() {
74
+ val notices = mutableListOf<String>()
75
+ var sentBody: String? = null
76
+ val check =
77
+ BluetoothSdkUpdateCheck(
78
+ context,
79
+ "android",
80
+ sdkVersion = "3.1.0",
81
+ transport = { body ->
82
+ sentBody = body
83
+ """{"status":"update_available","channel":"latest","latestVersion":"3.2.1","minimumSupportedVersion":null}"""
84
+ },
85
+ ) { banner, _ -> notices += banner }
86
+ check.start()
87
+ BluetoothSdkUpdateCheck.awaitIdle()
88
+ assertThat(notices).hasSize(1)
89
+ assertThat(notices.single()).contains("Latest: 3.2.1")
90
+ assertThat(JSONObject(sentBody!!).getString("sdk_version")).isEqualTo("3.1.0")
91
+ check.stop()
92
+ }
93
+
94
+ @Test
95
+ fun `failures and unknown versions are silent`() {
96
+ val notices = mutableListOf<String>()
97
+ BluetoothSdkUpdateCheck(context, "android", sdkVersion = "3.1.0", transport = { null }) { banner, _ -> notices += banner }.start()
98
+ BluetoothSdkUpdateCheck(context, "android", sdkVersion = "3.1.0", transport = { throw IllegalStateException("offline") }) { banner, _ -> notices += banner }.start()
99
+ var called = false
100
+ BluetoothSdkUpdateCheck(context, "android", sdkVersion = "unknown", transport = { called = true; null }) { banner, _ -> notices += banner }.start()
101
+ BluetoothSdkUpdateCheck.awaitIdle()
102
+ assertThat(notices).isEmpty()
103
+ assertThat(called).isFalse()
104
+ }
105
+
106
+ @Test
107
+ fun `a check stopped before the response arrives prints nothing`() {
108
+ val notices = mutableListOf<String>()
109
+ lateinit var check: BluetoothSdkUpdateCheck
110
+ check =
111
+ BluetoothSdkUpdateCheck(
112
+ context,
113
+ "android",
114
+ sdkVersion = "3.1.0",
115
+ transport = {
116
+ check.stop()
117
+ """{"status":"update_available","latestVersion":"3.2.1"}"""
118
+ },
119
+ ) { banner, _ -> notices += banner }
120
+ check.start()
121
+ BluetoothSdkUpdateCheck.awaitIdle()
122
+ assertThat(notices).isEmpty()
123
+ }
124
+ }
@@ -0,0 +1,263 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import org.assertj.core.api.Assertions.assertThat
4
+ import org.junit.Test
5
+
6
+ class BluetoothSdkUsageTrackerTest {
7
+ private val tracker = BluetoothSdkUsageTracker()
8
+
9
+ @Test
10
+ fun `an API photo reports its request shape, latency and outcome`() {
11
+ val ok = tracker.photoSettled("medium", "photo", "none", save = true, transferMethod = "auto", latencyMs = 812, fileSizeBytes = 204_800, errorCode = null)
12
+ assertThat(ok.name).isEqualTo("bluetooth_sdk_photo_taken")
13
+ assertThat(ok.properties)
14
+ .containsEntry("trigger", "api")
15
+ .containsEntry("success", true)
16
+ .containsEntry("latency_ms", 812L)
17
+ .containsEntry("photo_size", "medium")
18
+ .containsEntry("save_to_gallery", true)
19
+ .containsEntry("transfer_method", "auto")
20
+ .containsEntry("file_size_bytes", 204_800L)
21
+ .doesNotContainKey("error_code")
22
+
23
+ val failed = tracker.photoSettled("max", "photo", "none", save = false, transferMethod = "ble", latencyMs = 30_000, fileSizeBytes = null, errorCode = "request_timeout")
24
+ assertThat(failed.properties)
25
+ .containsEntry("success", false)
26
+ .containsEntry("error_code", "request_timeout")
27
+ .doesNotContainKey("file_size_bytes")
28
+ }
29
+
30
+ @Test
31
+ fun `a failed button photo is reported as a button trigger`() {
32
+ val event = tracker.buttonPhotoFailed("CAMERA_BUSY")
33
+ assertThat(event.properties).containsEntry("trigger", "button").containsEntry("success", false).containsEntry("error_code", "CAMERA_BUSY")
34
+ }
35
+
36
+ @Test
37
+ fun `an API recording reports its length, parameters and app stop once`() {
38
+ tracker.videoRequested("rec-1", width = 1920, height = 1080, fps = 30, save = true, maxDurationMinutes = 0)
39
+ assertThat(tracker.videoStatus("rec-1", "recording_started", success = true, nowMs = 1_000)).isNull()
40
+ // A duplicate start does not move the start time.
41
+ assertThat(tracker.videoStatus("rec-1", "recording_started", success = true, nowMs = 2_000)).isNull()
42
+ tracker.videoStopRequested("rec-1")
43
+
44
+ val stopped = tracker.videoStatus("rec-1", "recording_stopped", success = true, nowMs = 61_000)!!
45
+ assertThat(stopped.name).isEqualTo("bluetooth_sdk_video_recorded")
46
+ assertThat(stopped.properties)
47
+ .containsEntry("trigger", "api")
48
+ .containsEntry("success", true)
49
+ .containsEntry("duration_ms", 60_000L)
50
+ .containsEntry("width", 1920)
51
+ .containsEntry("fps", 30)
52
+ .containsEntry("save_to_gallery", true)
53
+ .containsEntry("stopped_by_app", true)
54
+ .doesNotContainKey("max_duration_minutes")
55
+
56
+ assertThat(tracker.videoStatus("rec-1", "recording_stopped", success = true, nowMs = 62_000)).isNull()
57
+ }
58
+
59
+ @Test
60
+ fun `a button recording is reported with a button trigger and no app stop`() {
61
+ val id = "local_video_1728000000_ab12"
62
+ tracker.videoStatus(id, "recording_started", success = true, nowMs = 0)
63
+ val stopped = tracker.videoStatus(id, "recording_stopped", success = true, nowMs = 5_000)!!
64
+ assertThat(stopped.properties)
65
+ .containsEntry("trigger", "button")
66
+ .containsEntry("duration_ms", 5_000L)
67
+ .containsEntry("stopped_by_app", false)
68
+ }
69
+
70
+ @Test
71
+ fun `a recording failure is reported, but not_recording is not a recording`() {
72
+ tracker.videoRequested("rec-2", 0, 0, 0, save = false, maxDurationMinutes = 5)
73
+ val failed = tracker.videoStatus("rec-2", "battery_low", success = false, nowMs = 0)!!
74
+ assertThat(failed.properties)
75
+ .containsEntry("success", false)
76
+ .containsEntry("error_code", "battery_low")
77
+ .containsEntry("max_duration_minutes", 5)
78
+ .doesNotContainKey("duration_ms")
79
+ .doesNotContainKey("width")
80
+
81
+ assertThat(tracker.videoStatus("rec-3", "not_recording", success = false, nowMs = 0)).isNull()
82
+ assertThat(tracker.videoStatus("", "recording_stopped", success = true, nowMs = 0)).isNull()
83
+ }
84
+
85
+ @Test
86
+ fun `a stream is reported at start and once at its terminal status`() {
87
+ assertThat(tracker.streamRequested("s1", "rtmps://live.example.com/app/secret-key", nowMs = 6_600)).isNull()
88
+ // The first live status can arrive before startStream returns.
89
+ assertThat(stream("streaming", nowMs = 10_000)).isNull()
90
+ val started =
91
+ tracker.streamStartSettled(
92
+ streamUrl = "rtmps://live.example.com/app/secret-key",
93
+ width = 1280,
94
+ height = 720,
95
+ fps = 30,
96
+ bitrate = 2_000_000,
97
+ captureAudio = true,
98
+ glassesNetwork = "wifi",
99
+ latencyMs = 3_400,
100
+ errorCode = null,
101
+ )
102
+ assertThat(started.name).isEqualTo("bluetooth_sdk_stream_started")
103
+ assertThat(started.properties)
104
+ .containsEntry("success", true)
105
+ .containsEntry("protocol", "rtmp")
106
+ .containsEntry("glasses_network", "wifi")
107
+ assertThat(started.properties.values.map { it.toString() }).noneMatch { it.contains("secret-key") }
108
+
109
+ assertThat(stream("reconnecting", reconnectAttempt = 1, nowMs = 20_000)).isNull()
110
+ assertThat(stream("reconnected", reconnectAttempt = 2, nowMs = 21_000)).isNull()
111
+ assertThat(stream("streaming", bitrate = 1_800_000, droppedFrames = 12, nowMs = 30_000)).isNull()
112
+ // Statuses for another stream id do not touch this one.
113
+ assertThat(tracker.streamStatus("other", "stopped", true, null, null, null, null, null, null, 31_000)).isNull()
114
+ tracker.streamStopRequested()
115
+
116
+ val ended = stream("stopped", terminal = true, nowMs = 70_000)!!
117
+ assertThat(ended.name).isEqualTo("bluetooth_sdk_stream_ended")
118
+ assertThat(ended.properties)
119
+ .containsEntry("protocol", "rtmp")
120
+ .containsEntry("duration_ms", 60_000L)
121
+ .containsEntry("end_state", "stopped")
122
+ .containsEntry("stopped_by_app", true)
123
+ .containsEntry("reconnect_attempts", 2)
124
+ .containsEntry("bitrate", 1_800_000L)
125
+ .containsEntry("dropped_frames", 12L)
126
+
127
+ assertThat(stream("stopped", terminal = true, nowMs = 71_000)).isNull()
128
+ }
129
+
130
+ @Test
131
+ fun `a stream that ends right after going live is still reported`() {
132
+ tracker.streamRequested("s1", "rtmp://host/app", nowMs = 0)
133
+ assertThat(stream("streaming", nowMs = 1_000)).isNull()
134
+ val ended = stream("error", terminal = true, nowMs = 1_500)!!
135
+ assertThat(ended.properties).containsEntry("duration_ms", 500L).containsEntry("end_state", "error")
136
+ }
137
+
138
+ @Test
139
+ fun `a new start reports the live stream it replaces`() {
140
+ tracker.streamRequested("s1", "rtmp://host/app", nowMs = 0)
141
+ stream("streaming", nowMs = 1_000)
142
+ val replaced = tracker.streamRequested("s2", "srt://host:9000", nowMs = 11_000)!!
143
+ assertThat(replaced.name).isEqualTo("bluetooth_sdk_stream_ended")
144
+ assertThat(replaced.properties)
145
+ .containsEntry("protocol", "rtmp")
146
+ .containsEntry("end_state", "replaced")
147
+ .containsEntry("duration_ms", 10_000L)
148
+ // The replaced stream's own late terminal status is not reported again.
149
+ assertThat(stream("stopped", terminal = true, nowMs = 12_000)).isNull()
150
+ assertThat(tracker.streamStatus("s2", "streaming", null, null, null, null, null, null, null, 12_000)).isNull()
151
+ val second = tracker.streamStatus("s2", "stopped", true, null, null, null, null, null, null, 20_000)!!
152
+ assertThat(second.properties).containsEntry("protocol", "srt").containsEntry("duration_ms", 8_000L)
153
+ }
154
+
155
+ @Test
156
+ fun `older glasses without a terminal flag end a stream on stopped, and error details lose their URLs`() {
157
+ tracker.streamRequested("s2", "https://whip.example.com/whip/abc", nowMs = 0)
158
+ assertThat(tracker.streamStatus(null, "streaming", null, null, null, null, null, null, null, 500)).isNull()
159
+ assertThat(tracker.streamStatus(null, "error", null, null, null, null, null, null, null, 1_000)).isNull()
160
+ val ended =
161
+ tracker.streamStatus(null, "reconnect_failed", null, null, null, null, null, null, "connect to https://whip.example.com/whip/abc failed", 9_000)!!
162
+ assertThat(ended.properties)
163
+ .containsEntry("protocol", "whip")
164
+ .containsEntry("end_state", "reconnect_failed")
165
+ .containsEntry("error_code", "connect to <url> failed")
166
+ .containsEntry("stopped_by_app", false)
167
+ }
168
+
169
+ @Test
170
+ fun `a stream that never went live ends without a second event`() {
171
+ tracker.streamRequested("s3", "srt://host:9000", nowMs = 0)
172
+ val failed = tracker.streamStartSettled("srt://host:9000", null, null, null, null, true, "none", 30_000, "stream_start_failed")
173
+ assertThat(failed.properties).containsEntry("success", false).containsEntry("error_code", "stream_start_failed").containsEntry("protocol", "srt")
174
+ assertThat(tracker.streamStatus("s3", "stopped", true, null, null, null, null, null, null, 1_000)).isNull()
175
+ // Nothing live was replaced either.
176
+ assertThat(tracker.streamRequested("s4", "srt://host:9000", nowMs = 2_000)).isNull()
177
+ }
178
+
179
+ @Test
180
+ fun `stream protocol follows the glasses scheme mapping`() {
181
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("rtmp://a")).isEqualTo("rtmp")
182
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("RTMPS://a")).isEqualTo("rtmp")
183
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("srt://a")).isEqualTo("srt")
184
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("http://a")).isEqualTo("whip")
185
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("rtmpt://a")).isEqualTo("unknown")
186
+ assertThat(BluetoothSdkUsageTracker.streamProtocol("not a url")).isEqualTo("unknown")
187
+ }
188
+
189
+ @Test
190
+ fun `a mic session ends when the source turns off or changes`() {
191
+ assertThat(tracker.observeMic("", transcribing = false, nowMs = 0)).isNull()
192
+ assertThat(tracker.observeMic("glasses", transcribing = false, nowMs = 1_000)).isNull()
193
+ assertThat(tracker.observeMic("glasses", transcribing = true, nowMs = 2_000)).isNull()
194
+
195
+ val switched = tracker.observeMic("phone", transcribing = false, nowMs = 11_000)!!
196
+ assertThat(switched.name).isEqualTo("bluetooth_sdk_mic_session")
197
+ assertThat(switched.properties)
198
+ .containsEntry("mic_source", "glasses")
199
+ .containsEntry("duration_ms", 10_000L)
200
+ .containsEntry("local_transcription", true)
201
+
202
+ val off = tracker.observeMic("", transcribing = false, nowMs = 14_000)!!
203
+ assertThat(off.properties).containsEntry("mic_source", "phone").containsEntry("duration_ms", 3_000L).containsEntry("local_transcription", false)
204
+ assertThat(tracker.observeMic("", transcribing = false, nowMs = 15_000)).isNull()
205
+ }
206
+
207
+ @Test
208
+ fun `wifi and hotspot setup report outcome and latency`() {
209
+ assertThat(tracker.wifiSetupSettled(4_000, null).properties).containsEntry("success", true).containsEntry("latency_ms", 4_000L)
210
+ assertThat(tracker.wifiSetupSettled(15_000, "connect_timeout").properties).containsEntry("error_code", "connect_timeout")
211
+ assertThat(tracker.hotspotStartSettled(2_500, null).name).isEqualTo("bluetooth_sdk_hotspot_started")
212
+ }
213
+
214
+ @Test
215
+ fun `an OTA session is reported once with its starting versions`() {
216
+ assertThat(ota("ota-1", "in_progress", nowMs = 0, fromBuild = "38")).isNull()
217
+ assertThat(ota("ota-1", "step_complete", nowMs = 60_000, fromBuild = "39")).isNull()
218
+ val done = ota("ota-1", "complete", nowMs = 300_000, fromBuild = "40")!!
219
+ assertThat(done.name).isEqualTo("bluetooth_sdk_ota_finished")
220
+ assertThat(done.properties)
221
+ .containsEntry("success", true)
222
+ .containsEntry("duration_ms", 300_000L)
223
+ .containsEntry("from_build_number", "38")
224
+ .containsEntry("total_steps", 2)
225
+ .doesNotContainKey("failed_step_type")
226
+ assertThat(ota("ota-1", "complete", nowMs = 301_000, fromBuild = "40")).isNull()
227
+
228
+ val failed = ota("ota-2", "failed", nowMs = 0, fromBuild = "40", stepType = "bes", error = "download failed: https://ota.example.com/x.bin")!!
229
+ assertThat(failed.properties)
230
+ .containsEntry("success", false)
231
+ .containsEntry("failed_step_type", "bes")
232
+ .containsEntry("error_message", "download failed: <url>")
233
+ .doesNotContainKey("duration_ms")
234
+ }
235
+
236
+ @Test
237
+ fun `request timeouts are capped per tracker`() {
238
+ val capped = BluetoothSdkUsageTracker(maxRequestTimeouts = 2)
239
+ assertThat(capped.requestTimedOut("photo request")!!.properties)
240
+ .containsEntry("operation", "photo request")
241
+ .containsEntry("error_code", "request_timeout")
242
+ assertThat(capped.requestTimedOut("start stream")).isNotNull()
243
+ assertThat(capped.requestTimedOut("start stream")).isNull()
244
+ }
245
+
246
+ private fun stream(
247
+ state: String,
248
+ terminal: Boolean? = null,
249
+ reconnectAttempt: Int? = null,
250
+ bitrate: Long? = null,
251
+ droppedFrames: Long? = null,
252
+ nowMs: Long,
253
+ ) = tracker.streamStatus("s1", state, terminal, reconnectAttempt, bitrate, null, droppedFrames, null, null, nowMs)
254
+
255
+ private fun ota(
256
+ sessionId: String,
257
+ status: String,
258
+ nowMs: Long,
259
+ fromBuild: String,
260
+ stepType: String = "apk",
261
+ error: String? = null,
262
+ ) = tracker.otaStatus(sessionId, status, stepType, totalSteps = 2, errorMessage = error, fromBuildNumber = fromBuild, fromBesFirmwareVersion = "", fromMtkFirmwareVersion = "", nowMs = nowMs)
263
+ }
@@ -0,0 +1,55 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertNull
6
+ import org.junit.Test
7
+
8
+ class NetworkDiagnosticsTest {
9
+ private val validatedInternet = mapOf("internet" to true, "validated" to true)
10
+ private val localOnly = mapOf("internet" to false, "validated" to false)
11
+
12
+ @Test
13
+ fun `distinguishes a process bound to glasses from a validated active network`() {
14
+ val snapshot = networkDiagnostics(123L, "private-glasses", "private-cellular", "private-glasses") {
15
+ if (it == "private-cellular") validatedInternet else localOnly
16
+ }
17
+
18
+ assertEquals(123L, snapshot["sampledAtMs"])
19
+ assertEquals(false, snapshot["processBoundMatchesActive"])
20
+ assertEquals(true, snapshot["processBoundMatchesGlassesLocal"])
21
+ assertEquals(false, snapshot["activeNetworkMatchesGlassesLocal"])
22
+ assertEquals(validatedInternet, observation(snapshot, "activeNetwork")["capabilities"])
23
+ assertFalse(snapshot.toString().contains("private-"))
24
+ }
25
+
26
+ @Test
27
+ fun `keeps an unvalidated active network distinct from a disappeared network`() {
28
+ val unvalidated = networkDiagnostics(124L, null, "default", null) { localOnly }
29
+ assertEquals(localOnly, observation(unvalidated, "activeNetwork")["capabilities"])
30
+ val disappeared = networkDiagnostics(125L, null, "default", null) { null }
31
+ assertEquals(true, observation(disappeared, "activeNetwork")["present"])
32
+ assertNull(observation(disappeared, "activeNetwork")["capabilities"])
33
+ }
34
+
35
+ @Test
36
+ fun `no network does not imply equal routes or attempt a capability read`() {
37
+ var read = false
38
+ val snapshot = networkDiagnostics<String>(126L, null, null, null) {
39
+ read = true
40
+ validatedInternet
41
+ }
42
+
43
+ assertFalse(read)
44
+ listOf("processBound", "activeNetwork", "glassesLocal").forEach {
45
+ assertEquals(false, observation(snapshot, it)["present"])
46
+ assertNull(observation(snapshot, it)["capabilities"])
47
+ }
48
+ assertEquals(false, snapshot["processBoundMatchesActive"])
49
+ assertEquals(false, snapshot["processBoundMatchesGlassesLocal"])
50
+ assertEquals(false, snapshot["activeNetworkMatchesGlassesLocal"])
51
+ }
52
+
53
+ @Suppress("UNCHECKED_CAST")
54
+ private fun observation(snapshot: Map<String, Any?>, name: String) = snapshot[name] as Map<String, Any?>
55
+ }
@@ -37,7 +37,11 @@ class ScanCompletionTest {
37
37
  error("Legacy callbacks must not query diagnostics")
38
38
  }
39
39
  assertThat(completed).isTrue()
40
- assertThat(ScanCallback::class.java.declaredMethods.map { it.name })
40
+ // Instance methods only: Kotlin 2.2+ compiles bodies to Java default
41
+ // methods plus static `access$...$jd` bridges, which nothing implements.
42
+ assertThat(ScanCallback::class.java.declaredMethods
43
+ .filterNot { java.lang.reflect.Modifier.isStatic(it.modifiers) }
44
+ .map { it.name })
41
45
  .containsExactlyInAnyOrder("onResults", "onComplete", "onError")
42
46
  }
43
47
 
@@ -0,0 +1,112 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import androidx.test.core.app.ApplicationProvider
4
+ import com.mentra.bluetoothsdk.sgcs.G1PairingTest
5
+ import com.mentra.bluetoothsdk.sgcs.MentraLive
6
+ import java.util.concurrent.ConcurrentLinkedQueue
7
+ import com.mentra.bluetoothsdk.utils.K900ProtocolUtils
8
+ import com.mentra.bluetoothsdk.utils.K900LengthCodec
9
+ import org.robolectric.annotation.Implementation
10
+ import org.robolectric.annotation.Implements
11
+ import org.robolectric.shadow.api.Shadow
12
+ import org.robolectric.util.ReflectionHelpers.ClassParameter
13
+ import java.util.concurrent.atomic.AtomicLong
14
+ import org.json.JSONObject
15
+ import org.junit.Assert.*
16
+ import org.junit.Test
17
+ import org.junit.runner.RunWith
18
+ import org.robolectric.RobolectricTestRunner
19
+ import org.robolectric.annotation.Config
20
+
21
+ @RunWith(RobolectricTestRunner::class)
22
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class, TouchGestureCommandTest.ShadowK900Encoder::class], instrumentedPackages = ["com.mentra.lc3Lib"])
23
+ class TouchGestureCommandTest {
24
+ @Implements(K900ProtocolUtils::class)
25
+ class ShadowK900Encoder {
26
+ companion object {
27
+ var beforeEncode: (() -> Unit)? = null
28
+ @JvmStatic
29
+ @Implementation
30
+ fun packDataToK900(data: ByteArray, cmdType: Byte, endian: K900LengthCodec.Endian): ByteArray? {
31
+ beforeEncode?.invoke()
32
+ return Shadow.directlyOn(K900ProtocolUtils::class.java, "packDataToK900",
33
+ ClassParameter.from(ByteArray::class.java, data),
34
+ ClassParameter.from(Byte::class.javaPrimitiveType!!, cmdType),
35
+ ClassParameter.from(K900LengthCodec.Endian::class.java, endian))
36
+ }
37
+ }
38
+ }
39
+
40
+ @Test
41
+ fun `disconnect during encoding cannot promote touch setting into next session`() {
42
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
43
+ val live = MentraLive()
44
+ val connection = MentraLive::class.java.getDeclaredField("isConnected").apply { isAccessible = true }
45
+ connection.setBoolean(live, true)
46
+ val queue = MentraLive::class.java.getDeclaredField("sendQueue").apply { isAccessible = true }
47
+ .get(live) as ConcurrentLinkedQueue<*>
48
+ val generation = MentraLive::class.java.getDeclaredField("bleSessionGeneration").apply { isAccessible = true }
49
+ .get(live) as AtomicLong
50
+ val admittedGeneration = generation.get()
51
+ val reset = MentraLive::class.java.getDeclaredMethod("resetPendingAckState").apply { isAccessible = true }
52
+ ShadowK900Encoder.beforeEncode = {
53
+ connection.setBoolean(live, false)
54
+ reset.invoke(live)
55
+ queue.clear()
56
+ connection.setBoolean(live, true)
57
+ }
58
+ try {
59
+ live.sendTouchGestureDefaultBehaviorEnabled("old-session", TouchGesture.DOUBLE_TAP, false)
60
+ val queued = queue.poll()!!
61
+ val queuedGeneration = queued.javaClass.getDeclaredField("sessionGeneration").apply { isAccessible = true }.getLong(queued)
62
+ assertEquals(admittedGeneration, queuedGeneration)
63
+ assertNotEquals(generation.get(), queuedGeneration)
64
+ } finally { ShadowK900Encoder.beforeEncode = null }
65
+ }
66
+
67
+ @Test
68
+ fun `each gesture serializes independently and acknowledgements retain typed event values`() {
69
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
70
+ val live = MentraLive()
71
+ val connection = MentraLive::class.java.getDeclaredField("isConnected").apply { isAccessible = true }
72
+ connection.setBoolean(live, true)
73
+ val queue = MentraLive::class.java.getDeclaredField("sendQueue").apply { isAccessible = true }
74
+ .get(live) as ConcurrentLinkedQueue<*>
75
+ val receive = MentraLive::class.java.getDeclaredMethod("processK900JsonMessage", JSONObject::class.java)
76
+ .apply { isAccessible = true }
77
+ val events = mutableListOf<Map<String, Any>>()
78
+ val sink = Bridge.addEventSink { name, values -> if (name == "settings_ack") events.add(values) }
79
+ try {
80
+ for (gesture in TouchGesture.entries) for (enabled in listOf(false, true)) {
81
+ live.sendTouchGestureDefaultBehaviorEnabled("request-${gesture.wireName}-$enabled", gesture, enabled)
82
+ val queued = queue.poll()!!
83
+ val bytes = queued.javaClass.getDeclaredField("data").apply { isAccessible = true }.get(queued) as ByteArray
84
+ assertEquals('#'.code.toByte(), bytes[0])
85
+ assertEquals('$'.code.toByte(), bytes.last())
86
+ val envelope = JSONObject(String(bytes, 5, bytes.size - 7, Charsets.UTF_8))
87
+ assertEquals("cs_tpdef", envelope.getString("C"))
88
+ val body = JSONObject(envelope.getString("B"))
89
+ assertEquals(gesture.wireName, body.getString("gesture"))
90
+ assertEquals(enabled, body.getBoolean("enabled"))
91
+ val ack = JSONObject().put("type", "settings_ack").put("setting", "touch_gesture_default")
92
+ .put("status", "applied").put("request_id", body.getString("request_id"))
93
+ .put("gesture", gesture.wireName).put("enabled", enabled)
94
+ receive.invoke(live, JSONObject().put("C", "sr_tpdef").put("B", if (enabled) ack.toString() else ack))
95
+ assertEquals(body.getString("request_id"), events.last()["requestId"])
96
+ assertEquals(enabled, events.last()["enabled"])
97
+ assertEquals(gesture.wireName, events.last()["gesture"])
98
+ }
99
+ assertEquals(16, events.size)
100
+ } finally { Bridge.removeEventSink(sink) }
101
+ }
102
+
103
+ @Test
104
+ fun `invalid gesture and disconnected radio reject before sending`() {
105
+ assertThrows(BluetoothSdkException::class.java) { TouchGesture.fromWireName("unknown") }
106
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
107
+ val live = MentraLive()
108
+ assertThrows(BluetoothSdkException::class.java) {
109
+ live.sendTouchGestureDefaultBehaviorEnabled("request", TouchGesture.DOUBLE_TAP, false)
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,69 @@
1
+ package com.mentra.bluetoothsdk.debug
2
+
3
+ import java.util.UUID
4
+ import org.json.JSONArray
5
+ import org.json.JSONObject
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertFalse
8
+ import org.junit.Test
9
+ import org.junit.runner.RunWith
10
+ import org.robolectric.RobolectricTestRunner
11
+ import org.robolectric.annotation.Config
12
+ import org.robolectric.shadows.ShadowLog
13
+
14
+ @RunWith(RobolectricTestRunner::class)
15
+ @Config(sdk = [28])
16
+ class BleTraceLoggerTest {
17
+ @Test
18
+ fun wifiScanPreservesBooleanSecurityWhileRedactingCredentials() {
19
+ val secret = UUID.randomUUID().toString()
20
+ val networks = JSONArray()
21
+ for (secured in listOf(true, false)) {
22
+ networks.put(
23
+ JSONObject()
24
+ .put("ssid", if (secured) "secured-fixture" else "open-fixture")
25
+ .put("requiresPassword", secured)
26
+ .put("signalStrength", -45)
27
+ .put("password", secret)
28
+ .put("token", secret)
29
+ )
30
+ }
31
+ ShadowLog.clear()
32
+ BleTraceLogger.logJson(
33
+ "glasses_to_phone",
34
+ "sdk_ble_event",
35
+ JSONObject().put("type", "wifi_scan_result").put("networks_neo", networks),
36
+ )
37
+ val message = ShadowLog.getLogsForTag("MentraBleTrace").single().msg
38
+ assertFalse(message.contains(secret))
39
+ val actual = JSONObject(message.substringAfter("payload=")).getJSONArray("networks_neo")
40
+ for ((index, secured) in listOf(true, false).withIndex()) {
41
+ val item = actual.getJSONObject(index)
42
+ assertEquals(secured, item.get("requiresPassword"))
43
+ assertEquals(-45, item.getInt("signalStrength"))
44
+ assertEquals("<redacted>", item.getString("password"))
45
+ assertEquals("<redacted>", item.getString("token"))
46
+ }
47
+ }
48
+
49
+ @Test
50
+ fun exceptionDoesNotExposeNonBooleanOrOtherPasswordFields() {
51
+ val secret = UUID.randomUUID().toString()
52
+ ShadowLog.clear()
53
+ BleTraceLogger.logJson(
54
+ "glasses_to_phone",
55
+ "sdk_ble_event",
56
+ JSONObject()
57
+ .put("type", "wifi_scan_result")
58
+ .put("requiresPassword", secret)
59
+ .put("password", true)
60
+ .put("RequiresPassword", false),
61
+ )
62
+ val message = ShadowLog.getLogsForTag("MentraBleTrace").single().msg
63
+ assertFalse(message.contains(secret))
64
+ val actual = JSONObject(message.substringAfter("payload="))
65
+ for (key in listOf("requiresPassword", "password", "RequiresPassword")) {
66
+ assertEquals("<redacted>", actual.getString(key))
67
+ }
68
+ }
69
+ }