Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / apple / FindFamily / FindFamilyiOS / UWB / RangingSession.swift

RangingSession.swift416 lines · 15.8 KiBRaw
1import Foundation
2import Combine
3import NearbyInteraction
4import simd
5import UIKit
6
7/// SwiftUI-friendly wrapper around `NISession`.
8///
9/// Owns a single ranging session at a time:
10/// - `start(peer:)` performs the platform-appropriate handshake (currently
11/// iOS↔iOS only; cross-platform comes in Phase 5) and begins ranging.
12/// - `invalidate()` tears down the session and sends a `cancel` envelope so
13/// the peer's UI exits too.
14///
15/// `@MainActor` because all SwiftUI bindings are read on the main thread and
16/// `NISession` callbacks are scheduled on whatever queue is set on the delegate
17/// (we set `.main`).
18@MainActor
19final class RangingSession: NSObject, ObservableObject, NISessionDelegate {
20
21 enum Phase: Equatable {
22 case idle
23 case starting
24 case waitingForPeer
25 case ranging
26 case peerLost
27 case unsupported(String)
28 case failed(String)
29 }
30
31 @Published private(set) var phase: Phase = .idle
32 /// Live distance in meters (nil when not yet measured or peer is out of range).
33 @Published private(set) var distance: Float?
34 /// Unit vector pointing toward the peer in the device's reference frame
35 /// (nil when direction info isn't available — happens when peer is outside
36 /// the device's narrow forward field-of-view).
37 @Published private(set) var direction: simd_float3?
38
39 private var session: NISession?
40 private var peer: User?
41 private var currentSessionId: String?
42 private var inboxSub: AnyCancellable?
43 private var timeoutTask: Task<Void, Never>?
44 private let pingHaptic = UIImpactFeedbackGenerator(style: .light)
45 private var lastHapticBucket: Int = -1
46
47 deinit {
48 // Synchronous deinit; the session is already invalidated by SwiftUI's
49 // .onDisappear normally — this is a defensive cleanup.
50 session?.invalidate()
51 }
52
53 func start(peer: User) {
54 guard phase == .idle else { return }
55 self.peer = peer
56 self.currentSessionId = UUID().uuidString
57 self.phase = .starting
58
59 // Hardware capability check.
60 guard NISession.deviceCapabilities.supportsPreciseDistanceMeasurement else {
61 phase = .unsupported("This device does not support Ultra-Wideband ranging.")
62 return
63 }
64
65 let s = NISession()
66 s.delegate = self
67 s.delegateQueue = .main
68 self.session = s
69
70 // Cross-platform (peer.platform == "android"): iOS acts as the
71 // controller via NINearbyAccessoryConfiguration. The Android peer is
72 // the "accessory" and will respond with an accessory-data blob on a
73 // separate `config` envelope (see UwbAccessoryProtocol.swift).
74 if peer.platform == "android" {
75 beginCrossPlatformAsController(peer: peer)
76 return
77 }
78
79 // Subscribe to incoming envelopes so we hear the peer's reply.
80 inboxSub = UwbInbox.shared.publisher
81 .receive(on: DispatchQueue.main)
82 .sink { [weak self] envelope in
83 self?.handleIncoming(envelope)
84 }
85
86 // Send our discovery token to the peer.
87 guard let myToken = s.discoveryToken else {
88 phase = .failed("Could not generate UWB token.")
89 return
90 }
91 guard let archived = try? NSKeyedArchiver.archivedData(
92 withRootObject: myToken, requiringSecureCoding: true
93 ) else {
94 phase = .failed("Could not encode UWB token.")
95 return
96 }
97
98 let envelope = UwbEnvelope(
99 sessionId: currentSessionId!,
100 sender: UInt64(bitPattern: Networking.shared.userid),
101 senderPlatform: Networking.platformTag,
102 kind: UwbEnvelopeKind.request,
103 payload: UwbHandshake(discoveryTokenB64: archived.base64EncodedString())
104 )
105 phase = .waitingForPeer
106 scheduleTimeout()
107 Task { [weak self] in
108 guard let self = self else { return }
109 let ok = await Networking.shared.publishUwbMessage(envelope, to: peer.id)
110 if !ok {
111 self.phase = .failed("Could not reach peer.")
112 self.invalidateLocal()
113 }
114 }
115 }
116
117 /// Responder-side entry. Called when the screen is opened via a notification tap.
118 func accept(request: UwbEnvelope, peer: User) {
119 guard phase == .idle else { return }
120 self.peer = peer
121 self.currentSessionId = request.sessionId
122 self.phase = .starting
123
124 guard NISession.deviceCapabilities.supportsPreciseDistanceMeasurement else {
125 phase = .unsupported("This device does not support Ultra-Wideband ranging.")
126 return
127 }
128
129 // Cross-platform: Android initiator pre-packaged its accessoryData in
130 // the REQUEST payload. Run NINearbyAccessoryConfiguration directly.
131 if request.senderPlatform == "android",
132 let payload = request.payload,
133 let accessoryDataB64 = payload.accessoryConfigDataB64,
134 let accessoryData = Data(base64Encoded: accessoryDataB64) {
135 let s = NISession()
136 s.delegate = self
137 s.delegateQueue = .main
138 self.session = s
139 inboxSub = UwbInbox.shared.publisher
140 .receive(on: DispatchQueue.main)
141 .sink { [weak self] envelope in self?.handleIncoming(envelope) }
142 do {
143 let config = try NINearbyAccessoryConfiguration(
144 accessoryData: accessoryData,
145 bluetoothPeerIdentifier: UUID()
146 )
147 s.run(config)
148 phase = .ranging
149 } catch {
150 phase = .failed("Could not start accessory session: \(error.localizedDescription)")
151 invalidateLocal()
152 }
153 return
154 }
155
156 // Same-platform iOS↔iOS: peer's NIDiscoveryToken is in the payload.
157 guard let payload = request.payload,
158 let tokenB64 = payload.discoveryTokenB64,
159 let tokenData = Data(base64Encoded: tokenB64),
160 let peerToken = try? NSKeyedUnarchiver.unarchivedObject(
161 ofClass: NIDiscoveryToken.self, from: tokenData
162 ) else {
163 phase = .failed("Invalid peer token.")
164 return
165 }
166
167 let s = NISession()
168 s.delegate = self
169 s.delegateQueue = .main
170 self.session = s
171
172 // Send our discovery token back as the ack.
173 guard let myToken = s.discoveryToken,
174 let archived = try? NSKeyedArchiver.archivedData(
175 withRootObject: myToken, requiringSecureCoding: true
176 ) else {
177 phase = .failed("Could not encode local UWB token.")
178 return
179 }
180 let ack = UwbEnvelope(
181 sessionId: request.sessionId,
182 sender: UInt64(bitPattern: Networking.shared.userid),
183 senderPlatform: Networking.platformTag,
184 kind: UwbEnvelopeKind.ack,
185 payload: UwbHandshake(discoveryTokenB64: archived.base64EncodedString())
186 )
187 Task { [weak self] in
188 guard let self = self else { return }
189 let ok = await Networking.shared.publishUwbMessage(ack, to: peer.id)
190 if !ok {
191 self.phase = .failed("Could not reach peer.")
192 self.invalidateLocal()
193 return
194 }
195 // Start ranging immediately with the peer's token from the request.
196 let config = NINearbyPeerConfiguration(peerToken: peerToken)
197 s.run(config)
198 self.phase = .ranging
199 }
200 }
201
202 func invalidate() {
203 // Notify the peer so their UI can exit too.
204 if let sid = currentSessionId, let p = peer {
205 let env = UwbEnvelope(
206 sessionId: sid,
207 sender: UInt64(bitPattern: Networking.shared.userid),
208 senderPlatform: Networking.platformTag,
209 kind: UwbEnvelopeKind.cancel,
210 payload: nil
211 )
212 Task { await Networking.shared.publishUwbMessage(env, to: p.id) }
213 }
214 invalidateLocal()
215 }
216
217 private func invalidateLocal() {
218 timeoutTask?.cancel(); timeoutTask = nil
219 inboxSub?.cancel(); inboxSub = nil
220 session?.invalidate(); session = nil
221 currentSessionId = nil
222 peer = nil
223 distance = nil
224 direction = nil
225 phase = .idle
226 lastHapticBucket = -1
227 }
228
229 private func scheduleTimeout() {
230 timeoutTask?.cancel()
231 timeoutTask = Task { [weak self] in
232 try? await Task.sleep(nanoseconds: 60 * 1_000_000_000)
233 guard let self = self else { return }
234 if self.phase == .waitingForPeer {
235 self.phase = .failed("Peer did not respond.")
236 self.invalidateLocal()
237 }
238 }
239 }
240
241 private func handleIncoming(_ envelope: UwbEnvelope) {
242 guard envelope.sessionId == currentSessionId else { return }
243 switch envelope.kind {
244 case UwbEnvelopeKind.ack:
245 startRangingWithAck(envelope)
246 case UwbEnvelopeKind.config:
247 handleCrossPlatformConfig(envelope)
248 case UwbEnvelopeKind.cancel:
249 invalidateLocal()
250 default:
251 break
252 }
253 }
254
255 // MARK: - Cross-platform (Android ↔ iOS) accessory-protocol path
256 //
257 // Apple's "UWB Specification for Third-Party Accessories" defines a small
258 // back-and-forth: the accessory (Android) sends a binary capability blob
259 // ("accessory configuration data"); iOS feeds it into
260 // `NINearbyAccessoryConfiguration(accessoryData:)`, runs the session, and
261 // receives a "shareableConfigurationData" blob via the delegate, which we
262 // return to the accessory so it can configure its own UWB. Transport is
263 // the same encrypted /api/uwb/* channel as same-platform.
264
265 private func beginCrossPlatformAsController(peer: User) {
266 inboxSub = UwbInbox.shared.publisher
267 .receive(on: DispatchQueue.main)
268 .sink { [weak self] envelope in self?.handleIncoming(envelope) }
269
270 // Send REQUEST with no payload. Android responds with a CONFIG envelope
271 // carrying its accessoryConfigDataB64.
272 let envelope = UwbEnvelope(
273 sessionId: currentSessionId!,
274 sender: UInt64(bitPattern: Networking.shared.userid),
275 senderPlatform: Networking.platformTag,
276 kind: UwbEnvelopeKind.request,
277 payload: nil
278 )
279 phase = .waitingForPeer
280 scheduleTimeout()
281 Task { [weak self] in
282 guard let self = self else { return }
283 let ok = await Networking.shared.publishUwbMessage(envelope, to: peer.id)
284 if !ok {
285 self.phase = .failed("Could not reach peer.")
286 self.invalidateLocal()
287 }
288 }
289 }
290
291 private func handleCrossPlatformConfig(_ envelope: UwbEnvelope) {
292 guard let s = session else { return }
293 guard let payload = envelope.payload,
294 let accessoryDataB64 = payload.accessoryConfigDataB64,
295 let accessoryData = Data(base64Encoded: accessoryDataB64) else {
296 phase = .failed("Invalid accessory data from peer.")
297 invalidateLocal()
298 return
299 }
300 timeoutTask?.cancel(); timeoutTask = nil
301 do {
302 // NINearbyAccessoryConfiguration parses Apple's standard accessory-data format.
303 // bluetoothPeerIdentifier is required by Apple's API since it was designed
304 // around a paired BLE peripheral. We pass a dummy UUID because our handshake
305 // travels over the existing server channel instead of BLE. NISession may still
306 // attempt to use BLE for parts of the protocol; if so, a true cross-platform
307 // implementation would need the peer's actual CB peripheral identifier.
308 let config = try NINearbyAccessoryConfiguration(
309 accessoryData: accessoryData,
310 bluetoothPeerIdentifier: UUID()
311 )
312 s.run(config)
313 phase = .ranging
314 // The framework will call `session(_:didGenerateShareableConfigurationData:for:)`
315 // shortly afterward so we can ship the resulting blob to the accessory.
316 } catch {
317 phase = .failed("Could not start accessory session: \(error.localizedDescription)")
318 invalidateLocal()
319 }
320 }
321
322 nonisolated func session(
323 _ session: NISession,
324 didGenerateShareableConfigurationData shareableConfigurationData: Data,
325 for object: NINearbyObject
326 ) {
327 let b64 = shareableConfigurationData.base64EncodedString()
328 Task { @MainActor in
329 guard let sid = self.currentSessionId, let peer = self.peer else { return }
330 let env = UwbEnvelope(
331 sessionId: sid,
332 sender: UInt64(bitPattern: Networking.shared.userid),
333 senderPlatform: Networking.platformTag,
334 kind: UwbEnvelopeKind.config,
335 payload: UwbHandshake(shareableConfigDataB64: b64)
336 )
337 _ = await Networking.shared.publishUwbMessage(env, to: peer.id)
338 }
339 }
340
341 private func startRangingWithAck(_ envelope: UwbEnvelope) {
342 guard let s = session else { return }
343 guard let payload = envelope.payload,
344 let tokenB64 = payload.discoveryTokenB64,
345 let tokenData = Data(base64Encoded: tokenB64),
346 let peerToken = try? NSKeyedUnarchiver.unarchivedObject(
347 ofClass: NIDiscoveryToken.self, from: tokenData
348 ) else {
349 phase = .failed("Invalid peer ack.")
350 invalidateLocal()
351 return
352 }
353 timeoutTask?.cancel(); timeoutTask = nil
354 let config = NINearbyPeerConfiguration(peerToken: peerToken)
355 s.run(config)
356 phase = .ranging
357 }
358
359 /// Light haptic ping every time the distance crosses into a smaller meter
360 /// bucket (≤5 m), and a stronger pulse below 0.5 m.
361 private func maybeHaptic() {
362 guard let d = distance else { return }
363 let bucket: Int
364 if d < 0.5 { bucket = 0 }
365 else if d < 1 { bucket = 1 }
366 else if d < 5 { bucket = Int(d) + 1 } // 2,3,4,5
367 else { bucket = 99 }
368 if bucket < lastHapticBucket {
369 pingHaptic.impactOccurred(intensity: d < 0.5 ? 1.0 : 0.4)
370 }
371 lastHapticBucket = bucket
372 }
373
374 // MARK: - NISessionDelegate
375
376 nonisolated func session(_ session: NISession, didUpdate nearbyObjects: [NINearbyObject]) {
377 Task { @MainActor in
378 guard let obj = nearbyObjects.first else { return }
379 self.distance = obj.distance
380 self.direction = obj.direction
381 self.maybeHaptic()
382 }
383 }
384
385 nonisolated func session(
386 _ session: NISession,
387 didRemove nearbyObjects: [NINearbyObject],
388 reason: NINearbyObject.RemovalReason
389 ) {
390 Task { @MainActor in
391 self.distance = nil
392 self.direction = nil
393 self.phase = .peerLost
394 }
395 }
396
397 nonisolated func sessionWasSuspended(_ session: NISession) {}
398 nonisolated func sessionSuspensionEnded(_ session: NISession) {}
399
400 nonisolated func session(_ session: NISession, didInvalidateWith error: Error) {
401 Task { @MainActor in
402 if let niError = error as? NIError {
403 switch niError.code {
404 case .userDidNotAllow:
405 self.phase = .unsupported("Precision Finding permission was denied.")
406 case .invalidConfiguration:
407 self.phase = .failed("Invalid ranging configuration.")
408 default:
409 self.phase = .failed(niError.localizedDescription)
410 }
411 } else {
412 self.phase = .failed(error.localizedDescription)
413 }
414 }
415 }
416}