WatchState.swift 22 KB

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