WatchStateModel.swift 6.1 KB

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