WatchStateModel.swift 6.4 KB

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