WatchState.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import Foundation
  2. import SwiftUI
  3. import WatchConnectivity
  4. /// WatchState manages the communication between the Watch app and the iPhone app using WatchConnectivity.
  5. /// It handles glucose data synchronization and sending treatment requests (bolus, carbs) to the phone.
  6. @Observable final class WatchState: NSObject, WCSessionDelegate {
  7. // MARK: - Properties
  8. /// The WatchConnectivity session instance used for communication
  9. var session: WCSession?
  10. /// Indicates if the paired iPhone is currently reachable
  11. var isReachable = false
  12. var lastWatchStateUpdate: TimeInterval?
  13. /// main view relevant metrics
  14. var currentGlucose: String = "--"
  15. var currentGlucoseColorString: String = "#ffffff"
  16. var trend: String? = ""
  17. var delta: String? = "--"
  18. var glucoseValues: [(date: Date, glucose: Double, color: Color)] = []
  19. var cob: String? = "--"
  20. var iob: String? = "--"
  21. var lastLoopTime: String? = "--"
  22. var overridePresets: [OverridePresetWatch] = []
  23. var tempTargetPresets: [TempTargetPresetWatch] = []
  24. /// treatments inputs
  25. /// used to store carbs for combined meal-bolus-treatments
  26. var carbsAmount: Int = 0
  27. var fatAmount: Int = 0
  28. var proteinAmount: Int = 0
  29. var bolusAmount = 0.0
  30. var activeBolusAmount = 0.0
  31. var confirmationProgress = 0.0
  32. var bolusProgress: Double = 0.0
  33. var isBolusCanceled = false
  34. // Safety limits
  35. var maxBolus: Decimal = 10
  36. var maxCarbs: Decimal = 250
  37. var maxFat: Decimal = 250
  38. var maxProtein: Decimal = 250
  39. var maxIOB: Decimal = 0
  40. var maxCOB: Decimal = 120
  41. // Pump specific dosing increment
  42. var bolusIncrement: Decimal = 0.05
  43. var confirmBolusFaster: Bool = false
  44. // Acknowlegement handling
  45. var showCommsAnimation: Bool = false
  46. var showAcknowledgmentBanner: Bool = false
  47. var acknowledgementStatus: AcknowledgementStatus = .pending
  48. var acknowledgmentMessage: String = ""
  49. var shouldNavigateToRoot: Bool = true
  50. // Bolus calculation progress
  51. var showBolusCalculationProgress: Bool = false
  52. // Meal bolus-specific properties
  53. var mealBolusStep: MealBolusStep = .savingCarbs
  54. var isMealBolusCombo: Bool = false
  55. var showBolusProgressOverlay: Bool {
  56. (!showAcknowledgmentBanner || !showCommsAnimation || !showCommsAnimation) && bolusProgress > 0 && bolusProgress < 1.0 &&
  57. !isBolusCanceled
  58. }
  59. var recommendedBolus: Decimal = 0
  60. // Debouncing and batch processing helpers
  61. /// Temporary storage for new data arriving via WatchConnectivity.
  62. private var pendingData: [String: Any] = [:]
  63. /// Work item to schedule finalizing the pending data.
  64. private var finalizeWorkItem: DispatchWorkItem?
  65. /// A flag to tell the UI we’re still updating.
  66. var showSyncingAnimation: Bool = false
  67. override init() {
  68. super.init()
  69. setupSession()
  70. }
  71. /// Configures the WatchConnectivity session if supported on the device
  72. private func setupSession() {
  73. if WCSession.isSupported() {
  74. let session = WCSession.default
  75. session.delegate = self
  76. session.activate()
  77. self.session = session
  78. } else {
  79. print("⌚️ WCSession is not supported on this device")
  80. }
  81. }
  82. // MARK: – Handle Acknowledgement Messages FROM Phone
  83. func handleAcknowledgment(success: Bool, message: String, isFinal: Bool = true) {
  84. if success {
  85. print("⌚️ Acknowledgment received: \(message)")
  86. acknowledgementStatus = .success
  87. acknowledgmentMessage = "\(message)"
  88. } else {
  89. print("⌚️ Acknowledgment failed: \(message)")
  90. acknowledgementStatus = .failure
  91. acknowledgmentMessage = "\(message)"
  92. }
  93. DispatchQueue.main.async {
  94. self.showCommsAnimation = false // Hide progress animation
  95. self.showSyncingAnimation = false // Just ensure this is 100% set to false
  96. }
  97. if isFinal {
  98. showAcknowledgmentBanner = true
  99. DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
  100. self.showAcknowledgmentBanner = false
  101. self.showSyncingAnimation = false // Just ensure this is 100% set to false
  102. }
  103. }
  104. }
  105. // MARK: - WCSessionDelegate
  106. /// Called when the session has completed activation
  107. /// Updates the reachability status and logs the activation state
  108. func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
  109. DispatchQueue.main.async {
  110. if let error = error {
  111. print("⌚️ Watch session activation failed: \(error.localizedDescription)")
  112. return
  113. }
  114. // the order here is probably not perfect and needs to be re-arranged
  115. if activationState == .activated,
  116. self.lastWatchStateUpdate == nil || self.lastWatchStateUpdate! < Date().timeIntervalSince1970 - 15
  117. {
  118. self.showSyncingAnimation = true
  119. self.requestWatchStateUpdate()
  120. }
  121. print("⌚️ Watch session activated with state: \(activationState.rawValue)")
  122. self.isReachable = session.isReachable
  123. print("⌚️ Watch isReachable after activation: \(session.isReachable)")
  124. }
  125. }
  126. /// Handles incoming messages from the paired iPhone when Phone is in the foreground
  127. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  128. print("⌚️ Watch received data: \(message)")
  129. // If the message has a nested "watchState" dictionary with date as TimeInterval
  130. if let watchStateDict = message[WatchMessageKeys.watchState] as? [String: Any],
  131. let timestamp = watchStateDict[WatchMessageKeys.date] as? TimeInterval
  132. {
  133. let date = Date(timeIntervalSince1970: timestamp)
  134. // Check if it's not older than 15 min
  135. if date >= Date().addingTimeInterval(-15 * 60) {
  136. print("⌚️ Handling watchState from \(date)")
  137. processWatchMessage(message)
  138. } else {
  139. print("⌚️ Received outdated watchState data (\(date))")
  140. DispatchQueue.main.async {
  141. self.showSyncingAnimation = false
  142. }
  143. }
  144. return
  145. }
  146. // Else if the message is an "ack" at the top level
  147. // e.g. { "acknowledged": true, "message": "Started Temp Target...", "date": Date(...) }
  148. else if
  149. let acknowledged = message[WatchMessageKeys.acknowledged] as? Bool,
  150. let ackMessage = message[WatchMessageKeys.message] as? String
  151. {
  152. print("⌚️ Handling ack with message: \(ackMessage), success: \(acknowledged)")
  153. DispatchQueue.main.async {
  154. // For ack messages, we do NOT show “Syncing...”
  155. self.showSyncingAnimation = false
  156. }
  157. processWatchMessage(message)
  158. return
  159. // Recommended bolus is also not part of the WatchState message, hence the extra condition here
  160. } else if
  161. let recommendedBolus = message[WatchMessageKeys.recommendedBolus] as? NSNumber
  162. {
  163. print("⌚️ Received recommended bolus: \(recommendedBolus)")
  164. DispatchQueue.main.async {
  165. self.recommendedBolus = recommendedBolus.decimalValue
  166. self.showBolusCalculationProgress = false
  167. }
  168. return
  169. // Handle bolus progress updates
  170. } else if
  171. let progress = message[WatchMessageKeys.bolusProgress] as? Double
  172. {
  173. DispatchQueue.main.async {
  174. if !self.isBolusCanceled {
  175. self.bolusProgress = progress
  176. }
  177. }
  178. return
  179. // Handle bolus cancellation
  180. } else if
  181. message[WatchMessageKeys.bolusCanceled] as? Bool == true
  182. {
  183. DispatchQueue.main.async {
  184. self.bolusProgress = 0
  185. self.activeBolusAmount = 0
  186. }
  187. return
  188. } else {
  189. print("⌚️ Faulty data. Skipping...")
  190. DispatchQueue.main.async {
  191. self.showSyncingAnimation = false
  192. }
  193. }
  194. }
  195. /// Handles incoming messages from the paired iPhone when Phone is in the background
  196. func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
  197. print("⌚️ Watch received data: \(userInfo)")
  198. // If the message has a nested "watchState" dictionary with date as TimeInterval
  199. if let watchStateDict = userInfo[WatchMessageKeys.watchState] as? [String: Any],
  200. let timestamp = watchStateDict[WatchMessageKeys.date] as? TimeInterval
  201. {
  202. let date = Date(timeIntervalSince1970: timestamp)
  203. // Check if it's not older than 15 min
  204. if date >= Date().addingTimeInterval(-15 * 60) {
  205. print("⌚️ Handling watchState from \(date)")
  206. processWatchMessage(userInfo)
  207. } else {
  208. print("⌚️ Received outdated watchState data (\(date))")
  209. DispatchQueue.main.async {
  210. self.showSyncingAnimation = false
  211. }
  212. }
  213. return
  214. }
  215. // Else if the message is an "ack" at the top level
  216. // e.g. { "acknowledged": true, "message": "Started Temp Target...", "date": Date(...) }
  217. else if
  218. let acknowledged = userInfo[WatchMessageKeys.acknowledged] as? Bool,
  219. let ackMessage = userInfo[WatchMessageKeys.message] as? String
  220. {
  221. print("⌚️ Handling ack with message: \(ackMessage), success: \(acknowledged)")
  222. DispatchQueue.main.async {
  223. // For ack messages, we do NOT show “Syncing...”
  224. self.showSyncingAnimation = false
  225. }
  226. processWatchMessage(userInfo)
  227. return
  228. // Recommended bolus is also not part of the WatchState message, hence the extra condition here
  229. } else if
  230. let recommendedBolus = userInfo[WatchMessageKeys.recommendedBolus] as? NSNumber
  231. {
  232. print("⌚️ Received recommended bolus: \(recommendedBolus)")
  233. self.recommendedBolus = recommendedBolus.decimalValue
  234. showBolusCalculationProgress = false
  235. return
  236. // Handle bolus progress updates
  237. } else if
  238. let progress = userInfo[WatchMessageKeys.bolusProgress] as? Double
  239. {
  240. DispatchQueue.main.async {
  241. if !self.isBolusCanceled {
  242. self.bolusProgress = progress
  243. }
  244. }
  245. return
  246. // Handle bolus cancellation
  247. } else if
  248. userInfo[WatchMessageKeys.bolusCanceled] as? Bool == true
  249. {
  250. DispatchQueue.main.async {
  251. self.bolusProgress = 0
  252. self.activeBolusAmount = 0
  253. }
  254. return
  255. } else {
  256. print("⌚️ Faulty data. Skipping...")
  257. DispatchQueue.main.async {
  258. self.showSyncingAnimation = false
  259. }
  260. }
  261. }
  262. /// Called when the reachability status of the paired iPhone changes
  263. /// Updates the local reachability status
  264. func sessionReachabilityDidChange(_ session: WCSession) {
  265. DispatchQueue.main.async {
  266. print("⌚️ Watch reachability changed: \(session.isReachable)")
  267. if session.isReachable {
  268. if let timestamp = self.lastWatchStateUpdate, timestamp < Date().timeIntervalSince1970 - 15 {
  269. // request fresh data from watch
  270. self.requestWatchStateUpdate()
  271. }
  272. // reset input amounts
  273. self.bolusAmount = 0
  274. self.carbsAmount = 0
  275. // reset auth progress
  276. self.confirmationProgress = 0
  277. }
  278. }
  279. }
  280. /// Handles incoming messages that either contain an acknowledgement or fresh watchState data (<15 min)
  281. private func processWatchMessage(_ message: [String: Any]) {
  282. DispatchQueue.main.async {
  283. // 1) Acknowledgment logic
  284. if let acknowledged = message[WatchMessageKeys.acknowledged] as? Bool,
  285. let ackMessage = message[WatchMessageKeys.message] as? String
  286. {
  287. DispatchQueue.main.async {
  288. self.showSyncingAnimation = false
  289. }
  290. print("⌚️ Received acknowledgment: \(ackMessage), success: \(acknowledged)")
  291. switch ackMessage {
  292. case "Saving carbs...":
  293. self.isMealBolusCombo = true
  294. self.mealBolusStep = .savingCarbs
  295. self.showCommsAnimation = true
  296. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
  297. case "Enacting bolus...":
  298. self.isMealBolusCombo = true
  299. self.mealBolusStep = .enactingBolus
  300. self.showCommsAnimation = true
  301. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
  302. case "Carbs and bolus logged successfully":
  303. self.isMealBolusCombo = false
  304. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
  305. default:
  306. self.isMealBolusCombo = false
  307. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
  308. }
  309. }
  310. // 2) Raw watchState data
  311. if let watchStateData = message[WatchMessageKeys.watchState] as? [String: Any] {
  312. self.scheduleUIUpdate(with: watchStateData)
  313. }
  314. }
  315. }
  316. /// Accumulate new data, set isSyncing, and debounce final update
  317. private func scheduleUIUpdate(with newData: [String: Any]) {
  318. // 1) Mark as syncing
  319. DispatchQueue.main.async {
  320. self.showSyncingAnimation = true
  321. }
  322. // 2) Merge data into our pendingData
  323. pendingData.merge(newData) { _, newVal in newVal }
  324. // 3) Cancel any previous finalization
  325. finalizeWorkItem?.cancel()
  326. // 4) Create and schedule a new finalization
  327. let workItem = DispatchWorkItem { [self] in
  328. self.finalizePendingData()
  329. }
  330. finalizeWorkItem = workItem
  331. DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: workItem)
  332. }
  333. /// Applies all pending data to the watch state in one shot
  334. private func finalizePendingData() {
  335. guard !pendingData.isEmpty else {
  336. // If we have no actual data, just end syncing
  337. DispatchQueue.main.async {
  338. self.showSyncingAnimation = false
  339. }
  340. return
  341. }
  342. print("⌚️ Finalizing pending data: \(pendingData)")
  343. // Actually set your main UI properties here
  344. processRawDataForWatchState(pendingData)
  345. // Clear
  346. pendingData.removeAll()
  347. // Done - but ensure this runs at least 2 sec, to avoid flickering
  348. DispatchQueue.main.async {
  349. self.showSyncingAnimation = false
  350. }
  351. }
  352. /// Updates the UI properties
  353. private func processRawDataForWatchState(_ message: [String: Any]) {
  354. if let timestamp = message[WatchMessageKeys.date] as? TimeInterval {
  355. lastWatchStateUpdate = timestamp
  356. }
  357. if let currentGlucose = message[WatchMessageKeys.currentGlucose] as? String {
  358. self.currentGlucose = currentGlucose
  359. }
  360. if let currentGlucoseColorString = message[WatchMessageKeys.currentGlucoseColorString] as? String {
  361. self.currentGlucoseColorString = currentGlucoseColorString
  362. }
  363. if let trend = message[WatchMessageKeys.trend] as? String {
  364. self.trend = trend
  365. }
  366. if let delta = message[WatchMessageKeys.delta] as? String {
  367. self.delta = delta
  368. }
  369. if let iob = message[WatchMessageKeys.iob] as? String {
  370. self.iob = iob
  371. }
  372. if let cob = message[WatchMessageKeys.cob] as? String {
  373. self.cob = cob
  374. }
  375. if let lastLoopTime = message[WatchMessageKeys.lastLoopTime] as? String {
  376. self.lastLoopTime = lastLoopTime
  377. }
  378. if let glucoseData = message[WatchMessageKeys.glucoseValues] as? [[String: Any]] {
  379. glucoseValues = glucoseData.compactMap { data in
  380. guard let glucose = data["glucose"] as? Double,
  381. let timestamp = data["date"] as? TimeInterval,
  382. let colorString = data["color"] as? String
  383. else { return nil }
  384. return (
  385. Date(timeIntervalSince1970: timestamp),
  386. glucose,
  387. colorString.toColor() // Convert colorString to Color
  388. )
  389. }
  390. .sorted { $0.date < $1.date }
  391. }
  392. if let overrideData = message[WatchMessageKeys.overridePresets] as? [[String: Any]] {
  393. overridePresets = overrideData.compactMap { data in
  394. guard let name = data["name"] as? String,
  395. let isEnabled = data["isEnabled"] as? Bool
  396. else { return nil }
  397. return OverridePresetWatch(name: name, isEnabled: isEnabled)
  398. }
  399. }
  400. if let tempTargetData = message[WatchMessageKeys.tempTargetPresets] as? [[String: Any]] {
  401. tempTargetPresets = tempTargetData.compactMap { data in
  402. guard let name = data["name"] as? String,
  403. let isEnabled = data["isEnabled"] as? Bool
  404. else { return nil }
  405. return TempTargetPresetWatch(name: name, isEnabled: isEnabled)
  406. }
  407. }
  408. if let bolusProgress = message[WatchMessageKeys.bolusProgress] as? Double {
  409. if !isBolusCanceled {
  410. self.bolusProgress = bolusProgress
  411. }
  412. }
  413. if let bolusWasCanceled = message[WatchMessageKeys.bolusCanceled] as? Bool, bolusWasCanceled {
  414. bolusProgress = 0
  415. activeBolusAmount = 0
  416. }
  417. if let maxBolusValue = message[WatchMessageKeys.maxBolus] {
  418. print("⌚️ Received maxBolus: \(maxBolusValue) of type \(type(of: maxBolusValue))")
  419. if let decimalValue = (maxBolusValue as? NSNumber)?.decimalValue {
  420. maxBolus = decimalValue
  421. print("⌚️ Converted maxBolus to: \(decimalValue)")
  422. }
  423. }
  424. if let maxCarbsValue = message[WatchMessageKeys.maxCarbs] {
  425. if let decimalValue = (maxCarbsValue as? NSNumber)?.decimalValue {
  426. maxCarbs = decimalValue
  427. }
  428. }
  429. if let maxFatValue = message[WatchMessageKeys.maxFat] {
  430. if let decimalValue = (maxFatValue as? NSNumber)?.decimalValue {
  431. maxFat = decimalValue
  432. }
  433. }
  434. if let maxProteinValue = message[WatchMessageKeys.maxProtein] {
  435. if let decimalValue = (maxProteinValue as? NSNumber)?.decimalValue {
  436. maxProtein = decimalValue
  437. }
  438. }
  439. if let maxIOBValue = message[WatchMessageKeys.maxIOB] {
  440. if let decimalValue = (maxIOBValue as? NSNumber)?.decimalValue {
  441. maxIOB = decimalValue
  442. }
  443. }
  444. if let maxCOBValue = message[WatchMessageKeys.maxCOB] {
  445. if let decimalValue = (maxCOBValue as? NSNumber)?.decimalValue {
  446. maxCOB = decimalValue
  447. }
  448. }
  449. if let bolusIncrement = message[WatchMessageKeys.bolusIncrement] {
  450. if let decimalValue = (bolusIncrement as? NSNumber)?.decimalValue {
  451. self.bolusIncrement = decimalValue
  452. }
  453. }
  454. if let confirmBolusFaster = message[WatchMessageKeys.confirmBolusFaster] {
  455. if let booleanValue = confirmBolusFaster as? Bool {
  456. self.confirmBolusFaster = booleanValue
  457. }
  458. }
  459. }
  460. }