@mentra/bluetooth-sdk 3.3.0-dev.943 → 3.4.0-dev.1003

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 (100) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +78 -0
  3. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +274 -0
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +13 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +8 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +79 -8
  7. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +22 -4
  11. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +832 -134
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +337 -39
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +8 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +1 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  25. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +16 -0
  26. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  30. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  37. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +564 -1
  38. package/build/BluetoothSdk.types.d.ts +110 -2
  39. package/build/BluetoothSdk.types.d.ts.map +1 -1
  40. package/build/BluetoothSdk.types.js.map +1 -1
  41. package/build/_private/BluetoothSdkModule.d.ts +6 -2
  42. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  43. package/build/_private/BluetoothSdkModule.js +1 -0
  44. package/build/_private/BluetoothSdkModule.js.map +1 -1
  45. package/build/generated/changelogCatalog.d.ts +3 -0
  46. package/build/generated/changelogCatalog.d.ts.map +1 -1
  47. package/build/generated/changelogCatalog.js +4 -0
  48. package/build/generated/changelogCatalog.js.map +1 -1
  49. package/build/generated/releaseMetadata.js +6 -6
  50. package/build/generated/releaseMetadata.js.map +1 -1
  51. package/build/index.d.ts +1 -1
  52. package/build/index.d.ts.map +1 -1
  53. package/build/index.js +4 -0
  54. package/build/index.js.map +1 -1
  55. package/ios/BluetoothSdkModule.swift +24 -4
  56. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  57. package/ios/Source/Bridge.swift +11 -3
  58. package/ios/Source/DeviceManager.swift +103 -7
  59. package/ios/Source/DeviceStore.swift +27 -0
  60. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  61. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  62. package/ios/Source/MentraBluetoothSDK.swift +41 -7
  63. package/ios/Source/TouchGesture.swift +13 -0
  64. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  65. package/ios/Source/events/BluetoothEvents.swift +4 -0
  66. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  67. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +181 -0
  68. package/ios/Source/sgcs/MentraLive.swift +1196 -173
  69. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  70. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  71. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  72. package/ios/Source/sgcs/Nimo.swift +278 -38
  73. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +77 -18
  74. package/ios/Source/sgcs/NimoCanvasSession.swift +1 -0
  75. package/ios/Source/sgcs/NimoMacResourceTransport.swift +217 -0
  76. package/ios/Source/sgcs/NimoResourceFixture.swift +384 -0
  77. package/ios/Source/sgcs/NimoResourceSession.swift +406 -0
  78. package/ios/Source/sgcs/SGCManager.swift +7 -0
  79. package/ios/Source/sgcs/Simulated.swift +2 -0
  80. package/ios/Source/status/DeviceStatus.swift +35 -0
  81. package/ios/Source/types/DeviceModels.swift +8 -1
  82. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  83. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  84. package/ios/Tests/DeviceManagerReconnectTests.swift +75 -2
  85. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +191 -0
  86. package/ios/Tests/MentraLiveAudioSetupTests.swift +215 -0
  87. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  88. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  89. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  90. package/ios/Tests/MentraLiveSessionReadinessTests.swift +328 -26
  91. package/ios/Tests/NimoCanvasTransportTests.swift +147 -0
  92. package/ios/Tests/NimoResourceSessionTests.swift +476 -0
  93. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  94. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  95. package/package.json +3 -2
  96. package/src/BluetoothSdk.types.ts +115 -1
  97. package/src/_private/BluetoothSdkModule.ts +7 -1
  98. package/src/generated/changelogCatalog.ts +4 -0
  99. package/src/generated/releaseMetadata.ts +6 -6
  100. package/src/index.ts +12 -0
