@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
@@ -65,6 +65,7 @@ import {
65
65
  WifiSearchResult,
66
66
  WifiStatusChangeEvent,
67
67
  } from "../BluetoothSdk.types"
68
+ import {fetchGlassesFileOverWifi} from "../glasses-wifi/files"
68
69
  import {warmUpCameraParamsForNative} from "./cameraRequestPayload"
69
70
  import {photoCaptureParamsForNative, photoUploadParamsForNative} from "./photoRequestPayload"
70
71
  import {streamRequestParamsForNative} from "./streamRequestPayload"
@@ -798,6 +799,24 @@ NativeBluetoothSdkModule.capturePhoto = function (params: PhotoCaptureParams): P
798
799
  const started = quiet(nativeCapturePhoto({...photoCaptureParamsForNative(params), requestId}))
799
800
  const stage = (name: "captured" | "preview" | "photo") =>
800
801
  quiet(started.then(() => nativePhotoCaptureStage(requestId, name)))
802
+ const overBluetooth = () =>
803
+ stage("photo").then((value): PhotoTaken => {
804
+ const response = value as PhotoSuccessResponseEvent
805
+ return {
806
+ requestId,
807
+ fileUri: response.photoUrl ?? "",
808
+ mimeType: response.contentType || "image/jpeg",
809
+ size: response.fileSizeBytes ?? -1,
810
+ }
811
+ })
812
+ // Glasses that keep the full photo serve it by ID, over the glasses Wi-Fi link when it is up.
813
+ const fetchPhoto = async (): Promise<PhotoTaken> => {
814
+ const status = await NativeBluetoothSdkModule.getGlassesStatus().catch(() => null)
815
+ if ((status?.deferredPhotosVersion ?? 0) <= 0) return overBluetooth()
816
+ await stage("captured")
817
+ const overWifi = await fetchGlassesFileOverWifi(requestId)
818
+ return overWifi ? {requestId, fileUri: overWifi.uri, mimeType: "image/jpeg", size: overWifi.bytes} : overBluetooth()
819
+ }
801
820
  // Each stage is asked for when first awaited, once.
802
821
  let captured: Promise<void> | undefined
803
822
  let preview: Promise<PhotoPreview> | undefined
@@ -810,16 +829,7 @@ NativeBluetoothSdkModule.capturePhoto = function (params: PhotoCaptureParams): P
810
829
  get preview() {
811
830
  return (preview ??= stage("preview") as Promise<PhotoPreview>)
812
831
  },
813
- photo: () =>
814
- (photo ??= stage("photo").then((value) => {
815
- const response = value as PhotoSuccessResponseEvent
816
- return {
817
- requestId,
818
- fileUri: response.photoUrl ?? "",
819
- mimeType: response.contentType || "image/jpeg",
820
- size: response.fileSizeBytes ?? -1,
821
- }
822
- })),
832
+ photo: () => (photo ??= fetchPhoto()),
823
833
  release: () => started.then(() => nativeReleasePhotoCapture(requestId)),
824
834
  }
825
835
  }
