@mentra/glasses-media 3.4.0-dev.999 → 3.4.0

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 (40) hide show
  1. package/README.md +1 -1
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/mentra/glassesmedia/GlassesMediaRelayModule.kt +12 -10
  4. package/android/src/main/java/com/mentra/glassesmedia/network/InternetHold.kt +1 -1
  5. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkChangeDetector.kt +3 -1
  6. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkObserver.kt +1 -1
  7. package/android/src/main/java/com/mentra/glassesmedia/publisher/PhoneWhipPublisher.kt +1 -1
  8. package/android/src/main/java/com/mentra/glassesmedia/source/CloudflareWhepSource.kt +1 -1
  9. package/android/src/main/java/com/mentra/glassesmedia/source/DecodedFrameTap.kt +1 -1
  10. package/android/src/main/java/com/mentra/glassesmedia/source/DecodedTrackRelay.kt +1 -1
  11. package/android/src/main/java/com/mentra/glassesmedia/source/GlassesMediaSource.kt +1 -1
  12. package/android/src/main/java/com/mentra/glassesmedia/source/LocalWhipIngestSource.kt +4 -4
  13. package/android/src/main/java/com/mentra/glassesmedia/source/SelectedIcePair.kt +1 -1
  14. package/android/src/main/java/com/mentra/glassesmedia/source/SoftApIceDiagnosis.kt +3 -2
  15. package/android/src/main/java/com/mentra/glassesmedia/source/SoftApSdpGuard.kt +1 -1
  16. package/android/src/main/java/com/mentra/glassesmedia/source/SyntheticI420Source.kt +1 -1
  17. package/android/src/main/java/com/mentra/glassesmedia/source/VideoSourceArm.kt +2 -0
  18. package/android/src/main/java/com/mentra/glassesmedia/source/WhipIngestServer.kt +3 -3
  19. package/android/src/main/java/com/mentra/glassesmedia/telemetry/AvSyncProbe.kt +1 -1
  20. package/android/src/main/java/com/mentra/glassesmedia/trace/MediaLog.kt +35 -0
  21. package/index.d.ts +6 -0
  22. package/index.js +21 -0
  23. package/ios/CoreKit/Sources/GlassesMediaCore/HotspotJoinFailure.swift +4 -0
  24. package/ios/CoreKit/Sources/GlassesMediaCore/HotspotReapplyPolicy.swift +26 -0
  25. package/ios/CoreKit/Sources/GlassesMediaCore/LocalNetworkAccessRequest.swift +33 -7
  26. package/ios/CoreKit/Sources/GlassesMediaCore/MacHotspotAssociation.swift +146 -18
  27. package/ios/GlassesHotspotNetwork.swift +90 -33
  28. package/ios/GlassesMediaRelayModule.swift +19 -2
  29. package/ios/LocalWhipIngestSource.swift +2 -2
  30. package/ios/MediaLog.swift +13 -0
  31. package/ios/WhepVideoSource.swift +8 -8
  32. package/package.json +4 -1
  33. package/android/src/main/java/com/mentra/glassesmedia/network/Ipv4Prefix.kt +0 -51
  34. package/android/src/main/java/com/mentra/glassesmedia/network/NetworkFacts.kt +0 -81
  35. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkError.kt +0 -109
  36. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkReadiness.kt +0 -103
  37. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkRequestSpec.kt +0 -53
  38. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedNetworkState.kt +0 -127
  39. package/android/src/main/java/com/mentra/glassesmedia/network/ScopedSoftApNetwork.kt +0 -573
  40. package/android/src/main/java/com/mentra/glassesmedia/trace/SoftApTrace.kt +0 -143
@@ -5,10 +5,21 @@ import ObjectiveC
5
5
  /// Blocking public CoreWLAN calls are isolated here; the existing hotspot owner
6
6
  /// retains custody until they return, even after cancellation or a timeout.
7
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
+
8
17
  private let condition = NSCondition()
9
18
  private var cancelled = false
10
19
  private var interface: MacWifiInterface?
11
20
  private var joinedSSID: String?
21
+ /// The Wi-Fi network the Mac was on before this join, which every leave returns it to.
22
+ private var previousSSID: String?
12
23
  private let deadline: TimeInterval
13
24
  private let now: () -> TimeInterval
14
25
  private let pause: ((TimeInterval) -> Void)?
