|
| 1 | +// LoopFollow |
| 2 | +// WatchConnectivityManager.swift |
| 3 | + |
| 4 | +import Foundation |
| 5 | +import WatchConnectivity |
| 6 | + |
| 7 | +final class WatchConnectivityManager: NSObject { |
| 8 | + // MARK: - Shared Instance |
| 9 | + |
| 10 | + static let shared = WatchConnectivityManager() |
| 11 | + |
| 12 | + // MARK: - Init |
| 13 | + |
| 14 | + /// Serial queue protecting mutable state (the last-ack timestamp) from |
| 15 | + /// concurrent access: `send(snapshot:)` may be called from any thread, and |
| 16 | + /// WCSession delegate callbacks arrive on an arbitrary background queue. |
| 17 | + private let stateQueue = DispatchQueue(label: "com.loopfollow.WatchConnectivityManager.state") |
| 18 | + |
| 19 | + /// Backing storage for `lastWatchAckTimestamp`. Always access via the |
| 20 | + /// thread-safe accessor below. |
| 21 | + private var _lastWatchAckTimestamp: TimeInterval = 0 |
| 22 | + |
| 23 | + /// Timestamp of the last snapshot the Watch ACK'd. Read/write is serialized |
| 24 | + /// through `stateQueue`. |
| 25 | + private var lastWatchAckTimestamp: TimeInterval { |
| 26 | + get { stateQueue.sync { _lastWatchAckTimestamp } } |
| 27 | + set { stateQueue.sync { _lastWatchAckTimestamp = newValue } } |
| 28 | + } |
| 29 | + |
| 30 | + override private init() { |
| 31 | + super.init() |
| 32 | + } |
| 33 | + |
| 34 | + // MARK: - Setup |
| 35 | + |
| 36 | + /// Call once from AppDelegate after app launch. |
| 37 | + func activate() { |
| 38 | + guard WCSession.isSupported() else { |
| 39 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: WCSession not supported on this device") |
| 40 | + return |
| 41 | + } |
| 42 | + WCSession.default.delegate = self |
| 43 | + WCSession.default.activate() |
| 44 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: WCSession activation requested") |
| 45 | + } |
| 46 | + |
| 47 | + // MARK: - Send Snapshot |
| 48 | + |
| 49 | + /// Sends the latest GlucoseSnapshot to the Watch via transferUserInfo. |
| 50 | + /// Safe to call from any thread. |
| 51 | + /// No-ops silently if Watch is not paired or reachable. |
| 52 | + func send(snapshot: GlucoseSnapshot) { |
| 53 | + guard WCSession.isSupported() else { return } |
| 54 | + |
| 55 | + let session = WCSession.default |
| 56 | + |
| 57 | + guard session.activationState == .activated else { |
| 58 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: session not activated, skipping send") |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + guard session.isPaired else { |
| 63 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: no paired Watch, skipping send") |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + do { |
| 68 | + // GlucoseSnapshot has a custom encoder that writes updatedAt as a |
| 69 | + // Double (timeIntervalSince1970), so no date strategy needs to be set. |
| 70 | + let encoder = JSONEncoder() |
| 71 | + let data = try encoder.encode(snapshot) |
| 72 | + let payload: [String: Any] = ["snapshot": data] |
| 73 | + |
| 74 | + // Warn if Watch hasn't ACK'd this or a recent snapshot. |
| 75 | + let behindBy = snapshot.updatedAt.timeIntervalSince1970 - lastWatchAckTimestamp |
| 76 | + if lastWatchAckTimestamp > 0, behindBy > 600 { |
| 77 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: Watch ACK is \(Int(behindBy))s behind — Watch may be missing deliveries") |
| 78 | + } |
| 79 | + |
| 80 | + // sendMessage: immediate delivery when Watch app is in foreground. |
| 81 | + if session.isReachable { |
| 82 | + session.sendMessage(payload, replyHandler: nil, errorHandler: nil) |
| 83 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: snapshot sent via sendMessage (reachable)") |
| 84 | + } |
| 85 | + |
| 86 | + // Cancel outstanding transfers before queuing — only the latest snapshot matters. |
| 87 | + // session.outstandingUserInfoTransfers.forEach { $0.cancel() } |
| 88 | + |
| 89 | + // transferUserInfo: guaranteed queued delivery for background wakes. |
| 90 | + session.transferUserInfo(payload) |
| 91 | + |
| 92 | + // applicationContext: latest-state mirror for next launch / scheduled refresh. |
| 93 | + do { |
| 94 | + try session.updateApplicationContext(payload) |
| 95 | + } catch { |
| 96 | + LogManager.shared.log( |
| 97 | + category: .watch, |
| 98 | + message: "WatchConnectivityManager: failed to update applicationContext — \(error)" |
| 99 | + ) |
| 100 | + } |
| 101 | + |
| 102 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: snapshot queued via transferUserInfo") |
| 103 | + } catch { |
| 104 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: failed to encode snapshot — \(error)") |
| 105 | + } |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +// MARK: - WCSessionDelegate |
| 110 | + |
| 111 | +extension WatchConnectivityManager: WCSessionDelegate { |
| 112 | + func session( |
| 113 | + _: WCSession, |
| 114 | + activationDidCompleteWith activationState: WCSessionActivationState, |
| 115 | + error: Error? |
| 116 | + ) { |
| 117 | + if let error = error { |
| 118 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: activation failed — \(error)") |
| 119 | + } else { |
| 120 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: activation complete — state \(activationState.rawValue)") |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + /// When the Watch app comes to the foreground, send the latest snapshot immediately |
| 125 | + /// so the Watch app has fresh data without waiting for the next BG poll. |
| 126 | + /// Receives ACKs from the Watch (sent after each snapshot is saved). |
| 127 | + func session(_: WCSession, didReceiveMessage message: [String: Any]) { |
| 128 | + if let ackTimestamp = message["watchAck"] as? TimeInterval { |
| 129 | + lastWatchAckTimestamp = ackTimestamp |
| 130 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: Watch ACK received for snapshot at \(ackTimestamp)") |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any]) { |
| 135 | + if let ackTimestamp = userInfo["watchAck"] as? TimeInterval { |
| 136 | + lastWatchAckTimestamp = ackTimestamp |
| 137 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: Watch ACK (userInfo) received for snapshot at \(ackTimestamp)") |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + func sessionReachabilityDidChange(_ session: WCSession) { |
| 142 | + guard session.isReachable else { return } |
| 143 | + if let snapshot = GlucoseSnapshotStore.shared.load() { |
| 144 | + send(snapshot: snapshot) |
| 145 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: Watch became reachable — snapshot pushed") |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + func sessionDidBecomeInactive(_: WCSession) { |
| 150 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: session became inactive") |
| 151 | + } |
| 152 | + |
| 153 | + func sessionDidDeactivate(_: WCSession) { |
| 154 | + LogManager.shared.log(category: .watch, message: "WatchConnectivityManager: session deactivated — reactivating") |
| 155 | + WCSession.default.activate() |
| 156 | + } |
| 157 | +} |
0 commit comments