WatchStateModel.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import Foundation
  2. import SwiftUI
  3. import WatchConnectivity
  4. class WatchStateModel: NSObject, ObservableObject {
  5. var session: WCSession
  6. @Published var result = ""
  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. init(session: WCSession = .default) {
  20. self.session = session
  21. super.init()
  22. session.delegate = self
  23. session.activate()
  24. }
  25. func addCarbs(_ carbs: Int) {
  26. session.sendMessage(["addCarbs": carbs], replyHandler: { _ in
  27. WKInterfaceDevice.current().play(.success)
  28. }) { error in
  29. print("ASDF: " + error.localizedDescription)
  30. }
  31. }
  32. private func processState(_ state: WatchState) {
  33. glucose = state.glucose ?? "?"
  34. trend = state.trend ?? "?"
  35. delta = state.delta ?? "?"
  36. glucoseDate = state.glucoseDate
  37. lastLoopDate = state.lastLoopDate
  38. bolusIncrement = state.bolusIncrement
  39. maxCOB = state.maxCOB
  40. bolusRecommended = state.bolusRecommended
  41. carbsRequired = state.carbsRequired
  42. iob = state.iob
  43. cob = state.cob
  44. }
  45. }
  46. extension WatchStateModel: WCSessionDelegate {
  47. func session(_: WCSession, activationDidCompleteWith state: WCSessionActivationState, error _: Error?) {
  48. print("WCSession activated: \(state == .activated)")
  49. session.sendMessage([WatchCommandKey.command.rawValue: WatchCommand.stateRequest.rawValue], replyHandler: nil) { error in
  50. print("WatchStateModel error: " + error.localizedDescription)
  51. }
  52. }
  53. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  54. if let text = message["message"] as? String {
  55. DispatchQueue.main.async {
  56. self.result = text
  57. }
  58. }
  59. }
  60. func sessionReachabilityDidChange(_ session: WCSession) {
  61. print("WCSession Reachability: \(session.isReachable)")
  62. }
  63. func session(_: WCSession, didReceiveMessageData messageData: Data) {
  64. if let state = try? JSONDecoder().decode(WatchState.self, from: messageData) {
  65. DispatchQueue.main.async {
  66. // WKInterfaceDevice.current().play(.click)
  67. self.processState(state)
  68. }
  69. }
  70. }
  71. }