@mentra/bluetooth-sdk 3.5.0-dev.1518 → 3.5.0-dev.1520

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 (110) hide show
  1. package/MIGRATION.md +9 -0
  2. package/README.md +64 -11
  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/build/BluetoothSdk.types.d.ts +23 -5
  6. package/build/BluetoothSdk.types.d.ts.map +1 -1
  7. package/build/BluetoothSdk.types.js +5 -0
  8. package/build/BluetoothSdk.types.js.map +1 -1
  9. package/build/_internal.d.ts +1 -0
  10. package/build/_internal.d.ts.map +1 -1
  11. package/build/_internal.js +1 -0
  12. package/build/_internal.js.map +1 -1
  13. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  14. package/build/_private/BluetoothSdkModule.js +20 -9
  15. package/build/_private/BluetoothSdkModule.js.map +1 -1
  16. package/build/_private/MentraLocalNetworkModule.d.ts +21 -0
  17. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  18. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  19. package/build/generated/releaseMetadata.js +5 -5
  20. package/build/generated/releaseMetadata.js.map +1 -1
  21. package/build/glasses-wifi/connection.d.ts +6 -0
  22. package/build/glasses-wifi/connection.d.ts.map +1 -0
  23. package/build/glasses-wifi/connection.js +44 -0
  24. package/build/glasses-wifi/connection.js.map +1 -0
  25. package/build/glasses-wifi/continuous.d.ts +39 -0
  26. package/build/glasses-wifi/continuous.d.ts.map +1 -0
  27. package/build/glasses-wifi/continuous.js +151 -0
  28. package/build/glasses-wifi/continuous.js.map +1 -0
  29. package/build/glasses-wifi/files.d.ts +11 -0
  30. package/build/glasses-wifi/files.d.ts.map +1 -0
  31. package/build/glasses-wifi/files.js +33 -0
  32. package/build/glasses-wifi/files.js.map +1 -0
  33. package/build/glasses-wifi/index.d.ts +20 -0
  34. package/build/glasses-wifi/index.d.ts.map +1 -0
  35. package/build/glasses-wifi/index.js +15 -0
  36. package/build/glasses-wifi/index.js.map +1 -0
  37. package/build/glasses-wifi/link.d.ts +31 -0
  38. package/build/glasses-wifi/link.d.ts.map +1 -0
  39. package/build/glasses-wifi/link.js +71 -0
  40. package/build/glasses-wifi/link.js.map +1 -0
  41. package/build/glasses-wifi/native.d.ts +63 -0
  42. package/build/glasses-wifi/native.d.ts.map +1 -0
  43. package/build/glasses-wifi/native.js +138 -0
  44. package/build/glasses-wifi/native.js.map +1 -0
  45. package/build/glasses-wifi/service.d.ts +86 -0
  46. package/build/glasses-wifi/service.d.ts.map +1 -0
  47. package/build/glasses-wifi/service.js +497 -0
  48. package/build/glasses-wifi/service.js.map +1 -0
  49. package/build/index.d.ts +4 -2
  50. package/build/index.d.ts.map +1 -1
  51. package/build/index.js +24 -6
  52. package/build/index.js.map +1 -1
  53. package/build/ota-transport/index.d.ts +2 -43
  54. package/build/ota-transport/index.d.ts.map +1 -1
  55. package/build/ota-transport/index.js +3 -49
  56. package/build/ota-transport/index.js.map +1 -1
  57. package/build/react/useBluetoothStatus.d.ts.map +1 -1
  58. package/build/react/useBluetoothStatus.js +5 -24
  59. package/build/react/useBluetoothStatus.js.map +1 -1
  60. package/build/react/useMentraBluetooth.d.ts +1 -2
  61. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  62. package/build/react/useMentraBluetooth.js +0 -1
  63. package/build/react/useMentraBluetooth.js.map +1 -1
  64. package/expo-module.config.json +1 -1
  65. package/ios/MentraBluetoothSDK.podspec +5 -4
  66. package/ios/MentraLocalNetworkModule.swift +264 -0
  67. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  68. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  69. package/ios/Source/hotspot/GlassesHotspotNetwork.swift +563 -0
  70. package/ios/Source/hotspot/HotspotAccessPurpose.swift +5 -0
  71. package/ios/Source/hotspot/HotspotAddressPolicy.swift +50 -0
  72. package/ios/Source/hotspot/HotspotInterfacePolicy.swift +155 -0
  73. package/ios/Source/hotspot/HotspotJoinFailure.swift +27 -0
  74. package/ios/Source/hotspot/HotspotLeaveCompletion.swift +24 -0
  75. package/ios/Source/hotspot/HotspotNetworkOwnership.swift +22 -0
  76. package/ios/Source/hotspot/HotspotReapplyPolicy.swift +26 -0
  77. package/ios/Source/hotspot/LocalNetworkAccessRequest.swift +160 -0
  78. package/ios/Source/hotspot/MacHotspotAssociation.swift +415 -0
  79. package/ios/Source/hotspot/MacHotspotAuthorization.swift +126 -0
  80. package/ios/Source/hotspot/MacHotspotAuthorizationFacts.swift +51 -0
  81. package/ios/Source/hotspot/MacHotspotCleanupContinuation.swift +35 -0
  82. package/ios/Tests/HotspotAddressPolicyTests.swift +30 -0
  83. package/ios/Tests/HotspotInterfacePolicyTests.swift +304 -0
  84. package/ios/Tests/HotspotJoinFailureTests.swift +37 -0
  85. package/ios/Tests/HotspotLeaveCompletionTests.swift +29 -0
  86. package/ios/Tests/HotspotReapplyPolicyTests.swift +18 -0
  87. package/ios/Tests/LocalNetworkAccessRequestTests.swift +237 -0
  88. package/ios/Tests/MacHotspotAssociationTests.swift +521 -0
  89. package/ios/Tests/MacHotspotAuthorizationFactsTests.swift +62 -0
  90. package/ios/Tests/MacHotspotAuthorizationTests.swift +348 -0
  91. package/ios/Tests/MacWifiInvocationTests.swift +76 -0
  92. package/package.json +7 -2
  93. package/plugin/build/withIos.d.ts +4 -0
  94. package/plugin/build/withIos.js +20 -1
  95. package/src/BluetoothSdk.types.ts +27 -5
  96. package/src/_internal.ts +1 -0
  97. package/src/_private/BluetoothSdkModule.ts +20 -10
  98. package/src/_private/MentraLocalNetworkModule.ts +22 -0
  99. package/src/generated/releaseMetadata.ts +5 -5
  100. package/src/glasses-wifi/connection.ts +47 -0
  101. package/src/glasses-wifi/continuous.ts +177 -0
  102. package/src/glasses-wifi/files.ts +32 -0
  103. package/src/glasses-wifi/index.ts +24 -0
  104. package/src/glasses-wifi/link.ts +94 -0
  105. package/src/glasses-wifi/native.ts +193 -0
  106. package/src/glasses-wifi/service.ts +554 -0
  107. package/src/index.ts +34 -10
  108. package/src/ota-transport/index.ts +3 -85
  109. package/src/react/useBluetoothStatus.ts +5 -26
  110. package/src/react/useMentraBluetooth.ts +0 -3
