WatchState.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. 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. // the order here is probably not perfect and needs to be re-arranged
  116. if activationState == .activated {
  117. guard let lastUpdateTimestamp = self.lastWatchStateUpdate else {
  118. // nil => force update
  119. self.showSyncingAnimation = true
  120. self.requestWatchStateUpdate()
  121. return
  122. }
  123. let now = Date().timeIntervalSince1970
  124. let secondsSinceUpdate = now - lastUpdateTimestamp
  125. // If more than 15 minutes in seconds
  126. if secondsSinceUpdate > 15 * 60 {
  127. self.showSyncingAnimation = true
  128. self.requestWatchStateUpdate()
  129. return
  130. }
  131. // Otherwise do the rest...
  132. print("⌚️ Watch session activated with state: \(activationState.rawValue)")
  133. self.isReachable = session.isReachable
  134. print("⌚️ Watch isReachable after activation: \(session.isReachable)")
  135. }
  136. }
  137. }
  138. /// Handles incoming messages from the paired iPhone when Phone is in the foreground
  139. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  140. print("⌚️ Watch received data: \(message)")
  141. // If the message has a nested "watchState" dictionary with date as TimeInterval
  142. if let watchStateDict = message[WatchMessageKeys.watchState] as? [String: Any],
  143. let timestamp = watchStateDict[WatchMessageKeys.date] as? TimeInterval
  144. {
  145. let date = Date(timeIntervalSince1970: timestamp)
  146. // Check if it's not older than 15 min
  147. if date >= Date().addingTimeInterval(-15 * 60) {
  148. print("⌚️ Handling watchState from \(date)")
  149. processWatchMessage(message)
  150. } else {
  151. print("⌚️ Received outdated watchState data (\(date))")
  152. DispatchQueue.main.async {
  153. self.showSyncingAnimation = false
  154. }
  155. }
  156. return
  157. }
  158. // Else if the message is an "ack" at the top level
  159. // e.g. { "acknowledged": true, "message": "Started Temp Target...", "date": Date(...) }
  160. else if
  161. let acknowledged = message[WatchMessageKeys.acknowledged] as? Bool,
  162. let ackMessage = message[WatchMessageKeys.message] as? String
  163. {
  164. print("⌚️ Handling ack with message: \(ackMessage), success: \(acknowledged)")
  165. DispatchQueue.main.async {
  166. // For ack messages, we do NOT show “Syncing...”
  167. self.showSyncingAnimation = false
  168. }
  169. processWatchMessage(message)
  170. return
  171. // Recommended bolus is also not part of the WatchState message, hence the extra condition here
  172. } else if
  173. let recommendedBolus = message[WatchMessageKeys.recommendedBolus] as? NSNumber
  174. {
  175. print("⌚️ Received recommended bolus: \(recommendedBolus)")
  176. DispatchQueue.main.async {
  177. self.recommendedBolus = recommendedBolus.decimalValue
  178. self.showBolusCalculationProgress = false
  179. }
  180. return
  181. // Handle bolus progress updates
  182. } else if
  183. let progress = message[WatchMessageKeys.bolusProgress] as? Double,
  184. let activeBolusAmount = message[WatchMessageKeys.activeBolusAmount] as? Double
  185. {
  186. DispatchQueue.main.async {
  187. if !self.isBolusCanceled {
  188. self.bolusProgress = progress
  189. // we only need to grab the active bolus amount from the phone if it is a phone-invoked bolus
  190. // when it comes from the watch, we already have it stored and available
  191. if self.activeBolusAmount == 0 {
  192. self.activeBolusAmount = activeBolusAmount
  193. }
  194. }
  195. }
  196. return
  197. // Handle bolus cancellation
  198. } else if
  199. message[WatchMessageKeys.bolusCanceled] as? Bool == true
  200. {
  201. DispatchQueue.main.async {
  202. self.bolusProgress = 0
  203. self.activeBolusAmount = 0
  204. }
  205. return
  206. } else {
  207. print("⌚️ Faulty data. Skipping...")
  208. DispatchQueue.main.async {
  209. self.showSyncingAnimation = false
  210. }
  211. }
  212. }
  213. /// Handles incoming messages from the paired iPhone when Phone is in the background
  214. func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
  215. print("⌚️ Watch received data: \(userInfo)")
  216. // If the message has a nested "watchState" dictionary with date as TimeInterval
  217. if let watchStateDict = userInfo[WatchMessageKeys.watchState] as? [String: Any],
  218. let timestamp = watchStateDict[WatchMessageKeys.date] as? TimeInterval
  219. {
  220. let date = Date(timeIntervalSince1970: timestamp)
  221. // Check if it's not older than 15 min
  222. if date >= Date().addingTimeInterval(-15 * 60) {
  223. print("⌚️ Handling watchState from \(date)")
  224. processWatchMessage(userInfo)
  225. } else {
  226. print("⌚️ Received outdated watchState data (\(date))")
  227. DispatchQueue.main.async {
  228. self.showSyncingAnimation = false
  229. }
  230. }
  231. return
  232. }
  233. // Else if the message is an "ack" at the top level
  234. // e.g. { "acknowledged": true, "message": "Started Temp Target...", "date": Date(...) }
  235. else if
  236. let acknowledged = userInfo[WatchMessageKeys.acknowledged] as? Bool,
  237. let ackMessage = userInfo[WatchMessageKeys.message] as? String
  238. {
  239. print("⌚️ Handling ack with message: \(ackMessage), success: \(acknowledged)")
  240. DispatchQueue.main.async {
  241. // For ack messages, we do NOT show “Syncing...”
  242. self.showSyncingAnimation = false
  243. }
  244. processWatchMessage(userInfo)
  245. return
  246. // Recommended bolus is also not part of the WatchState message, hence the extra condition here
  247. } else if
  248. let recommendedBolus = userInfo[WatchMessageKeys.recommendedBolus] as? NSNumber
  249. {
  250. print("⌚️ Received recommended bolus: \(recommendedBolus)")
  251. self.recommendedBolus = recommendedBolus.decimalValue
  252. showBolusCalculationProgress = false
  253. return
  254. // Handle bolus progress updates
  255. } else if
  256. let progress = userInfo[WatchMessageKeys.bolusProgress] as? Double,
  257. let activeBolusAmount = userInfo[WatchMessageKeys.activeBolusAmount] as? Double
  258. {
  259. DispatchQueue.main.async {
  260. if !self.isBolusCanceled {
  261. self.bolusProgress = progress
  262. // we only need to grab the active bolus amount from the phone if it is a phone-invoked bolus
  263. // when it comes from the watch, we already have it stored and available
  264. if self.activeBolusAmount == 0 {
  265. self.activeBolusAmount = activeBolusAmount
  266. }
  267. }
  268. }
  269. return
  270. // Handle bolus cancellation
  271. } else if
  272. userInfo[WatchMessageKeys.bolusCanceled] as? Bool == true
  273. {
  274. DispatchQueue.main.async {
  275. self.bolusProgress = 0
  276. self.activeBolusAmount = 0
  277. }
  278. return
  279. } else {
  280. print("⌚️ Faulty data. Skipping...")
  281. DispatchQueue.main.async {
  282. self.showSyncingAnimation = false
  283. }
  284. }
  285. }
  286. /// Called when the reachability status of the paired iPhone changes
  287. /// Updates the local reachability status
  288. func sessionReachabilityDidChange(_ session: WCSession) {
  289. DispatchQueue.main.async {
  290. print("⌚️ Watch reachability changed: \(session.isReachable)")
  291. if session.isReachable {
  292. if let timestamp = self.lastWatchStateUpdate, timestamp < Date().timeIntervalSince1970 - 15 {
  293. // request fresh data from watch
  294. self.requestWatchStateUpdate()
  295. }
  296. // reset input amounts
  297. self.bolusAmount = 0
  298. self.carbsAmount = 0
  299. // reset auth progress
  300. self.confirmationProgress = 0
  301. }
  302. }
  303. }
  304. /// Handles incoming messages that either contain an acknowledgement or fresh watchState data (<15 min)
  305. private func processWatchMessage(_ message: [String: Any]) {
  306. DispatchQueue.main.async {
  307. // 1) Acknowledgment logic
  308. if let acknowledged = message[WatchMessageKeys.acknowledged] as? Bool,
  309. let ackMessage = message[WatchMessageKeys.message] as? String
  310. {
  311. DispatchQueue.main.async {
  312. self.showSyncingAnimation = false
  313. }
  314. print("⌚️ Received acknowledgment: \(ackMessage), success: \(acknowledged)")
  315. switch ackMessage {
  316. case "Saving carbs...":
  317. self.isMealBolusCombo = true
  318. self.mealBolusStep = .savingCarbs
  319. self.showCommsAnimation = true
  320. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
  321. case "Enacting bolus...":
  322. self.isMealBolusCombo = true
  323. self.mealBolusStep = .enactingBolus
  324. self.showCommsAnimation = true
  325. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
  326. case "Carbs and bolus logged successfully":
  327. self.isMealBolusCombo = false
  328. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
  329. default:
  330. self.isMealBolusCombo = false
  331. self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
  332. }
  333. }
  334. // 2) Raw watchState data
  335. if let watchStateData = message[WatchMessageKeys.watchState] as? [String: Any] {
  336. self.scheduleUIUpdate(with: watchStateData)
  337. }
  338. }
  339. }
  340. /// Accumulate new data, set isSyncing, and debounce final update
  341. private func scheduleUIUpdate(with newData: [String: Any]) {
  342. // 1) Mark as syncing
  343. DispatchQueue.main.async {
  344. self.showSyncingAnimation = true
  345. }
  346. // 2) Merge data into our pendingData
  347. pendingData.merge(newData) { _, newVal in newVal }
  348. // 3) Cancel any previous finalization
  349. finalizeWorkItem?.cancel()
  350. // 4) Create and schedule a new finalization
  351. let workItem = DispatchWorkItem { [self] in
  352. self.finalizePendingData()
  353. }
  354. finalizeWorkItem = workItem
  355. DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: workItem)
  356. }
  357. /// Applies all pending data to the watch state in one shot
  358. private func finalizePendingData() {
  359. guard !pendingData.isEmpty else {
  360. // If we have no actual data, just end syncing
  361. DispatchQueue.main.async {
  362. self.showSyncingAnimation = false
  363. }
  364. return
  365. }
  366. print("⌚️ Finalizing pending data: \(pendingData)")
  367. // Actually set your main UI properties here
  368. processRawDataForWatchState(pendingData)
  369. // Clear
  370. pendingData.removeAll()
  371. // Done - hide sync animation
  372. DispatchQueue.main.async {
  373. self.showSyncingAnimation = false
  374. }
  375. }
  376. /// Updates the UI properties
  377. private func processRawDataForWatchState(_ message: [String: Any]) {
  378. if let timestamp = message[WatchMessageKeys.date] as? TimeInterval {
  379. lastWatchStateUpdate = timestamp
  380. }
  381. if let currentGlucose = message[WatchMessageKeys.currentGlucose] as? String {
  382. self.currentGlucose = currentGlucose
  383. }
  384. if let currentGlucoseColorString = message[WatchMessageKeys.currentGlucoseColorString] as? String {
  385. self.currentGlucoseColorString = currentGlucoseColorString
  386. }
  387. if let trend = message[WatchMessageKeys.trend] as? String {
  388. self.trend = trend
  389. }
  390. if let delta = message[WatchMessageKeys.delta] as? String {
  391. self.delta = delta
  392. }
  393. if let iob = message[WatchMessageKeys.iob] as? String {
  394. self.iob = iob
  395. }
  396. if let cob = message[WatchMessageKeys.cob] as? String {
  397. self.cob = cob
  398. }
  399. if let lastLoopTime = message[WatchMessageKeys.lastLoopTime] as? String {
  400. self.lastLoopTime = lastLoopTime
  401. }
  402. if let glucoseData = message[WatchMessageKeys.glucoseValues] as? [[String: Any]] {
  403. glucoseValues = glucoseData.compactMap { data in
  404. guard let glucose = data["glucose"] as? Double,
  405. let timestamp = data["date"] as? TimeInterval,
  406. let colorString = data["color"] as? String
  407. else { return nil }
  408. return (
  409. Date(timeIntervalSince1970: timestamp),
  410. glucose,
  411. colorString.toColor() // Convert colorString to Color
  412. )
  413. }
  414. .sorted { $0.date < $1.date }
  415. }
  416. if let overrideData = message[WatchMessageKeys.overridePresets] as? [[String: Any]] {
  417. overridePresets = overrideData.compactMap { data in
  418. guard let name = data["name"] as? String,
  419. let isEnabled = data["isEnabled"] as? Bool
  420. else { return nil }
  421. return OverridePresetWatch(name: name, isEnabled: isEnabled)
  422. }
  423. }
  424. if let tempTargetData = message[WatchMessageKeys.tempTargetPresets] as? [[String: Any]] {
  425. tempTargetPresets = tempTargetData.compactMap { data in
  426. guard let name = data["name"] as? String,
  427. let isEnabled = data["isEnabled"] as? Bool
  428. else { return nil }
  429. return TempTargetPresetWatch(name: name, isEnabled: isEnabled)
  430. }
  431. }
  432. if let bolusProgress = message[WatchMessageKeys.bolusProgress] as? Double {
  433. if !isBolusCanceled {
  434. self.bolusProgress = bolusProgress
  435. }
  436. }
  437. if let bolusWasCanceled = message[WatchMessageKeys.bolusCanceled] as? Bool, bolusWasCanceled {
  438. bolusProgress = 0
  439. activeBolusAmount = 0
  440. }
  441. if let maxBolusValue = message[WatchMessageKeys.maxBolus] {
  442. print("⌚️ Received maxBolus: \(maxBolusValue) of type \(type(of: maxBolusValue))")
  443. if let decimalValue = (maxBolusValue as? NSNumber)?.decimalValue {
  444. maxBolus = decimalValue
  445. print("⌚️ Converted maxBolus to: \(decimalValue)")
  446. }
  447. }
  448. if let maxCarbsValue = message[WatchMessageKeys.maxCarbs] {
  449. if let decimalValue = (maxCarbsValue as? NSNumber)?.decimalValue {
  450. maxCarbs = decimalValue
  451. }
  452. }
  453. if let maxFatValue = message[WatchMessageKeys.maxFat] {
  454. if let decimalValue = (maxFatValue as? NSNumber)?.decimalValue {
  455. maxFat = decimalValue
  456. }
  457. }
  458. if let maxProteinValue = message[WatchMessageKeys.maxProtein] {
  459. if let decimalValue = (maxProteinValue as? NSNumber)?.decimalValue {
  460. maxProtein = decimalValue
  461. }
  462. }
  463. if let maxIOBValue = message[WatchMessageKeys.maxIOB] {
  464. if let decimalValue = (maxIOBValue as? NSNumber)?.decimalValue {
  465. maxIOB = decimalValue
  466. }
  467. }
  468. if let maxCOBValue = message[WatchMessageKeys.maxCOB] {
  469. if let decimalValue = (maxCOBValue as? NSNumber)?.decimalValue {
  470. maxCOB = decimalValue
  471. }
  472. }
  473. if let bolusIncrement = message[WatchMessageKeys.bolusIncrement] {
  474. if let decimalValue = (bolusIncrement as? NSNumber)?.decimalValue {
  475. self.bolusIncrement = decimalValue
  476. }
  477. }
  478. if let confirmBolusFaster = message[WatchMessageKeys.confirmBolusFaster] {
  479. if let booleanValue = confirmBolusFaster as? Bool {
  480. self.confirmBolusFaster = booleanValue
  481. }
  482. }
  483. }
  484. }