WatchState.swift 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. var tempTargetPresets: [TempTargetPresetWatch] = []
  20. /// treatments inputs
  21. /// used to store carbs for combined meal-bolus-treatments
  22. var carbsAmount: Int = 0
  23. var fatAmount: Int = 0
  24. var proteinAmount: Int = 0
  25. var bolusAmount = 0.0
  26. var activeBolusAmount = 0.0
  27. var confirmationProgress = 0.0
  28. var bolusProgress: Double = 0.0
  29. override init() {
  30. super.init()
  31. setupSession()
  32. }
  33. /// Configures the WatchConnectivity session if supported on the device
  34. private func setupSession() {
  35. if WCSession.isSupported() {
  36. let session = WCSession.default
  37. session.delegate = self
  38. session.activate()
  39. self.session = session
  40. } else {
  41. print("⌚️ WCSession is not supported on this device")
  42. }
  43. }
  44. // MARK: - Send Data to Phone
  45. /// Sends a bolus insulin request to the paired iPhone
  46. /// - Parameters:
  47. /// - amount: The insulin amount to be delivered
  48. func sendBolusRequest(_ amount: Decimal) {
  49. guard let session = session, session.isReachable else { return }
  50. let message: [String: Any] = [
  51. "bolus": amount
  52. ]
  53. session.sendMessage(message, replyHandler: nil) { error in
  54. print("Error sending bolus request: \(error.localizedDescription)")
  55. }
  56. }
  57. /// Sends a carbohydrate entry request to the paired iPhone
  58. /// - Parameters:
  59. /// - amount: The amount of carbs in grams
  60. /// - date: The timestamp for the carb entry (defaults to current time)
  61. func sendCarbsRequest(_ amount: Int, _ date: Date = Date()) {
  62. guard let session = session, session.isReachable else { return }
  63. let message: [String: Any] = [
  64. "carbs": amount,
  65. "date": date.timeIntervalSince1970
  66. ]
  67. session.sendMessage(message, replyHandler: nil) { error in
  68. print("Error sending carbs request: \(error.localizedDescription)")
  69. }
  70. }
  71. /// Sends a meal and bolus insulin combo request to the paired iPhone
  72. /// - Parameters:
  73. /// - amount: The insulin amount to be delivered
  74. /// - isExternal: Indicates if the bolus is from an external source
  75. func sendMealBolusComboRequest(carbsAmount _: Decimal, bolusAmount: Decimal, _ date: Date = Date()) {
  76. guard let session = session, session.isReachable else { return }
  77. let message: [String: Any] = [
  78. "bolus": bolusAmount,
  79. "carbs": bolusAmount,
  80. "date": date.timeIntervalSince1970
  81. ]
  82. session.sendMessage(message, replyHandler: nil) { error in
  83. print("Error sending meal bolus combo request: \(error.localizedDescription)")
  84. }
  85. }
  86. func sendCancelOverrideRequest() {
  87. guard let session = session, session.isReachable else { return }
  88. let message: [String: Any] = [
  89. "cancelOverride": true
  90. ]
  91. session.sendMessage(message, replyHandler: nil) { error in
  92. print("⌚️ Error sending cancel override request: \(error.localizedDescription)")
  93. }
  94. }
  95. func sendActivateOverrideRequest(presetName: String) {
  96. guard let session = session, session.isReachable else { return }
  97. let message: [String: Any] = [
  98. "activateOverride": presetName
  99. ]
  100. session.sendMessage(message, replyHandler: nil) { error in
  101. print("⌚️ Error sending activate override request: \(error.localizedDescription)")
  102. }
  103. }
  104. func sendCancelTempTargetRequest() {
  105. guard let session = session, session.isReachable else { return }
  106. let message: [String: Any] = [
  107. "cancelTempTarget": true
  108. ]
  109. session.sendMessage(message, replyHandler: nil) { error in
  110. print("⌚️ Error sending cancel temp target request: \(error.localizedDescription)")
  111. }
  112. }
  113. func sendActivateTempTargetRequest(presetName: String) {
  114. guard let session = session, session.isReachable else { return }
  115. let message: [String: Any] = [
  116. "activateTempTarget": presetName
  117. ]
  118. session.sendMessage(message, replyHandler: nil) { error in
  119. print("⌚️ Error sending activate temp target request: \(error.localizedDescription)")
  120. }
  121. }
  122. func sendCancelBolusRequest() {
  123. guard let session = session, session.isReachable else { return }
  124. let message: [String: Any] = [
  125. "cancelBolus": true
  126. ]
  127. session.sendMessage(message, replyHandler: nil) { error in
  128. print("Error sending cancel bolus request: \(error.localizedDescription)")
  129. }
  130. }
  131. // MARK: - WCSessionDelegate
  132. /// Called when the session has completed activation
  133. /// Updates the reachability status and logs the activation state
  134. func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
  135. DispatchQueue.main.async {
  136. if let error = error {
  137. print("⌚️ Watch session activation failed: \(error.localizedDescription)")
  138. return
  139. }
  140. print("⌚️ Watch session activated with state: \(activationState.rawValue)")
  141. self.isReachable = session.isReachable
  142. print("⌚️ Watch isReachable after activation: \(session.isReachable)")
  143. }
  144. }
  145. /// Handles incoming messages from the paired iPhone
  146. /// Updates local glucose data, trend, and delta information
  147. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  148. print("⌚️ Watch received message: \(message)")
  149. DispatchQueue.main.async { [weak self] in
  150. guard let self = self else { return }
  151. if let currentGlucose = message["currentGlucose"] as? String {
  152. self.currentGlucose = currentGlucose
  153. }
  154. if let trend = message["trend"] as? String {
  155. self.trend = trend
  156. }
  157. if let delta = message["delta"] as? String {
  158. self.delta = delta
  159. }
  160. if let iob = message["iob"] as? String {
  161. self.iob = iob
  162. }
  163. if let cob = message["cob"] as? String {
  164. self.cob = cob
  165. }
  166. if let lastLoopTime = message["lastLoopTime"] as? String {
  167. self.lastLoopTime = lastLoopTime
  168. }
  169. if let glucoseData = message["glucoseValues"] as? [[String: Any]] {
  170. self.glucoseValues = glucoseData.compactMap { data in
  171. guard let glucose = data["glucose"] as? Double,
  172. let timestamp = data["date"] as? TimeInterval
  173. else { return nil }
  174. return (Date(timeIntervalSince1970: timestamp), glucose)
  175. }
  176. .sorted { $0.date < $1.date }
  177. }
  178. if let overrideData = message["overridePresets"] as? [[String: Any]] {
  179. self.overridePresets = overrideData.compactMap { data in
  180. guard let name = data["name"] as? String,
  181. let isEnabled = data["isEnabled"] as? Bool
  182. else { return nil }
  183. return OverridePresetWatch(name: name, isEnabled: isEnabled)
  184. }
  185. }
  186. if let tempTargetData = message["tempTargetPresets"] as? [[String: Any]] {
  187. self.tempTargetPresets = tempTargetData.compactMap { data in
  188. guard let name = data["name"] as? String,
  189. let isEnabled = data["isEnabled"] as? Bool
  190. else { return nil }
  191. return TempTargetPresetWatch(name: name, isEnabled: isEnabled)
  192. }
  193. }
  194. if let bolusProgress = message["bolusProgress"] as? Double {
  195. self.bolusProgress = bolusProgress
  196. }
  197. }
  198. }
  199. /// Called when the reachability status of the paired iPhone changes
  200. /// Updates the local reachability status
  201. func sessionReachabilityDidChange(_ session: WCSession) {
  202. DispatchQueue.main.async {
  203. self.isReachable = session.isReachable
  204. print("⌚️ Watch reachability changed: \(session.isReachable)")
  205. }
  206. }
  207. }