@@ -33,16 +44,28 @@ final class MacHotspotAssociation {
33
44
  try checkCurrent()
34
45
  let interface = try makeInterface()
35
46
  self.interface = interface
36
- if try readSSID(interface) != ssid {
47
+ let before = try readSSID(interface)
48
+ if before != ssid { previousSSID = before }
49
+ for attempt in 1 ... Self.associationAttempts {
50
+ guard try readSSID(interface) != ssid else { break }
37
51
  let network = try discoverNetwork(ssid: ssid, interface: interface)
38
52
  try checkDiscoveryCurrent()
39
- if let network, try readSSID(interface) != ssid {
40
- try checkDiscoveryCurrent()
41
- try authorization?.requireCurrentAuthorization()
42
- // Record the intended association before this blocking call. A late
43
- // successful join still belongs to us and must be cleaned up.
44
- joinedSSID = ssid
53
+ guard let network, try readSSID(interface) != ssid else { break }
54
+ try checkDiscoveryCurrent()
55
+ try authorization?.requireCurrentAuthorization()
56
+ // Record the intended association before this blocking call. A late
57
+ // successful join still belongs to us and must be cleaned up.
58
+ joinedSSID = ssid
59
+ do {
45
60
  try interface.associate(network: network, password: password)
61
+ break
62
+ } catch {
63
+ // A refusal is retried with a fresh scan; cancellation, a lost Location
64
+ // authorization (rechecked by the next read) and the deadline end it.
65
+ if error is CancellationError || attempt == Self.associationAttempts { throw error }
66
+ try checkCurrent()
67
+ guard now() + Self.associationRetryDelay < deadline else { throw error }
68
+ wait(Self.associationRetryDelay)
46
69
  }
47
70
  }
48
71
  try checkCurrent()
@@ -58,17 +81,71 @@ final class MacHotspotAssociation {
58
81
 
59
82
  /// Run on the same worker as association, after its blocking call returns.
60
83
  /// A connection the user replaced must never be disconnected by our cleanup.
61
- func leave() throws {
62
- if let joinedSSID {
63
- if let interface, try readSSID(interface) == joinedSSID {
84
+ ///
85
+ /// Once an association was requested, whether it succeeded, failed or timed out, the
86
+ /// Mac may have left its own network for it and macOS has saved the hotspot as a known
87
+ /// network. Leaving forgets the hotspot and gets the Mac back on the network it was on
88
+ /// before (lab air-1, 2026-11-11: a failed join left it with no network for 5 hours).
89
+ @discardableResult
90
+ func leave() throws -> MacHotspotLeaveReport {
91
+ var report = MacHotspotLeaveReport()
92
+ if let joinedSSID, let interface {
93
+ if try readSSID(interface) == joinedSSID {
64
94
  interface.disassociate()
65
95
  guard try readSSID(interface) != joinedSSID else {
66
96
  throw LocalMediaError("Mac Wi-Fi has not released the glasses hotspot")
67
97
  }
98
+ report.disassociated = true
68
99
  }
100
+ do { try interface.forget(ssid: joinedSSID); report.forgotHotspot = true }
101
+ catch { report.failures.append("forget: \(error.localizedDescription)") }
102
+ report.restore = restorePrevious(interface, report: &report)
69
103
  }
70
104
  interface = nil
71
105
  joinedSSID = nil
106
+ previousSSID = nil
107
+ return report
108
+ }
109
+
110
+ /// Never takes the Mac off a network it is on: only an interface left with no network is
111
+ /// power cycled. After a failed association air-1's Wi-Fi answered every auto-join scan with
112
+ /// EBUSY for hours; a power cycle starts auto-join over. An app cannot rejoin the previous
113
+ /// network itself: without the passphrase, CoreWLAN answers -3900 (tmpErr).
114
+ private func restorePrevious(_ interface: MacWifiInterface, report: inout MacHotspotLeaveReport) -> MacHotspotRestore {
115
+ guard let previous = previousSSID else { return .noPreviousNetwork }
116
+ if let outcome = settle(interface, previous: previous, within: Self.autoJoinWait, success: .autoJoined) { return outcome }
117
+ do {
118
+ try interface.setPower(false)
119
+ sleep(1)
120
+ try interface.setPower(true)
121
+ } catch {
122
+ report.failures.append("power cycle: \(error.localizedDescription)")
123
+ return .notRestored
124
+ }
125
+ return settle(interface, previous: previous, within: Self.powerCycleWait, success: .powerCycled) ?? .notRestored
126
+ }
127
+
128
+ /// Polls once a second until the Mac is on the previous network (success) or on
129
+ /// another one (left alone); nil while it is still on none when the time runs out.
130
+ private func settle(_ interface: MacWifiInterface, previous: String, within seconds: TimeInterval,
131
+ success: MacHotspotRestore) -> MacHotspotRestore?
132
+ {
133
+ var waited: TimeInterval = 0
134
+ while true {
135
+ // An unreadable SSID (Location revoked) counts as no network: recovery never disconnects.
136
+ switch try? readSSID(interface) {
137
+ case previous?: return success
138
+ case .some: return .otherNetwork
139
+ case nil: break
140
+ }
141
+ guard waited < seconds else { return nil }
142
+ sleep(1); waited += 1
143
+ }
144
+ }
145
+
146
+ /// Cleanup pacing: unlike wait(_:), runs after cancel() and must not be cut short by it.
147
+ private func sleep(_ seconds: TimeInterval) {
148
+ if let pause { pause(seconds) } else { Thread.sleep(forTimeInterval: seconds) }
72
149
  }
73
150
 
74
151
  func currentSSID() throws -> String? {
@@ -98,17 +175,19 @@ final class MacHotspotAssociation {
98
175
  if try readSSID(interface) == ssid { return nil }
99
176
  if let network { return network }
100
177
  // Successful empty scans remain pending within this same join window.
101
- // Native scan errors escape immediately; association is never retried.
102
- let remaining = max(0, deadline - now())
103
- if let pause { pause(min(1, remaining)) }
104
- else {
105
- condition.lock()
106
- if !cancelled { _ = condition.wait(until: Date(timeIntervalSinceNow: min(1, remaining))) }
107
- condition.unlock()
108
- }
178
+ // Native scan errors escape immediately.
179
+ wait(min(1, max(0, deadline - now())))
109
180
  }
110
181
  }
111
182
 
183
+ /// Pause on the association worker; cancellation wakes it.
184
+ private func wait(_ seconds: TimeInterval) {
185
+ if let pause { pause(seconds); return }
186
+ condition.lock()
187
+ if !cancelled { _ = condition.wait(until: Date(timeIntervalSinceNow: seconds)) }
188
+ condition.unlock()
189
+ }
190
+
112
191
  private func checkDiscoveryCurrent() throws {
113
192
  try checkCurrent()
114
193
  guard now() < deadline else {
@@ -128,6 +207,33 @@ protocol MacWifiInterface: AnyObject {
128
207
  func network(ssid: String) throws -> NSObject?
129
208
  func associate(network: NSObject, password: String) throws
130
209
  func disassociate()
210
+ /// Removes the network from the Mac's known networks, so auto-join never picks it.
211
+ func forget(ssid: String) throws
212
+ func setPower(_ on: Bool) throws
213
+ }
214
+
215
+ /// What leaving did to the Mac's Wi-Fi, for the hotspot log. Never holds an SSID.
216
+ struct MacHotspotLeaveReport: Equatable {
217
+ var disassociated = false
218
+ var forgotHotspot = false
219
+ var restore: MacHotspotRestore = .notNeeded
220
+ var failures: [String] = []
221
+
222
+ var summary: String {
223
+ "disassociated=\(disassociated) forgot_hotspot=\(forgotHotspot) previous_network=\(restore.rawValue)" +
224
+ (failures.isEmpty ? "" : " failures=[\(failures.joined(separator: "; "))]")
225
+ }
226
+ }
227
+
228
+ enum MacHotspotRestore: String, Equatable {
229
+ /// No association was requested, so the Mac never left its network.
230
+ case notNeeded = "not_needed"
231
+ case noPreviousNetwork = "none_before"
232
+ case autoJoined = "auto_joined"
233
+ case powerCycled = "power_cycled"
234
+ /// The Mac is on a network other than the previous one, which recovery leaves alone.
235
+ case otherNetwork = "other_network"
236
+ case notRestored = "not_restored"
131
237
  }
132
238
 
133
239
  enum MacWifiInvocation {
@@ -135,6 +241,8 @@ enum MacWifiInvocation {
135
241
  // pointer storage would over-release errors when the native pool drains.
136
242
  typealias Scan = @convention(c) (AnyObject, Selector, NSData, AutoreleasingUnsafeMutablePointer<NSError?>) -> Unmanaged<NSSet>?
137
243
  typealias Associate = @convention(c) (AnyObject, Selector, AnyObject, NSString, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
244
+ typealias Forget = @convention(c) (AnyObject, Selector, NSData, UInt64, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
245
+ typealias SetPower = @convention(c) (AnyObject, Selector, Bool, AutoreleasingUnsafeMutablePointer<NSError?>) -> Bool
138
246
  }
139
247
 
140
248
  /// CoreWLAN is a public macOS framework. Foundation loads it only in the Mac
@@ -143,6 +251,7 @@ enum MacWifiInvocation {
143
251
  private final class PublicCoreWlanInterface: MacWifiInterface {
144
252
  private let bundle: Bundle
145
253
  private let interface: NSObject
254
+ private let client: NSObject
146
255
  private let authorizationFacts: MacHotspotAuthorizationFacts
147
256
  private let authorization: MacHotspotAuthorization?
148
257
  private typealias Disassociate = @convention(c) (AnyObject, Selector) -> Void
@@ -167,6 +276,7 @@ private final class PublicCoreWlanInterface: MacWifiInterface {
167
276
  }
168
277
  }
169
278
  self.interface = interface
279
+ self.client = client
170
280
  self.bundle = bundle
171
281
  }
172
282
 
@@ -220,6 +330,24 @@ private final class PublicCoreWlanInterface: MacWifiInterface {
220
330
  guard invoke(interface, selector, network, password as NSString, &error) else { throw Self.failure("association", error) }
221
331
  }
222
332
 
333
+ /// associateToNetwork saves the network as a known network, and CoreWLAN has no public way to
334
+ /// remove one without an administrator's authorization. CWWiFiClient's forget call needs none.
335
+ func forget(ssid: String) throws {
336
+ let selector = NSSelectorFromString("forgetWiFiProfileWithSSID:event:error:")
337
+ guard client.responds(to: selector) else { throw LocalMediaError("Mac Wi-Fi cannot forget networks") }
338
+ let invoke = unsafeBitCast(client.method(for: selector), to: MacWifiInvocation.Forget.self)
339
+ var error: NSError?
340
+ guard invoke(client, selector, NSData(data: Data(ssid.utf8)), 0, &error) else { throw Self.failure("forget", error) }
341
+ }
342
+
343
+ func setPower(_ on: Bool) throws {
344
+ let selector = NSSelectorFromString("setPower:error:")
345
+ guard interface.responds(to: selector) else { throw LocalMediaError("Mac Wi-Fi cannot change power") }
346
+ let invoke = unsafeBitCast(interface.method(for: selector), to: MacWifiInvocation.SetPower.self)
347
+ var error: NSError?
348
+ guard invoke(interface, selector, on, &error) else { throw Self.failure("power", error) }
349
+ }
350
+
223
351
  func disassociate() {
224
352
  let selector = NSSelectorFromString("disassociate")
225
353
  let invoke = unsafeBitCast(interface.method(for: selector), to: Disassociate.self)
@@ -2,11 +2,9 @@ import Darwin
2
2
  import Foundation
3
3
  import Network
4
4
  import NetworkExtension
5
- import OSLog
6
5
 
7
6
  /// Shared hotspot association owner. Only local glasses traffic uses Wi-Fi.
8
7
  public final class GlassesHotspotNetwork {
9
- private let logger = Logger(subsystem: "com.mentra.glassesmedia", category: "hotspot")
10
8
  private let queue = DispatchQueue(label: "com.mentra.glassesmedia.hotspot")
11
9
  private var ssid: String?
12
10
  private var lastHotspotSSID: String?
@@ -17,6 +15,11 @@ public final class GlassesHotspotNetwork {
17
15
  private var generation = 0
18
16
  private var applying = false
19
17
  private var ownsConfiguration = false
18
+ private var applies = 0
19
+ /// When the pending apply() started: iOS answers it only once the person answers its join prompt.
20
+ private var promptSince: TimeInterval?
21
+ private var joinDeadline: TimeInterval = 0
22
+ private let reapplyPolicy = HotspotReapplyPolicy()
20
23
  private var cancelled = false
21
24
  private var joinReply: ((Result<String, Error>) -> Void)?
22
25
  private var leaveCompletion: HotspotLeaveCompletion?
@@ -37,8 +40,22 @@ public final class GlassesHotspotNetwork {
37
40
  private var waitForInternetAfterLeave = false
38
41
  private let internetObservationOwner = HotspotInternetObservationOwner()
39
42
  public var onLost: ((String) -> Void)?
40
- public var onPermissionRequired: (() -> Void)?
41
- public init() {}
43
+ /// Gets the system's answer that left the join waiting for Local Network access.
44
+ public var onPermissionRequired: ((String) -> Void)?
45
+ public init() { _ = Self.startupCleanup }
46
+
47
+ /// iOS keeps every applied configuration and joins it again by itself whenever that hotspot is up.
48
+ /// A configuration left by a crash or a kill mid-session would let a phone near many pairs wander onto
49
+ /// one it is not using. This app's configurations are all glasses hotspots, so each join removes the
50
+ /// others, and this clears leftovers once per launch, unless a join already owns the network: that join clears them itself.
51
+ private static let startupCleanup: Void = {
52
+ guard !ProcessInfo.processInfo.isiOSAppOnMac else { return }
53
+ NEHotspotConfigurationManager.shared.getConfiguredSSIDs { saved in
54
+ guard !saved.isEmpty, let token = HotspotNetworkOwnership.shared.acquire() else { return }
55
+ saved.forEach { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: $0) }
56
+ HotspotNetworkOwnership.shared.release(token)
57
+ }
58
+ }()
42
59
 
43
60
  public func join(ssid: String, passphrase: String, gateway: String? = nil, purpose: HotspotAccessPurpose = .outgoingClient, completion: @escaping (Result<String, Error>) -> Void) {
44
61
  queue.async {
@@ -56,6 +73,8 @@ public final class GlassesHotspotNetwork {
56
73
  self.generation += 1
57
74
  let gen = self.generation
58
75
  let deadline = ProcessInfo.processInfo.systemUptime + 60
76
+ self.joinDeadline = deadline
77
+ self.promptSince = nil
59
78
  self.ssid = ssid
60
79
  self.lastHotspotSSID = ssid
61
80
  self.gatewayAddress = gateway
@@ -63,26 +82,47 @@ public final class GlassesHotspotNetwork {
63
82
  self.cancelled = false
64
83
  self.applying = false
65
84
  self.ownsConfiguration = false
85
+ self.applies = 0
66
86
  self.joinReply = completion
67
87
  self.startInterfaceMonitors(generation: gen)
68
88
  if ProcessInfo.processInfo.isiOSAppOnMac {
69
89
  self.authorizeMacAssociation(ssid: ssid, passphrase: passphrase, generation: gen, deadline: deadline)
70
90
  } else {
71
- self.applyConfiguration(ssid: ssid, passphrase: passphrase, generation: gen)
72
- }
73
- self.queue.asyncAfter(deadline: .now() + max(0, deadline - ProcessInfo.processInfo.systemUptime)) {
74
- // Once associated, the user may still be reading the Local Network alert.
75
- // Its response time is not a hotspot association timeout.
76
- guard gen == self.generation, self.joinReply != nil, self.localAccess == nil else { return }
77
- self.cancelled = true
78
- self.macAssociation?.cancel()
79
- self.macAuthorization?.cancelPending()
80
- self.finishJoin(.failure(LocalMediaError("Hotspot join timed out")))
81
- // apply() cannot be cancelled. Retain the reservation until its callback and remove the
82
- // late configuration before another call is permitted to acquire the network.
83
- if self.ownsConfiguration { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ssid) }
84
- if !self.applying { self.finishLeave() }
91
+ NEHotspotConfigurationManager.shared.getConfiguredSSIDs { saved in
92
+ self.queue.async {
93
+ // A cancelled join's late answer must not remove the next pair's configuration.
94
+ guard gen == self.generation, !self.cancelled else { return }
95
+ for other in saved where other != ssid { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: other) }
96
+ self.applyConfiguration(ssid: ssid, passphrase: passphrase, generation: gen)
97
+ }
98
+ }
85
99
  }
100
+ self.scheduleJoinDeadline(ssid: ssid, generation: gen)
101
+ }
102
+ }
103
+
104
+ /// Time to associate after the person answers a join prompt late in the join.
105
+ private static let afterAnswer: TimeInterval = 30
106
+
107
+ /// The join gets 60 s of its own, plus however long the person takes to answer iOS's join
108
+ /// prompt. The engine keeps the glasses AP up meanwhile.
109
+ private func scheduleJoinDeadline(ssid: String, generation gen: Int) {
110
+ queue.asyncAfter(deadline: .now() + max(1, joinDeadline - ProcessInfo.processInfo.systemUptime)) {
111
+ // Once associated, the user may still be reading the Local Network alert.
112
+ // Its response time is not a hotspot association timeout.
113
+ guard gen == self.generation, self.joinReply != nil, self.localAccess == nil else { return }
114
+ let now = ProcessInfo.processInfo.systemUptime
115
+ if self.promptSince != nil { self.joinDeadline = max(self.joinDeadline, now + 1) }
116
+ if now < self.joinDeadline { self.scheduleJoinDeadline(ssid: ssid, generation: gen); return }
117
+ MediaLog.log("HOTSPOT_JOIN timed_out prompt_pending=\(self.promptSince != nil)")
118
+ self.cancelled = true
119
+ self.macAssociation?.cancel()
120
+ self.macAuthorization?.cancelPending()
121
+ self.finishJoin(.failure(LocalMediaError("Hotspot join timed out")))
122
+ // apply() cannot be cancelled. Retain the reservation until its callback and remove the
123
+ // late configuration before another call is permitted to acquire the network.
124
+ if self.ownsConfiguration { NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ssid) }
125
+ if !self.applying { self.finishLeave() }
86
126
  }
87
127
  }
88
128
 
@@ -324,16 +364,24 @@ public final class GlassesHotspotNetwork {
324
364
  }
325
365
  }
326
366
 
327
- private func applyConfiguration(ssid: String, passphrase: String, generation gen: Int) {
367
+ private func applyConfiguration(ssid: String, passphrase: String, generation gen: Int, remaining: Int = 60) {
328
368
  let config = NEHotspotConfiguration(ssid: ssid, passphrase: passphrase, isWEP: false)
329
369
  config.joinOnce = false
330
370
  applying = true
331
371
  ownsConfiguration = true
332
- logger.info("HOTSPOT_JOIN apply_start ios_on_mac=\(ProcessInfo.processInfo.isiOSAppOnMac)")
372
+ applies += 1
373
+ promptSince = ProcessInfo.processInfo.systemUptime
374
+ MediaLog.log("HOTSPOT_JOIN apply_start attempt=\(self.applies) ios_on_mac=\(ProcessInfo.processInfo.isiOSAppOnMac)")
333
375
  NEHotspotConfigurationManager.shared.apply(config) { error in
334
376
  self.queue.async {
335
377
  guard gen == self.generation else { return }
336
378
  self.applying = false
379
+ if let asked = self.promptSince {
380
+ let now = ProcessInfo.processInfo.systemUptime
381
+ self.promptSince = nil
382
+ self.joinDeadline = max(self.joinDeadline, now + Self.afterAnswer)
383
+ MediaLog.log("HOTSPOT_JOIN apply_answered after_s=\(Int(now - asked))")
384
+ }
337
385
  if self.cancelled { self.finishLeave(); return }
338
386
  if let error {
339
387
  let nativeError = error as NSError
@@ -342,17 +390,17 @@ public final class GlassesHotspotNetwork {
342
390
  if !alreadyAssociated {
343
391
  // Error identifiers are useful without credentials or full userInfo.
344
392
  let underlying = nativeError.userInfo[NSUnderlyingErrorKey] as? NSError
345
- self.logger.error("HOTSPOT_JOIN apply_failed domain=\(nativeError.domain, privacy: .public) code=\(nativeError.code) underlying_domain=\(underlying?.domain ?? "none", privacy: .public) underlying_code=\(underlying.map { String($0.code) } ?? "none", privacy: .public)")
393
+ MediaLog.log("HOTSPOT_JOIN apply_failed domain=\(nativeError.domain) code=\(nativeError.code) underlying_domain=\(underlying?.domain ?? "none") underlying_code=\(underlying.map { String($0.code) } ?? "none")")
346
394
  self.finishJoin(.failure(error)); self.finishLeave(); return
347
395
  }
348
396
  }
349
- self.logger.info("HOTSPOT_JOIN apply_accepted")
350
- self.waitForAddress(ssid: ssid, generation: gen, remaining: 60)
397
+ MediaLog.log("HOTSPOT_JOIN apply_accepted")
398
+ self.waitForAddress(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining, pollsSinceApply: 0)
351
399
  }
352
400
  }
353
401
  }
354
402
 
355
- private func waitForAddress(ssid: String, generation gen: Int, remaining: Int) {
403
+ private func waitForAddress(ssid: String, passphrase: String, generation gen: Int, remaining: Int, pollsSinceApply: Int) {
356
404
  guard gen == generation, !cancelled else { return }
357
405
  NEHotspotNetwork.fetchCurrent { [weak self] network in
358
406
  self?.queue.async {
@@ -361,8 +409,15 @@ public final class GlassesHotspotNetwork {
361
409
  if network?.ssid == ssid, let selected = self.selectBinding() {
362
410
  self.bind(selected)
363
411
  self.finishAssociation(address: selected.address, generation: gen)
412
+ } else if remaining > 0, network?.ssid != ssid,
413
+ self.reapplyPolicy.shouldReapply(applies: self.applies, pollsSinceApply: pollsSinceApply) {
414
+ // iOS reports the request applied even when its one scan missed the hotspot.
415
+ MediaLog.log("HOTSPOT_JOIN reapply after_polls=\(pollsSinceApply)")
416
+ self.applyConfiguration(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining)
364
417
  } else if remaining > 0 {
365
- self.queue.asyncAfter(deadline: .now() + 0.5) { self.waitForAddress(ssid: ssid, generation: gen, remaining: remaining - 1) }
418
+ self.queue.asyncAfter(deadline: .now() + 0.5) {
419
+ self.waitForAddress(ssid: ssid, passphrase: passphrase, generation: gen, remaining: remaining - 1, pollsSinceApply: pollsSinceApply + 1)
420
+ }
366
421
  } else {
367
422
  let association = network == nil ? "unavailable" : (network?.ssid == ssid ? "matched" : "different")
368
423
  self.finishJoin(.failure(LocalMediaError("Glasses hotspot has no verified Wi-Fi address (SSID=\(association), \(self.wifiDiagnostic()))")))
@@ -420,7 +475,7 @@ public final class GlassesHotspotNetwork {
420
475
  let evidence = wifiIdentity.trusted[selected.interface] == selected.index ? "wifi_report" : "hotspot_client"
421
476
  wifiIdentity.adopt(selected)
422
477
  binding = selected
423
- logger.info("HOTSPOT_JOIN address_verified interface=\(selected.interface, privacy: .public) evidence=\(evidence, privacy: .public)")
478
+ MediaLog.log("HOTSPOT_JOIN address_verified interface=\(selected.interface) evidence=\(evidence)")
424
479
  }
425
480
 
426
481
  /// Interface names and their IPv4 addresses only; never credentials or SSIDs.
@@ -450,15 +505,15 @@ public final class GlassesHotspotNetwork {
450
505
  let gateway = gatewayAddress ?? address.split(separator: ".").prefix(3).joined(separator: ".") + ".1"
451
506
  let request = LocalNetworkAccessRequest(localAddress: address, gateway: gateway, queue: queue)
452
507
  localAccess = request
453
- request.start(onPermissionRequired: { [weak self] in
508
+ request.start(onPermissionRequired: { [weak self] systemAnswer in
454
509
  guard let self, gen == generation, !cancelled else { return }
455
- NSLog("GLASSES-MEDIA local_network_permission=waiting")
456
- onPermissionRequired?()
510
+ MediaLog.log("GLASSES-MEDIA local_network_permission=waiting \(systemAnswer)")
511
+ onPermissionRequired?(systemAnswer)
457
512
  }) { [weak self] result in
458
513
  guard let self, gen == generation, !cancelled else { return }
459
514
  switch result {
460
515
  case .success:
461
- NSLog("GLASSES-MEDIA local_network_permission=ready")
516
+ MediaLog.log("GLASSES-MEDIA local_network_permission=ready")
462
517
  finishJoin(.success(address))
463
518
  case let .failure(error):
464
519
  finishJoin(.failure(error))
@@ -480,12 +535,14 @@ public final class GlassesHotspotNetwork {
480
535
  if let association = macAssociation {
481
536
  association.cancel()
482
537
  // This queue is also the association queue: cleanup cannot overtake
483
- // a blocking scan/join, and process-wide ownership remains held.
538
+ // a blocking scan/join, and process-wide ownership remains held, including
539
+ // while leave() forgets the hotspot and returns the Mac to its previous Wi-Fi.
484
540
  macWorker.async {
485
541
  let result = Result { try association.leave() }
486
542
  self.queue.async {
487
543
  switch result {
488
- case .success:
544
+ case let .success(report):
545
+ if report.restore != .notNeeded { MediaLog.log("HOTSPOT_LEAVE mac_wifi \(report.summary)") }
489
546
  self.macAssociation = nil
490
547
  self.completeLeave()
491
548
  case let .failure(error):
@@ -531,7 +588,7 @@ public final class GlassesHotspotNetwork {
531
588
  // bounded observation ends. Route readiness is not HTTP success;
532
589
  // the following ordinary update check still owns that result.
533
590
  startInternetObservation(allowWifiAfterRelease: true) { ready, reason in
534
- self.logger.info("HOTSPOT_LEAVE internet_recovery ready=\(ready) reason=\(reason, privacy: .public)")
591
+ MediaLog.log("HOTSPOT_LEAVE internet_recovery ready=\(ready) reason=\(reason)")
535
592
  finish()
536
593
  }
537
594
  } else { finish() }
@@ -1,5 +1,8 @@
1
1
  import ExpoModulesCore
2
2
  import Foundation
3
+ import OSLog
4
+
5
+ private let permissionLog = Logger(subsystem: "com.mentra.mentra", category: "Permission")
3
6
 
4
7
  public final class GlassesMediaRelayModule: Module {
5
8
  private let queue = DispatchQueue(label: "com.mentra.glassesmedia.relay")
@@ -9,7 +12,16 @@ public final class GlassesMediaRelayModule: Module {
9
12
 
10
13
  public func definition() -> ModuleDefinition {
11
14
  Name("MentraGlassesMediaRelay")
12
- Events("onRelayState")
15
+ Events("onRelayState", "onLocalHotspotPermissionRequired", "onNativeLog")
16
+
17
+ OnCreate {
18
+ MediaLog.sink = { [weak self] message in self?.sendEvent("onNativeLog", ["message": message]) }
19
+ }
20
+
21
+ // The app's `[Permission]` lines, readable in the unified log: NSLog and the JS console are not.
22
+ Function("logPermission") { (line: String) in
23
+ permissionLog.notice("\(line, privacy: .public)")
24
+ }
13
25
 
14
26
  AsyncFunction("joinLocalHotspot") { (id: String, ssid: String, password: String, gateway: String?, purpose: String, promise: Promise) in
15
27
  self.queue.async {
@@ -20,6 +32,10 @@ public final class GlassesMediaRelayModule: Module {
20
32
  promise.reject(LocalMediaError("Invalid hotspot access purpose")); return
21
33
  }
22
34
  self.localHotspotOwner = id
35
+ // The join waits while Local Network access is pending or denied; the caller explains it.
36
+ self.localHotspot.onPermissionRequired = { [weak self] systemAnswer in
37
+ self?.sendEvent("onLocalHotspotPermissionRequired", ["id": id, "systemAnswer": systemAnswer])
38
+ }
23
39
  self.localHotspot.join(ssid: ssid, passphrase: password, gateway: gateway, purpose: accessPurpose) { result in
24
40
  switch result {
25
41
  case let .success(address): promise.resolve(address)
@@ -88,6 +104,7 @@ public final class GlassesMediaRelayModule: Module {
88
104
  }
89
105
 
90
106
  OnDestroy {
107
+ MediaLog.sink = nil
91
108
  self.queue.async {
92
109
  self.session?.stop { result in
93
110
  if case .success = result { self.session = nil }
@@ -119,7 +136,7 @@ private final class ManagedRelaySession {
119
136
  {
120
137
  ready = completion
121
138
  hotspot.onLost = { reason in onState("failed", reason) }
122
- hotspot.onPermissionRequired = { [weak self] in
139
+ hotspot.onPermissionRequired = { [weak self] _ in
123
140
  self?.queue.async {
124
141
  guard let self, !self.stopped else { return }
125
142
  onState("permission_required", "Allow Local Network access to connect to your glasses. If you previously denied access, enable it in Settings, or cancel to return home.")
@@ -90,7 +90,7 @@ public final class LocalWhipIngestSource: NSObject, DecodedGlassesMediaSource {
90
90
  }
91
91
  self.forceCloseIngestLocked()
92
92
  let closed = self.awaitIngestClosedLocked(timeoutMs: timeoutMs)
93
- NSLog("SOFTAP_TRACE stage=ingest_rebind oldUrl=\(oldUrl ?? "none") newUrl=\(newUrl) closed=\(closed)")
93
+ MediaLog.log("SOFTAP_TRACE stage=ingest_rebind oldUrl=\(oldUrl ?? "none") newUrl=\(newUrl) closed=\(closed)")
94
94
  if !closed {
95
95
  completion(.failure(LocalMediaError("SoftAP ingest rebind did not release the old listener")))
96
96
  return
@@ -350,7 +350,7 @@ public final class LocalWhipIngestSource: NSObject, DecodedGlassesMediaSource {
350
350
  private func transition(_ state: SourceState, _ reason: String) {
351
351
  guard currentState != state else { return }
352
352
  currentState = state
353
- NSLog("GLASSES-MEDIA source=\(state.rawValue) reason=\(reason)")
353
+ MediaLog.log("GLASSES-MEDIA source=\(state.rawValue) reason=\(reason)")
354
354
  onStateChange?(state, reason)
355
355
  }
356
356
  }
@@ -0,0 +1,13 @@
1
+ import Foundation
2
+
3
+ /// The console plus the app's JavaScript console, which bug reports upload. glasses-media and
4
+ /// acs-meeting log through it, so the hotspot, relay, ingest and ACS traces reach a report.
5
+ public enum MediaLog {
6
+ /// Set by `GlassesMediaRelayModule` while it exists.
7
+ public static var sink: ((String) -> Void)?
8
+
9
+ public static func log(_ message: String) {
10
+ NSLog("%@", message)
11
+ sink?(message)
12
+ }
13
+ }
@@ -103,7 +103,7 @@ public final class WhepVideoSource: NSObject, DecodedGlassesMediaSource {
103
103
  /// networks; ICE may not have noticed the dead candidate pair yet).
104
104
  public func forceRestart() {
105
105
  guard let url = currentUrl else { return }
106
- NSLog("ACS-SPIKE WHEP forced rebuild state=\(state.rawValue)")
106
+ MediaLog.log("ACS-SPIKE WHEP forced rebuild state=\(state.rawValue)")
107
107
  start(whepUrl: url)
108
108
  }
109
109
 
@@ -118,7 +118,7 @@ public final class WhepVideoSource: NSObject, DecodedGlassesMediaSource {
118
118
  public func setPcmEnabled(_ enabled: Bool) {
119
119
  pcmEnabled = enabled
120
120
  audioTracks.forEach { $0.isEnabled = enabled }
121
- NSLog("ACS-SPIKE WHEP audio track enabled=\(enabled)")
121
+ MediaLog.log("ACS-SPIKE WHEP audio track enabled=\(enabled)")
122
122
  }
123
123
 
124
124
  public func stop() {
@@ -149,7 +149,7 @@ public final class WhepVideoSource: NSObject, DecodedGlassesMediaSource {
149
149
  let previous = state
150
150
  state = next
151
151
  guard previous != next else { return }
152
- NSLog("ACS-SPIKE WHEP source \(previous.rawValue) -> \(next.rawValue) (\(reason))")
152
+ MediaLog.log("ACS-SPIKE WHEP source \(previous.rawValue) -> \(next.rawValue) (\(reason))")
153
153
  onStateChange?(next, reason)
154
154
  }
155
155
 
@@ -193,11 +193,11 @@ public final class WhepVideoSource: NSObject, DecodedGlassesMediaSource {
193
193
  http.dataTask(with: request) { [weak self] data, response, error in
194
194
  guard let self, self.generation == gen else { return }
195
195
  let code = (response as? HTTPURLResponse)?.statusCode ?? -1
196
- NSLog("ACS-SPIKE P3 WHEP \(code) answer bytes=\(data?.count ?? 0)")
196
+ MediaLog.log("ACS-SPIKE P3 WHEP \(code) answer bytes=\(data?.count ?? 0)")
197
197
  guard error == nil, (200 ..< 300).contains(code),
198
198
  let data, let answer = String(data: data, encoding: .utf8)
199
199
  else {
200
- NSLog("ACS-SPIKE WHEP answer rejected code=\(code) error=\(error?.localizedDescription ?? "none")")
200
+ MediaLog.log("ACS-SPIKE WHEP answer rejected code=\(code) error=\(error?.localizedDescription ?? "none")")
201
201
  self.transition(.failed, reason: error != nil ? "whep_post_failed" : "whep_http_\(code)")
202
202
  return
203
203
  }
@@ -221,7 +221,7 @@ public final class WhepVideoSource: NSObject, DecodedGlassesMediaSource {
221
221
  guard let self else { return }
222
222
  self.firstFrameDeadline = nil
223
223
  guard self.generation == gen, self.firstFrameGeneration == gen, !self.firstFramePromoted else { return }
224
- NSLog("ACS-SPIKE WHEP answered but delivered no frame in \(Self.firstFrameTimeout)s")
224
+ MediaLog.log("ACS-SPIKE WHEP answered but delivered no frame in \(Self.firstFrameTimeout)s")
225
225
  self.transition(.failed, reason: "no_first_frame")
226
226
  }
227
227
  firstFrameDeadline = work
@@ -261,7 +261,7 @@ extension WhepVideoSource: RTCPeerConnectionDelegate {
261
261
  public func peerConnection(_: RTCPeerConnection, didRemove _: RTCMediaStream) {}
262
262
  public func peerConnectionShouldNegotiate(_: RTCPeerConnection) {}
263
263
  public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
264
- NSLog("ACS-SPIKE ICE \(newState.rawValue)")
264
+ MediaLog.log("ACS-SPIKE ICE \(newState.rawValue)")
265
265
  guard isCurrent(peerConnection) else { return }
266
266
  if newState == .failed || newState == .disconnected {
267
267
  transition(.failed, reason: newState == .failed ? "ice_failed" : "ice_disconnected")
@@ -305,7 +305,7 @@ extension WhepVideoSource: RTCVideoRenderer {
305
305
  frameCount += 1
306
306
  let now = Date()
307
307
  if now.timeIntervalSince(lastFpsLog) >= 1 {
308
- NSLog("ACS-SPIKE P3 video \(Int(frame.width))x\(Int(frame.height)) fps=\(frameCount)")
308
+ MediaLog.log("ACS-SPIKE P3 video \(Int(frame.width))x\(Int(frame.height)) fps=\(frameCount)")
309
309
  frameCount = 0
310
310
  lastFpsLog = now
311
311
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/glasses-media",
3
- "version": "3.4.0-dev.999",
3
+ "version": "3.4.0",
4
4
  "description": "Shared native glasses media receivers and local network transport",
5
5
  "license": "MIT",
6
6
  "author": "Mentra Community",
@@ -15,6 +15,9 @@
15
15
  "publishConfig": {
16
16
  "access": "public"
17
17
  },
18
+ "dependencies": {
19
+ "@mentra/bluetooth-sdk": "3.4.0"
20
+ },
18
21
  "peerDependencies": {
19
22
  "expo-modules-core": "~55.0.25"
20
23
  },