WatchStateModel.swift 6.6 KB

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