WatchStateModel.swift 5.8 KB

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