@@ -49,11 +49,33 @@ export type LocalNetworkDownloadProgress = {
49
49
 
50
50
  type LocalNetworkEvents = {
51
51
  downloadProgress: (event: LocalNetworkDownloadProgress) => void
52
+ /** Android: the joined network went away. */
52
53
  networkLost: (event: {ssid: string}) => void
54
+ /** iOS: the hotspot join has waited a few seconds for Local Network access. */
55
+ hotspotPermissionRequired: (event: {id: string; systemAnswer?: string}) => void
56
+ /** iOS: the phone left the joined hotspot. */
57
+ hotspotLost: (event: {id: string; reason?: string}) => void
53
58
  }
54
59
 
60
+ /**
61
+ * The glasses Wi-Fi link's native side. Android: `connect`, `connectWifiDirect`, `disconnect` and
62
+ * network-bound `request`; iOS: `joinHotspot` and `leaveHotspot`. Both: `download`, `cancel`,
63
+ * `cacheDirectory` and `delay`.
64
+ */
55
65
  declare class MentraLocalNetworkNativeModule extends NativeModule<LocalNetworkEvents> {
56
66
  getNetworkDiagnostics(): NetworkDiagnostics
67
+ joinHotspot(
68
+ id: string,
69
+ ssid: string,
70
+ password: string,
71
+ gateway: string | null,
72
+ purpose: string,
73
+ frequency: number | null,
74
+ ): Promise<string | undefined>
75
+ leaveHotspot(id: string): Promise<void>
76
+ cacheDirectory(): string
77
+ /** Resolves after `ms`, also while the app is in the background. */
78
+ delay(ms: number): Promise<void>
57
79
  connect(
58
80
  ssid: string,
59
81
  password: string,
@@ -11,9 +11,12 @@ function photoTransferMethodForNative(value: unknown): PhotoTransferMethod {
11
11
  throw new TypeError(`Invalid transferMethod ${JSON.stringify(value)}. Expected "auto", "direct", or "ble".`)
12
12
  }
13
13
 
14
- /** Maps unknown/legacy size strings to the current wire format. */
14
+ /** Maps unknown/legacy size strings to the current wire format; no size is `auto`. */
15
15
  export function normalizePhotoSizeTier(size: string | undefined): PhotoSize {
16
16
  switch (size) {
17
+ case undefined:
18
+ case "auto":
19
+ return "auto"
17
20
  case "small":
18
21
  return "low"
19
22
  case "large":
@@ -12,9 +12,9 @@ export interface BluetoothSdkReleaseMetadata {
12
12
  export const BLUETOOTH_SDK_RELEASE_METADATA: Readonly<BluetoothSdkReleaseMetadata> = Object.freeze({
13
13
  "schemaVersion": 1,
14
14
  "familyBaseVersion": "3.5.0",
15
- "releaseIdentity": "3.5.0-dev.1517",
16
- "releaseSetId": "mentra-3.5.0-dev.1517",
17
- "sourceCommit": "52257345cef5dd5dd44eb36a3ee336d9dd414d3c",
18
- "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1517.json",
19
- "otaManifestSha256": "72a2b3c622198f85e7743954bac75a0f1e5fab8a8d3ac23d03e10428bb02250f"
15
+ "releaseIdentity": "3.5.0-dev.1519",
16
+ "releaseSetId": "mentra-3.5.0-dev.1519",
17
+ "sourceCommit": "941b66acac0b51cbec181e3b7fee730339118b0b",
18
+ "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1519.json",
19
+ "otaManifestSha256": "dc250e0efe84f8f59e8097d7210a4797f1557500a3c5929cb6ea823acb1c57e3"
20
20
  })
@@ -0,0 +1,47 @@
1
+ // The glasses' Bluetooth connection, as the SDK's native side reports it.
2
+ // eslint-disable-next-line no-restricted-imports
3
+ import PrivateBluetoothSdkModule from "../_private/BluetoothSdkModule"
4
+ import type {GlassesConnectionStatus} from "../BluetoothSdk.types"
5
+
6
+ /**
7
+ * The glasses connection that the glasses Wi-Fi service and `link` read: one subscription to the
8
+ * glasses status, from first use for the app's lifetime, and the status read once at that start.
9
+ */
10
+
11
+ let connection: GlassesConnectionStatus = {state: "disconnected"}
12
+ let started: Promise<void> | null = null
13
+ const listeners = new Set<(connection: GlassesConnectionStatus) => void>()
14
+
15
+ /** Starts watching on first call; resolves once the current status has been read. */
16
+ export function watchGlassesConnection(): Promise<void> {
17
+ if (started) return started
18
+ let heard = false
19
+ PrivateBluetoothSdkModule.onGlassesStatus((changed) => {
20
+ if (!changed.connection) return
21
+ heard = true
22
+ connection = changed.connection
23
+ for (const listener of listeners) listener(connection)
24
+ })
25
+ started = PrivateBluetoothSdkModule.getGlassesStatus().then(
26
+ (status) => {
27
+ // A change heard while the read was on its way is newer than the read.
28
+ if (heard || !status?.connection) return
29
+ connection = status.connection
30
+ for (const listener of listeners) listener(connection)
31
+ },
32
+ () => undefined,
33
+ )
34
+ return started
35
+ }
36
+
37
+ export function glassesConnection(): GlassesConnectionStatus {
38
+ return connection
39
+ }
40
+
41
+ export function onGlassesConnection(listener: (connection: GlassesConnectionStatus) => void): () => void {
42
+ void watchGlassesConnection()
43
+ listeners.add(listener)
44
+ return () => {
45
+ listeners.delete(listener)
46
+ }
47
+ }
@@ -0,0 +1,177 @@
1
+ import {createLink} from "./link"
2
+ import {delay} from "./native"
3
+
4
+ /**
5
+ * Continuous capture: photos back to back for as long as the run lasts, the same in the Bluetooth
6
+ * SDK (`BluetoothSdk.captureContinuous`) and the Mentra Miniapp SDK (`camera.captureContinuous`),
7
+ * which the Mentra App runs with this. While a run is on, the SDK holds the glasses fast link for
8
+ * it, so full photos come over Wi-Fi; stopping gives the link back.
9
+ *
10
+ * The run takes one photo at a time: the next starts once the camera took the previous one. It
11
+ * takes photos on its own while it is `capturing`: the fast link is up and fewer than `maxPending`
12
+ * of its photos are still on the glasses (handed out and not released). Otherwise it is `paused`:
13
+ * photos would pile up on the glasses, behind Bluetooth or behind the ones not released yet. Its
14
+ * first state is heard once known. Photos asked for with `capture()` are taken in its turn either way.
15
+ */
16
+
17
+ export type ContinuousState = "capturing" | "paused"
18
+
19
+ /** How many of a run's photos may stay on the glasses before it waits. */
20
+ export const DEFAULT_MAX_PENDING = 12
21
+ /** How long a run waits before asking again for a fast link that could not come up. */
22
+ const LINK_RETRY_MS = 30_000
23
+
24
+ export interface ContinuousCapture<C> {
25
+ /** `capturing` while the run takes photos on its own, `paused` while only Bluetooth is left. */
26
+ readonly state: ContinuousState
27
+ /** Each photo the run takes on its own, a capture like `capturePhoto`'s; release it when done. */
28
+ onPhoto(handler: (capture: C) => void): () => void
29
+ onState(handler: (state: ContinuousState) => void): () => void
30
+ /** One more photo, with these options, taken in the run's turn even while it is paused. */
31
+ capture(options?: object): Promise<C>
32
+ /**
33
+ * Stop taking photos. The fast link is given back once every photo the run handed out is
34
+ * released, so photos still on their way keep coming over Wi-Fi; resolves then.
35
+ */
36
+ stop(): Promise<void>
37
+ }
38
+
39
+ /**
40
+ * A run over `take`, which starts one capture with the given options and calls `released` once
41
+ * that capture is released (the caller's `release()`, or the miniapp closing).
42
+ */
43
+ export function runContinuousCapture<O extends object, C extends {readonly captured: Promise<void>}>(
44
+ take: (options: O, released: () => void) => C,
45
+ options: O & {maxPending?: number},
46
+ consumer: string,
47
+ ): ContinuousCapture<C> {
48
+ const {maxPending = DEFAULT_MAX_PENDING, ...photoOptions} = options
49
+ const link = createLink(consumer)
50
+ const photoHandlers = new Set<(capture: C) => void>()
51
+ const stateHandlers = new Set<(state: ContinuousState) => void>()
52
+ const asked: Array<{options: O; resolve: (capture: C) => void; reject: (error: Error) => void}> = []
53
+ let state: ContinuousState = "paused"
54
+ let pending = 0
55
+ let stopped = false
56
+ let wake = () => {}
57
+ const drained: Array<() => void> = []
58
+
59
+ const notify = <T>(handlers: Set<(value: T) => void>, value: T) => {
60
+ for (const handler of handlers) {
61
+ try {
62
+ handler(value)
63
+ } catch (error) {
64
+ console.warn(`[ContinuousCapture] ${consumer} failed handling an event`, error)
65
+ }
66
+ }
67
+ }
68
+ /** The fast link's last known state; null until the first open settles or the link reports. */
69
+ let linkUp: boolean | null = null
70
+ let announced = false
71
+ /** Capturing while the fast link is up and the glasses have room; the first known state is always heard. */
72
+ const update = () => {
73
+ if (stopped || linkUp === null) return
74
+ const next: ContinuousState = linkUp && pending < maxPending ? "capturing" : "paused"
75
+ if (next === state && announced) return
76
+ state = next
77
+ announced = true
78
+ notify(stateHandlers, next)
79
+ wake()
80
+ }
81
+ const setLink = (up: boolean) => {
82
+ linkUp = up
83
+ update()
84
+ }
85
+
86
+ let holding = false
87
+ const hold = async () => {
88
+ if (holding) return
89
+ holding = true
90
+ try {
91
+ await holdUntilUp()
92
+ } finally {
93
+ holding = false
94
+ }
95
+ }
96
+ // Glasses that come back after the link ended get asked again; while it is held, opening waits on it.
97
+ const stopWatching = link.onChange((links) => {
98
+ setLink(links.fast === "up")
99
+ if (links.glasses === "connected" && links.fast === "down") void hold()
100
+ })
101
+ const holdUntilUp = async () => {
102
+ while (!stopped) {
103
+ try {
104
+ await link.openFast()
105
+ setLink(link.state.fast === "up")
106
+ return
107
+ } catch (error) {
108
+ console.warn(`[ContinuousCapture] ${consumer}: the fast link did not come up; photos wait`, error)
109
+ setLink(false)
110
+ await delay(LINK_RETRY_MS)
111
+ }
112
+ }
113
+ }
114
+
115
+ const loop = async () => {
116
+ while (!stopped) {
117
+ const next = asked.shift()
118
+ if (!next && state !== "capturing") {
119
+ await new Promise<void>((resolve) => (wake = resolve))
120
+ continue
121
+ }
122
+ let settled = false
123
+ const capture = take(next?.options ?? (photoOptions as O), () => {
124
+ if (settled) return
125
+ settled = true
126
+ pending--
127
+ update()
128
+ wake()
129
+ if (pending === 0) drained.splice(0).forEach((resolve) => resolve())
130
+ })
131
+ pending++
132
+ update()
133
+ if (next) next.resolve(capture)
134
+ else notify(photoHandlers, capture)
135
+ // A capture the glasses refused leaves the camera free at once: wait a little before the next.
136
+ await capture.captured.catch(() => delay(500))
137
+ }
138
+ }
139
+
140
+ void hold()
141
+ void loop()
142
+
143
+ return {
144
+ get state() {
145
+ return state
146
+ },
147
+ onPhoto(handler) {
148
+ photoHandlers.add(handler)
149
+ return () => {
150
+ photoHandlers.delete(handler)
151
+ }
152
+ },
153
+ onState(handler) {
154
+ stateHandlers.add(handler)
155
+ return () => {
156
+ stateHandlers.delete(handler)
157
+ }
158
+ },
159
+ capture(extra = {}) {
160
+ if (stopped) return Promise.reject(new Error("The continuous capture was stopped"))
161
+ return new Promise<C>((resolve, reject) => {
162
+ asked.push({options: {...(photoOptions as O), ...extra}, resolve, reject})
163
+ wake()
164
+ })
165
+ },
166
+ async stop() {
167
+ if (!stopped) {
168
+ stopped = true
169
+ stopWatching()
170
+ for (const waiting of asked.splice(0)) waiting.reject(new Error("The continuous capture was stopped"))
171
+ wake()
172
+ }
173
+ if (pending > 0) await new Promise<void>((resolve) => drained.push(resolve))
174
+ await link.closeFast()
175
+ },
176
+ }
177
+ }
@@ -0,0 +1,32 @@
1
+ import {downloadToCache} from "./native"
2
+ import {holdGlassesWifiIfUp} from "./service"
3
+
4
+ /** The glasses' file server: the camera server gallery sync uses. */
5
+ const GLASSES_FILE_SERVER_PORT = 8089
6
+
7
+ /**
8
+ * A file the glasses keep for the phone (a deferred photo), fetched over the glasses Wi-Fi link
9
+ * into this app's cache folder when that link is up, held for the fetch's duration so it isn't
10
+ * taken down underneath it. Null when the link is down or the fetch failed: the caller then asks
11
+ * for it over Bluetooth.
12
+ */
13
+ export async function fetchGlassesFileOverWifi(fileId: string): Promise<{uri: string; bytes: number} | null> {
14
+ const hold = await holdGlassesWifiIfUp(`file ${fileId}`)
15
+ if (!hold) return null
16
+ try {
17
+ const url = `http://${hold.binding.gateway}:${GLASSES_FILE_SERVER_PORT}/api/deferred?id=${encodeURIComponent(
18
+ fileId,
19
+ )}`
20
+ const {statusCode, uri, bytes} = await downloadToCache(url, `glasses-file-${fileId.replace(/[^\w.-]/g, "_")}`, {
21
+ connectionMs: 10_000,
22
+ readMs: 30_000,
23
+ })
24
+ if (statusCode === 200) return {uri, bytes}
25
+ throw new Error(`the glasses answered ${statusCode}`)
26
+ } catch (err) {
27
+ console.warn(`[GlassesFiles] ${fileId} over Wi-Fi failed; using Bluetooth:`, err)
28
+ return null
29
+ } finally {
30
+ await hold.release()
31
+ }
32
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `@mentra/bluetooth-sdk/glasses-wifi`: the glasses Wi-Fi service for the Mentra engine's own
3
+ * consumers (hotspot OTA, gallery sync, Mentra Call, the managed relay, miniapps' photos), which
4
+ * hold the link and talk to the glasses over it. Apps use `BluetoothSdk.link` and
5
+ * `captureContinuous` instead.
6
+ */
7
+ // The service's own native requests, behind the link the service holds.
8
+ // eslint-disable-next-line no-restricted-imports
9
+ import {cancel, download, isScoped, onDownloadProgress, request} from "./native"
10
+
11
+ export {
12
+ GlassesWifiError,
13
+ holdGlassesWifi,
14
+ type GlassesWifiBinding,
15
+ type GlassesWifiEvent,
16
+ type GlassesWifiHold,
17
+ type GlassesWifiHoldOptions,
18
+ } from "./service"
19
+ export {createLink, linkState, onLinkChange, type GlassesLink, type LinkState} from "./link"
20
+ export {runContinuousCapture, type ContinuousCapture, type ContinuousState} from "./continuous"
21
+ export type {HotspotStatus} from "../BluetoothSdk.types"
22
+
23
+ /** Requests to the glasses over the glasses Wi-Fi link the service holds. */
24
+ export const glassesWifiLink = Object.freeze({isScoped, request, download, cancel, onDownloadProgress})
@@ -0,0 +1,94 @@
1
+ import {isConnectedGlassesConnectionStatus} from "../BluetoothSdk.types"
2
+ import {glassesConnection, onGlassesConnection, watchGlassesConnection} from "./connection"
3
+ import {glassesWifiUp, holdGlassesWifi, onGlassesWifiUp, type GlassesWifiHold} from "./service"
4
+
5
+ /**
6
+ * The phone's links to the glasses, as the Bluetooth SDK's and the Miniapp SDK's `link` show them:
7
+ * the glasses connected over Bluetooth or not, and the fast link (the glasses Wi-Fi) up or down.
8
+ * Photos go over the fast link while it is up, whoever holds it, and over Bluetooth otherwise.
9
+ */
10
+ export type LinkState = {glasses: "connected" | "disconnected"; fast: "up" | "down"}
11
+
12
+ export interface GlassesLink {
13
+ /** The links as they are now. */
14
+ readonly state: LinkState
15
+ /** Hear the links change; the handler gets the new state. */
16
+ onChange(handler: (state: LinkState) => void): () => void
17
+ /**
18
+ * Hold the fast link, so photos travel over it instead of Bluetooth, until {@link closeFast}.
19
+ * The SDK picks the radio (Wi-Fi Direct on Android with glasses that support it, the glasses'
20
+ * hotspot otherwise), shares the one link with its other users and brings it back after the
21
+ * glasses restart. Resolves once it is up; rejects if it can't come up. Opening a link already
22
+ * held waits for the same one.
23
+ */
24
+ openFast(): Promise<void>
25
+ /** Give the fast link back; it goes down once nobody else holds it. Idempotent. */
26
+ closeFast(): Promise<void>
27
+ }
28
+
29
+ export function linkState(): LinkState {
30
+ return {
31
+ glasses: isConnectedGlassesConnectionStatus(glassesConnection()) ? "connected" : "disconnected",
32
+ fast: glassesWifiUp() ? "up" : "down",
33
+ }
34
+ }
35
+
36
+ /** Hear either link change, with the new state; only real changes are heard. */
37
+ export function onLinkChange(handler: (state: LinkState) => void): () => void {
38
+ let last = linkState()
39
+ const check = () => {
40
+ const next = linkState()
41
+ if (next.glasses === last.glasses && next.fast === last.fast) return
42
+ last = next
43
+ handler(next)
44
+ }
45
+ const stopConnection = onGlassesConnection(check)
46
+ const stopWifi = onGlassesWifiUp(check)
47
+ return () => {
48
+ stopConnection()
49
+ stopWifi()
50
+ }
51
+ }
52
+
53
+ /** One holder of the fast link: the app's own, or one per miniapp. */
54
+ export function createLink(consumer: string): GlassesLink {
55
+ let current: {abort: AbortController; hold: Promise<GlassesWifiHold>} | null = null
56
+ const closeFast = async () => {
57
+ const entry = current
58
+ if (!entry) return
59
+ current = null
60
+ entry.abort.abort()
61
+ await entry.hold.then((hold) => hold.release()).catch(() => undefined)
62
+ }
63
+ return {
64
+ get state() {
65
+ // Watched from the first read on: until the glasses status arrives, they show as disconnected.
66
+ void watchGlassesConnection()
67
+ return linkState()
68
+ },
69
+ onChange: onLinkChange,
70
+ async openFast() {
71
+ let entry = current
72
+ if (!entry) {
73
+ const abort = new AbortController()
74
+ const opened = {abort, hold: holdGlassesWifi({consumer, signal: abort.signal})}
75
+ current = entry = opened
76
+ // A link the glasses did not bring back is given back, so the next open asks again.
77
+ void opened.hold
78
+ .then((hold) =>
79
+ hold.onChange((event) => {
80
+ if (event.type === "ended" && current === opened) void closeFast()
81
+ }),
82
+ )
83
+ .catch(() => undefined)
84
+ }
85
+ try {
86
+ await (await entry.hold).ready()
87
+ } catch (error) {
88
+ if (current === entry) await closeFast()
89
+ throw error
90
+ }
91
+ },
92
+ closeFast,
93
+ }
94
+ }