WatchStateModel.swift 6.2 KB

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