@mentra/bluetooth-sdk 3.5.0-dev.1507 → 3.5.0-dev.1509

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 (44) hide show
  1. package/android/src/main/AndroidManifest.xml +0 -5
  2. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +0 -21
  3. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +0 -35
  4. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +0 -1
  5. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  6. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +1 -64
  7. package/android/src/main/java/com/mentra/bluetoothsdk/camera/CameraModels.kt +0 -36
  8. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +6 -190
  9. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +0 -7
  10. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveFileTransferSessionTest.kt +0 -16
  11. package/build/BluetoothSdk.types.d.ts +0 -75
  12. package/build/BluetoothSdk.types.d.ts.map +1 -1
  13. package/build/BluetoothSdk.types.js.map +1 -1
  14. package/build/_private/BluetoothSdkModule.d.ts +1 -3
  15. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  16. package/build/_private/BluetoothSdkModule.js +0 -14
  17. package/build/_private/BluetoothSdkModule.js.map +1 -1
  18. package/build/_private/photoRequestPayload.d.ts.map +1 -1
  19. package/build/_private/photoRequestPayload.js +0 -3
  20. package/build/_private/photoRequestPayload.js.map +1 -1
  21. package/build/generated/releaseMetadata.js +5 -5
  22. package/build/generated/releaseMetadata.js.map +1 -1
  23. package/build/index.d.ts +1 -1
  24. package/build/index.d.ts.map +1 -1
  25. package/build/index.js +0 -14
  26. package/build/index.js.map +1 -1
  27. package/ios/BluetoothSdkModule.swift +0 -15
  28. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  29. package/ios/Source/DeviceManager.swift +0 -10
  30. package/ios/Source/DeviceStore.swift +0 -1
  31. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  32. package/ios/Source/MentraBluetoothSDK.swift +2 -53
  33. package/ios/Source/camera/CameraModels.swift +8 -44
  34. package/ios/Source/sgcs/MentraLive.swift +6 -83
  35. package/ios/Source/sgcs/MentraLiveFileTransferSession.swift +0 -5
  36. package/ios/Source/status/DeviceStatus.swift +0 -9
  37. package/ios/Tests/PhotoRequestRoutingTests.swift +0 -31
  38. package/package.json +2 -2
  39. package/src/BluetoothSdk.types.ts +0 -80
  40. package/src/_private/BluetoothSdkModule.ts +0 -22
  41. package/src/_private/photoRequestPayload.ts +0 -3
  42. package/src/generated/releaseMetadata.ts +5 -5
  43. package/src/index.ts +0 -26
  44. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/WifiDirectLink.kt +0 -488
