@mentra/bluetooth-sdk 3.5.0-dev.1518 → 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 (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
@@ -0,0 +1,415 @@
1
+ import CoreLocation
2
+ import Foundation
3
+ import ObjectiveC
4
+
5
+ /// Blocking CoreWLAN calls are isolated here; the existing hotspot owner
6
+ /// retains custody until they return, even after cancellation or a timeout.
7
+ final class MacHotspotAssociation {
8
+ /// Rejoining the hotspot seconds after leaving it, as between an update's passes, can be refused while the
9
+ /// glasses still hold the Mac's previous association (-3912). A later attempt in the same window succeeds.
10
+ static let associationAttempts = 3
11
+ static let associationRetryDelay: TimeInterval = 2
12
+ /// After leaving, macOS auto-join normally returns to the previous network within a few seconds.
13
+ static let autoJoinWait: TimeInterval = 15
14
+ /// Auto-join after a Wi-Fi power cycle: 2 s on lab air-1.
15
+ static let powerCycleWait: TimeInterval = 30
16
+ /// macOS answers an app without the scan entitlement from its cache until 10 s after its last live
17
+ /// scan returned (airportd, 2026-11-17), so scanning sooner only reads the scan that just missed.
18
+ static let scanInterval: TimeInterval = 10
19
+ /// Time to find and join the hotspot. A full live scan took about 22 s while the Mac was on another network,
20
+ /// and one could miss an AP that had just come up (lab Mac, 2026-11-17). This window holds four.
21
+ static let joinWindow: TimeInterval = 120
22
+
23
+ private let condition = NSCondition()
24
+ private var cancelled = false
25
+ private var interface: MacWifiInterface?
26
+ private var joinedSSID: String?
27
+ /// The Wi-Fi network the Mac was on before this join, which every leave returns it to.
28
+ private var previousSSID: String?
29
+ private let deadline: TimeInterval
30
+ private let now: () -> TimeInterval
31
+ private let pause: ((TimeInterval) -> Void)?
32
+ private let makeInterface: () throws -> MacWifiInterface
33
+ private let authorization: MacHotspotAuthorization?
34
+ private var scansStarted = 0
35
+
36
+ init(deadline: TimeInterval = ProcessInfo.processInfo.systemUptime + MacHotspotAssociation.joinWindow,
37
+ now: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime },
38
+ pause: ((TimeInterval) -> Void)? = nil,
39
+ makeInterface: (() throws -> MacWifiInterface)? = nil,
40
+ authorizationFacts: MacHotspotAuthorizationFacts? = nil,
41
+ authorization: MacHotspotAuthorization? = nil)
42
+ {
43
+ self.deadline = deadline
44
+ self.now = now
45
+ self.pause = pause
46
+ self.authorization = authorization
47
+ self.makeInterface = makeInterface ?? { try PublicCoreWlanInterface(authorizationFacts: authorizationFacts, authorization: authorization) }
48
+ }
49
+
50
+ /// `frequency` is the channel the glasses report for their AP, in MHz, when they know it.
51
+ func associate(ssid: String, password: String, frequency: Int? = nil) throws -> String {
52
+ try checkCurrent()
53
+ let interface = try makeInterface()
54
+ self.interface = interface
55
+ let before = try readSSID(interface)
56
+ if before != ssid { previousSSID = before }
57
+ for attempt in 1 ... Self.associationAttempts {
58
+ guard try readSSID(interface) != ssid else { break }
59
+ let network = try discoverNetwork(ssid: ssid, frequency: frequency, interface: interface)
60
+ try checkDiscoveryCurrent()
61
+ guard let network, try readSSID(interface) != ssid else { break }
62
+ try checkDiscoveryCurrent()
63
+ try authorization?.requireCurrentAuthorization()
64
+ // Record the intended association before this blocking call. A late
65
+ // successful join still belongs to us and must be cleaned up.
66
+ joinedSSID = ssid
67
+ do {
68
+ try interface.associate(network: network, password: password)
69
+ break
70
+ } catch {
71
+ // A refusal is retried with a fresh scan; cancellation, a lost Location
72
+ // authorization (rechecked by the next read) and the deadline end it.
73
+ if error is CancellationError || attempt == Self.associationAttempts { throw error }
74
+ try checkCurrent()
75
+ guard now() + Self.associationRetryDelay < deadline else { throw error }
76
+ wait(Self.associationRetryDelay)
77
+ }
78
+ }
79
+ try checkCurrent()
80
+ guard try readSSID(interface) == ssid else {
81
+ throw HotspotError("Mac Wi-Fi did not associate with the requested glasses hotspot")
82
+ }
83
+ return try interface.name()
84
+ }
85
+
86
+ func cancel() {
87
+ condition.lock(); cancelled = true; condition.broadcast(); condition.unlock()
88
+ }
89
+
90
+ /// Run on the same worker as association, after its blocking call returns.
91
+ /// A connection the user replaced must never be disconnected by our cleanup.
92
+ ///
93
+ /// Once an association was requested, whether it succeeded, failed or timed out, the
94
+ /// Mac may have left its own network for it and macOS has saved the hotspot as a known
95
+ /// network. Leaving forgets the hotspot and gets the Mac back on the network it was on
96
+ /// before (lab air-1, 2026-11-11: a failed join left it with no network for 5 hours).
97
+ @discardableResult
98
+ func leave() throws -> MacHotspotLeaveReport {
99
+ var report = MacHotspotLeaveReport()
100
+ if let joinedSSID, let interface {
101
+ if try readSSID(interface) == joinedSSID {
102
+ interface.disassociate()
103
+ guard try readSSID(interface) != joinedSSID else {
104
+ throw HotspotError("Mac Wi-Fi has not released the glasses hotspot")
105
+ }
106
+ report.disassociated = true
107
+ }
108
+ do { try interface.forget(ssid: joinedSSID); report.forgotHotspot = true }
109
+ catch { report.failures.append("forget: \(error.localizedDescription)") }
110
+ report.restore = restorePrevious(interface, report: &report)
111
+ }
112
+ interface = nil
113
+ joinedSSID = nil
114
+ previousSSID = nil
115
+ return report
116
+ }
117
+
118
+ /// Never takes the Mac off a network it is on: only an interface left with no network is
119
+ /// power cycled. After a failed association air-1's Wi-Fi answered every auto-join scan with
120
+ /// EBUSY for hours; a power cycle starts auto-join over. An app cannot rejoin the previous
121
+ /// network itself: without the passphrase, CoreWLAN answers -3900 (tmpErr).
122
+ private func restorePrevious(_ interface: MacWifiInterface, report: inout MacHotspotLeaveReport) -> MacHotspotRestore {
123
+ guard let previous = previousSSID else { return .noPreviousNetwork }
124
+ if let outcome = settle(interface, previous: previous, within: Self.autoJoinWait, success: .autoJoined) { return outcome }
125
+ do {
126
+ try interface.setPower(false)
127
+ sleep(1)
128
+ try interface.setPower(true)
129
+ } catch {
130
+ report.failures.append("power cycle: \(error.localizedDescription)")
131
+ return .notRestored
132
+ }
133
+ return settle(interface, previous: previous, within: Self.powerCycleWait, success: .powerCycled) ?? .notRestored
134
+ }
135
+
136
+ /// Polls once a second until the Mac is on the previous network (success) or on
137
+ /// another one (left alone); nil while it is still on none when the time runs out.
138
+ private func settle(_ interface: MacWifiInterface, previous: String, within seconds: TimeInterval,
139
+ success: MacHotspotRestore) -> MacHotspotRestore?
140
+ {
141
+ var waited: TimeInterval = 0
142
+ while true {
143
+ // An unreadable SSID (Location revoked) counts as no network: recovery never disconnects.
144
+ switch try? readSSID(interface) {
145
+ case previous?: return success
146
+ case .some: return .otherNetwork
147
+ case nil: break
148
+ }
149
+ guard waited < seconds else { return nil }
150
+ sleep(1); waited += 1
151
+ }
152
+ }
153
+
154
+ /// Cleanup pacing: unlike wait(_:), runs after cancel() and must not be cut short by it.
155
+ private func sleep(_ seconds: TimeInterval) {
156
+ if let pause { pause(seconds) } else { Thread.sleep(forTimeInterval: seconds) }
157
+ }
158
+
159
+ func currentSSID() throws -> String? {
160
+ guard let interface else { return nil }
161
+ return try readSSID(interface)
162
+ }
163
+
164
+ private func readSSID(_ interface: MacWifiInterface) throws -> String? {
165
+ try authorization?.requireCurrentAuthorization()
166
+ let ssid = try interface.currentSSID()
167
+ try authorization?.requireCurrentAuthorization()
168
+ return ssid
169
+ }
170
+
171
+ static func observeCurrentSSID() throws -> String? {
172
+ try PublicCoreWlanInterface().currentSSID()
173
+ }
174
+
175
+ private func discoverNetwork(ssid: String, frequency: Int?, interface: MacWifiInterface) throws -> NSObject? {
176
+ while true {
177
+ try checkDiscoveryCurrent()
178
+ // Recheck Location authorization before and after each blocking scan.
179
+ if try readSSID(interface) == ssid { return nil }
180
+ try authorization?.requireCurrentAuthorization()
181
+ let network = try interface.network(ssid: ssid, channels: MacHotspotScan.next(after: scansStarted, frequency: frequency))
182
+ scansStarted += 1
183
+ try checkDiscoveryCurrent()
184
+ if try readSSID(interface) == ssid { return nil }
185
+ if let network { return network }
186
+ // Successful empty scans remain pending within this same join window, rescanning when
187
+ // macOS allows the next live scan. Native scan errors escape immediately.
188
+ wait(min(Self.scanInterval, max(0, deadline - now())))
189
+ }
190
+ }
191
+
192
+ /// Pause on the association worker; cancellation wakes it.
193
+ private func wait(_ seconds: TimeInterval) {
194
+ if let pause { pause(seconds); return }
195
+ condition.lock()
196
+ if !cancelled { _ = condition.wait(until: Date(timeIntervalSinceNow: seconds)) }
197
+ condition.unlock()
198
+ }
199
+
200
+ private func checkDiscoveryCurrent() throws {
201
+ try checkCurrent()
202
+ guard now() < deadline else {
203
+ throw HotspotError("The requested glasses hotspot was not found by Mac Wi-Fi before the hotspot join timed out")
204
+ }
205
+ }
206
+
207
+ private func checkCurrent() throws {
208
+ condition.lock(); let stopped = cancelled; condition.unlock()
209
+ if stopped { throw CancellationError() }
210
+ }
211
+ }
212
+
213
+ /// Which channels a hotspot scan covers. A scan of every channel took about 22 s, most of it in a 6 GHz pass
214
+ /// (2026-11-17), and these glasses cannot run a 6 GHz AP. One channel takes 0.07 s, the 2.4 GHz band 0.65 s (air-3).
215
+ enum MacHotspotScan: Equatable {
216
+ /// The channel the glasses reported: their station's, which their AP shares while it is connected.
217
+ case channel(band: Int, number: Int)
218
+ /// Where the glasses start their own AP, with their station off Wi-Fi (Android's 2.4 GHz SoftAP band).
219
+ case band2GHz
220
+ /// Every 2.4 and 5 GHz channel, once a narrower scan has missed.
221
+ case below6GHz
222
+
223
+ /// CWChannelBand raw values.
224
+ static let band2 = 1, band5 = 2
225
+
226
+ static func next(after scans: Int, frequency: Int?) -> MacHotspotScan {
227
+ guard scans == 0 else { return .below6GHz }
228
+ return frequency.flatMap(channel(frequency:)) ?? .band2GHz
229
+ }
230
+
231
+ static func channel(frequency: Int) -> MacHotspotScan? {
232
+ switch frequency {
233
+ case 2412 ... 2472: .channel(band: band2, number: (frequency - 2407) / 5)
234
+ case 2484: .channel(band: band2, number: 14)
235
+ case 5160 ... 5885: .channel(band: band5, number: (frequency - 5000) / 5)
236
+ default: nil
237
+ }
238
+ }
239
+
240
+ func includes(band: Int, number: Int) -> Bool {
241
+ switch self {
242
+ case let .channel(b, n): band == b && number == n
243
+ case .band2GHz: band == Self.band2
244
+ case .below6GHz: band == Self.band2 || band == Self.band5
245
+ }
246
+ }
247
+ }
248
+
249
+ protocol MacWifiInterface: AnyObject {
250
+ func name() throws -> String
251
+ func currentSSID() throws -> String?
252
+ func network(ssid: String, channels: MacHotspotScan) throws -> NSObject?
253
+ func associate(network: NSObject, password: String) throws
254
+ func disassociate()
255
+ /// Removes the network from the Mac's known networks, so auto-join never picks it.
256
+ func forget(ssid: String) throws
257
+ func setPower(_ on: Bool) throws
258
+ }
259
+
260
+ /// What leaving did to the Mac's Wi-Fi, for the hotspot log. Never holds an SSID.
261
+ struct MacHotspotLeaveReport: Equatable {
262
+ var disassociated = false
263
+ var forgotHotspot = false
264
+ var restore: MacHotspotRestore = .notNeeded
265
+ var failures: [String] = []
266
+
267
+ var summary: String {
268
+ "disassociated=\(disassociated) forgot_hotspot=\(forgotHotspot) previous_network=\(restore.rawValue)" +
269
+ (failures.isEmpty ? "" : " failures=[\(failures.joined(separator: "; "))]")
270
+ }
271
+ }
272
+
273
+ enum MacHotspotRestore: String, Equatable {
274
+ /// No association was requested, so the Mac never left its network.
275
+ case notNeeded = "not_needed"
276
+ case noPreviousNetwork = "none_before"
277
+ case autoJoined = "auto_joined"
278
+ case powerCycled = "power_cycled"
279
+ /// The Mac is on a network other than the previous one, which recovery leaves alone.
280
+ case otherNetwork = "other_network"
281
+ case notRestored = "not_restored"
282
+ }
283
+
284
+ enum MacWifiInvocation {
285
+ // Objective-C NSError** parameters use autoreleasing writeback. Strong
286
+ // pointer storage would over-release errors when the native pool drains.
287
+ typealias Scan = @convention(c) (AnyObject, Selector, NSSet, NSData, NSString?, AutoreleasingUnsafeMutablePointer<NSError?>) -> Unmanaged<NSSet>?
288
+ typealias Associate = @convention(c) (AnyObject, Selector, AnyObject, NSString, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
289
+ typealias Forget = @convention(c) (AnyObject, Selector, NSData, UInt64, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
290
+ typealias SetPower = @convention(c) (AnyObject, Selector, Bool, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
291
+ }
292
+
293
+ /// CoreWLAN is a public macOS framework. Foundation loads it only in the Mac
294
+ /// process; Apple dyld permits macOS frameworks in iOS-on-Mac. The checked
295
+ /// Objective-C signatures below are the public CWInterface SDK declarations.
296
+ private final class PublicCoreWlanInterface: MacWifiInterface {
297
+ private let bundle: Bundle
298
+ private let interface: NSObject
299
+ private let client: NSObject
300
+ private let authorizationFacts: MacHotspotAuthorizationFacts
301
+ private let authorization: MacHotspotAuthorization?
302
+ private typealias Disassociate = @convention(c) (AnyObject, Selector) -> Void
303
+
304
+ init(authorizationFacts: MacHotspotAuthorizationFacts? = nil, authorization: MacHotspotAuthorization? = nil) throws {
305
+ self.authorizationFacts = authorizationFacts ?? MacHotspotAuthorizationFacts()
306
+ self.authorization = authorization
307
+ guard let bundle = Bundle(path: "/System/Library/Frameworks/CoreWLAN.framework") else {
308
+ throw HotspotError("Mac Wi-Fi framework is unavailable")
309
+ }
310
+ do { try bundle.loadAndReturnError() }
311
+ catch { throw Self.failure("framework loading", error as NSError) }
312
+ guard let clientClass = NSClassFromString("CWWiFiClient") as? NSObject.Type,
313
+ clientClass.responds(to: NSSelectorFromString("sharedWiFiClient")),
314
+ let client = clientClass.perform(NSSelectorFromString("sharedWiFiClient"))?.takeUnretainedValue() as? NSObject,
315
+ client.responds(to: NSSelectorFromString("interface")),
316
+ let interface = client.perform(NSSelectorFromString("interface"))?.takeUnretainedValue() as? NSObject
317
+ else { throw HotspotError("Mac Wi-Fi interface is unavailable") }
318
+ for method in ["interfaceName", "ssidData", "supportedWLANChannels", "scanForNetworksWithChannels:ssid:bssid:error:",
319
+ "associateToNetwork:password:error:", "disassociate"] {
320
+ guard interface.responds(to: NSSelectorFromString(method)) else {
321
+ throw HotspotError("Mac Wi-Fi interface does not support hotspot association")
322
+ }
323
+ }
324
+ self.interface = interface
325
+ self.client = client
326
+ self.bundle = bundle
327
+ }
328
+
329
+ func name() throws -> String {
330
+ guard let name = interface.perform(NSSelectorFromString("interfaceName"))?.takeUnretainedValue() as? String,
331
+ !name.isEmpty else { throw HotspotError("Mac Wi-Fi interface has no identity") }
332
+ return name
333
+ }
334
+
335
+ func currentSSID() throws -> String? {
336
+ try requireAuthorization()
337
+ guard let data = interface.perform(NSSelectorFromString("ssidData"))?.takeUnretainedValue() as? Data else { return nil }
338
+ return String(data: data, encoding: .utf8)
339
+ }
340
+
341
+ private func requireAuthorization() throws {
342
+ if let authorization { try authorization.requireCurrentAuthorization(); return }
343
+ // Independent internet-return observation has no owned join recipient.
344
+ // Its existing static authorization guard remains unchanged.
345
+ let authorization = CLLocationManager.authorizationStatus()
346
+ guard MacHotspotAuthorization.isAuthorized(authorization) else {
347
+ throw authorizationFacts.failure("Location access is required to verify the current Mac Wi-Fi network", raw: authorization.rawValue,
348
+ getter: .staticSSID, foreground: MacHotspotAuthorizationFacts.foreground())
349
+ }
350
+ }
351
+
352
+ /// CoreWLAN's public scan always covers every channel, 6 GHz included; its channel-scoped scan is not public.
353
+ func network(ssid: String, channels scan: MacHotspotScan) throws -> NSObject? {
354
+ try requireAuthorization()
355
+ let supported = interface.perform(NSSelectorFromString("supportedWLANChannels"))?.takeUnretainedValue() as? NSSet ?? []
356
+ let channels = NSSet(array: supported.compactMap { $0 as? NSObject }.filter {
357
+ scan.includes(band: $0.value(forKey: "channelBand") as? Int ?? 0, number: $0.value(forKey: "channelNumber") as? Int ?? 0)
358
+ })
359
+ // A reported channel this Mac cannot use is a miss: an empty set would scan every channel.
360
+ guard channels.count > 0 else { return nil }
361
+ let selector = NSSelectorFromString("scanForNetworksWithChannels:ssid:bssid:error:")
362
+ let invoke = unsafeBitCast(interface.method(for: selector), to: MacWifiInvocation.Scan.self)
363
+ var error: NSError?
364
+ guard let networks = invoke(interface, selector, channels, NSData(data: Data(ssid.utf8)), nil, &error)?.takeUnretainedValue() else {
365
+ throw Self.failure("scan", error)
366
+ }
367
+ // A directed scan can include unrelated networks. Match the requested
368
+ // SSID bytes without reading or logging BSSID or other scan identities.
369
+ for case let network as NSObject in networks {
370
+ guard network.responds(to: NSSelectorFromString("ssidData")),
371
+ let data = network.perform(NSSelectorFromString("ssidData"))?.takeUnretainedValue() as? Data,
372
+ data == Data(ssid.utf8) else { continue }
373
+ return network
374
+ }
375
+ return nil
376
+ }
377
+
378
+ func associate(network: NSObject, password: String) throws {
379
+ try requireAuthorization()
380
+ let selector = NSSelectorFromString("associateToNetwork:password:error:")
381
+ let invoke = unsafeBitCast(interface.method(for: selector), to: MacWifiInvocation.Associate.self)
382
+ var error: NSError?
383
+ guard invoke(interface, selector, network, password as NSString, &error) else { throw Self.failure("association", error) }
384
+ }
385
+
386
+ /// associateToNetwork saves the network as a known network, and CoreWLAN has no public way to
387
+ /// remove one without an administrator's authorization. CWWiFiClient's forget call needs none.
388
+ func forget(ssid: String) throws {
389
+ let selector = NSSelectorFromString("forgetWiFiProfileWithSSID:event:error:")
390
+ guard client.responds(to: selector) else { throw HotspotError("Mac Wi-Fi cannot forget networks") }
391
+ let invoke = unsafeBitCast(client.method(for: selector), to: MacWifiInvocation.Forget.self)
392
+ var error: NSError?
393
+ guard invoke(client, selector, NSData(data: Data(ssid.utf8)), 0, &error) else { throw Self.failure("forget", error) }
394
+ }
395
+
396
+ func setPower(_ on: Bool) throws {
397
+ let selector = NSSelectorFromString("setPower:error:")
398
+ guard interface.responds(to: selector) else { throw HotspotError("Mac Wi-Fi cannot change power") }
399
+ let invoke = unsafeBitCast(interface.method(for: selector), to: MacWifiInvocation.SetPower.self)
400
+ var error: NSError?
401
+ guard invoke(interface, selector, on, &error) else { throw Self.failure("power", error) }
402
+ }
403
+
404
+ func disassociate() {
405
+ let selector = NSSelectorFromString("disassociate")
406
+ let invoke = unsafeBitCast(interface.method(for: selector), to: Disassociate.self)
407
+ invoke(interface, selector)
408
+ }
409
+
410
+ private static func failure(_ operation: String, _ error: NSError?) -> Error {
411
+ let domain = error?.domain ?? "unavailable"
412
+ let safeDomain = domain.range(of: "^[A-Za-z0-9_.-]{1,128}$", options: .regularExpression) == nil ? "unavailable" : domain
413
+ return HotspotError("Mac Wi-Fi \(operation) failed (\(safeDomain), \(error?.code ?? -1))")
414
+ }
415
+ }
@@ -0,0 +1,126 @@
1
+ import CoreLocation
2
+ import Foundation
3
+
4
+ /// CoreWLAN requires Location authorization to identify the requested network.
5
+ /// Use the app's existing system permission, with no separate connection screen.
6
+ final class MacHotspotAuthorization: NSObject, CLLocationManagerDelegate {
7
+ private var manager: CLLocationManager?
8
+ private var completion: ((Result<Void, Error>) -> Void)?
9
+ private var started = false
10
+ private var closed = false
11
+ private var ready = false
12
+ private var revoked = false
13
+ private let facts: MacHotspotAuthorizationFacts
14
+ private let makeManager: () -> CLLocationManager
15
+ private let locationServicesEnabled: () -> Bool
16
+ var onRevoked: ((Error) -> Void)?
17
+ var onRestored: (() -> Void)?
18
+
19
+ init(facts: MacHotspotAuthorizationFacts = MacHotspotAuthorizationFacts(), makeManager: @escaping () -> CLLocationManager = { CLLocationManager() },
20
+ locationServicesEnabled: @escaping () -> Bool = { CLLocationManager.locationServicesEnabled() })
21
+ {
22
+ self.facts = facts
23
+ self.makeManager = makeManager
24
+ self.locationServicesEnabled = locationServicesEnabled
25
+ super.init()
26
+ }
27
+
28
+ func start(completion: @escaping (Result<Void, Error>) -> Void) {
29
+ DispatchQueue.main.async {
30
+ guard !self.closed, !self.started else { completion(.failure(CancellationError())); return }
31
+ self.started = true
32
+ self.completion = completion
33
+ let manager = self.makeManager()
34
+ self.manager = manager
35
+ manager.delegate = self
36
+ self.handle(manager.authorizationStatus, getter: .instanceInitial)
37
+ if manager.authorizationStatus == .notDetermined { manager.requestWhenInUseAuthorization() }
38
+ }
39
+ }
40
+
41
+ func cancel() {
42
+ DispatchQueue.main.async {
43
+ self.closed = true
44
+ self.ready = false
45
+ self.reply(.failure(CancellationError()))
46
+ self.manager?.delegate = nil
47
+ self.manager = nil
48
+ self.onRevoked = nil
49
+ self.onRestored = nil
50
+ }
51
+ }
52
+
53
+ /// A ready session retains its manager through owned Wi-Fi cleanup. An unanswered
54
+ /// authorization request must still settle when the join is cancelled.
55
+ func cancelPending() {
56
+ DispatchQueue.main.async {
57
+ if self.completion != nil { self.cancel() }
58
+ }
59
+ }
60
+
61
+ /// Query the same initialized recipient on its owning thread for every native read
62
+ /// or write. An earlier success is never an authorization cache.
63
+ func requireCurrentAuthorization() throws {
64
+ let check = {
65
+ guard !self.closed, let manager = self.manager else { throw CancellationError() }
66
+ let status = manager.authorizationStatus
67
+ let foreground = MacHotspotAuthorizationFacts.foreground()
68
+ self.facts.observeInstance(raw: status.rawValue, getter: .instanceCurrent, foreground: foreground)
69
+ guard self.locationServicesEnabled() else {
70
+ throw self.facts.failure("Location services are required to verify the current Mac Wi-Fi network", raw: status.rawValue,
71
+ getter: .instanceCurrent, foreground: foreground)
72
+ }
73
+ guard Self.isAuthorized(status) else {
74
+ throw self.facts.failure("Location access is required to verify the current Mac Wi-Fi network", raw: status.rawValue,
75
+ getter: .instanceCurrent, foreground: foreground)
76
+ }
77
+ }
78
+ if Thread.isMainThread { try check() }
79
+ else { try DispatchQueue.main.sync(execute: check) }
80
+ }
81
+
82
+ func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
83
+ guard manager === self.manager, !closed else { return }
84
+ handle(manager.authorizationStatus, getter: .instanceCallback)
85
+ }
86
+
87
+ static func isAuthorized(_ status: CLAuthorizationStatus) -> Bool {
88
+ if status == .authorizedAlways { return true }
89
+ #if !os(macOS)
90
+ if status == .authorizedWhenInUse { return true }
91
+ #endif
92
+ return false
93
+ }
94
+
95
+ private func handle(_ status: CLAuthorizationStatus, getter: MacHotspotAuthorizationFacts.Getter) {
96
+ let foreground = MacHotspotAuthorizationFacts.foreground()
97
+ guard !closed else { return }
98
+ facts.observeInstance(raw: status.rawValue, getter: getter, foreground: foreground)
99
+ if Self.isAuthorized(status) {
100
+ ready = true
101
+ if revoked { revoked = false; onRestored?() }
102
+ reply(.success(()))
103
+ return
104
+ }
105
+ let error = facts.failure("Location access is required to identify the glasses hotspot on Mac", raw: status.rawValue, getter: getter, foreground: foreground)
106
+ if ready {
107
+ ready = false
108
+ revoked = true
109
+ onRevoked?(error)
110
+ return
111
+ }
112
+ switch status {
113
+ case .denied, .restricted:
114
+ reply(.failure(error))
115
+ case .notDetermined: break
116
+ default:
117
+ reply(.failure(facts.failure("Mac hotspot Location authorization is unavailable", raw: status.rawValue, getter: getter, foreground: foreground)))
118
+ }
119
+ }
120
+
121
+ private func reply(_ result: Result<Void, Error>) {
122
+ let reply = completion
123
+ completion = nil
124
+ reply?(result)
125
+ }
126
+ }
@@ -0,0 +1,51 @@
1
+ import Foundation
2
+ #if canImport(UIKit)
3
+ import UIKit
4
+ #elseif canImport(AppKit)
5
+ import AppKit
6
+ #endif
7
+
8
+ /// Diagnostic observations only. These facts never authorize a network read or a join.
9
+ final class MacHotspotAuthorizationFacts {
10
+ enum Getter: String { case instanceInitial = "instance-initial", instanceCallback = "instance-callback", instanceCurrent = "instance-current", staticSSID = "static-ssid" }
11
+ enum Foreground: String { case active, inactive, background, unknown }
12
+ private let lock = NSLock()
13
+ private var instance: (raw: Int32, getter: Getter, foreground: Foreground)?
14
+ private var initialCallbackObserved = false
15
+ private let pid = ProcessInfo.processInfo.processIdentifier
16
+ private let bundleID = Bundle.main.bundleIdentifier.flatMap { value in
17
+ value.range(of: "^[A-Za-z0-9_.-]{1,128}$", options: .regularExpression) == nil ? nil : value
18
+ } ?? "unknown"
19
+
20
+ /// UIKit/AppKit state is sampled only on its owning thread. A worker read stays unknown.
21
+ static func foreground() -> Foreground {
22
+ guard Thread.isMainThread else { return .unknown }
23
+ #if canImport(UIKit)
24
+ switch UIApplication.shared.applicationState {
25
+ case .active: return .active
26
+ case .inactive: return .inactive
27
+ case .background: return .background
28
+ @unknown default: return .unknown
29
+ }
30
+ #elseif canImport(AppKit)
31
+ return NSApplication.shared.isActive ? .active : .inactive
32
+ #else
33
+ return .unknown
34
+ #endif
35
+ }
36
+
37
+ func observeInstance(raw: Int32, getter: Getter, foreground: Foreground) {
38
+ lock.lock(); defer { lock.unlock() }
39
+ instance = (raw, getter, foreground)
40
+ if getter == .instanceCallback { initialCallbackObserved = true }
41
+ }
42
+
43
+ /// Only enums and this process's identity cross the existing bounded error bridge.
44
+ func failure(_ message: String, raw: Int32, getter: Getter, foreground: Foreground) -> HotspotError {
45
+ lock.lock(); defer { lock.unlock() }
46
+ let instanceRaw = instance.map { String($0.raw) } ?? "unknown"
47
+ let instanceGetter = instance?.getter.rawValue ?? "unknown"
48
+ let instanceForeground = instance?.foreground.rawValue ?? "unknown"
49
+ return HotspotError("\(message) [location raw=\(raw) getter=\(getter.rawValue) foreground=\(foreground.rawValue) instanceRaw=\(instanceRaw) instanceGetter=\(instanceGetter) instanceForeground=\(instanceForeground) initialCallbackObserved=\(initialCallbackObserved) pid=\(pid) bundle=\(bundleID)]")
50
+ }
51
+ }
@@ -0,0 +1,35 @@
1
+ import Foundation
2
+
3
+ /// Retain a real authorization restoration while this session's cleanup result
4
+ /// is still returning from its worker. All state belongs to the hotspot owner queue.
5
+ final class MacHotspotCleanupContinuation {
6
+ private var restorationPending = false
7
+ private let isCurrentCancelledSession: () -> Bool
8
+ private let requestCleanup: () -> Void
9
+
10
+ init(authorization: MacHotspotAuthorization, queue: DispatchQueue,
11
+ isCurrentCancelledSession: @escaping () -> Bool, requestCleanup: @escaping () -> Void)
12
+ {
13
+ self.isCurrentCancelledSession = isCurrentCancelledSession
14
+ self.requestCleanup = requestCleanup
15
+ authorization.onRestored = { [weak self] in
16
+ queue.async { [weak self] in
17
+ guard let self, self.isCurrentCancelledSession() else { return }
18
+ self.restorationPending = true
19
+ self.requestCleanup()
20
+ }
21
+ }
22
+ }
23
+
24
+ func cleanupStarted() {
25
+ restorationPending = false
26
+ }
27
+
28
+ func cleanupFailed() {
29
+ guard restorationPending, isCurrentCancelledSession() else { return }
30
+ restorationPending = false
31
+ // A current restoration was not consumed by the failed worker attempt.
32
+ // Resume only its owned cleanup, which rechecks live permission and SSID.
33
+ requestCleanup()
34
+ }
35
+ }
@@ -0,0 +1,30 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ final class HotspotAddressPolicyTests: XCTestCase {
5
+ func testHotspotAddressWaitsForDhcpAfterSsidAssociation() {
6
+ // The reported incident associated the glasses SSID while en0 still had the home-router IP.
7
+ let addresses = ["192.168.1.10", "169.254.1.10", "192.168.43.142"]
8
+ XCTAssertEqual(addresses.filter { HotspotAddressPolicy.isHotspotClientAddress($0, gateway: "192.168.43.1") }, ["192.168.43.142"])
9
+ XCTAssertTrue(HotspotAddressPolicy.isHotspotClientAddress("10.5.6.8", gateway: "10.5.6.1"))
10
+ for address in ["192.168.43.1", "192.168.43.0", "192.168.43.255", "192.168.43.256", "host.local"] {
11
+ XCTAssertFalse(HotspotAddressPolicy.isHotspotClientAddress(address, gateway: "192.168.43.1"), address)
12
+ }
13
+ XCTAssertFalse(HotspotAddressPolicy.isHotspotClientAddress("8.8.8.2", gateway: "8.8.8.1"))
14
+ }
15
+
16
+ func testReusingHotspotRequiresExactSsidAndReportedGateway() {
17
+ XCTAssertTrue(HotspotAddressPolicy.canReuseHotspot(requestedSSID: "glasses", currentSSID: "glasses", address: "192.168.43.2", gateway: "192.168.43.1"))
18
+ for current in [nil, "", "home", "Glasses"] as [String?] {
19
+ XCTAssertFalse(HotspotAddressPolicy.canReuseHotspot(requestedSSID: "glasses", currentSSID: current, address: "192.168.43.2", gateway: "192.168.43.1"))
20
+ }
21
+ XCTAssertFalse(HotspotAddressPolicy.canReuseHotspot(requestedSSID: "", currentSSID: "", address: "192.168.43.2", gateway: "192.168.43.1"))
22
+ XCTAssertFalse(HotspotAddressPolicy.canReuseHotspot(requestedSSID: "glasses", currentSSID: "glasses", address: "192.168.43.2", gateway: nil))
23
+ }
24
+
25
+ func testReusingHotspotRejectsStaleDhcpAndNonClientAddresses() {
26
+ for address in [nil, "192.168.1.2", "192.168.43.0", "192.168.43.1", "192.168.43.255", "host.local"] as [String?] {
27
+ XCTAssertFalse(HotspotAddressPolicy.canReuseHotspot(requestedSSID: "glasses", currentSSID: "glasses", address: address, gateway: "192.168.43.1"))
28
+ }
29
+ }
30
+ }