@mentra/bluetooth-sdk 3.5.0-dev.1517 → 3.5.0-dev.1519

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 (119) hide show
  1. package/MIGRATION.md +9 -0
  2. package/README.md +67 -12
  3. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  4. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +10 -0
  5. package/android/src/main/java/com/mentra/bluetoothsdk/camera/CameraModels.kt +9 -2
  6. package/android/src/test/java/com/mentra/bluetoothsdk/camera/PhotoRequestTest.kt +8 -0
  7. package/build/BluetoothSdk.types.d.ts +33 -7
  8. package/build/BluetoothSdk.types.d.ts.map +1 -1
  9. package/build/BluetoothSdk.types.js +5 -0
  10. package/build/BluetoothSdk.types.js.map +1 -1
  11. package/build/_internal.d.ts +1 -0
  12. package/build/_internal.d.ts.map +1 -1
  13. package/build/_internal.js +1 -0
  14. package/build/_internal.js.map +1 -1
  15. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  16. package/build/_private/BluetoothSdkModule.js +20 -9
  17. package/build/_private/BluetoothSdkModule.js.map +1 -1
  18. package/build/_private/MentraLocalNetworkModule.d.ts +21 -0
  19. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  20. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  21. package/build/_private/photoRequestPayload.d.ts +1 -1
  22. package/build/_private/photoRequestPayload.d.ts.map +1 -1
  23. package/build/_private/photoRequestPayload.js +4 -1
  24. package/build/_private/photoRequestPayload.js.map +1 -1
  25. package/build/generated/releaseMetadata.js +5 -5
  26. package/build/generated/releaseMetadata.js.map +1 -1
  27. package/build/glasses-wifi/connection.d.ts +6 -0
  28. package/build/glasses-wifi/connection.d.ts.map +1 -0
  29. package/build/glasses-wifi/connection.js +44 -0
  30. package/build/glasses-wifi/connection.js.map +1 -0
  31. package/build/glasses-wifi/continuous.d.ts +39 -0
  32. package/build/glasses-wifi/continuous.d.ts.map +1 -0
  33. package/build/glasses-wifi/continuous.js +151 -0
  34. package/build/glasses-wifi/continuous.js.map +1 -0
  35. package/build/glasses-wifi/files.d.ts +11 -0
  36. package/build/glasses-wifi/files.d.ts.map +1 -0
  37. package/build/glasses-wifi/files.js +33 -0
  38. package/build/glasses-wifi/files.js.map +1 -0
  39. package/build/glasses-wifi/index.d.ts +20 -0
  40. package/build/glasses-wifi/index.d.ts.map +1 -0
  41. package/build/glasses-wifi/index.js +15 -0
  42. package/build/glasses-wifi/index.js.map +1 -0
  43. package/build/glasses-wifi/link.d.ts +31 -0
  44. package/build/glasses-wifi/link.d.ts.map +1 -0
  45. package/build/glasses-wifi/link.js +71 -0
  46. package/build/glasses-wifi/link.js.map +1 -0
  47. package/build/glasses-wifi/native.d.ts +63 -0
  48. package/build/glasses-wifi/native.d.ts.map +1 -0
  49. package/build/glasses-wifi/native.js +138 -0
  50. package/build/glasses-wifi/native.js.map +1 -0
  51. package/build/glasses-wifi/service.d.ts +86 -0
  52. package/build/glasses-wifi/service.d.ts.map +1 -0
  53. package/build/glasses-wifi/service.js +497 -0
  54. package/build/glasses-wifi/service.js.map +1 -0
  55. package/build/index.d.ts +4 -2
  56. package/build/index.d.ts.map +1 -1
  57. package/build/index.js +24 -6
  58. package/build/index.js.map +1 -1
  59. package/build/ota-transport/index.d.ts +2 -43
  60. package/build/ota-transport/index.d.ts.map +1 -1
  61. package/build/ota-transport/index.js +3 -49
  62. package/build/ota-transport/index.js.map +1 -1
  63. package/build/react/useBluetoothStatus.d.ts.map +1 -1
  64. package/build/react/useBluetoothStatus.js +5 -24
  65. package/build/react/useBluetoothStatus.js.map +1 -1
  66. package/build/react/useMentraBluetooth.d.ts +1 -2
  67. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  68. package/build/react/useMentraBluetooth.js +0 -1
  69. package/build/react/useMentraBluetooth.js.map +1 -1
  70. package/expo-module.config.json +1 -1
  71. package/ios/MentraBluetoothSDK.podspec +5 -4
  72. package/ios/MentraLocalNetworkModule.swift +264 -0
  73. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  74. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  75. package/ios/Source/camera/CameraModels.swift +7 -2
  76. package/ios/Source/hotspot/GlassesHotspotNetwork.swift +563 -0
  77. package/ios/Source/hotspot/HotspotAccessPurpose.swift +5 -0
  78. package/ios/Source/hotspot/HotspotAddressPolicy.swift +50 -0
  79. package/ios/Source/hotspot/HotspotInterfacePolicy.swift +155 -0
  80. package/ios/Source/hotspot/HotspotJoinFailure.swift +27 -0
  81. package/ios/Source/hotspot/HotspotLeaveCompletion.swift +24 -0
  82. package/ios/Source/hotspot/HotspotNetworkOwnership.swift +22 -0
  83. package/ios/Source/hotspot/HotspotReapplyPolicy.swift +26 -0
  84. package/ios/Source/hotspot/LocalNetworkAccessRequest.swift +160 -0
  85. package/ios/Source/hotspot/MacHotspotAssociation.swift +415 -0
  86. package/ios/Source/hotspot/MacHotspotAuthorization.swift +126 -0
  87. package/ios/Source/hotspot/MacHotspotAuthorizationFacts.swift +51 -0
  88. package/ios/Source/hotspot/MacHotspotCleanupContinuation.swift +35 -0
  89. package/ios/Tests/HotspotAddressPolicyTests.swift +30 -0
  90. package/ios/Tests/HotspotInterfacePolicyTests.swift +304 -0
  91. package/ios/Tests/HotspotJoinFailureTests.swift +37 -0
  92. package/ios/Tests/HotspotLeaveCompletionTests.swift +29 -0
  93. package/ios/Tests/HotspotReapplyPolicyTests.swift +18 -0
  94. package/ios/Tests/LocalNetworkAccessRequestTests.swift +237 -0
  95. package/ios/Tests/MacHotspotAssociationTests.swift +521 -0
  96. package/ios/Tests/MacHotspotAuthorizationFactsTests.swift +62 -0
  97. package/ios/Tests/MacHotspotAuthorizationTests.swift +348 -0
  98. package/ios/Tests/MacWifiInvocationTests.swift +76 -0
  99. package/ios/Tests/PhotoRequestRoutingTests.swift +7 -0
  100. package/package.json +7 -2
  101. package/plugin/build/withIos.d.ts +4 -0
  102. package/plugin/build/withIos.js +20 -1
  103. package/src/BluetoothSdk.types.ts +37 -7
  104. package/src/_internal.ts +1 -0
  105. package/src/_private/BluetoothSdkModule.ts +20 -10
  106. package/src/_private/MentraLocalNetworkModule.ts +22 -0
  107. package/src/_private/photoRequestPayload.ts +4 -1
  108. package/src/generated/releaseMetadata.ts +5 -5
  109. package/src/glasses-wifi/connection.ts +47 -0
  110. package/src/glasses-wifi/continuous.ts +177 -0
  111. package/src/glasses-wifi/files.ts +32 -0
  112. package/src/glasses-wifi/index.ts +24 -0
  113. package/src/glasses-wifi/link.ts +94 -0
  114. package/src/glasses-wifi/native.ts +193 -0
  115. package/src/glasses-wifi/service.ts +554 -0
  116. package/src/index.ts +34 -10
  117. package/src/ota-transport/index.ts +3 -85
  118. package/src/react/useBluetoothStatus.ts +5 -26
  119. package/src/react/useMentraBluetooth.ts +0 -3
