WatchStateModel.swift 5.9 KB

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