@@ -12,9 +12,9 @@ export interface BluetoothSdkReleaseMetadata {
12
12
  export const BLUETOOTH_SDK_RELEASE_METADATA: Readonly<BluetoothSdkReleaseMetadata> = Object.freeze({
13
13
  "schemaVersion": 1,
14
14
  "familyBaseVersion": "3.5.0",
15
- "releaseIdentity": "3.5.0-dev.1507",
16
- "releaseSetId": "mentra-3.5.0-dev.1507",
17
- "sourceCommit": "2b932b3acc5117f4b9a086533e3508c4c2c033bd",
18
- "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1507.json",
19
- "otaManifestSha256": "fdb250c61c2c4541a34a6912531d118888962ef10e9c6b63b3052ed2fc7d3cc4"
15
+ "releaseIdentity": "3.5.0-dev.1509",
16
+ "releaseSetId": "mentra-3.5.0-dev.1509",
17
+ "sourceCommit": "c51ab169af7e451ae9b250bc7436421c43b1ed66",
18
+ "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1509.json",
19
+ "otaManifestSha256": "02523ef80ca019ca896cce503619f02ea8566c5df9652c29750bfbe8d639a875"
20
20
  })
package/src/index.ts CHANGED
@@ -4,7 +4,6 @@ import type {
4
4
  BluetoothSdkEventListener,
5
5
  BluetoothSdkEventName,
6
6
  BluetoothSdkPublicModule,
7
- FastLinkStatus,
8
7
  PhotoCaptureDefaults,
9
8
  PublicBluetoothStatus,
10
9
  PublicGlassesStatus,
@@ -35,7 +34,6 @@ const PUBLIC_EVENT_NAMES = new Set<BluetoothSdkEventName>([
35
34
  "saved_wifi_networks",
36
35
  "hotspot_status_change",
37
36
  "hotspot_error",
38
- "fast_link_status",
39
37
  "photo_response",
40
38
  "photo_status",
41
39
  "camera_status",
@@ -87,20 +85,6 @@ const queryOtaStatus: BluetoothSdkPublicModule["queryOtaStatus"] = () => {
87
85
  return PrivateBluetoothSdkModule.sendOtaQueryStatus()
88
86
  }
89
87
 
90
- const UNSUPPORTED_FAST_LINK: FastLinkStatus = {
91
- state: "unavailable",
92
- link: "wifi_direct",
93
- glassesSupported: false,
94
- reason: "unsupported_platform",
95
- }
96
-
97
- /** Wi-Fi Direct exists only in the Android native module; elsewhere the link is unavailable. */
98
- const fastLinkNative = PrivateBluetoothSdkModule as unknown as {
99
- openFastLink?: () => FastLinkStatus
100
- closeFastLink?: () => void
101
- getFastLinkStatus?: () => FastLinkStatus
102
- }
103
-
104
88
  const bindPublicMethod = <K extends keyof BluetoothSdkPublicModule>(name: K): BluetoothSdkPublicModule[K] => {
105
89
  const method = (PrivateBluetoothSdkModule as unknown as Record<string, unknown>)[name]
106
90
  if (typeof method === "function") {
@@ -147,9 +131,6 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
147
131
  sendWifiCredentials: bindPublicMethod("sendWifiCredentials"),
148
132
  forgetWifiNetwork: bindPublicMethod("forgetWifiNetwork"),
149
133
  setHotspotState: bindPublicMethod("setHotspotState"),
150
- openFastLink: () => fastLinkNative.openFastLink?.() ?? UNSUPPORTED_FAST_LINK,
151
- closeFastLink: () => fastLinkNative.closeFastLink?.(),
152
- getFastLinkStatus: () => fastLinkNative.getFastLinkStatus?.() ?? UNSUPPORTED_FAST_LINK,
153
134
  setSystemTime: bindPublicMethod("setSystemTime"),
154
135
  setWifiAdbState: bindPublicMethod("setWifiAdbState"),
155
136
  setGalleryServerEnabled: bindPublicMethod("setGalleryServerEnabled"),
@@ -184,8 +165,6 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
184
165
  setCameraTuningConfig: bindPublicMethod("setCameraTuningConfig"),
185
166
  queryGalleryStatus: bindPublicMethod("queryGalleryStatus"),
186
167
  requestPhoto: bindPublicMethod("requestPhoto"),
187
- fetchHeldPhoto: bindPublicMethod("fetchHeldPhoto"),
188
- releaseHeldPhotos: bindPublicMethod("releaseHeldPhotos"),
189
168
  warmUpCamera: bindPublicMethod("warmUpCamera"),
190
169
  stopCameraWarmUp: bindPublicMethod("stopCameraWarmUp"),
191
170
  startVideoRecording: bindPublicMethod("startVideoRecording"),
@@ -279,10 +258,6 @@ export type {
279
258
  GlassesNotReadyEvent,
280
259
  HeadUpEvent,
281
260
  HotspotErrorEvent,
282
- FastLinkState,
283
- FastLinkStatus,
284
- FastLinkStatusEvent,
285
- PhotoTransport,
286
261
  HotspotStatus,
287
262
  HotspotStatusChangeEvent,
288
263
  GlassesSessionChangedEvent,
@@ -328,7 +303,6 @@ export type {
328
303
  PhotoTransferMethod,
329
304
  PhotoResponseEvent,
330
305
  PhotoRequestedCaptureConfig,
331
- FetchHeldPhotoParams,
332
306
  PhotoRequestParams,
333
307
  PhotoSize,
334
308
  PhotoStatusEvent,
@@ -1,488 +0,0 @@
1
- package com.mentra.bluetoothsdk.sgcs
2
-
3
- import android.Manifest
4
- import android.content.BroadcastReceiver
5
- import android.content.Context
6
- import android.content.Intent
7
- import android.content.IntentFilter
8
- import android.content.pm.PackageManager
9
- import android.net.ConnectivityManager
10
- import android.net.Network
11
- import android.net.NetworkCapabilities
12
- import android.net.wifi.WifiManager
13
- import android.net.wifi.p2p.WifiP2pConfig
14
- import android.net.wifi.p2p.WifiP2pInfo
15
- import android.net.wifi.p2p.WifiP2pManager
16
- import android.os.Build
17
- import android.os.Handler
18
- import android.os.Looper
19
- import android.os.SystemClock
20
- import androidx.core.content.ContextCompat
21
- import com.mentra.bluetoothsdk.utils.NativeLog as Log
22
- import java.io.ByteArrayOutputStream
23
- import java.net.HttpURLConnection
24
- import java.net.Inet4Address
25
- import java.net.InetAddress
26
- import java.net.URL
27
- import org.json.JSONObject
28
-
29
- /**
30
- * The phone's side of the Wi-Fi Direct link to Mentra Live, used to fetch photos fast.
31
- *
32
- * Bluetooth is the control channel. [open] asks the glasses for a group (`wifi_direct_start`);
33
- * they create it as group owner and answer `wifi_direct_status` with its name and passphrase. The
34
- * phone joins with [WifiP2pConfig.Builder], which goes straight to the WPA2 join: no peer
35
- * discovery, no WPS, and no "Invitation to connect" dialog on either side. Android keeps the group
36
- * on its local network, so the phone's own Wi-Fi or cellular stays its internet.
37
- *
38
- * Photos then arrive as `fast_photo_ready` with a URL on the link, fetched by [fetchPhoto]. When
39
- * there is no group but the phone is on the glasses hotspot for something else (gallery sync,
40
- * Mentra Call, an update), photos use that instead ([hotspotNetwork]). Everything else goes over Bluetooth.
41
- */
42
- class WifiDirectLink(
43
- context: Context,
44
- private val sendToGlasses: (JSONObject) -> Boolean,
45
- private val onStatus: (Map<String, Any>) -> Unit,
46
- ) {
47
- companion object {
48
- private const val TAG = "WifiDirectLink"
49
- private const val GLASSES_ANSWER_TIMEOUT_MS = 20_000L
50
- private const val JOIN_TIMEOUT_MS = 20_000L
51
- private const val FETCH_CONNECT_TIMEOUT_MS = 3_000
52
- private const val FETCH_READ_TIMEOUT_MS = 5_000
53
-
54
- const val STATE_CLOSED = "closed"
55
- const val STATE_OPENING = "opening"
56
- const val STATE_OPEN = "open"
57
- const val STATE_UNAVAILABLE = "unavailable"
58
- }
59
-
60
- private val context = context.applicationContext
61
- private val handler = Handler(Looper.getMainLooper())
62
- private val lock = Any()
63
-
64
- private var manager: WifiP2pManager? = null
65
- private var channel: WifiP2pManager.Channel? = null
66
- private var receiver: BroadcastReceiver? = null
67
-
68
- private var state = STATE_CLOSED
69
- private var reason: String? = null
70
- private var wanted = false
71
- private var joining = false
72
- private var openingStartedMs = 0L
73
- private var openedAfterMs = 0L
74
- private var frequencyMhz = 0
75
- /** The group owner's address the glasses reported; Mentra Live uses 192.168.43.1. */
76
- private var ownerAddress: String? = null
77
-
78
- /**
79
- * The glasses' `wifi_direct_version` from `version_info`: 0 when they can't hold a group (older
80
- * ASG), so the link is unavailable at once instead of waiting for an answer that never comes.
81
- */
82
- @Volatile var glassesVersion: Int = 0
83
- set(value) {
84
- if (field == value) return
85
- field = value
86
- // Tell listeners whether these glasses can hold a group.
87
- handler.post { synchronized(lock) { publishLocked() } }
88
- }
89
-
90
- private val answerTimeout = Runnable { fail("glasses_no_answer") }
91
- private val joinTimeout = Runnable { fail("join_timeout") }
92
-
93
- /** `closed`, `opening`, `open` or `unavailable`, with the reason for the last two. */
94
- fun status(): Map<String, Any> = synchronized(lock) { statusLocked() }
95
-
96
- fun isOpen(): Boolean = synchronized(lock) { state == STATE_OPEN }
97
-
98
- /**
99
- * Opens the link, or reports the one already open or opening. The result arrives through
100
- * `onStatus`; nothing here waits.
101
- */
102
- fun open() {
103
- handler.post { openOnMain() }
104
- }
105
-
106
- /** Leaves the group and tells the glasses to remove it. */
107
- fun close(reason: String = "closed") {
108
- handler.post { closeOnMain(reason, tellGlasses = true) }
109
- }
110
-
111
- /** The Bluetooth link to the glasses is gone, so is the group's owner. */
112
- fun onGlassesDisconnected() {
113
- handler.post { closeOnMain("glasses_disconnected", tellGlasses = false) }
114
- }
115
-
116
- /** A `wifi_direct_status` message from the glasses. */
117
- fun onGlassesStatus(json: JSONObject) {
118
- handler.post { onGlassesStatusOnMain(json) }
119
- }
120
-
121
- private fun openOnMain() {
122
- synchronized(lock) {
123
- if (state == STATE_OPEN || state == STATE_OPENING) {
124
- publishLocked()
125
- return
126
- }
127
- }
128
- val blocker = blocker()
129
- if (blocker != null) {
130
- setState(STATE_UNAVAILABLE, blocker)
131
- return
132
- }
133
- synchronized(lock) {
134
- wanted = true
135
- joining = false
136
- openingStartedMs = SystemClock.elapsedRealtime()
137
- }
138
- setState(STATE_OPENING, null)
139
- // Sharing the phone's own Wi-Fi channel keeps both links at full speed on one radio.
140
- frequencyMhz = currentWifiFrequency()
141
- val sent =
142
- sendToGlasses(
143
- JSONObject().put("type", "wifi_direct_start").apply {
144
- if (frequencyMhz > 0) put("frequency", frequencyMhz)
145
- },
146
- )
147
- if (!sent) {
148
- fail("glasses_not_connected")
149
- return
150
- }
151
- handler.removeCallbacks(answerTimeout)
152
- handler.postDelayed(answerTimeout, GLASSES_ANSWER_TIMEOUT_MS)
153
- }
154
-
155
- private fun onGlassesStatusOnMain(json: JSONObject) {
156
- val glassesState = json.optString("state")
157
- val active = synchronized(lock) { wanted }
158
- if (!active) {
159
- if (glassesState == "ready" || glassesState == "starting") {
160
- // A group nobody here asked for (an earlier session): let the glasses drop it.
161
- sendToGlasses(JSONObject().put("type", "wifi_direct_stop"))
162
- }
163
- return
164
- }
165
- when (glassesState) {
166
- "starting" -> Unit
167
- "ready" -> {
168
- handler.removeCallbacks(answerTimeout)
169
- val alreadyJoining = synchronized(lock) { joining || state == STATE_OPEN }
170
- synchronized(lock) { ownerAddress = json.optString("address").ifEmpty { null } }
171
- if (!alreadyJoining) {
172
- join(
173
- json.optString("ssid"),
174
- json.optString("passphrase"),
175
- json.optInt("frequency", 0),
176
- )
177
- }
178
- }
179
- "stopped" -> closeOnMain("glasses_stopped", tellGlasses = false)
180
- "error" -> fail("glasses_" + json.optString("error", "error"))
181
- }
182
- }
183
-
184
- private fun join(ssid: String, passphrase: String, groupFrequencyMhz: Int) {
185
- if (ssid.isEmpty() || passphrase.isEmpty()) {
186
- fail("glasses_sent_no_credentials")
187
- return
188
- }
189
- if (!ensureChannel()) {
190
- fail("p2p_unavailable")
191
- return
192
- }
193
- synchronized(lock) { joining = true }
194
- val config =
195
- WifiP2pConfig.Builder()
196
- .setNetworkName(ssid)
197
- .setPassphrase(passphrase)
198
- .enablePersistentMode(false)
199
- .apply { if (groupFrequencyMhz > 0) setGroupOperatingFrequency(groupFrequencyMhz) }
200
- .build()
201
- Log.i(TAG, "Joining Wi-Fi Direct group $ssid on $groupFrequencyMhz MHz")
202
- handler.removeCallbacks(joinTimeout)
203
- handler.postDelayed(joinTimeout, JOIN_TIMEOUT_MS)
204
- try {
205
- manager!!.connect(
206
- channel,
207
- config,
208
- object : WifiP2pManager.ActionListener {
209
- override fun onSuccess() {
210
- Log.i(TAG, "P2P connect accepted; waiting for the group")
211
- }
212
-
213
- override fun onFailure(reason: Int) {
214
- fail("join_failed_" + reasonName(reason))
215
- }
216
- },
217
- )
218
- } catch (e: SecurityException) {
219
- fail("permission")
220
- }
221
- }
222
-
223
- private fun onConnectionChanged(info: WifiP2pInfo?) {
224
- val formed = info != null && info.groupFormed && !info.isGroupOwner
225
- val groupOwner = info?.groupOwnerAddress?.hostAddress
226
- synchronized(lock) {
227
- if (!wanted) return
228
- val ours = ownerAddress == null || groupOwner == ownerAddress
229
- if (formed && ours && state != STATE_OPEN) {
230
- handler.removeCallbacks(joinTimeout)
231
- openedAfterMs = SystemClock.elapsedRealtime() - openingStartedMs
232
- joining = false
233
- state = STATE_OPEN
234
- reason = null
235
- Log.i(TAG, "Wi-Fi Direct open after ${openedAfterMs} ms")
236
- publishLocked()
237
- } else if (!formed && state == STATE_OPEN) {
238
- state = STATE_OPENING
239
- reason = "link_lost"
240
- joining = false
241
- publishLocked()
242
- // Ask the glasses again: they answer with the group, and we rejoin it.
243
- openingStartedMs = SystemClock.elapsedRealtime()
244
- sendToGlasses(JSONObject().put("type", "wifi_direct_start"))
245
- handler.removeCallbacks(answerTimeout)
246
- handler.postDelayed(answerTimeout, GLASSES_ANSWER_TIMEOUT_MS)
247
- }
248
- }
249
- }
250
-
251
- private fun fail(why: String) {
252
- Log.w(TAG, "Wi-Fi Direct unavailable: $why")
253
- handler.removeCallbacks(answerTimeout)
254
- handler.removeCallbacks(joinTimeout)
255
- leaveGroup()
256
- sendToGlasses(JSONObject().put("type", "wifi_direct_stop"))
257
- synchronized(lock) {
258
- wanted = false
259
- joining = false
260
- }
261
- setState(STATE_UNAVAILABLE, why)
262
- }
263
-
264
- private fun closeOnMain(why: String, tellGlasses: Boolean) {
265
- handler.removeCallbacks(answerTimeout)
266
- handler.removeCallbacks(joinTimeout)
267
- val wasActive =
268
- synchronized(lock) {
269
- val active = wanted || state != STATE_CLOSED
270
- wanted = false
271
- joining = false
272
- active
273
- }
274
- if (!wasActive) return
275
- leaveGroup()
276
- if (tellGlasses) sendToGlasses(JSONObject().put("type", "wifi_direct_stop"))
277
- setState(STATE_CLOSED, why)
278
- }
279
-
280
- private fun leaveGroup() {
281
- val m = manager ?: return
282
- val c = channel ?: return
283
- try {
284
- m.cancelConnect(c, null)
285
- m.removeGroup(c, null)
286
- } catch (e: RuntimeException) {
287
- Log.w(TAG, "Could not leave the group: ${e.message}")
288
- }
289
- }
290
-
291
- /** Why the phone can't use Wi-Fi Direct right now, or null. */
292
- private fun blocker(): String? {
293
- if (glassesVersion < 1) return "glasses_unsupported"
294
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return "android_too_old"
295
- if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) return "unsupported"
296
- val wifi = context.getSystemService(WifiManager::class.java)
297
- if (wifi == null || !wifi.isWifiEnabled) return "wifi_off"
298
- val permission =
299
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
300
- Manifest.permission.NEARBY_WIFI_DEVICES
301
- } else {
302
- Manifest.permission.ACCESS_FINE_LOCATION
303
- }
304
- if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
305
- return "permission"
306
- }
307
- return null
308
- }
309
-
310
- @Suppress("DEPRECATION")
311
- private fun currentWifiFrequency(): Int =
312
- try {
313
- context.getSystemService(WifiManager::class.java)?.connectionInfo?.frequency?.takeIf { it > 0 } ?: 0
314
- } catch (e: RuntimeException) {
315
- 0
316
- }
317
-
318
- @Suppress("DEPRECATION")
319
- private fun ensureChannel(): Boolean {
320
- if (manager != null && channel != null) return true
321
- val m = context.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager ?: return false
322
- val c =
323
- m.initialize(context, Looper.getMainLooper()) {
324
- Log.w(TAG, "Wi-Fi P2P channel lost")
325
- channel = null
326
- manager = null
327
- if (synchronized(lock) { wanted }) fail("channel_lost")
328
- } ?: return false
329
- manager = m
330
- channel = c
331
- if (receiver == null) {
332
- val r =
333
- object : BroadcastReceiver() {
334
- override fun onReceive(ctx: Context, intent: Intent) {
335
- if (intent.action != WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) return
336
- // The broadcast's extras vary by Android version and vendor: ask for the
337
- // connection itself.
338
- requestConnectionInfo()
339
- }
340
- }
341
- val filter = IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)
342
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
343
- context.registerReceiver(r, filter, Context.RECEIVER_NOT_EXPORTED)
344
- } else {
345
- context.registerReceiver(r, filter)
346
- }
347
- receiver = r
348
- }
349
- return true
350
- }
351
-
352
- private fun requestConnectionInfo() {
353
- val m = manager ?: return
354
- val c = channel ?: return
355
- try {
356
- m.requestConnectionInfo(c) { info -> onConnectionChanged(info) }
357
- } catch (e: SecurityException) {
358
- Log.w(TAG, "requestConnectionInfo not permitted: ${e.message}")
359
- }
360
- }
361
-
362
- private fun setState(next: String, why: String?) {
363
- synchronized(lock) {
364
- state = next
365
- reason = why
366
- publishLocked()
367
- }
368
- }
369
-
370
- private fun publishLocked() {
371
- val status = statusLocked()
372
- Log.i(TAG, "Fast link: $status")
373
- onStatus(status)
374
- }
375
-
376
- private fun statusLocked(): Map<String, Any> =
377
- buildMap {
378
- put("state", state)
379
- put("link", "wifi_direct")
380
- put("glassesSupported", glassesVersion >= 1)
381
- reason?.let { put("reason", it) }
382
- if (state == STATE_OPEN) put("openedAfterMs", openedAfterMs)
383
- }
384
-
385
- /** A photo fetched over a fast link, with how long the fetch took. */
386
- class FetchedPhoto(val bytes: ByteArray, val fetchMs: Long)
387
-
388
- /**
389
- * Fetches a photo the glasses announced with `fast_photo_ready` and confirms it. Blocks: call it
390
- * off the main thread.
391
- *
392
- * @throws Exception when the link can't deliver it; the caller then asks for Bluetooth
393
- */
394
- fun fetchPhoto(url: String, ackUrl: String, link: String): FetchedPhoto {
395
- val started = SystemClock.elapsedRealtime()
396
- val bytes = request(url, "GET", link)
397
- val fetchMs = SystemClock.elapsedRealtime() - started
398
- try {
399
- request(ackUrl, "POST", link)
400
- } catch (e: Exception) {
401
- // The photo is here; the glasses fall back to Bluetooth only if the ack is lost, and the
402
- // duplicate is dropped as an unknown transfer.
403
- Log.w(TAG, "Fast photo ack failed: ${e.message}")
404
- }
405
- return FetchedPhoto(bytes, fetchMs)
406
- }
407
-
408
- private fun request(url: String, method: String, link: String): ByteArray {
409
- val target = URL(url)
410
- val connection =
411
- if (link == "hotspot") {
412
- val network = hotspotNetwork(target.host)
413
- ?: throw IllegalStateException("The phone is not on the glasses hotspot")
414
- network.openConnection(target)
415
- } else {
416
- // The P2P subnet is a directly connected local network: any app socket reaches it.
417
- target.openConnection()
418
- } as HttpURLConnection
419
- try {
420
- connection.requestMethod = method
421
- connection.connectTimeout = FETCH_CONNECT_TIMEOUT_MS
422
- connection.readTimeout = FETCH_READ_TIMEOUT_MS
423
- connection.useCaches = false
424
- if (method == "POST") {
425
- connection.doOutput = true
426
- connection.setFixedLengthStreamingMode(0)
427
- }
428
- val code = connection.responseCode
429
- if (code != 200) throw IllegalStateException("HTTP $code from $link")
430
- val expected = connection.contentLength
431
- connection.inputStream.use { input ->
432
- val out = ByteArrayOutputStream(if (expected > 0) expected else 64 * 1024)
433
- input.copyTo(out, 64 * 1024)
434
- val bytes = out.toByteArray()
435
- if (expected >= 0 && bytes.size != expected) {
436
- throw IllegalStateException("Got ${bytes.size} of $expected bytes from $link")
437
- }
438
- return bytes
439
- }
440
- } finally {
441
- connection.disconnect()
442
- }
443
- }
444
-
445
- /**
446
- * The phone's Wi-Fi network whose subnet holds the glasses' hotspot address, however the phone
447
- * joined it (a scoped request from gallery sync or Mentra Call, a process-bound join, or by
448
- * hand), or null when the phone is not on the glasses hotspot.
449
- */
450
- @Suppress("DEPRECATION")
451
- fun hotspotNetwork(gatewayIp: String?): Network? {
452
- val gateway = gatewayIp?.takeIf { it.isNotEmpty() }?.let { parseIpv4(it) } ?: return null
453
- val connectivity = context.getSystemService(ConnectivityManager::class.java) ?: return null
454
- return connectivity.allNetworks.firstOrNull { network ->
455
- val capabilities = connectivity.getNetworkCapabilities(network)
456
- if (capabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) != true) return@firstOrNull false
457
- connectivity.getLinkProperties(network)?.linkAddresses?.any { link ->
458
- val local = (link.address as? Inet4Address)?.address ?: return@any false
459
- sameSubnet(local, gateway, link.prefixLength)
460
- } == true
461
- }
462
- }
463
-
464
- private fun parseIpv4(text: String): ByteArray? =
465
- try {
466
- (InetAddress.getByName(text) as? Inet4Address)?.address
467
- } catch (e: Exception) {
468
- null
469
- }
470
-
471
- private fun sameSubnet(a: ByteArray, b: ByteArray, prefixLength: Int): Boolean {
472
- val bits = prefixLength.coerceIn(0, 32)
473
- for (i in 0 until 4) {
474
- val maskBits = (bits - i * 8).coerceIn(0, 8)
475
- val mask = (0xFF shl (8 - maskBits)) and 0xFF
476
- if ((a[i].toInt() and mask) != (b[i].toInt() and mask)) return false
477
- }
478
- return true
479
- }
480
-
481
- private fun reasonName(reason: Int): String =
482
- when (reason) {
483
- WifiP2pManager.ERROR -> "error"
484
- WifiP2pManager.P2P_UNSUPPORTED -> "unsupported"
485
- WifiP2pManager.BUSY -> "busy"
486
- else -> reason.toString()
487
- }
488
- }