@mentra/bluetooth-sdk 3.5.0-dev.1502 → 3.5.0-dev.1504
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/src/main/AndroidManifest.xml +5 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +7 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +21 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +13 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/camera/CameraModels.kt +12 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +105 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/WifiDirectLink.kt +488 -0
- package/build/BluetoothSdk.types.d.ts +41 -0
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +12 -0
- package/build/index.js.map +1 -1
- package/ios/Source/BluetoothSdkDefaults.swift +1 -1
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- package/package.json +2 -2
- package/src/BluetoothSdk.types.ts +45 -0
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/index.ts +23 -0
|
@@ -0,0 +1,488 @@
|
|
|
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
|
+
}
|
|
@@ -186,6 +186,30 @@ export declare function isEnabledHotspotStatus(status: HotspotStatus): status is
|
|
|
186
186
|
export type HotspotStatusChangeEvent = HotspotStatus & {
|
|
187
187
|
type: "hotspot_status_change";
|
|
188
188
|
};
|
|
189
|
+
/**
|
|
190
|
+
* The fast photo link: Wi-Fi Direct between an Android phone and Mentra Live. While it is
|
|
191
|
+
* `open`, photos travel over it; otherwise over Bluetooth. `unavailable` carries a `reason`,
|
|
192
|
+
* such as `glasses_unsupported`, `permission` (NEARBY_WIFI_DEVICES, or location before Android 13), `wifi_off`,
|
|
193
|
+
* `glasses_not_connected`, `join_timeout` or a `glasses_...` error.
|
|
194
|
+
*/
|
|
195
|
+
export type FastLinkState = "closed" | "opening" | "open" | "unavailable";
|
|
196
|
+
export type FastLinkStatus = {
|
|
197
|
+
state: FastLinkState;
|
|
198
|
+
link: "wifi_direct";
|
|
199
|
+
/**
|
|
200
|
+
* Whether the connected glasses can hold a Wi-Fi Direct group (they advertise
|
|
201
|
+
* `wifi_direct_version`). Without it, use the glasses hotspot.
|
|
202
|
+
*/
|
|
203
|
+
glassesSupported: boolean;
|
|
204
|
+
reason?: string;
|
|
205
|
+
/** How long the link took to open, from the request. */
|
|
206
|
+
openedAfterMs?: number;
|
|
207
|
+
};
|
|
208
|
+
export type FastLinkStatusEvent = FastLinkStatus & {
|
|
209
|
+
type: "fast_link_status";
|
|
210
|
+
};
|
|
211
|
+
/** How a photo reached the phone. */
|
|
212
|
+
export type PhotoTransport = "ble" | "wifi_direct" | "hotspot";
|
|
189
213
|
export type HotspotErrorEvent = {
|
|
190
214
|
type: "hotspot_error";
|
|
191
215
|
errorMessage: string;
|
|
@@ -241,6 +265,12 @@ export type PhotoResponseEvent = {
|
|
|
241
265
|
contentType?: string;
|
|
242
266
|
fileSizeBytes?: number;
|
|
243
267
|
timestamp: number;
|
|
268
|
+
/** How the photo reached the phone (Android `localFile` requests). */
|
|
269
|
+
transport?: PhotoTransport;
|
|
270
|
+
/** Its last hop: the fetch over a fast link, or the Bluetooth packets. */
|
|
271
|
+
transferMs?: number;
|
|
272
|
+
/** From the phone's request to the saved file. */
|
|
273
|
+
totalMs?: number;
|
|
244
274
|
} | {
|
|
245
275
|
type: "photo_response";
|
|
246
276
|
state: "error";
|
|
@@ -1133,6 +1163,7 @@ export type BluetoothSdkModuleEvents = {
|
|
|
1133
1163
|
saved_wifi_networks: (event: SavedWifiNetworksEvent) => void;
|
|
1134
1164
|
hotspot_status_change: (event: HotspotStatusChangeEvent) => void;
|
|
1135
1165
|
hotspot_error: (event: HotspotErrorEvent) => void;
|
|
1166
|
+
fast_link_status: (event: FastLinkStatusEvent) => void;
|
|
1136
1167
|
photo_response: (event: PhotoResponseEvent) => void;
|
|
1137
1168
|
photo_status: (event: PhotoStatusEvent) => void;
|
|
1138
1169
|
camera_status: (event: CameraStatusEvent) => void;
|
|
@@ -1282,6 +1313,7 @@ export type BluetoothSdkEventMap = {
|
|
|
1282
1313
|
saved_wifi_networks: SavedWifiNetworksEvent;
|
|
1283
1314
|
hotspot_status_change: HotspotStatusChangeEvent;
|
|
1284
1315
|
hotspot_error: HotspotErrorEvent;
|
|
1316
|
+
fast_link_status: FastLinkStatusEvent;
|
|
1285
1317
|
photo_response: PhotoResponseEvent;
|
|
1286
1318
|
photo_status: PhotoStatusEvent;
|
|
1287
1319
|
camera_status: CameraStatusEvent;
|
|
@@ -1375,6 +1407,15 @@ export interface BluetoothSdkPublicModule {
|
|
|
1375
1407
|
/** Forget a saved network and return its correlated semantic outcome. */
|
|
1376
1408
|
forgetWifiNetwork(ssid: string): Promise<WifiForgetResult>;
|
|
1377
1409
|
setHotspotState(enabled: boolean): Promise<HotspotStatusChangeEvent>;
|
|
1410
|
+
/**
|
|
1411
|
+
* Open the fast photo link (Wi-Fi Direct to Mentra Live, Android only). Returns the state now;
|
|
1412
|
+
* `fast_link_status` reports each change. Photos use the link while it is open, and Bluetooth
|
|
1413
|
+
* otherwise, with no change to `requestPhoto`. Needs NEARBY_WIFI_DEVICES on Android 13+.
|
|
1414
|
+
*/
|
|
1415
|
+
openFastLink(): FastLinkStatus;
|
|
1416
|
+
/** Close the fast photo link; photos go over Bluetooth again. */
|
|
1417
|
+
closeFastLink(): void;
|
|
1418
|
+
getFastLinkStatus(): FastLinkStatus;
|
|
1378
1419
|
/** Set the glasses clock from the phone after an OTA clock-skew failure. */
|
|
1379
1420
|
setSystemTime(timestampMs: number): Promise<void>;
|
|
1380
1421
|
/** Enable or disable Wi-Fi ADB on Mentra Live (no-op on other devices). */
|