WatchStateModel.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import Combine
  2. import Foundation
  3. import SwiftUI
  4. import WatchConnectivity
  5. enum AwConfig: String, CaseIterable, Identifiable, Codable {
  6. var id: String { rawValue }
  7. case HR
  8. case BGTarget
  9. case steps
  10. case isf
  11. case override
  12. }
  13. class WatchStateModel: NSObject, ObservableObject {
  14. var session: WCSession
  15. @Published var glucose = "00"
  16. @Published var trend = "→"
  17. @Published var delta = "+00"
  18. @Published var lastLoopDate: Date?
  19. @Published var glucoseDate: Date?
  20. @Published var bolusIncrement: Decimal?
  21. @Published var maxCOB: Decimal?
  22. @Published var maxBolus: Decimal?
  23. @Published var bolusRecommended: Decimal?
  24. @Published var carbsRequired: Decimal?
  25. @Published var iob: Decimal?
  26. @Published var cob: Decimal?
  27. @Published var tempTargets: [TempTargetWatchPreset] = []
  28. @Published var bolusAfterCarbs = true
  29. @Published var isCarbsViewActive = false
  30. @Published var isTempTargetViewActive = false
  31. @Published var isBolusViewActive = false
  32. @Published var displayOnWatch: AwConfig = .BGTarget
  33. @Published var eventualBG = ""
  34. @Published var isConfirmationViewActive = false {
  35. didSet {
  36. confirmationTimeout = nil
  37. if isConfirmationViewActive {
  38. confirmationTimeout = Just(())
  39. .delay(for: 30, scheduler: DispatchQueue.main)
  40. .sink {
  41. WKInterfaceDevice.current().play(.retry)
  42. self.isConfirmationViewActive = false
  43. }
  44. }
  45. }
  46. }
  47. @Published var isConfirmationBolusViewActive = false
  48. @Published var confirmationSuccess: Bool?
  49. @Published var lastUpdate: Date = .distantPast
  50. @Published var timerDate = Date()
  51. @Published var pendingBolus: Double?
  52. @Published var isf: Decimal?
  53. @Published var override: String?
  54. private var lifetime = Set<AnyCancellable>()
  55. private var confirmationTimeout: AnyCancellable?
  56. let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()
  57. init(session: WCSession = .default) {
  58. self.session = session
  59. super.init()
  60. session.delegate = self
  61. session.activate()
  62. }
  63. func addCarbs(_ carbs: Int) {
  64. confirmationSuccess = nil
  65. isConfirmationViewActive = true
  66. isCarbsViewActive = false
  67. session.sendMessage(["carbs": carbs], replyHandler: { reply in
  68. self.completionHandler(reply)
  69. if let ok = reply["confirmation"] as? Bool, ok, self.bolusAfterCarbs {
  70. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  71. self.isBolusViewActive = true
  72. }
  73. }
  74. }) { error in
  75. print(error.localizedDescription)
  76. DispatchQueue.main.async {
  77. self.confirmation(false)
  78. }
  79. }
  80. }
  81. func enactTempTarget(id: String) {
  82. confirmationSuccess = nil
  83. isConfirmationViewActive = true
  84. isTempTargetViewActive = false
  85. session.sendMessage(["tempTarget": id], replyHandler: completionHandler) { error in
  86. print(error.localizedDescription)
  87. DispatchQueue.main.async {
  88. self.confirmation(false)
  89. }
  90. }
  91. }
  92. func addBolus(amount: Double) {
  93. isBolusViewActive = false
  94. pendingBolus = amount
  95. isConfirmationBolusViewActive = true
  96. }
  97. func enactBolus() {
  98. isConfirmationBolusViewActive = false
  99. guard let amount = pendingBolus else { return }
  100. confirmationSuccess = nil
  101. isConfirmationViewActive = true
  102. session.sendMessage(["bolus": amount], replyHandler: completionHandler) { error in
  103. print(error.localizedDescription)
  104. DispatchQueue.main.async {
  105. self.confirmation(false)
  106. }
  107. }
  108. }
  109. func requestState() {
  110. guard session.activationState == .activated else {
  111. session.activate()
  112. return
  113. }
  114. session.sendMessage(["stateRequest": true], replyHandler: nil) { error in
  115. print("WatchStateModel error: " + error.localizedDescription)
  116. }
  117. }
  118. private func completionHandler(_ reply: [String: Any]) {
  119. if let ok = reply["confirmation"] as? Bool {
  120. DispatchQueue.main.async {
  121. self.confirmation(ok)
  122. }
  123. } else {
  124. DispatchQueue.main.async {
  125. self.confirmation(false)
  126. }
  127. }
  128. }
  129. private func confirmation(_ ok: Bool) {
  130. WKInterfaceDevice.current().play(ok ? .success : .failure)
  131. withAnimation {
  132. confirmationSuccess = ok
  133. }
  134. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  135. withAnimation {
  136. self.isConfirmationViewActive = false
  137. }
  138. }
  139. }
  140. private func processState(_ state: WatchState) {
  141. glucose = state.glucose ?? "?"
  142. trend = state.trend ?? "?"
  143. delta = state.delta ?? "?"
  144. glucoseDate = state.glucoseDate
  145. lastLoopDate = state.lastLoopDate
  146. bolusIncrement = state.bolusIncrement
  147. maxCOB = state.maxCOB
  148. maxBolus = state.maxBolus
  149. bolusRecommended = state.bolusRecommended
  150. carbsRequired = state.carbsRequired
  151. iob = state.iob
  152. cob = state.cob
  153. tempTargets = state.tempTargets
  154. bolusAfterCarbs = state.bolusAfterCarbs ?? true
  155. lastUpdate = Date()
  156. eventualBG = state.eventualBG ?? ""
  157. displayOnWatch = state.displayOnWatch ?? .BGTarget
  158. isf = state.isf
  159. override = state.override
  160. }
  161. }
  162. extension WatchStateModel: WCSessionDelegate {
  163. func session(_: WCSession, activationDidCompleteWith state: WCSessionActivationState, error _: Error?) {
  164. print("WCSession activated: \(state == .activated)")
  165. requestState()
  166. }
  167. func session(_: WCSession, didReceiveMessage _: [String: Any]) {}
  168. func sessionReachabilityDidChange(_ session: WCSession) {
  169. print("WCSession Reachability: \(session.isReachable)")
  170. }
  171. func session(_: WCSession, didReceiveMessageData messageData: Data) {
  172. if let state = try? JSONDecoder().decode(WatchState.self, from: messageData) {
  173. DispatchQueue.main.async {
  174. self.processState(state)
  175. }
  176. }
  177. }
  178. }