WatchStateModel.swift 5.2 KB

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