WatchStateModel.swift 5.1 KB

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