@@ -0,0 +1,554 @@
1
+ // The service is the one sender of hotspot commands; apps never see them.
2
+ // eslint-disable-next-line no-restricted-imports
3
+ import PrivateBluetoothSdkModule from "../_private/BluetoothSdkModule"
4
+ import {
5
+ isConnectedGlassesConnectionStatus,
6
+ isEnabledHotspotStatus,
7
+ isReadyGlassesConnectionStatus,
8
+ type GlassesConnectionStatus,
9
+ type HotspotStatus,
10
+ } from "../BluetoothSdk.types"
11
+ import {glassesConnection, onGlassesConnection, watchGlassesConnection} from "./connection"
12
+ import * as native from "./native"
13
+
14
+ /**
15
+ * The glasses Wi-Fi service: the one owner of the phone-to-glasses Wi-Fi link.
16
+ *
17
+ * Photo fetches, gallery sync, hotspot OTA, Mentra Call, the managed relay and every fast link
18
+ * hold the link here and use the binding it gives them; none of them sends a hotspot command or
19
+ * joins a network itself. The link is shared: the first holder brings it up (Wi-Fi Direct on
20
+ * Android with glasses that advertise it, else the glasses' hotspot, then the phone's one native
21
+ * join), later holders get the same binding, and the last release takes it down.
22
+ *
23
+ * When the link goes down (the phone leaves the network, the glasses turn the AP off, restart, or
24
+ * leave Bluetooth), holders hear `lost`; the service asks for the link again once the glasses are
25
+ * back and ready, and holders hear `restored` with the new binding. Glasses that do not come back
26
+ * within [RESTORE_DEADLINE_MS] end it: holders hear `ended` and still release.
27
+ */
28
+
29
+ export type GlassesWifiBinding = {
30
+ ssid: string
31
+ password: string
32
+ /** The glasses' address on the link. */
33
+ gateway: string
34
+ /** The phone's address on the link, when the native join reports it. */
35
+ phoneIpv4?: string
36
+ frequency?: number
37
+ }
38
+
39
+ export type GlassesWifiEvent =
40
+ | {type: "lost"; reason: string}
41
+ | {type: "restored"; binding: GlassesWifiBinding}
42
+ | {type: "ended"; reason: string}
43
+
44
+ export type GlassesWifiHoldOptions = {
45
+ /** Who holds it, for logs. */
46
+ consumer: string
47
+ /** "incoming-server" when the glasses connect to the phone (OTA, video); it adds the VPN check. */
48
+ purpose?: native.JoinPurpose
49
+ /** Aborting it while the link comes up gives the hold back. */
50
+ signal?: AbortSignal
51
+ /** Runs once the glasses report the network and before the first join, e.g. an explanation. */
52
+ beforeJoin?: (ssid: string) => Promise<void>
53
+ /** iOS: the join waited a few seconds for Local Network access, which may have been denied. */
54
+ onPermissionRequired?: (systemAnswer: string) => void
55
+ /** Narration for a consumer that shows its steps. */
56
+ report?: (line: string) => void
57
+ }
58
+
59
+ export interface GlassesWifiHold {
60
+ /** The link as it is now; after `lost`, the last one until `restored`. */
61
+ readonly binding: GlassesWifiBinding
62
+ onChange(listener: (event: GlassesWifiEvent) => void): () => void
63
+ /** The binding once the link is up: now, or when it is restored. Rejects when it ends or on abort. */
64
+ ready(signal?: AbortSignal): Promise<GlassesWifiBinding>
65
+ /** Idempotent. The link goes down once nobody holds it. */
66
+ release(): Promise<void>
67
+ }
68
+
69
+ /** Bringing the link up failed: the glasses did not enable it, or the phone did not join it. */
70
+ export class GlassesWifiError extends Error {
71
+ /** The native join's code, e.g. `SOFTAP_UNAVAILABLE`, when it has one. */
72
+ readonly code?: string
73
+ constructor(readonly stage: "enable" | "join", readonly cause: unknown) {
74
+ super(cause instanceof Error ? cause.message : String(cause))
75
+ this.name = "GlassesWifiError"
76
+ const code = (cause as {code?: unknown} | null)?.code
77
+ if (typeof code === "string") this.code = code
78
+ }
79
+ }
80
+
81
+ /** How often an enable is re-sent while a join waits: the glasses stop an AP unused for 120 s. */
82
+ export const JOIN_KEEPALIVE_MS = 30_000
83
+ /** The glasses report the AP enabled before its SSID is in the phone's scan. */
84
+ export const BROADCAST_WAIT_MS = 3_000
85
+ /** How long holders wait for glasses that restarted or left before the link ends. */
86
+ export const RESTORE_DEADLINE_MS = 3 * 60_000
87
+ /** How long after the last release an enabled report is taken as a late enable to undo (OS-2133). */
88
+ export const LATE_ENABLE_WINDOW_MS = 60_000
89
+
90
+ const SESSION_REFRESH_CODES = new Set(["wifi_session_restarted", "wifi_session_changed"])
91
+
92
+ type Holder = {options: GlassesWifiHoldOptions; listeners: Set<(event: GlassesWifiEvent) => void>}
93
+ type Link = "hotspot" | "wifi_direct"
94
+
95
+ const holders = new Set<Holder>()
96
+ let binding: GlassesWifiBinding | null = null
97
+ let bringingUp: Promise<GlassesWifiBinding> | null = null
98
+ let takingDown: Promise<void> | null = null
99
+ /** The radio of the link up or coming up. */
100
+ let linkType: Link | null = null
101
+ let lostAt: number | null = null
102
+ /** Why the link ended, while it stays down; ready() rejects with it. */
103
+ let endedReason: string | null = null
104
+ let releasedAt = Number.NEGATIVE_INFINITY
105
+ let commands: Promise<unknown> = Promise.resolve()
106
+ let watching: (() => void) | null = null
107
+ let cancelRestore: (() => void) | null = null
108
+ let cancelDeadline: (() => void) | null = null
109
+ const upListeners = new Set<(up: boolean) => void>()
110
+ let reclaiming: {remove(): void} | null = null
111
+
112
+ /** The link's binding; whoever listens hears it go up and down. */
113
+ function setBinding(next: GlassesWifiBinding | null): void {
114
+ const changed = (binding === null) !== (next === null)
115
+ binding = next
116
+ if (!changed) return
117
+ for (const listener of upListeners) {
118
+ try {
119
+ listener(next !== null)
120
+ } catch (error) {
121
+ console.warn("[GlassesWifi] A link listener failed", error)
122
+ }
123
+ }
124
+ }
125
+
126
+ const message = (error: unknown) => (error instanceof Error ? error.message : String(error))
127
+
128
+ /** Run `callback` after `ms`, also in the background; the returned function cancels it. */
129
+ function after(ms: number, callback: () => void): () => void {
130
+ let cancelled = false
131
+ void native.delay(ms).then(() => {
132
+ if (!cancelled) callback()
133
+ })
134
+ return () => {
135
+ cancelled = true
136
+ }
137
+ }
138
+
139
+ /**
140
+ * One hotspot command at a time, re-sent once when a restarting ASG dropped it. ASG answers a
141
+ * same-state command with its current status, so a re-send never cycles the AP.
142
+ */
143
+ function setHotspot(enabled: boolean): Promise<HotspotStatus> {
144
+ const send = async () => {
145
+ try {
146
+ return await PrivateBluetoothSdkModule.setHotspotState(enabled)
147
+ } catch (error) {
148
+ const code = (error as {code?: string} | null)?.code
149
+ if (!code || !SESSION_REFRESH_CODES.has(code)) throw error
150
+ await native.delay(500)
151
+ return await PrivateBluetoothSdkModule.setHotspotState(enabled)
152
+ }
153
+ }
154
+ const run = commands.then(send, send)
155
+ commands = run.catch(() => undefined)
156
+ return run
157
+ }
158
+
159
+ /** Hold the glasses Wi-Fi link, bringing it up if nobody holds it yet. */
160
+ export async function holdGlassesWifi(options: GlassesWifiHoldOptions): Promise<GlassesWifiHold> {
161
+ const holder: Holder = {options, listeners: new Set()}
162
+ if (takingDown) await takingDown
163
+ holders.add(holder)
164
+ watchLateHotspots()
165
+ await watch()
166
+ // A cancelled hold settles at once, whatever the link is doing; giving it back stops the
167
+ // bring-up when nobody else wants the link (the join waits on the person answering a prompt).
168
+ let abort = () => {}
169
+ const aborted = new Promise<never>((_, reject) => {
170
+ abort = () => reject(new Error("Glasses Wi-Fi hold cancelled"))
171
+ })
172
+ aborted.catch(() => undefined)
173
+ options.signal?.addEventListener("abort", abort, {once: true})
174
+ let current: GlassesWifiBinding
175
+ try {
176
+ if (options.signal?.aborted) throw new Error("Glasses Wi-Fi hold cancelled")
177
+ current = binding ?? (await Promise.race([bringingUp ?? bringUp(holder), aborted]))
178
+ } catch (error) {
179
+ // Not awaited: the teardown waits for the bring-up to settle, and the next hold waits for it.
180
+ void release(holder).catch((cause) => console.warn("[GlassesWifi] Giving back a failed hold failed", cause))
181
+ throw error
182
+ } finally {
183
+ options.signal?.removeEventListener("abort", abort)
184
+ }
185
+ console.log(`[GlassesWifi] ${options.consumer} holds the link (${holders.size} holder(s))`)
186
+ let released: Promise<void> | null = null
187
+ return {
188
+ get binding() {
189
+ return binding ?? current
190
+ },
191
+ onChange(listener) {
192
+ holder.listeners.add(listener)
193
+ return () => holder.listeners.delete(listener)
194
+ },
195
+ ready(signal) {
196
+ if (binding) return Promise.resolve(binding)
197
+ if (endedReason) return Promise.reject(new Error(endedReason))
198
+ return new Promise((resolve, reject) => {
199
+ const done = () => {
200
+ holder.listeners.delete(listener)
201
+ signal?.removeEventListener("abort", onAbort)
202
+ }
203
+ const listener = (event: GlassesWifiEvent) => {
204
+ if (event.type === "lost") return
205
+ done()
206
+ if (event.type === "restored") resolve(event.binding)
207
+ else reject(new Error(event.reason))
208
+ }
209
+ const onAbort = () => {
210
+ done()
211
+ reject(new Error("Glasses Wi-Fi wait cancelled"))
212
+ }
213
+ holder.listeners.add(listener)
214
+ signal?.addEventListener("abort", onAbort, {once: true})
215
+ })
216
+ },
217
+ release() {
218
+ released ??= release(holder)
219
+ return released
220
+ },
221
+ }
222
+ }
223
+
224
+ /**
225
+ * The radio, chosen once per bring-up from the platform and the glasses' capability: Wi-Fi Direct
226
+ * on Android with glasses that advertise `wifi_direct_version`, the hotspot otherwise.
227
+ */
228
+ function chooseLink(): Link {
229
+ return native.wifiDirectAvailable() ? "wifi_direct" : "hotspot"
230
+ }
231
+
232
+ const purpose = (): native.JoinPurpose =>
233
+ [...holders].some((holder) => holder.options.purpose === "incoming-server") ? "incoming-server" : "outgoing-client"
234
+
235
+ function bringUp(first: Holder | null): Promise<GlassesWifiBinding> {
236
+ const attempt = (async () => {
237
+ const report = (line: string) => first?.options.report?.(line)
238
+ linkType = chooseLink()
239
+ console.log(`[GlassesWifi] Bringing up the ${linkType} link`)
240
+ const joined = linkType === "wifi_direct" ? await joinWifiDirect(report) : await joinHotspot(first, report)
241
+ const wasLost = lostAt !== null
242
+ setBinding(joined)
243
+ lostAt = null
244
+ endedReason = null
245
+ if (wasLost) notify({type: "restored", binding: joined})
246
+ return joined
247
+ })()
248
+ bringingUp = attempt
249
+ const settled = () => {
250
+ if (bringingUp === attempt) bringingUp = null
251
+ }
252
+ attempt.then(settled, settled)
253
+ return attempt
254
+ }
255
+
256
+ async function joinHotspot(first: Holder | null, report: (line: string) => void): Promise<GlassesWifiBinding> {
257
+ const status = await enableHotspot(report).catch((error) => {
258
+ throw new GlassesWifiError("enable", error)
259
+ })
260
+ assertWanted()
261
+ await beforeJoin(first, status.ssid)
262
+ assertWanted()
263
+ return await joinWithRetry(status, first, report).catch((error) => {
264
+ throw error instanceof GlassesWifiError ? error : new GlassesWifiError("join", error)
265
+ })
266
+ }
267
+
268
+ /** The native join asks the glasses for their group over Bluetooth and joins it, with no prompt. */
269
+ async function joinWifiDirect(report: (line: string) => void): Promise<GlassesWifiBinding> {
270
+ assertWanted()
271
+ const joined = await native.joinWifiDirect(purpose()).catch((error) => {
272
+ throw new GlassesWifiError("join", error)
273
+ })
274
+ if (!joined.gateway) throw new GlassesWifiError("join", new Error("The glasses reported no group address"))
275
+ report(`Joined the glasses' Wi-Fi Direct group ${joined.ssid}`)
276
+ // A group has no password the consumers need: the phone joined it with the one the glasses sent.
277
+ return {ssid: joined.ssid, password: "", gateway: joined.gateway, phoneIpv4: joined.localAddress}
278
+ }
279
+
280
+ async function enableHotspot(report: (line: string) => void) {
281
+ let status = await setHotspot(true).catch(async (error) => {
282
+ // An unanswered enable may still land: ask again rather than turn it off.
283
+ if (!/timed out waiting for glasses response|glasses did not answer/i.test(message(error))) throw error
284
+ report("Glasses did not answer; asking again")
285
+ return setHotspot(true)
286
+ })
287
+ if (!isEnabledHotspotStatus(status)) {
288
+ // A start racing the previous stop reports disabled: turn it off and start again once.
289
+ report("Glasses hotspot did not start; turning it off and trying again")
290
+ await setHotspot(false).catch(() => undefined)
291
+ await native.delay(1_000)
292
+ status = await setHotspot(true)
293
+ }
294
+ if (!isEnabledHotspotStatus(status) || !status.password) {
295
+ throw new Error(`The glasses hotspot did not start (state=${status.state})`)
296
+ }
297
+ report(`Glasses report hotspot ${status.ssid} enabled`)
298
+ await native.delay(BROADCAST_WAIT_MS)
299
+ return status
300
+ }
301
+
302
+ async function joinWithRetry(
303
+ status: Extract<HotspotStatus, {state: "enabled"}>,
304
+ first: Holder | null,
305
+ report: (line: string) => void,
306
+ ): Promise<GlassesWifiBinding> {
307
+ try {
308
+ return await join(status, first)
309
+ } catch (error) {
310
+ // Leaving the phone's previous Wi-Fi can make Android's first join fail as Unavailable.
311
+ // Cycle the AP and join again from an idle radio.
312
+ if (!/SOFTAP_UNAVAILABLE/.test(`${(error as {code?: string})?.code} ${message(error)}`)) throw error
313
+ if (holders.size === 0) throw error
314
+ report("Phone couldn't join; cycling the glasses hotspot and trying again")
315
+ await setHotspot(false)
316
+ const again = await enableHotspot(report)
317
+ return await join(again, first)
318
+ }
319
+ }
320
+
321
+ /**
322
+ * The first holder's step before the join, such as gallery's one-time explanation. It belongs to
323
+ * that holder: once it cancels, the bring-up stops waiting for it and goes on for anyone else.
324
+ */
325
+ async function beforeJoin(first: Holder | null, ssid: string): Promise<void> {
326
+ const step = first?.options.beforeJoin
327
+ const signal = first?.options.signal
328
+ if (!step || signal?.aborted) return
329
+ let onAbort = () => {}
330
+ const cancelled = new Promise<void>((resolve) => {
331
+ onAbort = resolve
332
+ signal?.addEventListener("abort", onAbort, {once: true})
333
+ })
334
+ try {
335
+ await Promise.race([
336
+ step(ssid).catch((error) => {
337
+ if (!signal?.aborted) throw error
338
+ }),
339
+ cancelled,
340
+ ])
341
+ } finally {
342
+ signal?.removeEventListener("abort", onAbort)
343
+ }
344
+ }
345
+
346
+ /** A bring-up nobody holds any more stops before it starts a join, which has no time limit. */
347
+ function assertWanted(): void {
348
+ if (holders.size === 0) throw new Error("Glasses Wi-Fi hold cancelled")
349
+ }
350
+
351
+ async function join(
352
+ status: Extract<HotspotStatus, {state: "enabled"}>,
353
+ first: Holder | null,
354
+ ): Promise<GlassesWifiBinding> {
355
+ assertWanted()
356
+ const joining = native.joinHotspot(status.ssid, status.password, {
357
+ gateway: status.localIp,
358
+ frequency: status.frequency,
359
+ purpose: purpose(),
360
+ onPermissionRequired: (answer) => first?.options.onPermissionRequired?.(answer),
361
+ })
362
+ // The join has no time limit, so a person can take their time with the phone's prompt. Keep
363
+ // the AP up meanwhile: a repeated enable restarts the glasses' idle clock.
364
+ let keepAlive = () => {}
365
+ const scheduleKeepAlive = () => {
366
+ keepAlive = after(JOIN_KEEPALIVE_MS, () => {
367
+ setHotspot(true).then(
368
+ (current) => {
369
+ if (current.state !== "enabled") void native.leave().catch(() => undefined)
370
+ },
371
+ (error) => console.warn("[GlassesWifi] Keeping the hotspot up during the join failed", error),
372
+ )
373
+ scheduleKeepAlive()
374
+ })
375
+ }
376
+ scheduleKeepAlive()
377
+ try {
378
+ const phoneIpv4 = await joining
379
+ return {
380
+ ssid: status.ssid,
381
+ password: status.password,
382
+ gateway: status.localIp,
383
+ phoneIpv4,
384
+ frequency: status.frequency,
385
+ }
386
+ } finally {
387
+ keepAlive()
388
+ }
389
+ }
390
+
391
+ async function release(holder: Holder): Promise<void> {
392
+ if (!holders.delete(holder)) return
393
+ console.log(`[GlassesWifi] ${holder.options.consumer} released the link (${holders.size} left)`)
394
+ if (holders.size > 0) return
395
+ takingDown = takeDown().finally(() => {
396
+ takingDown = null
397
+ })
398
+ await takingDown
399
+ }
400
+
401
+ async function takeDown(): Promise<void> {
402
+ unwatch()
403
+ if (bringingUp) {
404
+ void native.leave().catch(() => undefined)
405
+ await bringingUp.catch(() => undefined)
406
+ }
407
+ setBinding(null)
408
+ lostAt = null
409
+ endedReason = null
410
+ await native.leave().catch((error) => console.warn("[GlassesWifi] Leaving the glasses network failed", error))
411
+ releasedAt = Date.now()
412
+ // Leaving the Wi-Fi Direct group above also told the glasses to remove it.
413
+ const down = linkType
414
+ linkType = null
415
+ if (down === "wifi_direct") return
416
+ // Glasses away now get their AP turned off on return, by the late-hotspot watch, or by their idle stop.
417
+ if (!isConnectedGlassesConnectionStatus(glassesConnection())) return
418
+ for (let attempt = 1; attempt <= 2; attempt++) {
419
+ const status = await setHotspot(false).catch(() => null)
420
+ if (status?.state === "disabled") return
421
+ // A just-replaced ASG can drop the first command while its command path settles.
422
+ await native.delay(500)
423
+ }
424
+ console.warn("[GlassesWifi] The glasses did not confirm their hotspot is off")
425
+ }
426
+
427
+ function notify(event: GlassesWifiEvent): void {
428
+ for (const holder of holders) {
429
+ for (const listener of holder.listeners) {
430
+ try {
431
+ listener(event)
432
+ } catch (error) {
433
+ console.warn(`[GlassesWifi] ${holder.options.consumer} failed handling ${event.type}`, error)
434
+ }
435
+ }
436
+ }
437
+ }
438
+
439
+ function lose(reason: string): void {
440
+ if (!binding || holders.size === 0) return
441
+ console.warn(`[GlassesWifi] The link went down: ${reason}`)
442
+ setBinding(null)
443
+ lostAt = Date.now()
444
+ void native.leave().catch(() => undefined)
445
+ notify({type: "lost", reason})
446
+ scheduleRestore()
447
+ // Glasses that never come back still end the link at the deadline.
448
+ cancelDeadline?.()
449
+ cancelDeadline = after(RESTORE_DEADLINE_MS + 1, () => {
450
+ cancelDeadline = null
451
+ void restore()
452
+ })
453
+ }
454
+
455
+ /** Ask for the link again once the glasses are ready, until it is back or the deadline passes. */
456
+ function scheduleRestore(delayMs = 0): void {
457
+ cancelRestore?.()
458
+ cancelRestore = after(delayMs, () => {
459
+ cancelRestore = null
460
+ void restore()
461
+ })
462
+ }
463
+
464
+ async function restore(): Promise<void> {
465
+ if (binding || bringingUp || holders.size === 0 || lostAt === null) return
466
+ if (Date.now() - lostAt > RESTORE_DEADLINE_MS) {
467
+ lostAt = null
468
+ endedReason = "the glasses did not bring the link back"
469
+ notify({type: "ended", reason: endedReason})
470
+ return
471
+ }
472
+ if (!isReadyGlassesConnectionStatus(glassesConnection())) return // the connection watch calls again
473
+ try {
474
+ await bringUp(null)
475
+ } catch (error) {
476
+ console.warn("[GlassesWifi] Bringing the link back failed; trying again", error)
477
+ scheduleRestore(5_000)
478
+ }
479
+ }
480
+
481
+ async function watch(): Promise<void> {
482
+ if (watching) return
483
+ const unsubscribeStatus = onGlassesConnection(onConnection)
484
+ const networkLost = native.onLost(() => lose("the phone left the glasses network"))
485
+ const hotspot = PrivateBluetoothSdkModule.addListener("hotspot_status_change", (event) => {
486
+ if (linkType === "hotspot" && event.state !== "enabled" && !bringingUp) lose("the glasses turned their hotspot off")
487
+ })
488
+ watching = () => {
489
+ unsubscribeStatus()
490
+ networkLost()
491
+ hotspot.remove()
492
+ }
493
+ await watchGlassesConnection()
494
+ }
495
+
496
+ function onConnection(next: GlassesConnectionStatus): void {
497
+ if (!isConnectedGlassesConnectionStatus(next)) {
498
+ // A join still waiting cannot finish without the glasses: end it, as a loss does.
499
+ if (bringingUp) void native.leave().catch(() => undefined)
500
+ lose("the glasses left Bluetooth")
501
+ } else if (lostAt !== null && isReadyGlassesConnectionStatus(next)) scheduleRestore()
502
+ }
503
+
504
+ function unwatch(): void {
505
+ watching?.()
506
+ watching = null
507
+ cancelRestore?.()
508
+ cancelRestore = null
509
+ cancelDeadline?.()
510
+ cancelDeadline = null
511
+ }
512
+
513
+ /**
514
+ * Hold the link only if it is up now (someone else brought it up): for a use that is just as well
515
+ * served over Bluetooth, like a file fetch, and must not bring the link up itself. Null when it
516
+ * is down, coming up or going down.
517
+ */
518
+ export async function holdGlassesWifiIfUp(consumer: string): Promise<GlassesWifiHold | null> {
519
+ if (holders.size === 0 || !binding || lostAt !== null || bringingUp || takingDown) return null
520
+ return holdGlassesWifi({consumer})
521
+ }
522
+
523
+ /** Whether anyone holds the link now. */
524
+ function held(): boolean {
525
+ return holders.size > 0 || takingDown !== null
526
+ }
527
+
528
+ /**
529
+ * Turn off a hotspot that came up with no holder soon after the last release: a hotspot command
530
+ * can wait in the BLE queue past its caller and reach the glasses after the release (OS-2133).
531
+ * An AP the glasses start on their own, long after any phone use, is left alone. Watched from the
532
+ * first hold on, since only a release opens the window.
533
+ */
534
+ function watchLateHotspots(): void {
535
+ if (reclaiming) return
536
+ reclaiming = PrivateBluetoothSdkModule.addListener("hotspot_status_change", (event) => {
537
+ if (event.state !== "enabled" || held() || Date.now() - releasedAt >= LATE_ENABLE_WINDOW_MS) return
538
+ console.warn("[GlassesWifi] An enabled hotspot has no holder after a release; turning it off")
539
+ void setHotspot(false).catch((error) => console.warn("[GlassesWifi] Could not turn off the late hotspot", error))
540
+ })
541
+ }
542
+
543
+ /** Whether the glasses Wi-Fi link is up now, for whoever holds it. */
544
+ export function glassesWifiUp(): boolean {
545
+ return binding !== null
546
+ }
547
+
548
+ /** Hear the glasses Wi-Fi link go up and down, whoever holds it. */
549
+ export function onGlassesWifiUp(listener: (up: boolean) => void): () => void {
550
+ upListeners.add(listener)
551
+ return () => {
552
+ upListeners.delete(listener)
553
+ }
554
+ }
package/src/index.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  import {parsePhotoCompression} from "@mentra/cloud-protocol/photo-compression"
2
2
  import PrivateBluetoothSdkModule from "./_private/BluetoothSdkModule"
