MainView.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import HealthKit
  2. import SwiftDate
  3. import SwiftUI
  4. struct MainView: View {
  5. private enum Config {
  6. static let lag: TimeInterval = 30
  7. }
  8. @EnvironmentObject var state: WatchStateModel
  9. @State var isCarbsActive = false
  10. @State var isTargetsActive = false
  11. @State var isBolusActive = false
  12. private var healthStore = HKHealthStore()
  13. let heartRateQuantity = HKUnit(from: "count/min")
  14. @State private var value = 0
  15. var body: some View {
  16. ZStack(alignment: .topLeading) {
  17. if state.timerDate.timeIntervalSince(state.lastUpdate) > 10 {
  18. HStack {
  19. withAnimation {
  20. BlinkingView(count: 5, size: 3)
  21. .frame(width: 14, height: 14)
  22. .padding(2)
  23. }
  24. Text("Updating...").font(.caption2).foregroundColor(.secondary)
  25. }
  26. }
  27. VStack {
  28. header
  29. Spacer()
  30. buttons
  31. }
  32. if state.isConfirmationViewActive {
  33. ConfirmationView(success: $state.confirmationSuccess)
  34. .background(Rectangle().fill(.black))
  35. }
  36. if state.isConfirmationBolusViewActive {
  37. BolusConfirmationView()
  38. .environmentObject(state)
  39. .background(Rectangle().fill(.black))
  40. }
  41. }
  42. .frame(maxHeight: .infinity)
  43. .padding()
  44. .onReceive(state.timer) { date in
  45. state.timerDate = date
  46. state.requestState()
  47. }
  48. .onAppear {
  49. state.requestState()
  50. }
  51. }
  52. var header: some View {
  53. VStack {
  54. HStack(alignment: .top) {
  55. VStack(alignment: .leading) {
  56. HStack {
  57. Text(state.glucose).font(.largeTitle)
  58. Text(state.trend)
  59. }
  60. Text(state.delta).font(.caption2).foregroundColor(.gray)
  61. }
  62. Spacer()
  63. VStack(spacing: 0) {
  64. HStack {
  65. Circle().stroke(color, lineWidth: 6).frame(width: 30, height: 30).padding(10)
  66. }
  67. if state.lastLoopDate != nil {
  68. Text(timeString).font(.caption2).foregroundColor(.gray)
  69. } else {
  70. Text("--").font(.caption2).foregroundColor(.gray)
  71. }
  72. }
  73. }
  74. Spacer()
  75. Spacer()
  76. HStack {
  77. Text(iobFormatter.string(from: (state.cob ?? 0) as NSNumber)!).font(.caption2)
  78. Text("g").foregroundColor(.loopGreen)
  79. Spacer()
  80. Text(iobFormatter.string(from: (state.iob ?? 0) as NSNumber)!).font(.caption2)
  81. Text("U").foregroundColor(.insulin)
  82. Spacer()
  83. Text("❤️" + " \(value)")
  84. .fontWeight(.regular)
  85. .font(.system(size: 18)).foregroundColor(Color.red)
  86. }
  87. Spacer()
  88. Spacer()
  89. }.padding()
  90. .onAppear(perform: start)
  91. }
  92. var buttons: some View {
  93. HStack {
  94. NavigationLink(isActive: $state.isCarbsViewActive) {
  95. CarbsView()
  96. .environmentObject(state)
  97. } label: {
  98. Image("carbs", bundle: nil)
  99. .renderingMode(.template)
  100. .resizable()
  101. .frame(width: 24, height: 24)
  102. .foregroundColor(.loopGreen)
  103. }
  104. NavigationLink(isActive: $state.isBolusViewActive) {
  105. BolusView()
  106. .environmentObject(state)
  107. } label: {
  108. Image("bolus", bundle: nil)
  109. .renderingMode(.template)
  110. .resizable()
  111. .frame(width: 24, height: 24)
  112. .foregroundColor(.insulin)
  113. }
  114. NavigationLink(isActive: $state.isTempTargetViewActive) {
  115. TempTargetsView()
  116. .environmentObject(state)
  117. } label: {
  118. VStack {
  119. Image("target", bundle: nil)
  120. .renderingMode(.template)
  121. .resizable()
  122. .frame(width: 24, height: 24)
  123. .foregroundColor(.loopYellow)
  124. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  125. Text(until, style: .timer).font(.system(size: 8))
  126. }
  127. }
  128. }
  129. }
  130. }
  131. func start() {
  132. autorizeHealthKit()
  133. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  134. }
  135. func autorizeHealthKit() {
  136. let healthKitTypes: Set = [
  137. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  138. ]
  139. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  140. }
  141. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  142. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  143. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  144. _, samples, _, _, _ in
  145. guard let samples = samples as? [HKQuantitySample] else {
  146. return
  147. }
  148. self.process(samples, type: quantityTypeIdentifier)
  149. }
  150. let query = HKAnchoredObjectQuery(
  151. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  152. predicate: devicePredicate,
  153. anchor: nil,
  154. limit: HKObjectQueryNoLimit,
  155. resultsHandler: updateHandler
  156. )
  157. query.updateHandler = updateHandler
  158. healthStore.execute(query)
  159. }
  160. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  161. var lastHeartRate = 0.0
  162. for sample in samples {
  163. if type == .heartRate {
  164. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  165. }
  166. value = Int(lastHeartRate)
  167. }
  168. }
  169. private var iobFormatter: NumberFormatter {
  170. let formatter = NumberFormatter()
  171. formatter.maximumFractionDigits = 2
  172. formatter.numberStyle = .decimal
  173. return formatter
  174. }
  175. private var timeString: String {
  176. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  177. if minAgo > 1440 {
  178. return "--"
  179. }
  180. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  181. }
  182. private var color: Color {
  183. guard let lastLoopDate = state.lastLoopDate else {
  184. return .loopGray
  185. }
  186. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  187. if delta <= 5.minutes.timeInterval {
  188. return .loopGreen
  189. } else if delta <= 10.minutes.timeInterval {
  190. return .loopYellow
  191. } else {
  192. return .loopRed
  193. }
  194. }
  195. }
  196. struct ContentView_Previews: PreviewProvider {
  197. static var previews: some View {
  198. Group {
  199. MainView().environmentObject(WatchStateModel())
  200. MainView().previewDevice("Apple Watch Series 5 - 40mm").environmentObject(WatchStateModel())
  201. }
  202. }
  203. }