@mentra/bluetooth-sdk 3.4.0-beta.1277 → 3.4.0-beta.1279

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 (48) hide show
  1. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  2. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
  3. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
  4. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
  5. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +109 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +53 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +127 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +604 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
  12. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
  13. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
  14. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
  15. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +96 -0
  16. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +187 -0
  17. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
  18. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +69 -0
  19. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
  20. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
  21. package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
  22. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  23. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  24. package/build/generated/releaseMetadata.js +5 -5
  25. package/build/generated/releaseMetadata.js.map +1 -1
  26. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  27. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  28. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  29. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  30. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  31. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  32. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  33. package/build/ota-transport/index.d.ts +3 -3
  34. package/build/ota-transport/index.d.ts.map +1 -1
  35. package/build/ota-transport/index.js +4 -4
  36. package/build/ota-transport/index.js.map +1 -1
  37. package/ios/LocalIPv4.swift +0 -61
  38. package/ios/MentraOtaServerModule.swift +0 -16
  39. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  40. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  41. package/package.json +2 -2
  42. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  43. package/src/generated/releaseMetadata.ts +5 -5
  44. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  45. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  46. package/src/ota-transport/index.ts +4 -5
  47. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  48. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
@@ -0,0 +1,604 @@
1
+ package com.mentra.bluetoothsdk.hotspot
2
+
3
+ import android.content.Context
4
+ import android.content.pm.PackageManager
5
+ import android.net.ConnectivityManager
6
+ import android.net.LinkProperties
7
+ import android.net.Network
8
+ import android.net.NetworkCapabilities
9
+ import android.net.NetworkRequest
10
+ import android.net.wifi.WifiManager
11
+ import android.net.wifi.WifiNetworkSpecifier
12
+ import android.os.Build
13
+ import java.net.Inet4Address
14
+ import java.util.concurrent.CountDownLatch
15
+ import java.util.concurrent.TimeUnit
16
+
17
+ /**
18
+ * Joins the glasses' SoftAP as a scoped, internet-less network and keeps the [Network] handle
19
+ * in-process.
20
+ *
21
+ * Gallery sync and hotspot OTA (through `MentraLocalNetworkModule`), Mentra Call and the managed
22
+ * relay all join through this class, so the hotspot has one join on Android. Callers that use
23
+ * libwebrtc bind their sockets to the [Network] it produces.
24
+ *
25
+ * ## Dual-homing
26
+ *
27
+ * The request drops `NET_CAPABILITY_INTERNET` (see [ScopedNetworkRequestSpec]), so Android never
28
+ * promotes the hotspot to the default network and ACS keeps using cellular.
29
+ */
30
+ class ScopedSoftApNetwork(private val context: Context) {
31
+
32
+ /** Notified on the ConnectivityManager callback thread. */
33
+ interface Listener {
34
+ fun onAvailable(network: Network, localIpv4: String)
35
+
36
+ fun onLost(error: ScopedNetworkError)
37
+ }
38
+
39
+ private val lock = Any()
40
+ private val state = ScopedNetworkState()
41
+ private val readiness = ScopedNetworkReadiness()
42
+
43
+ private var callback: ConnectivityManager.NetworkCallback? = null
44
+ /** The pending request's wait, so [release] can end it at once. */
45
+ private var pendingReady: CountDownLatch? = null
46
+ /** Counts [release] calls; a join that saw one stops instead of retrying. */
47
+ private var releases = 0
48
+ private var network: Network? = null
49
+ private var localIpv4: String? = null
50
+ private var spec: ScopedNetworkRequestSpec? = null
51
+ private var listener: Listener? = null
52
+
53
+ /** The joined network, or null. Pass this to anything that must send over the SoftAP link. */
54
+ fun network(): Network? = synchronized(lock) { network }
55
+
56
+ /** This phone's address on the hotspot subnet, e.g. `192.168.43.20`. */
57
+ fun localIpv4(): String? = synchronized(lock) { localIpv4 }
58
+
59
+ /**
60
+ * The subnet this phone joined, straight from `LinkProperties`.
61
+ *
62
+ * This is the invariant every SoftAP media check is written against: the selected ICE candidate
63
+ * has to be on *this* prefix, not merely on some private range. Reading the prefix length rather
64
+ * than assuming /24 is what keeps the check true when an OEM hands out a different hotspot
65
+ * subnet.
66
+ */
67
+ fun scopedPrefix(): Ipv4Prefix? {
68
+ val net = network() ?: return null
69
+ val properties = connectivityManager().getLinkProperties(net) ?: return null
70
+ return properties.linkAddresses
71
+ .firstOrNull { it.address is Inet4Address }
72
+ ?.let { link -> link.address.hostAddress?.let { Ipv4Prefix(it, link.prefixLength) } }
73
+ }
74
+
75
+ fun isAvailable(): Boolean = synchronized(lock) { state.phase == ScopedNetworkState.Phase.AVAILABLE }
76
+
77
+ /** Station radio on? `WifiNetworkSpecifier` is a no-op while this is false. */
78
+ fun isWifiEnabled(): Boolean {
79
+ val wifi = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager
80
+ return wifi?.isWifiEnabled == true
81
+ }
82
+
83
+ /**
84
+ * Block until the station radio is on, or [timeoutMs] elapses. Used after the system Wi-Fi
85
+ * panel is shown: the join must wait for the user, not abort and remint ACS over a broken
86
+ * default route.
87
+ */
88
+ fun awaitWifiEnabled(timeoutMs: Long = WIFI_ENABLE_WAIT_MS): Boolean {
89
+ if (isWifiEnabled()) return true
90
+ val deadline = android.os.SystemClock.elapsedRealtime() + timeoutMs
91
+ while (android.os.SystemClock.elapsedRealtime() < deadline) {
92
+ Thread.sleep(WIFI_ENABLE_POLL_MS)
93
+ if (isWifiEnabled()) return true
94
+ }
95
+ return isWifiEnabled()
96
+ }
97
+
98
+ /**
99
+ * True when a VPN is this app's default network — i.e. our UID falls inside its captured
100
+ * ranges. A VPN that excludes us (split tunneling) or is simply installed does not count: the
101
+ * default network is then cellular/Wi-Fi and the hotspot path works.
102
+ */
103
+ fun isVpnCapturingApp(): Boolean {
104
+ val manager = connectivityManager()
105
+ val active = manager.activeNetwork ?: return false
106
+ val capabilities = manager.getNetworkCapabilities(active) ?: return false
107
+ return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
108
+ }
109
+
110
+ /** Verdict of [probeGateway]: [detail] is one human-readable line for the UI and the trace. */
111
+ data class GatewayProbe(val reachable: Boolean, val detail: String)
112
+
113
+ /**
114
+ * The hotspot's own address on the joined network — the DHCP server, since the glasses
115
+ * deliberately advertise no default route. Falls back to `.1` of the phone's /24.
116
+ */
117
+ fun gatewayIpv4(): String? {
118
+ val net = network() ?: return null
119
+ val properties = connectivityManager().getLinkProperties(net)
120
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
121
+ properties?.dhcpServerAddress?.hostAddress?.let { return it }
122
+ }
123
+ val local = localIpv4() ?: return null
124
+ val prefix = local.substringBeforeLast('.', "")
125
+ return if (prefix.isEmpty()) null else "$prefix.1"
126
+ }
127
+
128
+ /**
129
+ * Prove the phone can reach the glasses over the network it just joined.
130
+ *
131
+ * TCP, through [Network.getSocketFactory], so the kernel routes via the hotspot's table rather
132
+ * than the cellular default that unbound sockets would take. A *refused* connection is a pass:
133
+ * the SYN arrived and the RST came back, which is the reachability question. Only a timeout or
134
+ * an unreachable-network error is a fail.
135
+ */
136
+ fun probeGateway(timeoutMs: Int = GATEWAY_PROBE_TIMEOUT_MS): GatewayProbe {
137
+ val net = network() ?: return GatewayProbe(false, "no scoped network")
138
+ val gateway = gatewayIpv4() ?: return GatewayProbe(false, "no gateway address on the scoped network")
139
+ var lastFailure = "no ports tried"
140
+ for (port in GATEWAY_PROBE_PORTS) {
141
+ val startedAt = android.os.SystemClock.elapsedRealtime()
142
+ val socket =
143
+ try {
144
+ net.socketFactory.createSocket()
145
+ } catch (error: java.io.IOException) {
146
+ // netd answers EPERM when a VPN owns our UID and forbids binding elsewhere.
147
+ val message = error.message ?: error.javaClass.simpleName
148
+ val detail =
149
+ if (message.contains("EPERM")) {
150
+ "cannot bind to the hotspot network ($message): a VPN is capturing this app"
151
+ } else {
152
+ "cannot bind to the hotspot network: $message"
153
+ }
154
+ SoftApTrace.failure("gateway_probe", "gateway" to gateway, "result" to detail)
155
+ return GatewayProbe(false, detail)
156
+ }
157
+ try {
158
+ socket.connect(java.net.InetSocketAddress(gateway, port), timeoutMs)
159
+ val elapsed = android.os.SystemClock.elapsedRealtime() - startedAt
160
+ SoftApTrace.stage("gateway_probe", "gateway" to gateway, "port" to port, "result" to "connected", "ms" to elapsed)
161
+ return GatewayProbe(true, "tcp $gateway:$port connected in ${elapsed}ms")
162
+ } catch (error: java.net.ConnectException) {
163
+ val elapsed = android.os.SystemClock.elapsedRealtime() - startedAt
164
+ val message = error.message ?: ""
165
+ if (message.contains("refused", ignoreCase = true)) {
166
+ SoftApTrace.stage("gateway_probe", "gateway" to gateway, "port" to port, "result" to "refused", "ms" to elapsed)
167
+ return GatewayProbe(true, "tcp $gateway:$port refused (host answered) in ${elapsed}ms")
168
+ }
169
+ lastFailure = "tcp $gateway:$port $message"
170
+ } catch (error: java.net.SocketTimeoutException) {
171
+ lastFailure = "tcp $gateway:$port timed out after ${timeoutMs}ms"
172
+ } catch (error: java.io.IOException) {
173
+ lastFailure = "tcp $gateway:$port ${error.message ?: error.javaClass.simpleName}"
174
+ } finally {
175
+ runCatching { socket.close() }
176
+ }
177
+ }
178
+ SoftApTrace.failure("gateway_probe", "gateway" to gateway, "result" to lastFailure)
179
+ return GatewayProbe(false, lastFailure)
180
+ }
181
+
182
+ /**
183
+ * Whether the local-network permission is granted. Below the SDK level that enforces it, access
184
+ * is implicit and this reports true.
185
+ */
186
+ fun hasLocalNetworkPermission(): Boolean =
187
+ hasLocalNetworkPermission(Build.VERSION.SDK_INT, context.applicationInfo.targetSdkVersion) {
188
+ context.checkSelfPermission(ScopedNetworkError.LOCAL_NETWORK_PERMISSION) ==
189
+ PackageManager.PERMISSION_GRANTED
190
+ }
191
+
192
+ /**
193
+ * Join [ssid] and block until it is usable or the request fails. An Unavailable request is
194
+ * made once more after a short settle; every caller gets that retry.
195
+ * [incoming] is false for a caller that only dials the glasses (gallery): a VPN that
196
+ * captures the app blocks the glasses reaching us, not us reaching them.
197
+ *
198
+ * @throws ScopedNetworkError on permission denial, timeout, or an unavailable network
199
+ */
200
+ @Throws(ScopedNetworkError::class)
201
+ fun join(ssid: String, passphrase: String, listener: Listener? = null, incoming: Boolean = true): Network {
202
+ if (!hasLocalNetworkPermission()) {
203
+ SoftApTrace.failure("scoped_join_permission_denied", "ssid" to ssid)
204
+ throw ScopedNetworkError.PermissionDenied(ScopedNetworkError.LOCAL_NETWORK_PERMISSION)
205
+ }
206
+
207
+ // A disabled radio makes WifiNetworkSpecifier fail as Unavailable in under 10ms, which is
208
+ // indistinguishable from a hotspot that never came up. Report the real cause instead.
209
+ if (!isWifiEnabled()) {
210
+ SoftApTrace.failure("scoped_join_wifi_disabled", "ssid" to ssid)
211
+ throw ScopedNetworkError.WifiDisabled()
212
+ }
213
+
214
+ // The specifier join would succeed, but the glasses could never complete a TCP handshake
215
+ // to our listener and we could not bind to the hotspot. Fail here, where the message can
216
+ // say why, instead of ten seconds into the camera step.
217
+ if (incoming && isVpnCapturingApp()) {
218
+ SoftApTrace.failure("scoped_join_vpn_captures_app", "ssid" to ssid)
219
+ throw ScopedNetworkError.VpnCapturesApp()
220
+ }
221
+
222
+ val releasesAtStart = synchronized(lock) { releases }
223
+ return retryUnavailableOnce(
224
+ request = { requestOnce(ssid, passphrase, listener) },
225
+ settle = {
226
+ SoftApTrace.stage("scoped_join_unavailable_retry", "ssid" to ssid, "settleMs" to UNAVAILABLE_RETRY_SETTLE_MS)
227
+ Thread.sleep(UNAVAILABLE_RETRY_SETTLE_MS)
228
+ },
229
+ released = { synchronized(lock) { releases } != releasesAtStart },
230
+ )
231
+ }
232
+
233
+ @Throws(ScopedNetworkError::class)
234
+ private fun requestOnce(ssid: String, passphrase: String, listener: Listener?): Network {
235
+ synchronized(lock) { releaseLocked() }
236
+
237
+ val requestSpec = ScopedNetworkRequestSpec.forSoftAp(ssid, passphrase)
238
+ val manager = connectivityManager()
239
+ val ready = CountDownLatch(1)
240
+
241
+ val generation: Int
242
+ synchronized(lock) {
243
+ pendingReady = ready
244
+ generation = state.startRequest()
245
+ spec = requestSpec
246
+ this.listener = listener
247
+ readiness.reset()
248
+ }
249
+ SoftApTrace.stage(
250
+ "scoped_join_requested",
251
+ "ssid" to ssid,
252
+ "timeoutMs" to requestSpec.timeoutMs,
253
+ "avoidsInternetCapability" to requestSpec.avoidsInternetCapability,
254
+ )
255
+ val startedAtMs = System.currentTimeMillis()
256
+
257
+ val networkCallback =
258
+ object : ConnectivityManager.NetworkCallback() {
259
+ override fun onAvailable(available: Network) {
260
+ val properties = manager.getLinkProperties(available)
261
+ val resolvedIpv4 = firstIpv4(properties)
262
+ synchronized(lock) {
263
+ if (!state.onAvailable(generation)) return
264
+ network = available
265
+ localIpv4 = resolvedIpv4
266
+ readiness.onAvailable()
267
+ readiness.seedLinkProperties(properties?.interfaceName, resolvedIpv4)
268
+ }
269
+ SoftApTrace.stage(
270
+ "scoped_network_available",
271
+ "ssid" to ssid,
272
+ "localIpv4" to resolvedIpv4,
273
+ "joinMs" to (System.currentTimeMillis() - startedAtMs),
274
+ "defaultNetworkIsCellular" to defaultNetworkIsCellular(manager),
275
+ )
276
+ // Does the address we were just handed exist in the kernel's interface table,
277
+ // and under the name LinkProperties claims? ICE gathers from that table, so a
278
+ // mismatch here is the difference between a hotspot candidate and none. The
279
+ // address can also land in the table *after* onAvailable, which is why this is
280
+ // only a snapshot for the trace and readiness is decided by polling below.
281
+ val table = NetworkFacts.snapshot()
282
+ SoftApTrace.stage(
283
+ "scoped_network_ifaddrs",
284
+ "localIpv4" to resolvedIpv4,
285
+ "claimed" to (properties?.interfaceName ?: "none"),
286
+ "owner" to (resolvedIpv4?.let { NetworkFacts.ownerOf(it, table) } ?: "ABSENT"),
287
+ "gatherable" to NetworkFacts.render(NetworkFacts.gatherable(table)),
288
+ )
289
+ if (readiness.callbacksSatisfied()) ready.countDown()
290
+ }
291
+
292
+ /**
293
+ * The callback Android says to read properties from. It also arrives again when
294
+ * DHCP completes, which is the case `onAvailable` alone missed.
295
+ */
296
+ override fun onLinkPropertiesChanged(
297
+ changed: Network,
298
+ properties: LinkProperties,
299
+ ) {
300
+ val address = firstIpv4(properties)
301
+ synchronized(lock) {
302
+ if (!state.accepts(generation)) return
303
+ // Sticky, unlike the readiness observation: the WHIP listener is bound to
304
+ // this address and mid-call disappearance is `onLost`'s business, so a
305
+ // transient property update must not blank the ingest URL.
306
+ if (address != null) localIpv4 = address
307
+ readiness.onLinkProperties(properties.interfaceName, address)
308
+ }
309
+ SoftApTrace.stage(
310
+ "scoped_link_properties",
311
+ "interface" to (properties.interfaceName ?: "none"),
312
+ "localIpv4" to (address ?: "none"),
313
+ )
314
+ if (readiness.callbacksSatisfied()) ready.countDown()
315
+ }
316
+
317
+ override fun onCapabilitiesChanged(
318
+ changed: Network,
319
+ capabilities: NetworkCapabilities,
320
+ ) {
321
+ // A background network is not usable by the app yet; wait for the foreground.
322
+ if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)) return
323
+ synchronized(lock) {
324
+ if (!state.accepts(generation)) return
325
+ readiness.onCapabilities()
326
+ }
327
+ if (readiness.callbacksSatisfied()) ready.countDown()
328
+ }
329
+
330
+ override fun onUnavailable() {
331
+ synchronized(lock) { if (!state.onUnavailable(generation)) return }
332
+ SoftApTrace.failure("scoped_network_unavailable", "ssid" to ssid)
333
+ ready.countDown()
334
+ }
335
+
336
+ override fun onLost(lost: Network) {
337
+ val notify: Listener?
338
+ synchronized(lock) {
339
+ if (!state.onLost(generation)) return
340
+ network = null
341
+ localIpv4 = null
342
+ notify = this@ScopedSoftApNetwork.listener
343
+ }
344
+ SoftApTrace.failure("scoped_network_lost", "ssid" to ssid)
345
+ ready.countDown()
346
+ notify?.onLost(ScopedNetworkError.Lost(ssid))
347
+ }
348
+ }
349
+
350
+ synchronized(lock) { callback = networkCallback }
351
+
352
+ try {
353
+ manager.requestNetwork(request(requestSpec), networkCallback, requestSpec.timeoutMs)
354
+ } catch (error: SecurityException) {
355
+ synchronized(lock) { state.onRequestFailed(generation, permissionDenied = true) }
356
+ clearCallback(networkCallback)
357
+ SoftApTrace.failure("scoped_join_security_exception", "ssid" to ssid)
358
+ throw ScopedNetworkError.PermissionDenied(ScopedNetworkError.LOCAL_NETWORK_PERMISSION)
359
+ } catch (error: Exception) {
360
+ synchronized(lock) { state.onRequestFailed(generation, permissionDenied = false) }
361
+ clearCallback(networkCallback)
362
+ SoftApTrace.failure("scoped_join_request_failed", "ssid" to ssid)
363
+ throw ScopedNetworkError.RequestFailed(error.message ?: "unknown")
364
+ }
365
+
366
+ // requestNetwork's own timeout fires onUnavailable, but a slightly longer await guards
367
+ // against never being called back at all.
368
+ val awaited =
369
+ ready.await(requestSpec.timeoutMs.toLong() + AWAIT_GRACE_MS, TimeUnit.MILLISECONDS)
370
+ if (!awaited) synchronized(lock) { state.onTimeout(generation) }
371
+
372
+ val joinedNetwork =
373
+ synchronized(lock) {
374
+ network.takeIf { state.phase == ScopedNetworkState.Phase.AVAILABLE }
375
+ }
376
+ if (joinedNetwork != null) {
377
+ val verdict = awaitReadiness(ssid)
378
+ val notify = synchronized(lock) { listener }
379
+ notify?.onAvailable(joinedNetwork, verdict.address)
380
+ probeUnmarkedUdpSend(verdict.address)
381
+ return joinedNetwork
382
+ }
383
+
384
+ throw synchronized(lock) {
385
+ val failure =
386
+ ScopedNetworkError.from(state.failure, ssid, requestSpec.timeoutMs)
387
+ ?: ScopedNetworkError.Timeout(ssid, requestSpec.timeoutMs)
388
+ releaseLocked()
389
+ failure
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Block until the joined network is ready for ICE, or fail with the source that never reported.
395
+ *
396
+ * The kernel interface table is the one input with no callback, so it is polled: the hotspot
397
+ * address is regularly absent when `onAvailable` returns and appears a moment later. Starting
398
+ * ingest before it exists produced an answer with zero candidates, which looked identical to a
399
+ * binding bug and was misdiagnosed as one.
400
+ */
401
+ @Throws(ScopedNetworkError::class)
402
+ private fun awaitReadiness(ssid: String): ScopedNetworkReadiness.Verdict.Ready {
403
+ val deadline = android.os.SystemClock.elapsedRealtime() + READINESS_WAIT_MS
404
+ var verdict: ScopedNetworkReadiness.Verdict
405
+ while (true) {
406
+ val address = readiness.observations.linkAddress
407
+ readiness.onInterfaceTable(address?.let { NetworkFacts.ownerOf(it) })
408
+ verdict = readiness.verdict()
409
+ if (verdict is ScopedNetworkReadiness.Verdict.Ready) break
410
+ if (android.os.SystemClock.elapsedRealtime() >= deadline) break
411
+ Thread.sleep(READINESS_POLL_MS)
412
+ }
413
+
414
+ val observed = readiness.observations
415
+ if (verdict is ScopedNetworkReadiness.Verdict.Ready) {
416
+ SoftApTrace.stage(
417
+ "scoped_network_ready",
418
+ "localIpv4" to verdict.address,
419
+ "claimed" to (verdict.interfaceName ?: "none"),
420
+ "owner" to verdict.owner,
421
+ "agrees" to (verdict.interfaceName == null || verdict.interfaceName == verdict.owner),
422
+ "capabilitiesSeen" to observed.capabilities,
423
+ )
424
+ return verdict
425
+ }
426
+
427
+ val waiting = verdict as ScopedNetworkReadiness.Verdict.Waiting
428
+ SoftApTrace.failure(
429
+ "scoped_network_not_ready",
430
+ "ssid" to ssid,
431
+ "missing" to waiting.missing,
432
+ "localIpv4" to (observed.linkAddress ?: "none"),
433
+ "claimed" to (observed.linkInterface ?: "none"),
434
+ "capabilitiesSeen" to observed.capabilities,
435
+ "gatherable" to NetworkFacts.render(NetworkFacts.gatherable()),
436
+ )
437
+ release()
438
+ throw ScopedNetworkError.NotReady(ssid, waiting.missing)
439
+ }
440
+
441
+ /**
442
+ * Whether an unmarked UDP socket on the hotspot address can even be created and written to.
443
+ *
444
+ * Diagnostic only, and deliberately not a gate. A successful `send` means the OS accepted the
445
+ * datagram; it says nothing about whether the glasses received it or can reply, so it cannot
446
+ * establish that unmarked UDP works. What it *can* do is separate "bind refused outright" from
447
+ * "bound fine, nothing came back", which is the FAILED_BINDING hypothesis. The real answer to
448
+ * whether this path carries traffic is the ICE connectivity-check result.
449
+ */
450
+ private fun probeUnmarkedUdpSend(address: String) {
451
+ val gateway = gatewayIpv4()
452
+ val result =
453
+ runCatching {
454
+ java.net.DatagramSocket(0, java.net.InetAddress.getByName(address)).use { socket ->
455
+ val target = gateway ?: return@runCatching "bound to $address; no gateway to send to"
456
+ socket.send(
457
+ java.net.DatagramPacket(
458
+ ByteArray(1),
459
+ 1,
460
+ java.net.InetAddress.getByName(target),
461
+ UDP_PROBE_PORT,
462
+ ),
463
+ )
464
+ "bound to ${socket.localAddress?.hostAddress}:${socket.localPort}, send accepted"
465
+ }
466
+ }
467
+ SoftApTrace.stage(
468
+ "unmarked_udp_send",
469
+ "address" to address,
470
+ "gateway" to (gateway ?: "none"),
471
+ "accepted" to result.isSuccess,
472
+ "detail" to
473
+ (result.getOrNull() ?: result.exceptionOrNull()?.let { "${it.javaClass.simpleName}: ${it.message}" }),
474
+ "proves" to "the OS accepted a datagram; not that the glasses received one",
475
+ )
476
+ }
477
+
478
+ /** Drop the network. A join in progress on another thread stops waiting and fails. */
479
+ fun release() {
480
+ synchronized(lock) {
481
+ releases++
482
+ pendingReady?.countDown()
483
+ releaseLocked()
484
+ }
485
+ }
486
+
487
+ private fun releaseLocked() {
488
+ pendingReady = null
489
+ val active = callback
490
+ if (active != null) {
491
+ runCatching { connectivityManager().unregisterNetworkCallback(active) }
492
+ SoftApTrace.stage("scoped_network_released")
493
+ }
494
+ callback = null
495
+ network = null
496
+ localIpv4 = null
497
+ spec = null
498
+ listener = null
499
+ state.release()
500
+ state.reset()
501
+ }
502
+
503
+ private fun clearCallback(expected: ConnectivityManager.NetworkCallback) {
504
+ synchronized(lock) {
505
+ if (callback !== expected) return
506
+ runCatching { connectivityManager().unregisterNetworkCallback(expected) }
507
+ callback = null
508
+ }
509
+ }
510
+
511
+ private fun connectivityManager(): ConnectivityManager =
512
+ requireNotNull(context.getSystemService(ConnectivityManager::class.java)) {
513
+ "ConnectivityManager is unavailable"
514
+ }
515
+
516
+
517
+
518
+ /** Translate the pure spec into the framework request. */
519
+ private fun request(spec: ScopedNetworkRequestSpec): NetworkRequest {
520
+ val specifier =
521
+ WifiNetworkSpecifier.Builder()
522
+ .setSsid(spec.ssid)
523
+ .apply { if (spec.hasPassphrase) setWpa2Passphrase(spec.passphrase) }
524
+ .build()
525
+
526
+ val builder = NetworkRequest.Builder()
527
+ spec.transportTypes.forEach { builder.addTransportType(it) }
528
+ spec.removedCapabilities.forEach { builder.removeCapability(it) }
529
+ return builder.setNetworkSpecifier(specifier).build()
530
+ }
531
+
532
+ private fun firstIpv4(properties: LinkProperties?): String? =
533
+ properties
534
+ ?.linkAddresses
535
+ ?.firstOrNull { it.address is Inet4Address }
536
+ ?.address
537
+ ?.hostAddress
538
+
539
+ /** Dual-homing check: the default route must still be cellular after the scoped join. */
540
+ private fun defaultNetworkIsCellular(manager: ConnectivityManager): Boolean {
541
+ val active = manager.activeNetwork ?: return false
542
+ val capabilities = manager.getNetworkCapabilities(active) ?: return false
543
+ return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
544
+ }
545
+
546
+ companion object {
547
+ /** Android 17. `ACCESS_LOCAL_NETWORK` is enforced for apps targeting SDK 37+. */
548
+ const val LOCAL_NETWORK_ENFORCED_SDK = 37
549
+
550
+ /** Legacy targets retain implicit LAN access, even when the runtime grant reports denied. */
551
+ internal fun hasLocalNetworkPermission(
552
+ sdkInt: Int,
553
+ targetSdkInt: Int,
554
+ permissionGranted: () -> Boolean,
555
+ ): Boolean =
556
+ sdkInt < LOCAL_NETWORK_ENFORCED_SDK ||
557
+ targetSdkInt < LOCAL_NETWORK_ENFORCED_SDK ||
558
+ permissionGranted()
559
+
560
+ private const val AWAIT_GRACE_MS = 2_000L
561
+
562
+ /** How long we hold the scoped-join step open for the user to flip the Wi-Fi toggle. */
563
+ const val WIFI_ENABLE_WAIT_MS = 90_000L
564
+ const val WIFI_ENABLE_POLL_MS = 300L
565
+ /** Radio + scan need a beat after `isWifiEnabled` flips before specifier can see the AP. */
566
+ const val WIFI_ENABLE_SETTLE_MS = 1_500L
567
+
568
+ /** The gap before [join] asks again after an Unavailable while leaving another AP. */
569
+ private const val UNAVAILABLE_RETRY_SETTLE_MS = 2_000L
570
+
571
+ /**
572
+ * Leaving the phone's current Wi-Fi (office AP, a phone hotspot) can make the first
573
+ * specifier fail as Unavailable: Samsung assoc-rejects the glasses SoftAP (status 1025)
574
+ * after dropping the old network. The same request from the now idle STA succeeds, so
575
+ * [join] asks once more, unless it was released before or during the settle.
576
+ */
577
+ internal fun <T> retryUnavailableOnce(request: () -> T, settle: () -> Unit, released: () -> Boolean): T =
578
+ try {
579
+ request()
580
+ } catch (error: ScopedNetworkError.Unavailable) {
581
+ if (released()) throw error
582
+ settle()
583
+ if (released()) throw error
584
+ request()
585
+ }
586
+
587
+ /**
588
+ * dnsmasq (DHCP/DNS) on the hotspot, then the glasses' local HTTP servers. Any answer —
589
+ * accept or refuse — proves the path; only silence fails it.
590
+ */
591
+ private val GATEWAY_PROBE_PORTS = intArrayOf(53, 8089, 80)
592
+ private const val GATEWAY_PROBE_TIMEOUT_MS = 2_000
593
+
594
+ /**
595
+ * How long the address is given to appear in the kernel table after the callbacks agree.
596
+ * Generous because failing here aborts the call, and the observed lag is sub-second.
597
+ */
598
+ private const val READINESS_WAIT_MS = 5_000L
599
+ private const val READINESS_POLL_MS = 150L
600
+
601
+ /** dnsmasq on the hotspot. Nothing is expected back; only the send is being observed. */
602
+ private const val UDP_PROBE_PORT = 53
603
+ }
604
+ }