@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 @@
1
+ {"version":3,"file":"native.js","sourceRoot":"","sources":["../../src/glasses-wifi/native.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,cAAc,CAAA;AAErC,oFAAoF;AACpF,iDAAiD;AACjD,OAAO,kBAAkB,MAAM,sCAAsC,CAAA;AAWrE,IAAI,UAAU,GAAG,CAAC,CAAA;AAClB,2EAA2E;AAC3E,IAAI,MAAM,GAAG,KAAK,CAAA;AAClB,gEAAgE;AAChE,IAAI,QAAQ,GAAkB,IAAI,CAAA;AAElC,MAAM,MAAM,GAAG,GAAG,EAAE;IAClB,IAAI,CAAC,kBAAkB;QAAE,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAA;IACxG,OAAO,kBAAkB,CAAA;AAC3B,CAAC,CAAA;AAED,MAAM,SAAS,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,GAAG,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,C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IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;IAC/G,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAA;AAC1D,CAAC","sourcesContent":["import {Platform} from \"react-native\"\n\n// The service is this module's only caller; it reaches the native joins through it.\n// eslint-disable-next-line no-restricted-imports\nimport MentraLocalNetwork from \"../_private/MentraLocalNetworkModule\"\n\n/**\n * The phone's native joins to the glasses' Wi-Fi, under the glasses Wi-Fi service: one link at a\n * time. Android joins the hotspot or the Wi-Fi Direct group through `ScopedSoftApNetwork` and\n * sends requests over the `Network` it gets; iOS joins the hotspot through `GlassesHotspotNetwork`\n * and its requests take the system's route to it.\n */\n\nexport type JoinPurpose = \"outgoing-client\" | \"incoming-server\"\n\nlet generation = 0\n/** Android: requests go over the joined `Network`, not the default one. */\nlet scoped = false\n/** iOS: the native join's owner id, while joined or joining. */\nlet iosOwner: string | null = null\n\nconst native = () => {\n if (!MentraLocalNetwork) throw new Error(\"The glasses Wi-Fi link is not available in this native build\")\n return MentraLocalNetwork\n}\n\nconst requestId = (prefix: string) => `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2)}`\n\n/** Android: whether the phone and the connected glasses can use the Wi-Fi Direct link now. */\nexport function wifiDirectAvailable(): boolean {\n return Platform.OS === \"android\" && MentraLocalNetwork?.wifiDirectAvailable?.() === true\n}\n\n/** Join the glasses' hotspot. Resolves with the phone's address on it, when the platform reports it. */\nexport async function joinHotspot(\n ssid: string,\n password: string,\n options: {\n gateway?: string\n /** The hotspot's channel in MHz, when the glasses report it: a Mac then scans only that channel. */\n frequency?: number\n purpose: JoinPurpose\n /** iOS: the join has waited a few seconds for Local Network access, which may have been denied. */\n onPermissionRequired?: (systemAnswer: string) => void\n },\n): Promise<string | undefined> {\n const current = ++generation\n scoped = false\n if (Platform.OS === \"ios\") {\n if (iosOwner) throw new Error(\"Previous hotspot session has not been released\")\n const owner = requestId(\"ios_hotspot\")\n iosOwner = owner\n const permission = native().addListener(\"hotspotPermissionRequired\", (event) => {\n if (event.id === owner) options.onPermissionRequired?.(event.systemAnswer ?? \"unknown\")\n })\n try {\n const address = await native().joinHotspot(\n owner,\n ssid,\n password,\n options.gateway ?? null,\n options.purpose,\n options.frequency ?? null,\n )\n if (current !== generation) throw new Error(\"Local network connection was superseded\")\n return address\n } catch (error) {\n try {\n await native().leaveHotspot(owner)\n } catch (cleanupError) {\n // The owner stays recorded: the next join must not start over a session still being left.\n console.warn(\"[GlassesWifi] Leaving a failed hotspot join failed\", cleanupError)\n throw error\n }\n if (iosOwner === owner) iosOwner = null\n throw error\n } finally {\n permission.remove()\n }\n }\n if (Platform.OS !== \"android\") throw new Error(\"The glasses hotspot cannot be joined on this platform\")\n const result = await native().connect(ssid, password, options.purpose === \"incoming-server\")\n scoped = true\n return result.localAddress\n}\n\n/** Android: join the glasses' Wi-Fi Direct group; the native join asks the glasses for it over Bluetooth. */\nexport async function joinWifiDirect(\n purpose: JoinPurpose,\n): Promise<{ssid: string; localAddress?: string; gateway?: string}> {\n generation += 1\n scoped = false\n const result = await native().connectWifiDirect(purpose === \"incoming-server\")\n scoped = true\n return result\n}\n\n/** Leave whatever the phone joined, or stop a join in progress. Leaving a group also removes it. */\nexport async function leave(): Promise<void> {\n generation += 1\n if (!MentraLocalNetwork) return\n if (Platform.OS === \"ios\") {\n const owner = iosOwner\n if (!owner) return\n await MentraLocalNetwork.leaveHotspot(owner)\n if (iosOwner === owner) iosOwner = null\n return\n }\n // A failed release keeps the network for the next leave.\n await MentraLocalNetwork.disconnect()\n scoped = false\n}\n\n/** The phone left the glasses' network without being asked to. */\nexport function onLost(listener: () => void): () => void {\n if (!MentraLocalNetwork) return () => {}\n const subscription =\n Platform.OS === \"ios\"\n ? MentraLocalNetwork.addListener(\"hotspotLost\", (event) => {\n if (event.id === iosOwner) listener()\n })\n : MentraLocalNetwork.addListener(\"networkLost\", () => {\n scoped = false\n listener()\n })\n return () => subscription.remove()\n}\n\n/** Android: requests to the glasses must go over the joined `Network` (`MentraLocalNetwork.request`). */\nexport function isScoped(): boolean {\n return scoped\n}\n\n/** Android: an HTTP request to the glasses over the joined `Network`; the body comes back as base64. */\nexport function request(\n requestId: string,\n url: string,\n method: string,\n headers: Record<string, string>,\n body: string | null,\n timeoutMs: number,\n): Promise<{status: number; headers: Record<string, string>; bodyBase64: string}> {\n return native().request(requestId, url, method, headers, body, timeoutMs)\n}\n\n/** A download from the glasses over the link into `destination`, a path; progress comes by `onDownloadProgress`. */\nexport function download(\n requestId: string,\n url: string,\n destination: string,\n headers: Record<string, string>,\n connectionTimeoutMs: number,\n readTimeoutMs: number,\n): Promise<{statusCode: number; bytesWritten: number; headers: Record<string, string>}> {\n return native().download(requestId, url, destination, headers, connectionTimeoutMs, readTimeoutMs)\n}\n\n/** Stop a request or download in progress. */\nexport async function cancel(requestId: string): Promise<void> {\n await MentraLocalNetwork?.cancel(requestId)\n}\n\nexport function onDownloadProgress(\n listener: (event: {\n requestId: string\n bytesWritten: number\n contentLength: number\n statusCode?: number\n headers?: Record<string, string>\n }) => void,\n): () => void {\n if (!MentraLocalNetwork) return () => {}\n const subscription = MentraLocalNetwork.addListener(\"downloadProgress\", listener)\n return () => subscription.remove()\n}\n\n/** Download a file from the glasses over the link into this app's cache folder, as a `file://` URI. */\nexport async function downloadToCache(\n url: string,\n fileName: string,\n timeouts: {connectionMs: number; readMs: number},\n): Promise<{statusCode: number; uri: string; bytes: number}> {\n const path = `${native().cacheDirectory().replace(/\\/$/, \"\")}/${fileName}`\n const {statusCode, bytesWritten} = await download(requestId(\"file\"), url, path, {}, timeouts.connectionMs, timeouts.readMs)\n return {statusCode, uri: `file://${path}`, bytes: bytesWritten}\n}\n\n/** A wait that keeps running while the app is in the background, unlike a JS timer on Android. */\nexport function delay(ms: number): Promise<void> {\n const nativeDelay = MentraLocalNetwork?.delay\n if (typeof nativeDelay === \"function\") return nativeDelay.call(MentraLocalNetwork, Math.max(0, Math.round(ms)))\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n"]}
@@ -0,0 +1,86 @@
1
+ import * as native from "./native";
2
+ /**
3
+ * The glasses Wi-Fi service: the one owner of the phone-to-glasses Wi-Fi link.
4
+ *
5
+ * Photo fetches, gallery sync, hotspot OTA, Mentra Call, the managed relay and every fast link
6
+ * hold the link here and use the binding it gives them; none of them sends a hotspot command or
7
+ * joins a network itself. The link is shared: the first holder brings it up (Wi-Fi Direct on
8
+ * Android with glasses that advertise it, else the glasses' hotspot, then the phone's one native
9
+ * join), later holders get the same binding, and the last release takes it down.
10
+ *
11
+ * When the link goes down (the phone leaves the network, the glasses turn the AP off, restart, or
12
+ * leave Bluetooth), holders hear `lost`; the service asks for the link again once the glasses are
13
+ * back and ready, and holders hear `restored` with the new binding. Glasses that do not come back
14
+ * within [RESTORE_DEADLINE_MS] end it: holders hear `ended` and still release.
15
+ */
16
+ export type GlassesWifiBinding = {
17
+ ssid: string;
18
+ password: string;
19
+ /** The glasses' address on the link. */
20
+ gateway: string;
21
+ /** The phone's address on the link, when the native join reports it. */
22
+ phoneIpv4?: string;
23
+ frequency?: number;
24
+ };
25
+ export type GlassesWifiEvent = {
26
+ type: "lost";
27
+ reason: string;
28
+ } | {
29
+ type: "restored";
30
+ binding: GlassesWifiBinding;
31
+ } | {
32
+ type: "ended";
33
+ reason: string;
34
+ };
35
+ export type GlassesWifiHoldOptions = {
36
+ /** Who holds it, for logs. */
37
+ consumer: string;
38
+ /** "incoming-server" when the glasses connect to the phone (OTA, video); it adds the VPN check. */
39
+ purpose?: native.JoinPurpose;
40
+ /** Aborting it while the link comes up gives the hold back. */
41
+ signal?: AbortSignal;
42
+ /** Runs once the glasses report the network and before the first join, e.g. an explanation. */
43
+ beforeJoin?: (ssid: string) => Promise<void>;
44
+ /** iOS: the join waited a few seconds for Local Network access, which may have been denied. */
45
+ onPermissionRequired?: (systemAnswer: string) => void;
46
+ /** Narration for a consumer that shows its steps. */
47
+ report?: (line: string) => void;
48
+ };
49
+ export interface GlassesWifiHold {
50
+ /** The link as it is now; after `lost`, the last one until `restored`. */
51
+ readonly binding: GlassesWifiBinding;
52
+ onChange(listener: (event: GlassesWifiEvent) => void): () => void;
53
+ /** The binding once the link is up: now, or when it is restored. Rejects when it ends or on abort. */
54
+ ready(signal?: AbortSignal): Promise<GlassesWifiBinding>;
55
+ /** Idempotent. The link goes down once nobody holds it. */
56
+ release(): Promise<void>;
57
+ }
58
+ /** Bringing the link up failed: the glasses did not enable it, or the phone did not join it. */
59
+ export declare class GlassesWifiError extends Error {
60
+ readonly stage: "enable" | "join";
61
+ readonly cause: unknown;
62
+ /** The native join's code, e.g. `SOFTAP_UNAVAILABLE`, when it has one. */
63
+ readonly code?: string;
64
+ constructor(stage: "enable" | "join", cause: unknown);
65
+ }
66
+ /** How often an enable is re-sent while a join waits: the glasses stop an AP unused for 120 s. */
67
+ export declare const JOIN_KEEPALIVE_MS = 30000;
68
+ /** The glasses report the AP enabled before its SSID is in the phone's scan. */
69
+ export declare const BROADCAST_WAIT_MS = 3000;
70
+ /** How long holders wait for glasses that restarted or left before the link ends. */
71
+ export declare const RESTORE_DEADLINE_MS: number;
72
+ /** How long after the last release an enabled report is taken as a late enable to undo (OS-2133). */
73
+ export declare const LATE_ENABLE_WINDOW_MS = 60000;
74
+ /** Hold the glasses Wi-Fi link, bringing it up if nobody holds it yet. */
75
+ export declare function holdGlassesWifi(options: GlassesWifiHoldOptions): Promise<GlassesWifiHold>;
76
+ /**
77
+ * Hold the link only if it is up now (someone else brought it up): for a use that is just as well
78
+ * served over Bluetooth, like a file fetch, and must not bring the link up itself. Null when it
79
+ * is down, coming up or going down.
80
+ */
81
+ export declare function holdGlassesWifiIfUp(consumer: string): Promise<GlassesWifiHold | null>;
82
+ /** Whether the glasses Wi-Fi link is up now, for whoever holds it. */
83
+ export declare function glassesWifiUp(): boolean;
84
+ /** Hear the glasses Wi-Fi link go up and down, whoever holds it. */
85
+ export declare function onGlassesWifiUp(listener: (up: boolean) => void): () => void;
86
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../src/glasses-wifi/service.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,MAAM,MAAM,UAAU,CAAA;AAElC;;;;;;;;;;;;;GAaG;AAEH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,MAAM,CAAA;IAChB,wCAAwC;IACxC,OAAO,EAAE,MAAM,CAAA;IACf,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,MAAM,MAAM,gBAAgB,GACxB;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAC,GAC9B;IAAC,IAAI,EAAE,UAAU,CAAC;IAAC,OAAO,EAAE,kBAAkB,CAAA;CAAC,GAC/C;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAC,CAAA;AAEnC,MAAM,MAAM,sBAAsB,GAAG;IACnC,8BAA8B;IAC9B,QAAQ,EAAE,MAAM,CAAA;IAChB,mGAAmG;IACnG,OAAO,CAAC,EAAE,MAAM,CAAC,WAAW,CAAA;IAC5B,+DAA+D;IAC/D,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,+FAA+F;IAC/F,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC5C,+FAA+F;IAC/F,oBAAoB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAA;IACrD,qDAAqD;IACrD,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;CAChC,CAAA;AAED,MAAM,WAAW,eAAe;IAC9B,0EAA0E;IAC1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// eslint-disable-next-line no-restricted-imports
3
+ import PrivateBluetoothSdkModule from "../_private/BluetoothSdkModule";
4
+ import { isConnectedGlassesConnectionStatus, isEnabledHotspotStatus, isReadyGlassesConnectionStatus, } from "../BluetoothSdk.types";
5
+ import { glassesConnection, onGlassesConnection, watchGlassesConnection } from "./connection";
6
+ import * as native from "./native";
7
+ /** Bringing the link up failed: the glasses did not enable it, or the phone did not join it. */
8
+ export class GlassesWifiError extends Error {
9
+ stage;
10
+ cause;
11
+ /** The native join's code, e.g. `SOFTAP_UNAVAILABLE`, when it has one. */
12
+ code;
13
+ constructor(stage, cause) {
14
+ super(cause instanceof Error ? cause.message : String(cause));
15
+ this.stage = stage;
16
+ this.cause = cause;
17
+ this.name = "GlassesWifiError";
18
+ const code = cause?.code;
19
+ if (typeof code === "string")
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** How often an enable is re-sent while a join waits: the glasses stop an AP unused for 120 s. */
24
+ export const JOIN_KEEPALIVE_MS = 30_000;
25
+ /** The glasses report the AP enabled before its SSID is in the phone's scan. */
26
+ export const BROADCAST_WAIT_MS = 3_000;
27
+ /** How long holders wait for glasses that restarted or left before the link ends. */
28
+ export const RESTORE_DEADLINE_MS = 3 * 60_000;
29
+ /** How long after the last release an enabled report is taken as a late enable to undo (OS-2133). */
30
+ export const LATE_ENABLE_WINDOW_MS = 60_000;
31
+ const SESSION_REFRESH_CODES = new Set(["wifi_session_restarted", "wifi_session_changed"]);
32
+ const holders = new Set();
33
+ let binding = null;
34
+ let bringingUp = null;
35
+ let takingDown = null;
36
+ /** The radio of the link up or coming up. */
37
+ let linkType = null;
38
+ let lostAt = null;
39
+ /** Why the link ended, while it stays down; ready() rejects with it. */
40
+ let endedReason = null;
41
+ let releasedAt = Number.NEGATIVE_INFINITY;
42
+ let commands = Promise.resolve();
43
+ let watching = null;
44
+ let cancelRestore = null;
45
+ let cancelDeadline = null;
46
+ const upListeners = new Set();
47
+ let reclaiming = null;
48
+ /** The link's binding; whoever listens hears it go up and down. */
49
+ function setBinding(next) {
50
+ const changed = (binding === null) !== (next === null);
51
+ binding = next;
52
+ if (!changed)
53
+ return;
54
+ for (const listener of upListeners) {
55
+ try {
56
+ listener(next !== null);
57
+ }
58
+ catch (error) {
59
+ console.warn("[GlassesWifi] A link listener failed", error);
60
+ }
61
+ }
62
+ }
63
+ const message = (error) => (error instanceof Error ? error.message : String(error));
64
+ /** Run `callback` after `ms`, also in the background; the returned function cancels it. */
65
+ function after(ms, callback) {
66
+ let cancelled = false;
67
+ void native.delay(ms).then(() => {
68
+ if (!cancelled)
69
+ callback();
70
+ });
71
+ return () => {
72
+ cancelled = true;
73
+ };
74
+ }
75
+ /**
76
+ * One hotspot command at a time, re-sent once when a restarting ASG dropped it. ASG answers a
77
+ * same-state command with its current status, so a re-send never cycles the AP.
78
+ */
79
+ function setHotspot(enabled) {
80
+ const send = async () => {
81
+ try {
82
+ return await PrivateBluetoothSdkModule.setHotspotState(enabled);
83
+ }
84
+ catch (error) {
85
+ const code = error?.code;
86
+ if (!code || !SESSION_REFRESH_CODES.has(code))
87
+ throw error;
88
+ await native.delay(500);
89
+ return await PrivateBluetoothSdkModule.setHotspotState(enabled);
90
+ }
91
+ };
92
+ const run = commands.then(send, send);
93
+ commands = run.catch(() => undefined);
94
+ return run;
95
+ }
96
+ /** Hold the glasses Wi-Fi link, bringing it up if nobody holds it yet. */
97
+ export async function holdGlassesWifi(options) {
98
+ const holder = { options, listeners: new Set() };
99
+ if (takingDown)
100
+ await takingDown;
101
+ holders.add(holder);
102
+ watchLateHotspots();
103
+ await watch();
104
+ // A cancelled hold settles at once, whatever the link is doing; giving it back stops the
105
+ // bring-up when nobody else wants the link (the join waits on the person answering a prompt).
106
+ let abort = () => { };
107
+ const aborted = new Promise((_, reject) => {
108
+ abort = () => reject(new Error("Glasses Wi-Fi hold cancelled"));
109
+ });
110
+ aborted.catch(() => undefined);
111
+ options.signal?.addEventListener("abort", abort, { once: true });
112
+ let current;
113
+ try {
114
+ if (options.signal?.aborted)
115
+ throw new Error("Glasses Wi-Fi hold cancelled");
116
+ current = binding ?? (await Promise.race([bringingUp ?? bringUp(holder), aborted]));
117
+ }
118
+ catch (error) {
119
+ // Not awaited: the teardown waits for the bring-up to settle, and the next hold waits for it.
120
+ void release(holder).catch((cause) => console.warn("[GlassesWifi] Giving back a failed hold failed", cause));
121
+ throw error;
122
+ }
123
+ finally {
124
+ options.signal?.removeEventListener("abort", abort);
125
+ }
126
+ console.log(`[GlassesWifi] ${options.consumer} holds the link (${holders.size} holder(s))`);
127
+ let released = null;
128
+ return {
129
+ get binding() {
130
+ return binding ?? current;
131
+ },
132
+ onChange(listener) {
133
+ holder.listeners.add(listener);
134
+ return () => holder.listeners.delete(listener);
135
+ },
136
+ ready(signal) {
137
+ if (binding)
138
+ return Promise.resolve(binding);
139
+ if (endedReason)
140
+ return Promise.reject(new Error(endedReason));
141
+ return new Promise((resolve, reject) => {
142
+ const done = () => {
143
+ holder.listeners.delete(listener);
144
+ signal?.removeEventListener("abort", onAbort);
145
+ };
146
+ const listener = (event) => {
147
+ if (event.type === "lost")
148
+ return;
149
+ done();
150
+ if (event.type === "restored")
151
+ resolve(event.binding);
152
+ else
153
+ reject(new Error(event.reason));
154
+ };
155
+ const onAbort = () => {
156
+ done();
157
+ reject(new Error("Glasses Wi-Fi wait cancelled"));
158
+ };
159
+ holder.listeners.add(listener);
160
+ signal?.addEventListener("abort", onAbort, { once: true });
161
+ });
162
+ },
163
+ release() {
164
+ released ??= release(holder);
165
+ return released;
166
+ },
167
+ };
168
+ }
169
+ /**
170
+ * The radio, chosen once per bring-up from the platform and the glasses' capability: Wi-Fi Direct
171
+ * on Android with glasses that advertise `wifi_direct_version`, the hotspot otherwise.
172
+ */
173
+ function chooseLink() {
174
+ return native.wifiDirectAvailable() ? "wifi_direct" : "hotspot";
175
+ }
176
+ const purpose = () => [...holders].some((holder) => holder.options.purpose === "incoming-server") ? "incoming-server" : "outgoing-client";
177
+ function bringUp(first) {
178
+ const attempt = (async () => {
179
+ const report = (line) => first?.options.report?.(line);
180
+ linkType = chooseLink();
181
+ console.log(`[GlassesWifi] Bringing up the ${linkType} link`);
182
+ const joined = linkType === "wifi_direct" ? await joinWifiDirect(report) : await joinHotspot(first, report);
183
+ const wasLost = lostAt !== null;
184
+ setBinding(joined);
185
+ lostAt = null;
186
+ endedReason = null;
187
+ if (wasLost)
188
+ notify({ type: "restored", binding: joined });
189
+ return joined;
190
+ })();
191
+ bringingUp = attempt;
192
+ const settled = () => {
193
+ if (bringingUp === attempt)
194
+ bringingUp = null;
195
+ };
196
+ attempt.then(settled, settled);
197
+ return attempt;
198
+ }
199
+ async function joinHotspot(first, report) {
200
+ const status = await enableHotspot(report).catch((error) => {
201
+ throw new GlassesWifiError("enable", error);
202
+ });
203
+ assertWanted();
204
+ await beforeJoin(first, status.ssid);
205
+ assertWanted();
206
+ return await joinWithRetry(status, first, report).catch((error) => {
207
+ throw error instanceof GlassesWifiError ? error : new GlassesWifiError("join", error);
208
+ });
209
+ }
210
+ /** The native join asks the glasses for their group over Bluetooth and joins it, with no prompt. */
211
+ async function joinWifiDirect(report) {
212
+ assertWanted();
213
+ const joined = await native.joinWifiDirect(purpose()).catch((error) => {
214
+ throw new GlassesWifiError("join", error);
215
+ });
216
+ if (!joined.gateway)
217
+ throw new GlassesWifiError("join", new Error("The glasses reported no group address"));
218
+ report(`Joined the glasses' Wi-Fi Direct group ${joined.ssid}`);
219
+ // A group has no password the consumers need: the phone joined it with the one the glasses sent.
220
+ return { ssid: joined.ssid, password: "", gateway: joined.gateway, phoneIpv4: joined.localAddress };
221
+ }
222
+ async function enableHotspot(report) {
223
+ let status = await setHotspot(true).catch(async (error) => {
224
+ // An unanswered enable may still land: ask again rather than turn it off.
225
+ if (!/timed out waiting for glasses response|glasses did not answer/i.test(message(error)))
226
+ throw error;
227
+ report("Glasses did not answer; asking again");
228
+ return setHotspot(true);
229
+ });
230
+ if (!isEnabledHotspotStatus(status)) {
231
+ // A start racing the previous stop reports disabled: turn it off and start again once.
232
+ report("Glasses hotspot did not start; turning it off and trying again");
233
+ await setHotspot(false).catch(() => undefined);
234
+ await native.delay(1_000);
235
+ status = await setHotspot(true);
236
+ }
237
+ if (!isEnabledHotspotStatus(status) || !status.password) {
238
+ throw new Error(`The glasses hotspot did not start (state=${status.state})`);
239
+ }
240
+ report(`Glasses report hotspot ${status.ssid} enabled`);
241
+ await native.delay(BROADCAST_WAIT_MS);
242
+ return status;
243
+ }
244
+ async function joinWithRetry(status, first, report) {
245
+ try {
246
+ return await join(status, first);
247
+ }
248
+ catch (error) {
249
+ // Leaving the phone's previous Wi-Fi can make Android's first join fail as Unavailable.
250
+ // Cycle the AP and join again from an idle radio.
251
+ if (!/SOFTAP_UNAVAILABLE/.test(`${error?.code} ${message(error)}`))
252
+ throw error;
253
+ if (holders.size === 0)
254
+ throw error;
255
+ report("Phone couldn't join; cycling the glasses hotspot and trying again");
256
+ await setHotspot(false);
257
+ const again = await enableHotspot(report);
258
+ return await join(again, first);
259
+ }
260
+ }
261
+ /**
262
+ * The first holder's step before the join, such as gallery's one-time explanation. It belongs to
263
+ * that holder: once it cancels, the bring-up stops waiting for it and goes on for anyone else.
264
+ */
265
+ async function beforeJoin(first, ssid) {
266
+ const step = first?.options.beforeJoin;
267
+ const signal = first?.options.signal;
268
+ if (!step || signal?.aborted)
269
+ return;
270
+ let onAbort = () => { };
271
+ const cancelled = new Promise((resolve) => {
272
+ onAbort = resolve;
273
+ signal?.addEventListener("abort", onAbort, { once: true });
274
+ });
275
+ try {
276
+ await Promise.race([
277
+ step(ssid).catch((error) => {
278
+ if (!signal?.aborted)
279
+ throw error;
280
+ }),
281
+ cancelled,
282
+ ]);
283
+ }
284
+ finally {
285
+ signal?.removeEventListener("abort", onAbort);
286
+ }
287
+ }
288
+ /** A bring-up nobody holds any more stops before it starts a join, which has no time limit. */
289
+ function assertWanted() {
290
+ if (holders.size === 0)
291
+ throw new Error("Glasses Wi-Fi hold cancelled");
292
+ }
293
+ async function join(status, first) {
294
+ assertWanted();
295
+ const joining = native.joinHotspot(status.ssid, status.password, {
296
+ gateway: status.localIp,
297
+ frequency: status.frequency,
298
+ purpose: purpose(),
299
+ onPermissionRequired: (answer) => first?.options.onPermissionRequired?.(answer),
300
+ });
301
+ // The join has no time limit, so a person can take their time with the phone's prompt. Keep
302
+ // the AP up meanwhile: a repeated enable restarts the glasses' idle clock.
303
+ let keepAlive = () => { };
304
+ const scheduleKeepAlive = () => {
305
+ keepAlive = after(JOIN_KEEPALIVE_MS, () => {
306
+ setHotspot(true).then((current) => {
307
+ if (current.state !== "enabled")
308
+ void native.leave().catch(() => undefined);
309
+ }, (error) => console.warn("[GlassesWifi] Keeping the hotspot up during the join failed", error));
310
+ scheduleKeepAlive();
311
+ });
312
+ };
313
+ scheduleKeepAlive();
314
+ try {
315
+ const phoneIpv4 = await joining;
316
+ return {
317
+ ssid: status.ssid,
318
+ password: status.password,
319
+ gateway: status.localIp,
320
+ phoneIpv4,
321
+ frequency: status.frequency,
322
+ };
323
+ }
324
+ finally {
325
+ keepAlive();
326
+ }
327
+ }
328
+ async function release(holder) {
329
+ if (!holders.delete(holder))
330
+ return;
331
+ console.log(`[GlassesWifi] ${holder.options.consumer} released the link (${holders.size} left)`);
332
+ if (holders.size > 0)
333
+ return;
334
+ takingDown = takeDown().finally(() => {
335
+ takingDown = null;
336
+ });
337
+ await takingDown;
338
+ }
339
+ async function takeDown() {
340
+ unwatch();
341
+ if (bringingUp) {
342
+ void native.leave().catch(() => undefined);
343
+ await bringingUp.catch(() => undefined);
344
+ }
345
+ setBinding(null);
346
+ lostAt = null;
347
+ endedReason = null;
348
+ await native.leave().catch((error) => console.warn("[GlassesWifi] Leaving the glasses network failed", error));
349
+ releasedAt = Date.now();
350
+ // Leaving the Wi-Fi Direct group above also told the glasses to remove it.
351
+ const down = linkType;
352
+ linkType = null;
353
+ if (down === "wifi_direct")
354
+ return;
355
+ // Glasses away now get their AP turned off on return, by the late-hotspot watch, or by their idle stop.
356
+ if (!isConnectedGlassesConnectionStatus(glassesConnection()))
357
+ return;
358
+ for (let attempt = 1; attempt <= 2; attempt++) {
359
+ const status = await setHotspot(false).catch(() => null);
360
+ if (status?.state === "disabled")
361
+ return;
362
+ // A just-replaced ASG can drop the first command while its command path settles.
363
+ await native.delay(500);
364
+ }
365
+ console.warn("[GlassesWifi] The glasses did not confirm their hotspot is off");
366
+ }
367
+ function notify(event) {
368
+ for (const holder of holders) {
369
+ for (const listener of holder.listeners) {
370
+ try {
371
+ listener(event);
372
+ }
373
+ catch (error) {
374
+ console.warn(`[GlassesWifi] ${holder.options.consumer} failed handling ${event.type}`, error);
375
+ }
376
+ }
377
+ }
378
+ }
379
+ function lose(reason) {
380
+ if (!binding || holders.size === 0)
381
+ return;
382
+ console.warn(`[GlassesWifi] The link went down: ${reason}`);
383
+ setBinding(null);
384
+ lostAt = Date.now();
385
+ void native.leave().catch(() => undefined);
386
+ notify({ type: "lost", reason });
387
+ scheduleRestore();
388
+ // Glasses that never come back still end the link at the deadline.
389
+ cancelDeadline?.();
390
+ cancelDeadline = after(RESTORE_DEADLINE_MS + 1, () => {
391
+ cancelDeadline = null;
392
+ void restore();
393
+ });
394
+ }
395
+ /** Ask for the link again once the glasses are ready, until it is back or the deadline passes. */
396
+ function scheduleRestore(delayMs = 0) {
397
+ cancelRestore?.();
398
+ cancelRestore = after(delayMs, () => {
399
+ cancelRestore = null;
400
+ void restore();
401
+ });
402
+ }
403
+ async function restore() {
404
+ if (binding || bringingUp || holders.size === 0 || lostAt === null)
405
+ return;
406
+ if (Date.now() - lostAt > RESTORE_DEADLINE_MS) {
407
+ lostAt = null;
408
+ endedReason = "the glasses did not bring the link back";
409
+ notify({ type: "ended", reason: endedReason });
410
+ return;
411
+ }
412
+ if (!isReadyGlassesConnectionStatus(glassesConnection()))
413
+ return; // the connection watch calls again
414
+ try {
415
+ await bringUp(null);
416
+ }
417
+ catch (error) {
418
+ console.warn("[GlassesWifi] Bringing the link back failed; trying again", error);
419
+ scheduleRestore(5_000);
420
+ }
421
+ }
422
+ async function watch() {
423
+ if (watching)
424
+ return;
425
+ const unsubscribeStatus = onGlassesConnection(onConnection);
426
+ const networkLost = native.onLost(() => lose("the phone left the glasses network"));
427
+ const hotspot = PrivateBluetoothSdkModule.addListener("hotspot_status_change", (event) => {
428
+ if (linkType === "hotspot" && event.state !== "enabled" && !bringingUp)
429
+ lose("the glasses turned their hotspot off");
430
+ });
431
+ watching = () => {
432
+ unsubscribeStatus();
433
+ networkLost();
434
+ hotspot.remove();
435
+ };
436
+ await watchGlassesConnection();
437
+ }
438
+ function onConnection(next) {
439
+ if (!isConnectedGlassesConnectionStatus(next)) {
440
+ // A join still waiting cannot finish without the glasses: end it, as a loss does.
441
+ if (bringingUp)
442
+ void native.leave().catch(() => undefined);
443
+ lose("the glasses left Bluetooth");
444
+ }
445
+ else if (lostAt !== null && isReadyGlassesConnectionStatus(next))
446
+ scheduleRestore();
447
+ }
448
+ function unwatch() {
449
+ watching?.();
450
+ watching = null;
451
+ cancelRestore?.();
452
+ cancelRestore = null;
453
+ cancelDeadline?.();
454
+ cancelDeadline = null;
455
+ }
456
+ /**
457
+ * Hold the link only if it is up now (someone else brought it up): for a use that is just as well
458
+ * served over Bluetooth, like a file fetch, and must not bring the link up itself. Null when it
459
+ * is down, coming up or going down.
460
+ */
461
+ export async function holdGlassesWifiIfUp(consumer) {
462
+ if (holders.size === 0 || !binding || lostAt !== null || bringingUp || takingDown)
463
+ return null;
464
+ return holdGlassesWifi({ consumer });
465
+ }
466
+ /** Whether anyone holds the link now. */
467
+ function held() {
468
+ return holders.size > 0 || takingDown !== null;
469
+ }
470
+ /**
471
+ * Turn off a hotspot that came up with no holder soon after the last release: a hotspot command
472
+ * can wait in the BLE queue past its caller and reach the glasses after the release (OS-2133).
473
+ * An AP the glasses start on their own, long after any phone use, is left alone. Watched from the
474
+ * first hold on, since only a release opens the window.
475
+ */
476
+ function watchLateHotspots() {
477
+ if (reclaiming)
478
+ return;
479
+ reclaiming = PrivateBluetoothSdkModule.addListener("hotspot_status_change", (event) => {
480
+ if (event.state !== "enabled" || held() || Date.now() - releasedAt >= LATE_ENABLE_WINDOW_MS)
481
+ return;
482
+ console.warn("[GlassesWifi] An enabled hotspot has no holder after a release; turning it off");
483
+ void setHotspot(false).catch((error) => console.warn("[GlassesWifi] Could not turn off the late hotspot", error));
484
+ });
485
+ }
486
+ /** Whether the glasses Wi-Fi link is up now, for whoever holds it. */
487
+ export function glassesWifiUp() {
488
+ return binding !== null;
489
+ }
490
+ /** Hear the glasses Wi-Fi link go up and down, whoever holds it. */
491
+ export function onGlassesWifiUp(listener) {
492
+ upListeners.add(listener);
493
+ return () => {
494
+ upListeners.delete(listener);
495
+ };
496
+ }
497
+ //# sourceMappingURL=service.js.map