package/MIGRATION.md ADDED
@@ -0,0 +1,61 @@
1
+ # Bluetooth SDK migration: Mentra Live pairing state
2
+
3
+ This note covers the public pairing API in `@mentra/bluetooth-sdk` `3.3.0` relative to the published `3.2.1` package. `3.3.0` is the current release family in `package.json` and is not on npm yet.
4
+
5
+ ## Version
6
+
7
+ The SDK version is `package.json` `"version"`. The iOS podspec (`ios/MentraBluetoothSDK.podspec`) and the Android Gradle module (`android/build.gradle`) read that same value. Swift package metadata is injected from it at pack time.
8
+
9
+ This repository keeps the Bluetooth SDK version aligned with the matching Mentra Live software release. It does not cut an independent major for a breaking SDK change. The break below ships in the unpublished `3.3.0` family. No further version bump was applied in this change. Integrators on `3.2.1` pick it up by moving to `3.3.0` when that release is published.
10
+
11
+ ## Removed
12
+
13
+ - `confirmReplaceOwner()` is removed.
14
+ - The `confirm_replace_owner_result` event and its types are removed.
15
+ - `owner_replaced` is deprecated and is never emitted. Remove listeners. Use `pairing_state_changed` or `GlassesStatus.pairingState`.
16
+ - `pairing_info` no longer includes `awaiting_confirm` or `retained_owner_link`.
17
+
18
+ ## Added
19
+
20
+ `GlassesStatus.pairingState` (absent on models other than Mentra Live):
21
+
22
+ ```ts
23
+ type MentraLivePairingState =
24
+ | {state: "normal"}
25
+ | {state: "pairing_mode"; windowId: number; endsAtMs: number}
26
+ | {state: "pairing_rejected"}
27
+ ```
28
+
29
+ | State | What to do |
30
+ | --- | --- |
31
+ | `normal` | Automatic reconnect is allowed. |
32
+ | `pairing_mode` | A pairing window is open. Leave reconnect paused until `endsAtMs`. That timestamp is the window plus a 30-second margin. `windowId` identifies the window and survives a cold start. |
33
+ | `pairing_rejected` | The glasses no longer accept this phone (another phone paired, or repeated authentication rejections on secure-pairing firmware). Reconnect has stopped. Show **Pair Again**. This clears only after a successful explicit `connect()` / `connectDefault()`, or after `forget()`. |
34
+
35
+ `useMentraBluetooth().glasses` does not include `pairingState`. Read `getGlassesStatus()`, `subscribeGlassesStatus()`, or the `pairing_state_changed` event (`{state: MentraLivePairingState}`).
36
+
37
+ `GlassesStatus.audioSetup` (every model) says whether the user has to do anything for glasses audio:
38
+
39
+ ```ts
40
+ type GlassesAudioSetupState =
41
+ | {state: "idle"}
42
+ | {state: "not_applicable"}
43
+ | {state: "connecting"}
44
+ | {state: "connected"}
45
+ | {state: "needs_user"; action: "connect_in_settings"}
46
+ ```
47
+
48
+ Render `needs_user` as a step that sends the user to Settings > Bluetooth, and treat `connected` and `not_applicable` as done. The SDK owns the waits (on iPhone: up to 8 seconds after a pair on firmware with `auto_audio`, none on older firmware, 10 seconds after a reconnect). Remove any app-side audio timers or `pairing_info.auto_audio` checks. Changes also arrive as `audio_setup_changed` (`{state: GlassesAudioSetupState}`).
49
+
50
+ Other additions:
51
+
52
+ - `entering_pairing_mode` includes `window_id` (same window as `pairingState.windowId`).
53
+ - `pairing_mode_ended` fires when the glasses close the window and this phone is still accepted. `reason` is `"paired"`, `"cancelled"`, or `"timeout"`. Optional `window_id`. The previous phone does not get this event when another phone pairs; it moves to `pairing_rejected`.
54
+ - `pairing_info.auto_audio` is true when the glasses derive Classic audio from the LE pair (CTKD). The SDK already uses it for `audioSetup`.
55
+ - `pair_failure.code` may be `"ios_forget_pairing"`: iOS holds a stale Bluetooth pairing for these glasses during an explicit attempt. The user must open Settings > Bluetooth, choose Forget This Device, then pair again. On Android and iOS native apps this arrives as the pairing-failure error's `failureCode`.
56
+
57
+ ## Behavior
58
+
59
+ On supported Mentra Live firmware, three presses of the power button open one 120-second pairing window. The glasses speak a 4-character code. Three presses again cancel the window. After a timeout or a cancel, the phone that was already paired reconnects automatically. If another phone pairs, that previous phone gets `pairing_rejected`. Pairing readiness needs no app-side `pairing_info` wait: the SDK reports the glasses ready only after secure firmware commits the bond, and treats glasses that send no `pairing_info` within 5 seconds as older firmware.
60
+
61
+ User-facing sample copy should say "Pair Again". Do not say "owner" in that copy. API fields such as `owner_retained`, `owner_committed`, and `ownership_transfer` are unchanged identifiers on `entering_pairing_mode` and `pairing_info`.
package/README.md CHANGED
@@ -448,6 +448,51 @@ await BluetoothSdk.clearDefaultDevice()
448
448
  await saveDeviceToYourAppStorage(null)
