WatchState.swift 23 KB

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