WatchStateModel.swift 5.1 KB

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