WatchState.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import Foundation
  2. import WatchConnectivity
  3. /// WatchState manages the communication between the Watch app and the iPhone app using WatchConnectivity.
  4. /// It handles glucose data synchronization and sending treatment requests (bolus, carbs) to the phone.
  5. @Observable final class WatchState: NSObject, WCSessionDelegate {
  6. // MARK: - Properties
  7. /// The WatchConnectivity session instance used for communication
  8. private var session: WCSession?
  9. /// Indicates if the paired iPhone is currently reachable
  10. var isReachable = false
  11. var currentGlucose: String = "--"
  12. var trend: String? = ""
  13. var delta: String? = "--"
  14. var glucoseValues: [(date: Date, glucose: Double)] = []
  15. var cob: String? = "--"
  16. var iob: String? = "--"
  17. var lastLoopTime: String? = "--"
  18. var overridePresets: [OverridePresetWatch] = []
  19. override init() {
  20. super.init()
  21. setupSession()
  22. }
  23. /// Configures the WatchConnectivity session if supported on the device
  24. private func setupSession() {
  25. if WCSession.isSupported() {
  26. let session = WCSession.default
  27. session.delegate = self
  28. session.activate()
  29. self.session = session
  30. } else {
  31. print("⌚️ WCSession is not supported on this device")
  32. }
  33. }
  34. // MARK: - Send Data to Phone
  35. /// Sends a bolus insulin request to the paired iPhone
  36. /// - Parameters:
  37. /// - amount: The insulin amount to be delivered
  38. /// - isExternal: Indicates if the bolus is from an external source
  39. func sendBolusRequest(_ amount: Decimal, isExternal: Bool) {
  40. guard let session = session, session.isReachable else { return }
  41. let message: [String: Any] = [
  42. "bolus": amount,
  43. "isExternal": isExternal
  44. ]
  45. session.sendMessage(message, replyHandler: nil) { error in
  46. print("Error sending bolus request: \(error.localizedDescription)")
  47. }
  48. }
  49. /// Sends a carbohydrate entry request to the paired iPhone
  50. /// - Parameters:
  51. /// - amount: The amount of carbs in grams
  52. /// - date: The timestamp for the carb entry (defaults to current time)
  53. func sendCarbsRequest(_ amount: Int, _ date: Date = Date()) {
  54. guard let session = session, session.isReachable else { return }
  55. let message: [String: Any] = [
  56. "carbs": amount,
  57. "date": date.timeIntervalSince1970
  58. ]
  59. session.sendMessage(message, replyHandler: nil) { error in
  60. print("Error sending carbs request: \(error.localizedDescription)")
  61. }
  62. }
  63. func sendCancelOverrideRequest() {
  64. guard let session = session, session.isReachable else { return }
  65. let message: [String: Any] = [
  66. "cancelOverride": true
  67. ]
  68. session.sendMessage(message, replyHandler: nil) { error in
  69. print("⌚️ Error sending cancel override request: \(error.localizedDescription)")
  70. }
  71. }
  72. func sendActivateOverrideRequest(presetName: String) {
  73. guard let session = session, session.isReachable else { return }
  74. let message: [String: Any] = [
  75. "activateOverride": presetName
  76. ]
  77. session.sendMessage(message, replyHandler: nil) { error in
  78. print("⌚️ Error sending activate override request: \(error.localizedDescription)")
  79. }
  80. }
  81. // MARK: - WCSessionDelegate
  82. /// Called when the session has completed activation
  83. /// Updates the reachability status and logs the activation state
  84. func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
  85. DispatchQueue.main.async {
  86. if let error = error {
  87. print("⌚️ Watch session activation failed: \(error.localizedDescription)")
  88. return
  89. }
  90. print("⌚️ Watch session activated with state: \(activationState.rawValue)")
  91. self.isReachable = session.isReachable
  92. print("⌚️ Watch isReachable after activation: \(session.isReachable)")
  93. }
  94. }
  95. /// Handles incoming messages from the paired iPhone
  96. /// Updates local glucose data, trend, and delta information
  97. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  98. print("⌚️ Watch received message: \(message)")
  99. DispatchQueue.main.async { [weak self] in
  100. guard let self = self else { return }
  101. if let currentGlucose = message["currentGlucose"] as? String {
  102. self.currentGlucose = currentGlucose
  103. }
  104. if let trend = message["trend"] as? String {
  105. self.trend = trend
  106. }
  107. if let delta = message["delta"] as? String {
  108. self.delta = delta
  109. }
  110. if let iob = message["iob"] as? String {
  111. self.iob = iob
  112. }
  113. if let cob = message["cob"] as? String {
  114. self.cob = cob
  115. }
  116. if let lastLoopTime = message["lastLoopTime"] as? String {
  117. self.lastLoopTime = lastLoopTime
  118. }
  119. if let glucoseData = message["glucoseValues"] as? [[String: Any]] {
  120. self.glucoseValues = glucoseData.compactMap { data in
  121. guard let glucose = data["glucose"] as? Double,
  122. let timestamp = data["date"] as? TimeInterval
  123. else { return nil }
  124. return (Date(timeIntervalSince1970: timestamp), glucose)
  125. }
  126. .sorted { $0.date < $1.date }
  127. }
  128. if let overrideData = message["overridePresets"] as? [[String: Any]] {
  129. self.overridePresets = overrideData.compactMap { data in
  130. guard let name = data["name"] as? String,
  131. let isEnabled = data["isEnabled"] as? Bool
  132. else { return nil }
  133. return OverridePresetWatch(name: name, isEnabled: isEnabled)
  134. }
  135. }
  136. }
  137. }
  138. /// Called when the reachability status of the paired iPhone changes
  139. /// Updates the local reachability status
  140. func sessionReachabilityDidChange(_ session: WCSession) {
  141. DispatchQueue.main.async {
  142. self.isReachable = session.isReachable
  143. print("⌚️ Watch reachability changed: \(session.isReachable)")
  144. }
  145. }
  146. }