449
449
  ```
450
450
 
451
+ ## Mentra Live pairing
452
+
453
+ `confirmReplaceOwner()` and `confirm_replace_owner_result` are removed. `owner_replaced` is deprecated and is never emitted. The replacement is `GlassesStatus.pairingState`, also delivered as `pairing_state_changed`. Full steps are in [MIGRATION.md](./MIGRATION.md). The version stays `3.3.0` in `package.json` (podspec and Gradle read it). npm still publishes `3.2.1`.
454
+
455
+ On supported Mentra Live firmware, three power-button presses open one 120-second window and the glasses speak a 4-character code. Three presses again cancel it. The phone that was already paired pauses automatic reconnect for that window plus a 30-second margin (`pairingState.endsAtMs`), then reconnects after `pairing_mode_ended` with `reason` `"timeout"` or `"cancelled"`. If the glasses stop accepting this phone (another phone paired, or repeated authentication rejections on secure-pairing firmware), this phone's state becomes `pairing_rejected`: reconnect stops, and the UI should show Pair Again. That state clears only after a successful explicit pair or `forget()`.
456
+
457
+ `useMentraBluetooth().glasses` does not include `pairingState`. Read `getGlassesStatus()`, `subscribeGlassesStatus()`, or:
458
+
459
+ ```ts
460
+ BluetoothSdk.addListener("pairing_state_changed", (event) => {
461
+ if (event.state.state === "pairing_rejected") showPairAgain()
462
+ })
463
+
464
+ BluetoothSdk.addListener("pair_failure", (event) => {
465
+ if (event.code === "ios_forget_pairing") {
466
+ // iOS still has a Bluetooth pairing for these glasses.
467
+ // Settings > Bluetooth > Forget This Device, then pair again.
468
+ }
469
+ })
470
+ ```
471
+
472
+ `entering_pairing_mode` includes `window_id`. `pairing_info` includes `auto_audio` and no longer includes `awaiting_confirm` or `retained_owner_link`. Do not use the word "owner" in user-facing sample copy.
473
+
474
+ ## Glasses audio setup
475
+
476
+ `GlassesStatus.audioSetup`, also delivered as `audio_setup_changed` (`{state}`), says whether the user has to do anything to get glasses audio working. The SDK decides it for every glasses model. Render it; do not add your own audio timers or platform checks.
477
+
478
+ | `audioSetup.state` | Meaning | What to show |
479
+ | --- | --- | --- |
480
+ | `idle` | No glasses session | Nothing |
481
+ | `not_applicable` | No audio step (Android attaches audio from the BLE bond; glasses without Classic audio) | Nothing |
482
+ | `connecting` | Glasses connected, audio expected to come up on its own | A "connecting" state |
483
+ | `connected` | Classic audio (A2DP or HFP) is up | Nothing |
484
+ | `needs_user` | Audio did not come up on its own (`action: "connect_in_settings"`) | Ask the user to connect the glasses in Settings > Bluetooth |
485
+
486
+ On iPhone, after a pair the SDK waits up to 8 seconds on firmware that brings audio up from the BLE pair and reports `needs_user` at once on older firmware. After a reconnect it waits 10 seconds. The state moves to `connected` as soon as audio comes up. Mentra Live firmware that reports its own audio link (`classic_link`) is preferred over the phone's audio route, which is wrong while another Bluetooth audio device holds it.
487
+
488
+ ```ts
489
+ BluetoothSdk.addListener("audio_setup_changed", (event) => {
490
+ if (event.state.state === "needs_user") showConnectAudioInSettings()
491
+ })
492
+ ```
493
+
494
+ `useMentraBluetooth().glasses` does not include `audioSetup`. Read `getGlassesStatus()`, `subscribeGlassesStatus()`, or the event.
495
+
451
496
  ## Native notification controls
452
497
 
453
498
  G2 exposes firmware-owned notification history and popups. `getNativeNotificationStatus()` reports support, source (`phone` on Android or `ancs` on iOS), authorization, the desired controls, and submission/failure state. `submitted` means the controls were queued for the glasses, not that firmware acknowledged them. Unsupported drivers reject configuration instead of silently succeeding.
@@ -751,6 +796,39 @@ export function HardwareEventLogger() {
751
796
 
752
797
  For non-React modules, `BluetoothSdk.addListener(...)` is the low-level subscription API. Keep the returned subscription and call `remove()` when the listener is no longer needed.
753
798
 
799
+ Common event names include `button_press`, `touch_event`, `head_up`, `battery_status`, `wifi_status_change`, `wifi_scan_result`, `hotspot_status_change`, `photo_status`, `photo_response`, `gallery_status`, `settings_ack`, `version_info`, `stream_status`, `ota_start_ack`, `ota_status`, `mic_pcm`, `mic_lc3`, `mic_health`, `local_transcription`, `rgb_led_control_response`, `pair_failure`, `pairing_info`, `entering_pairing_mode`, `pairing_mode_ended`, `pairing_state_changed`, `audio_connected`, `audio_disconnected`, and `log`. `owner_replaced` remains in the type map and is never emitted.
800
+
801
+ ### Claiming touchpad gestures
802
+
803
+ On Mentra Live, disable a gesture's stock action before using it in your app:
804
+
805
+ ```ts
806
+ await BluetoothSdk.setTouchGestureDefaultBehaviorEnabled("double_tap", false)
807
+ // double_tap events still reach useBluetoothEvent("touch_event", ...).
808
+ // Restore play/pause when your app releases the gesture:
809
+ await BluetoothSdk.setTouchGestureDefaultBehaviorEnabled("double_tap", true)
810
+ ```
811
+
812
+ The supported names are `single_tap`, `double_tap`, `triple_tap`, `long_press`,
813
+ `forward_swipe`, `backward_swipe`, `up_swipe`, and `down_swipe`. Each setting
814
+ changes only that gesture. Stock media actions (play/pause, volume, previous/next
815
+ track) and gesture feedback are suppressed; the gesture event itself is still
816
+ sent. This applies on both Android and iOS, without claiming a phone media player
817
+ or relying on remote media-key interception.
818
+
819
+ Overrides are RAM-only on the glasses and reset to the normal stock behavior on
820
+ BLE disconnect or reboot. Set them again after reconnecting. They do not change
821
+ camera-button behavior or gallery mode. Gestures without a stock action still
822
+ produce events. On native Android use `TouchGesture.DOUBLE_TAP`; on native iOS
823
+ use `.doubleTap` with `setTouchGestureDefaultBehaviorEnabled(_:enabled:)`.
824
+
825
+ This requires BES firmware implementing `cs_tpdef` / `sr_tpdef`. The promise
826
+ resolves only after the matching firmware `settings_ack` with
827
+ `setting: "touch_gesture_default"`, `gesture`, and `enabled`. Unsupported devices
828
+ and invalid gesture names reject. Older firmware cannot suppress these actions
829
+ and will time out; do not treat that timeout as success. A release containing this
830
+ SDK API alone does not update BES firmware.
831
+
754
832
  Common event names include `button_press`, `touch_event`, `head_up`, `battery_status`, `wifi_status_change`, `wifi_scan_result`, `hotspot_status_change`, `photo_status`, `photo_response`, `gallery_status`, `settings_ack`, `version_info`, `stream_status`, `ota_start_ack`, `ota_status`, `mic_pcm`, `mic_lc3`, `mic_health`, `local_transcription`, `rgb_led_control_response`, `audio_connected`, `audio_disconnected`, and `log`.
755
833
 
756
834
  React Native event payload fields usually use camelCase. OTA events intentionally mirror the glasses firmware field names, such as `overall_percent` and `version_name`. For example, `touch_event` includes `gestureName`, `wifi_scan_result` includes `networks` and `scanComplete`, `version_info` matches the `requestVersionInfo()` result shape, `photo_response` success includes `uploadUrl` and may include webhook-returned `photoUrl`, `statusUrl`, `contentType`, and `fileSizeBytes`, and `gallery_status` includes `hasContent`, `cameraBusy`, and optional `cameraBusyReason`. `photo_status` reports intermediate photo states such as `accepted`, `queued`, `configuring`, `capturing`, `captured`, `compressing`, `ble_fallback_compression`, `uploading`, `ready_for_transfer`, `transferring`, and `failed`; the `configuring` event includes `resolvedConfig` with the effective JPEG dimensions, quality, requested size, transfer method, compression, and manual exposure fields when present. The `capturing` event may include `requestedCaptureConfig` and `meteredPreview`; the `captured` event may include `captureMetadata` with the HAL-applied exposure, ISO, frame duration, and AE state. `mic_pcm` includes `sampleRate`, `bitsPerSample`, `channels`, and `encoding`; `mic_lc3` includes `sampleRate`, `channels`, `encoding`, `frameDurationMs`, `frameSizeBytes`, `bitrate`, and `packetizedFromGlasses`.
@@ -0,0 +1,274 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.content.IntentFilter
7
+ import android.os.Build
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.os.Process
11
+ import android.os.SystemClock
12
+ import com.mentra.bluetoothsdk.BuildConfig
13
+ import com.mentra.bluetoothsdk.DeviceManager
14
+ import org.json.JSONObject
15
+ import java.io.File
16
+ import java.lang.ref.WeakReference
17
+ import java.util.UUID
18
+
19
+ /** Fixed, DUMP-protected debug commands. Expected address is comparison-only, never a connection target.
20
+ * No packet, device-command, caller path, reset, bond or radio inputs are accepted. */
21
+ internal object NimoResourceDiagnostics {
22
+ const val CLOCK_PROTOCOL = "nimo-monotonic-receipt-v1"
23
+ const val ACTION = "com.mentra.bluetoothsdk.NIMO_RESOURCE_LIFECYCLE"
24
+ private val main = Handler(Looper.getMainLooper())
25
+ private val processInstanceId = UUID.randomUUID().toString()
26
+ private data class Observed(val instance: WeakReference<Nimo>, var tombstone: JSONObject)
27
+ private val sessions = linkedMapOf<String, Observed>()
28
+ private var registered = false
29
+ private var application: Context? = null
30
+ private val requests = linkedSetOf<String>()
31
+ private data class Capture(val nonce: String, val name: String, val address: String,
32
+ var instance: Nimo? = null, var cancelled: Boolean = false, var connectStarted: Boolean = false,
33
+ var transportStarted: Boolean = false, val armedElapsedMs: Long,
34
+ var admittedElapsedMs: Long? = null)
35
+ // One diagnostic attempt per app process. Cancellation is a process-lifetime fence.
36
+ @Volatile private var capture: Capture? = null
37
+ internal fun preArmCaptureRequired(buildType: String = BuildConfig.BUILD_TYPE): Boolean = buildType == "nimoDiagnostic"
38
+ internal fun allowUnarmedWearable(buildType: String, wearable: String): Boolean =
39
+ !preArmCaptureRequired(buildType) || !wearable.contains("NIMO", ignoreCase = true)
40
+
41
+
42
+ /** Debug entries share the main admission queue even before arm, so a call that
43
+ * starts just before arm cannot resume effects past it. Release builds are no-op.
44
+ * Queued calls re-enter current capture guards before any connection effect. */
45
+ fun dispatchCapturedEntry(entry: () -> Unit): Boolean {
46
+ if (!preArmCaptureRequired() && capture == null) return false
47
+ if (Looper.myLooper() == main.looper) return false
48
+ val task = java.util.concurrent.FutureTask<Unit> { entry() }
49
+ main.post(task)
50
+ try {
51
+ task.get()
52
+ } catch (error: java.util.concurrent.ExecutionException) {
53
+ throw (error.cause ?: error)
54
+ } catch (error: InterruptedException) {
55
+ // A queued entry must not run later after its original caller abandoned it.
56
+ task.cancel(false)
57
+ Thread.currentThread().interrupt()
58
+ throw error
59
+ }
60
+ return true
61
+ }
62
+
63
+ @Synchronized
64
+ fun allowManagerConnect(wearable: String, name: String? = null): Boolean {
65
+ val owned = capture ?: return allowUnarmedWearable(BuildConfig.BUILD_TYPE, wearable)
66
+ if (Looper.myLooper() != main.looper) return false
67
+ if (!wearable.contains("NIMO", ignoreCase = true)) return true
68
+ val current = DeviceManager.getInstance().sgc
69
+ return !owned.cancelled && (name == null || !owned.connectStarted && name == owned.name) &&
70
+ (current == null || current is Nimo && (owned.instance === current ||
71
+ owned.instance == null && current.resourceCaptureEligible()))
72
+ }
73
+
74
+ /** Scan-to-connect is one captured attempt: never destroy or transfer its instance. */
75
+ @Synchronized
76
+ fun preserveCapturedScan(wearable: String, name: String): Boolean {
77
+ val owned = capture ?: return false
78
+ if (Looper.myLooper() != main.looper || !wearable.contains("NIMO", ignoreCase = true) ||
79
+ owned.cancelled || owned.connectStarted || name != owned.name) return false
80
+ val original = owned.instance ?: return false
81
+ return DeviceManager.getInstance().sgc === original &&
82
+ original.resourceSnapshot().getLong("sessionGeneration") == 0L
83
+ }
84
+
85
+ @Synchronized
86
+ fun admit(instance: Nimo, name: String?, connect: Boolean): Boolean {
87
+ val owned = capture ?: return !preArmCaptureRequired()
88
+ if (Looper.myLooper() != main.looper) return false
89
+ if (!allowManagerConnect("NIMO", name) || DeviceManager.getInstance().sgc !== instance ||
90
+ owned.instance != null && owned.instance !== instance || owned.connectStarted) return false
91
+ if (owned.instance == null) {
92
+ if (!instance.resourceCaptureEligible()) return false
93
+ val candidateAdmittedElapsedMs = SystemClock.elapsedRealtime()
94
+ owned.instance = instance
95
+ // Immutable admission survives a setup timeout before any GATT session exists.
96
+ val app = application ?: run { owned.cancelled = true; return false }
97
+ val root = File(app.filesDir, "nimo-lifecycle")
98
+ val target = File(root, "${owned.nonce}.admission.json")
99
+ if (target.exists()) { owned.cancelled = true; return false }
100
+ val pending = File(root, "${owned.nonce}.admission.tmp")
101
+ try {
102
+ pending.outputStream().use { it.write(captureSnapshot(owned, candidateAdmittedElapsedMs).toString().toByteArray(Charsets.UTF_8)); it.flush() }
103
+ check(pending.renameTo(target))
104
+ // Durable admission is authoritative; no live clock may claim it
105
+ // before the original immutable receipt is safely committed.
106
+ instance.resourceCaptureAdmission(owned.nonce, owned.armedElapsedMs, candidateAdmittedElapsedMs)
107
+ owned.admittedElapsedMs = candidateAdmittedElapsedMs
108
+ } catch (_: Exception) {
109
+ owned.cancelled = true
110
+ return false
111
+ } finally { pending.delete() }
112
+ }
113
+ if (connect) owned.connectStarted = true
114
+ return true
115
+ }
116
+
117
+ @Synchronized
118
+ fun allowPeer(instance: Nimo, address: String, bonded: Boolean): Boolean {
119
+ val owned = capture ?: return !preArmCaptureRequired()
120
+ if (Looper.myLooper() != main.looper) return false
121
+ return !owned.cancelled && owned.instance === instance && address == owned.address && bonded &&
122
+ DeviceManager.getInstance().sgc === instance
123
+ }
124
+
125
+ @Synchronized
126
+ fun beginTransport(instance: Nimo, address: String, bonded: Boolean): Boolean {
127
+ val owned = capture ?: return !preArmCaptureRequired()
128
+ if (Looper.myLooper() != main.looper) return false
129
+ if (!allowPeer(instance, address, bonded) || owned.transportStarted) return false
130
+ owned.transportStarted = true
131
+ return true
132
+ }
133
+
134
+ @Synchronized
135
+ private fun captureSnapshot(owned: Capture, admittedElapsedMs: Long? = owned.admittedElapsedMs): JSONObject = JSONObject()
136
+ .put("clockProtocol", CLOCK_PROTOCOL)
137
+ .put("clock", JSONObject().put("kind", "android-elapsed-realtime-v1").put("armedElapsedMs", owned.armedElapsedMs)
138
+ .put("admittedElapsedMs", admittedElapsedMs ?: JSONObject.NULL).put("observedElapsedMs", SystemClock.elapsedRealtime()))
139
+ .put("version", "nimo-preconnect-capture-v1").put("nonce", owned.nonce)
140
+ .put("captureRequiredBeforeArm", preArmCaptureRequired())
141
+ .put("expectedPair", JSONObject().put("name", owned.name).put("bluetoothAddress", owned.address))
142
+ .put("instanceId", owned.instance?.resourceInstanceId ?: JSONObject.NULL)
143
+ .put("sessionGeneration", owned.instance?.resourceSnapshot()?.getLong("sessionGeneration") ?: JSONObject.NULL)
144
+ .put("observedPair", if (owned.transportStarted) owned.instance?.resourceSnapshot()?.getJSONObject("pair") ?: JSONObject.NULL else JSONObject.NULL)
145
+ .put("cancelled", owned.cancelled).put("connectStarted", owned.connectStarted)
146
+ .put("transportStarted", owned.transportStarted)
147
+ .put("appPid", Process.myPid()).put("processInstanceId", processInstanceId)
148
+ .put("observedAtEpochMs", System.currentTimeMillis())
149
+
150
+
151
+ fun start(context: Context) {
152
+ if (Looper.myLooper() != main.looper) { main.post { start(context) }; return }
153
+ if (registered) return
154
+ val app = context.applicationContext
155
+ val filter = IntentFilter(ACTION)
156
+ if (Build.VERSION.SDK_INT >= 33) app.registerReceiver(receiver, filter, "android.permission.DUMP", main, Context.RECEIVER_EXPORTED)
157
+ else { @Suppress("DEPRECATION") app.registerReceiver(receiver, filter, "android.permission.DUMP", main) }
158
+ application = app
159
+ registered = true
160
+ }
161
+
162
+ fun track(instance: Nimo) {
163
+ check(Looper.myLooper() == main.looper)
164
+ val snapshot = instance.resourceSnapshot()
165
+ sessions["${instance.resourceInstanceId}:${snapshot.getLong("sessionGeneration")}"] = Observed(WeakReference(instance), snapshot)
166
+ while (sessions.size > 8) sessions.remove(sessions.keys.first())
167
+ }
168
+
169
+ private val receiver = object : BroadcastReceiver() {
170
+ override fun onReceive(context: Context?, intent: Intent?) {
171
+ if (intent?.action != ACTION) return
172
+ try { execute(intent) } catch (_: Exception) { /* No receipt means unknown; never crash the product app. */ }
173
+ }
174
+ }
175
+
176
+ /** Separate from BroadcastReceiver for source tests; no exported unrestricted app API. */
177
+ @Synchronized
178
+ internal fun execute(intent: Intent) {
179
+ check(Looper.myLooper() == main.looper)
180
+ val requestReceivedElapsedMs = SystemClock.elapsedRealtime()
181
+ val nonce = intent.getStringExtra("nonce") ?: return
182
+ if (!uuid(nonce) || nonce in requests) return
183
+ val app = application ?: return
184
+ val root = File(app.filesDir, "nimo-lifecycle")
185
+ if ((!root.isDirectory && !root.mkdir()) || File(root, "$nonce.json").exists()) return
186
+ requests.add(nonce)
187
+ while (requests.size > 128) requests.remove(requests.first())
188
+ val mode = intent.getStringExtra("mode") ?: "status"
189
+ val address = intent.getStringExtra("expectedAddress") ?: ""
190
+ val instanceId = intent.getStringExtra("instanceId")
191
+ val generation = intent.getLongExtra("sessionGeneration", -1)
192
+ val request = JSONObject().put("nonce", nonce).put("mode", mode).put("expectedAddress", address)
193
+ .put("instanceId", instanceId ?: JSONObject.NULL).put("sessionGeneration", if (generation >= 0) generation else JSONObject.NULL)
194
+ fun save(session: JSONObject?, error: String? = null): Boolean {
195
+ val current = DeviceManager.getInstance().sgc
196
+ val receipt = JSONObject().put("clockProtocol", CLOCK_PROTOCOL)
197
+ .put("clock", JSONObject().put("kind", "android-elapsed-realtime-v1").put("requestReceivedElapsedMs", requestReceivedElapsedMs).put("observedElapsedMs", SystemClock.elapsedRealtime()))
198
+ .put("schemaVersion", 1).put("request", request).put("observedAtEpochMs", System.currentTimeMillis())
199
+ .put("appPid", Process.myPid()).put("processInstanceId", processInstanceId)
200
+ .put("currentManager", JSONObject().put("type", current?.type ?: JSONObject.NULL)
201
+ .put("instanceId", (current as? Nimo)?.resourceInstanceId ?: JSONObject.NULL))
202
+ .put("session", session ?: JSONObject.NULL).put("error", error ?: JSONObject.NULL)
203
+ val pending = File(root, "$nonce.tmp")
204
+ try {
205
+ pending.outputStream().use { it.write(receipt.toString().toByteArray(Charsets.UTF_8)); it.flush() }
206
+ check(pending.renameTo(File(root, "$nonce.json")))
207
+ return true
208
+ } catch (_: Exception) { return false /* Absent receipt is unknown. */ } finally { pending.delete() }
209
+ }
210
+ if (mode in listOf("arm-capture", "capture-status", "cancel-capture")) {
211
+ val expectedName = intent.getStringExtra("expectedName")
212
+ val captureNonce = intent.getStringExtra("captureNonce")
213
+ request.remove("instanceId"); request.remove("sessionGeneration")
214
+ request.put("expectedName", expectedName ?: JSONObject.NULL).put("captureNonce", captureNonce ?: JSONObject.NULL)
215
+ if (!Regex("^[0-9A-F]{2}(:[0-9A-F]{2}){5}$").matches(address) ||
216
+ intent.extras?.keySet()?.any { it !in setOf("nonce", "mode", "expectedAddress", "expectedName", "captureNonce") } == true ||
217
+ expectedName == null || !Regex("^Nimo-[A-Za-z0-9]{1,32}$").matches(expectedName) ||
218
+ captureNonce == null || !uuid(captureNonce)) { save(null, "invalid-fixed-capture-request"); return }
219
+ if (mode == "arm-capture") {
220
+ val manager = DeviceManager.getInstance().sgc
221
+ if (capture != null || captureNonce != nonce || manager != null) {
222
+ save(null, "capture-arm-refused-existing-owner"); return
223
+ }
224
+ capture = Capture(captureNonce, expectedName, address, armedElapsedMs = requestReceivedElapsedMs)
225
+ }
226
+ val owned = capture
227
+ if (owned == null || owned.nonce != captureNonce || owned.name != expectedName || owned.address != address) {
228
+ save(null, "capture-not-original"); return
229
+ }
230
+ fun captureReceipt(session: JSONObject? = null, error: String? = null): Boolean {
231
+ return save(JSONObject().put("capture", captureSnapshot(owned)).put("originalSession", session ?: JSONObject.NULL), error)
232
+ }
233
+ if (mode != "cancel-capture") {
234
+ if (!captureReceipt(owned.instance?.resourceSnapshot()) && mode == "arm-capture") owned.cancelled = true
235
+ return
236
+ }
237
+ owned.cancelled = true // fence before draining or emitting a no-admission receipt
238
+ val original = owned.instance
239
+ if (original == null) { captureReceipt(); return }
240
+ if (DeviceManager.getInstance().sgc !== original) { captureReceipt(original.resourceSnapshot(), "capture-cancel-refused-replacement"); return }
241
+ original.releaseCapturedResource({ DeviceManager.getInstance().sgc === original }, { result -> captureReceipt(result) }, nonce, requestReceivedElapsedMs)
242
+ return
243
+ }
244
+ if (mode !in listOf("status", "release") || !Regex("^[0-9A-F]{2}(:[0-9A-F]{2}){5}$").matches(address) ||
245
+ instanceId != null && !uuid(instanceId) || intent.extras?.keySet()?.any { it !in setOf("nonce", "mode", "expectedAddress", "instanceId", "sessionGeneration") } == true) {
246
+ save(null, "invalid-fixed-request"); return
247
+ }
248
+ val current = DeviceManager.getInstance().sgc as? Nimo
249
+ current?.let { track(it) }
250
+ val selected = if (instanceId != null) sessions["$instanceId:$generation"] else sessions.values.lastOrNull {
251
+ it.tombstone.getJSONObject("pair").optString("bluetoothAddress") == address
252
+ }
253
+ val candidate = selected?.instance?.get()
254
+ val live = candidate?.resourceSnapshot()
255
+ val instance = candidate?.takeIf { live?.optLong("sessionGeneration") == selected?.tombstone?.optLong("sessionGeneration") }
256
+ val snapshot = if (instance != null) live else selected?.tombstone
257
+ if (snapshot == null || snapshot.getJSONObject("pair").optString("bluetoothAddress") != address ||
258
+ generation >= 0 && snapshot.optLong("sessionGeneration", -1) != generation) {
259
+ save(null, "target-not-observed-or-generation-mismatch"); return
260
+ }
261
+ if (mode == "status") {
262
+ save(JSONObject(snapshot.toString()).put("sessionObservationCurrent", instance != null).put("source", if (instance != null) "live-original-instance" else "retained-tombstone")); return
263
+ }
264
+ if (instanceId == null || generation < 1 || instance == null || instance !== current) {
265
+ save(snapshot, "release-refused-replaced-or-unowned-target"); return
266
+ }
267
+ instance.releaseResource(generation, { DeviceManager.getInstance().sgc === instance }, { result ->
268
+ track(instance)
269
+ if (result.has("error")) save(instance.resourceSnapshot(), result.getString("error")) else save(result)
270
+ }, nonce, requestReceivedElapsedMs)
271
+ }
272
+
273
+ private fun uuid(value: String): Boolean = try { UUID.fromString(value).toString() == value } catch (_: IllegalArgumentException) { false }
274
+ }
@@ -310,7 +310,9 @@ class BluetoothSdkModule : Module() {
310
310
  }
311
311
 
312
312
  override fun onError(error: BluetoothError) {
313
- sendEvent("pair_failure", mapOf("error" to error.message))
313
+ val body = mutableMapOf<String, Any>("error" to error.message)
314
+ error.failureCode?.let { body["code"] = it }
315
+ sendEvent("pair_failure", body)
314
316
  }
315
317
 
316
318
  override fun onRawEvent(eventName: String, values: Map<String, Any>) {
@@ -379,6 +381,9 @@ class BluetoothSdkModule : Module() {
379
381
  "pair_failure",
380
382
  "pairing_info",
381
383
  "entering_pairing_mode",
384
+ "pairing_mode_ended",
385
+ "pairing_state_changed",
386
+ "audio_setup_changed",
382
387
  "owner_replaced",
383
388
  "audio_pairing_needed",
384
389
  "audio_connected",
@@ -652,8 +657,9 @@ class BluetoothSdkModule : Module() {
652
657
  requireSdk().setHotspotState(enabled).values
653
658
  }
654
659
 
655
- SdkAsyncFunction("setWifiAdbState") { enabled: Boolean ->
656
- sdk?.setWifiAdbState(enabled)
660
+ SdkAsyncFunction("setWifiAdbState") { enabled: Boolean, expectedBluetoothMac: String? ->
661
+ val current = sdk ?: throw BluetoothSdkException("glasses_not_connected", "Bluetooth SDK is unavailable.")
662
+ current.setWifiAdbState(enabled, expectedBluetoothMac)
657
663
  }
658
664
 
659
665
  SdkAsyncFunction("setSystemTime") { timestampMs: Double ->
@@ -666,6 +672,10 @@ class BluetoothSdkModule : Module() {
666
672
  requireSdk().setGalleryServerEnabled(enabled).values
667
673
  }
668
674
 
675
+ SdkCoroutineFunction("setTouchGestureDefaultBehaviorEnabled") { gesture: String, enabled: Boolean ->
676
+ requireSdk().setTouchGestureDefaultBehaviorEnabled(TouchGesture.fromWireName(gesture), enabled).values
677
+ }
678
+
669
679
  SdkCoroutineFunction("setGalleryModeEnabled") { enabled: Boolean ->
670
680
  requireSdk().setGalleryModeEnabled(enabled).values
671
681
  }
@@ -125,9 +125,10 @@ public class Bridge private constructor() {
125
125
 
126
126
  /** Send pair failure event */
127
127
  @JvmStatic
128
- fun sendPairFailureEvent(error: String) {
128
+ fun sendPairFailureEvent(error: String, code: String? = null) {
129
129
  val data = HashMap<String, Any>()
130
130
  data["error"] = error
131
+ if (code != null) data["code"] = code
131
132
  sendTypedMessage("pair_failure", data as Map<String, Any>)
132
133
  }
133
134
 
@@ -138,6 +139,9 @@ public class Bridge private constructor() {
138
139
  classicBondReady: Boolean = false,
139
140
  securePairingCapable: Boolean = true,
140
141
  protocolVersion: Int = 1,
142
+ ownershipTransfer: Boolean = false,
143
+ ownerCommitted: Boolean = false,
144
+ autoAudio: Boolean = false,
141
145
  ) {
142
146
  val data = HashMap<String, Any>()
143
147
  data["had_previous_bond"] = hadPreviousBond
@@ -145,6 +149,9 @@ public class Bridge private constructor() {
145
149
  data["classic_bond_ready"] = classicBondReady
146
150
  data["secure_pairing_capable"] = securePairingCapable
147
151
  data["protocol_version"] = protocolVersion
152
+ data["ownership_transfer"] = ownershipTransfer
153
+ data["owner_committed"] = ownerCommitted
154
+ data["auto_audio"] = autoAudio
148
155
  sendTypedMessage("pairing_info", data as Map<String, Any>)
149
156
  }
150
157