WatchStateModel.swift 5.0 KB

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