MainView.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. HStack {
  84. Text("❤️").font(.system(size: 25))
  85. Text("\(value)")
  86. .fontWeight(.regular)
  87. .font(.system(size: 20)).foregroundColor(Color.red)
  88. }
  89. }
  90. Spacer()
  91. Spacer()
  92. }.padding()
  93. .onAppear(perform: start)
  94. }
  95. var buttons: some View {
  96. HStack {
  97. NavigationLink(isActive: $state.isCarbsViewActive) {
  98. CarbsView()
  99. .environmentObject(state)
  100. } label: {
  101. Image("carbs", bundle: nil)
  102. .renderingMode(.template)
  103. .resizable()
  104. .frame(width: 24, height: 24)
  105. .foregroundColor(.loopGreen)
  106. }
  107. NavigationLink(isActive: $state.isBolusViewActive) {
  108. BolusView()
  109. .environmentObject(state)
  110. } label: {
  111. Image("bolus", bundle: nil)
  112. .renderingMode(.template)
  113. .resizable()
  114. .frame(width: 24, height: 24)
  115. .foregroundColor(.insulin)
  116. }
  117. NavigationLink(isActive: $state.isTempTargetViewActive) {
  118. TempTargetsView()
  119. .environmentObject(state)
  120. } label: {
  121. VStack {
  122. Image("target", bundle: nil)
  123. .renderingMode(.template)
  124. .resizable()
  125. .frame(width: 24, height: 24)
  126. .foregroundColor(.loopYellow)
  127. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  128. Text(until, style: .timer).font(.system(size: 8))
  129. }
  130. }
  131. }
  132. }
  133. }
  134. func start() {
  135. autorizeHealthKit()
  136. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  137. }
  138. func autorizeHealthKit() {
  139. let healthKitTypes: Set = [
  140. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  141. ]
  142. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  143. }
  144. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  145. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  146. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  147. _, samples, _, _, _ in
  148. guard let samples = samples as? [HKQuantitySample] else {
  149. return
  150. }
  151. self.process(samples, type: quantityTypeIdentifier)
  152. }
  153. let query = HKAnchoredObjectQuery(
  154. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  155. predicate: devicePredicate,
  156. anchor: nil,
  157. limit: HKObjectQueryNoLimit,
  158. resultsHandler: updateHandler
  159. )
  160. query.updateHandler = updateHandler
  161. healthStore.execute(query)
  162. }
  163. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  164. var lastHeartRate = 0.0
  165. for sample in samples {
  166. if type == .heartRate {
  167. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  168. }
  169. value = Int(lastHeartRate)
  170. }
  171. }
  172. private var iobFormatter: NumberFormatter {
  173. let formatter = NumberFormatter()
  174. formatter.maximumFractionDigits = 2
  175. formatter.numberStyle = .decimal
  176. return formatter
  177. }
  178. private var timeString: String {
  179. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  180. if minAgo > 1440 {
  181. return "--"
  182. }
  183. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  184. }
  185. private var color: Color {
  186. guard let lastLoopDate = state.lastLoopDate else {
  187. return .loopGray
  188. }
  189. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  190. if delta <= 5.minutes.timeInterval {
  191. return .loopGreen
  192. } else if delta <= 10.minutes.timeInterval {
  193. return .loopYellow
  194. } else {
  195. return .loopRed
  196. }
  197. }
  198. }
  199. struct ContentView_Previews: PreviewProvider {
  200. static var previews: some View {
  201. Group {
  202. MainView().environmentObject(WatchStateModel())
  203. MainView().previewDevice("Apple Watch Series 5 - 40mm").environmentObject(WatchStateModel())
  204. }
  205. }
  206. }