3
+ import {publicGlassesStatus} from "./BluetoothSdk.types"
3
4
  import type {
4
5
  BluetoothSdkEventListener,
5
6
  BluetoothSdkEventName,
6
7
  BluetoothSdkPublicModule,
7
8
  PhotoCaptureDefaults,
9
+ PhotoCapture,
10
+ PhotoCaptureParams,
8
11
  PublicBluetoothStatus,
9
12
  PublicGlassesStatus,
10
13
  VideoRecordingDefaults,
11
14
  } from "./BluetoothSdk.types"
12
15
  import {getReleaseChangelogs} from "./changelogs"
16
+ import {runContinuousCapture} from "./glasses-wifi/continuous"
17
+ import {createLink} from "./glasses-wifi/link"
18
+
19
+ /** The app's own links to the glasses, and its hold on the fast link. */
20
+ const link = createLink("app fast link")
13
21
 
14
22
  const PUBLIC_EVENT_NAMES = new Set<BluetoothSdkEventName>([
15
23
  "native_notification_status",
@@ -32,8 +40,6 @@ const PUBLIC_EVENT_NAMES = new Set<BluetoothSdkEventName>([
32
40
  "wifi_scan_result",
33
41
  "wifi_forget_result",
34
42
  "saved_wifi_networks",
35
- "hotspot_status_change",
36
- "hotspot_error",
37
43
  "photo_response",
38
44
  "photo_status",
39
45
  "camera_status",
@@ -100,10 +106,10 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
100
106
  configureNativeNotifications: bindPublicMethod("configureNativeNotifications"),
101
107
  getNativeNotificationStatus: bindPublicMethod("getNativeNotificationStatus"),
102
108
  addListener,
103
- getGlassesStatus: bindPublicMethod("getGlassesStatus"),
109
+ getGlassesStatus: async () => publicGlassesStatus(await PrivateBluetoothSdkModule.getGlassesStatus()),
104
110
  getBluetoothStatus: bindPublicMethod("getBluetoothStatus"),
105
111
  subscribeGlassesStatus: (listener: (changed: Partial<PublicGlassesStatus>) => void) =>
106
- PrivateBluetoothSdkModule.onGlassesStatus(listener),
112
+ PrivateBluetoothSdkModule.onGlassesStatus((changed) => listener(publicGlassesStatus(changed))),
107
113
  subscribeBluetoothStatus: (listener: (changed: Partial<PublicBluetoothStatus>) => void) =>
108
114
  PrivateBluetoothSdkModule.onBluetoothStatus(listener),
109
115
  getDefaultDevice: bindPublicMethod("getDefaultDevice"),
@@ -130,7 +136,6 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
130
136
  getSavedWifiNetworks: bindPublicMethod("getSavedWifiNetworks"),
131
137
  sendWifiCredentials: bindPublicMethod("sendWifiCredentials"),
132
138
  forgetWifiNetwork: bindPublicMethod("forgetWifiNetwork"),
133
- setHotspotState: bindPublicMethod("setHotspotState"),
134
139
  setSystemTime: bindPublicMethod("setSystemTime"),
135
140
  setWifiAdbState: bindPublicMethod("setWifiAdbState"),
136
141
  setGalleryServerEnabled: bindPublicMethod("setGalleryServerEnabled"),
@@ -167,6 +172,27 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
167
172
  uploadPhoto: bindPublicMethod("uploadPhoto"),
168
173
  capturePhoto: bindPublicMethod("capturePhoto"),
169
174
  takePhoto: bindPublicMethod("takePhoto"),
175
+ link,
176
+ captureContinuous: (options: PhotoCaptureParams & {maxPending?: number}) =>
177
+ runContinuousCapture(
178
+ (params: PhotoCaptureParams, released): PhotoCapture => {
179
+ const capture = PrivateBluetoothSdkModule.capturePhoto(params)
180
+ // The run counts the photos still on the glasses: this one stops counting once released.
181
+ return {
182
+ requestId: capture.requestId,
183
+ get captured() {
184
+ return capture.captured
185
+ },
186
+ get preview() {
187
+ return capture.preview
188
+ },
189
+ photo: () => capture.photo(),
190
+ release: () => capture.release().finally(released),
191
+ }
192
+ },
193
+ options,
194
+ "app continuous capture",
195
+ ),
170
196
  warmUpCamera: bindPublicMethod("warmUpCamera"),
171
197
  stopCameraWarmUp: bindPublicMethod("stopCameraWarmUp"),
172
198
  startVideoRecording: bindPublicMethod("startVideoRecording"),
@@ -210,6 +236,9 @@ export const BluetoothSdk: BluetoothSdkPublicModule = Object.freeze({
210
236
 
211
237
  export default BluetoothSdk
212
238
 
239
+ export type {GlassesLink, LinkState} from "./glasses-wifi/link"
240
+ export type {ContinuousCapture, ContinuousState} from "./glasses-wifi/continuous"
241
+
213
242
  export {
214
243
  CAMERA_FOV_DEFAULT,
215
244
  CAMERA_FOV_MAX,
@@ -218,7 +247,6 @@ export {
218
247
  isBusyGlassesConnectionStatus,
219
248
  isConnectedGlassesConnectionStatus,
220
249
  isConnectedWifiStatus,
221
- isEnabledHotspotStatus,
222
250
  isReadyGlassesConnectionStatus,
223
251
  } from "./BluetoothSdk.types"
224
252
 
@@ -252,16 +280,12 @@ export type {
252
280
  ConnectedWifiStatus,
253
281
  Device,
254
282
  DeviceModel,
255
- EnabledHotspotStatus,
256
283
  GalleryStatusEvent,
257
284
  GlassesConnectionStatus,
258
285
  GlassesMediaVolumeGetResult,
259
286
  GlassesMediaVolumeSetResult,
260
287
  GlassesNotReadyEvent,
261
288
  HeadUpEvent,
262
- HotspotErrorEvent,
263
- HotspotStatus,
264
- HotspotStatusChangeEvent,
265
289
  GlassesSessionChangedEvent,
266
290
  KeepAliveAckEvent,
267
291
  LocalTranscriptionEvent,