@@ -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,
@@ -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.1518",
16
- "releaseSetId": "mentra-3.5.0-dev.1518",
17
- "sourceCommit": "666b7fc139108169a874e0d76ce563209c428602",
18
- "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.5.0/mentra-live-ota-3.5.0-dev.1518.json",
19
- "otaManifestSha256": "2c8c1306b29194991049a6681612aab422a28f5ed1cec6d2a0b45225f9a33bbb"
15
+ "releaseIdentity": "3.5.0-dev.1520",
16
+ "releaseSetId": "mentra-3.5.0-dev.1520",
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.1520.json",
19
+ "otaManifestSha256": "9efdfafd4882f26862fcf762817a8ca2058d4b0dd4b0c192a1a4dd0729aced08"
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
+ }
@@ -0,0 +1,193 @@
1
+ import {Platform} from "react-native"
2
+
3
+ // The service is this module's only caller; it reaches the native joins through it.
4
+ // eslint-disable-next-line no-restricted-imports
5
+ import MentraLocalNetwork from "../_private/MentraLocalNetworkModule"
6
+
7
+ /**
8
+ * The phone's native joins to the glasses' Wi-Fi, under the glasses Wi-Fi service: one link at a
9
+ * time. Android joins the hotspot or the Wi-Fi Direct group through `ScopedSoftApNetwork` and
10
+ * sends requests over the `Network` it gets; iOS joins the hotspot through `GlassesHotspotNetwork`
11
+ * and its requests take the system's route to it.
12
+ */
13
+
14
+ export type JoinPurpose = "outgoing-client" | "incoming-server"
15
+
16
+ let generation = 0
17
+ /** Android: requests go over the joined `Network`, not the default one. */
18
+ let scoped = false
19
+ /** iOS: the native join's owner id, while joined or joining. */
20
+ let iosOwner: string | null = null
21
+
22
+ const native = () => {
23
+ if (!MentraLocalNetwork) throw new Error("The glasses Wi-Fi link is not available in this native build")
24
+ return MentraLocalNetwork
25
+ }
26
+
27
+ const requestId = (prefix: string) => `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2)}`
28
+
29
+ /** Android: whether the phone and the connected glasses can use the Wi-Fi Direct link now. */
30
+ export function wifiDirectAvailable(): boolean {
31
+ return Platform.OS === "android" && MentraLocalNetwork?.wifiDirectAvailable?.() === true
32
+ }
33
+
34
+ /** Join the glasses' hotspot. Resolves with the phone's address on it, when the platform reports it. */
35
+ export async function joinHotspot(
36
+ ssid: string,
37
+ password: string,
38
+ options: {
39
+ gateway?: string
40
+ /** The hotspot's channel in MHz, when the glasses report it: a Mac then scans only that channel. */
41
+ frequency?: number
42
+ purpose: JoinPurpose
43
+ /** iOS: the join has waited a few seconds for Local Network access, which may have been denied. */
44
+ onPermissionRequired?: (systemAnswer: string) => void
45
+ },
46
+ ): Promise<string | undefined> {
47
+ const current = ++generation
48
+ scoped = false
49
+ if (Platform.OS === "ios") {
50
+ if (iosOwner) throw new Error("Previous hotspot session has not been released")
51
+ const owner = requestId("ios_hotspot")
52
+ iosOwner = owner
53
+ const permission = native().addListener("hotspotPermissionRequired", (event) => {
54
+ if (event.id === owner) options.onPermissionRequired?.(event.systemAnswer ?? "unknown")
55
+ })
56
+ try {
57
+ const address = await native().joinHotspot(
58
+ owner,
59
+ ssid,
60
+ password,
61
+ options.gateway ?? null,
62
+ options.purpose,
63
+ options.frequency ?? null,
64
+ )
65
+ if (current !== generation) throw new Error("Local network connection was superseded")
66
+ return address
67
+ } catch (error) {
68
+ try {
69
+ await native().leaveHotspot(owner)
70
+ } catch (cleanupError) {
71
+ // The owner stays recorded: the next join must not start over a session still being left.
72
+ console.warn("[GlassesWifi] Leaving a failed hotspot join failed", cleanupError)
73
+ throw error
74
+ }
75
+ if (iosOwner === owner) iosOwner = null
76
+ throw error
77
+ } finally {
78
+ permission.remove()
79
+ }
80
+ }
81
+ if (Platform.OS !== "android") throw new Error("The glasses hotspot cannot be joined on this platform")
82
+ const result = await native().connect(ssid, password, options.purpose === "incoming-server")
83
+ scoped = true
84
+ return result.localAddress
85
+ }
86
+
87
+ /** Android: join the glasses' Wi-Fi Direct group; the native join asks the glasses for it over Bluetooth. */
88
+ export async function joinWifiDirect(
89
+ purpose: JoinPurpose,
90
+ ): Promise<{ssid: string; localAddress?: string; gateway?: string}> {
91
+ generation += 1
92
+ scoped = false
93
+ const result = await native().connectWifiDirect(purpose === "incoming-server")
94
+ scoped = true
95
+ return result
96
+ }
97
+
98
+ /** Leave whatever the phone joined, or stop a join in progress. Leaving a group also removes it. */
99
+ export async function leave(): Promise<void> {
100
+ generation += 1
101
+ if (!MentraLocalNetwork) return
102
+ if (Platform.OS === "ios") {
103
+ const owner = iosOwner
104
+ if (!owner) return
105
+ await MentraLocalNetwork.leaveHotspot(owner)
106
+ if (iosOwner === owner) iosOwner = null
107
+ return
108
+ }
109
+ // A failed release keeps the network for the next leave.
110
+ await MentraLocalNetwork.disconnect()
111
+ scoped = false
112
+ }
113
+
114
+ /** The phone left the glasses' network without being asked to. */
115
+ export function onLost(listener: () => void): () => void {
116
+ if (!MentraLocalNetwork) return () => {}
117
+ const subscription =
118
+ Platform.OS === "ios"
119
+ ? MentraLocalNetwork.addListener("hotspotLost", (event) => {
120
+ if (event.id === iosOwner) listener()
121
+ })
122
+ : MentraLocalNetwork.addListener("networkLost", () => {
123
+ scoped = false
124
+ listener()
125
+ })
126
+ return () => subscription.remove()
127
+ }
128
+
129
+ /** Android: requests to the glasses must go over the joined `Network` (`MentraLocalNetwork.request`). */
130
+ export function isScoped(): boolean {
131
+ return scoped
132
+ }
133
+
134
+ /** Android: an HTTP request to the glasses over the joined `Network`; the body comes back as base64. */
135
+ export function request(
136
+ requestId: string,
137
+ url: string,
138
+ method: string,
139
+ headers: Record<string, string>,
140
+ body: string | null,
141
+ timeoutMs: number,
142
+ ): Promise<{status: number; headers: Record<string, string>; bodyBase64: string}> {
143
+ return native().request(requestId, url, method, headers, body, timeoutMs)
144
+ }
145
+
146
+ /** A download from the glasses over the link into `destination`, a path; progress comes by `onDownloadProgress`. */
147
+ export function download(
148
+ requestId: string,
149
+ url: string,
150
+ destination: string,
151
+ headers: Record<string, string>,
152
+ connectionTimeoutMs: number,
153
+ readTimeoutMs: number,
154
+ ): Promise<{statusCode: number; bytesWritten: number; headers: Record<string, string>}> {
155
+ return native().download(requestId, url, destination, headers, connectionTimeoutMs, readTimeoutMs)
156
+ }
157
+
158
+ /** Stop a request or download in progress. */
159
+ export async function cancel(requestId: string): Promise<void> {
160
+ await MentraLocalNetwork?.cancel(requestId)
161
+ }
162
+
163
+ export function onDownloadProgress(
164
+ listener: (event: {
165
+ requestId: string
166
+ bytesWritten: number
167
+ contentLength: number
168
+ statusCode?: number
169
+ headers?: Record<string, string>
170
+ }) => void,
171
+ ): () => void {
172
+ if (!MentraLocalNetwork) return () => {}
173
+ const subscription = MentraLocalNetwork.addListener("downloadProgress", listener)
174
+ return () => subscription.remove()
175
+ }
176
+
177
+ /** Download a file from the glasses over the link into this app's cache folder, as a `file://` URI. */
178
+ export async function downloadToCache(
179
+ url: string,
180
+ fileName: string,
181
+ timeouts: {connectionMs: number; readMs: number},
182
+ ): Promise<{statusCode: number; uri: string; bytes: number}> {
183
+ const path = `${native().cacheDirectory().replace(/\/$/, "")}/${fileName}`
184
+ const {statusCode, bytesWritten} = await download(requestId("file"), url, path, {}, timeouts.connectionMs, timeouts.readMs)
185
+ return {statusCode, uri: `file://${path}`, bytes: bytesWritten}
186
+ }
187
+
188
+ /** A wait that keeps running while the app is in the background, unlike a JS timer on Android. */
189
+ export function delay(ms: number): Promise<void> {
190
+ const nativeDelay = MentraLocalNetwork?.delay
191
+ if (typeof nativeDelay === "function") return nativeDelay.call(MentraLocalNetwork, Math.max(0, Math.round(ms)))
192
+ return new Promise((resolve) => setTimeout(resolve, ms))
193
+ }