MainView.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. @State private var pulse = 0
  13. private var healthStore = HKHealthStore()
  14. let heartRateQuantity = HKUnit(from: "count/min")
  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(.title)
  58. Text(state.trend)
  59. .scaledToFill()
  60. .minimumScaleFactor(0.5)
  61. }
  62. Text(state.delta).font(.caption2).foregroundColor(.gray)
  63. }
  64. Spacer()
  65. VStack(spacing: 0) {
  66. HStack {
  67. Circle().stroke(color, lineWidth: 6).frame(width: 30, height: 30).padding(10)
  68. }
  69. if state.lastLoopDate != nil {
  70. Text(timeString).font(.caption2).foregroundColor(.gray)
  71. } else {
  72. Text("--").font(.caption2).foregroundColor(.gray)
  73. }
  74. }
  75. }
  76. Spacer()
  77. Spacer()
  78. HStack {
  79. Text(iobFormatter.string(from: (state.cob ?? 0) as NSNumber)!).font(.caption2)
  80. Text("g").foregroundColor(.loopGreen)
  81. Spacer()
  82. Text(iobFormatter.string(from: (state.iob ?? 0) as NSNumber)!).font(.caption2)
  83. Text("U").foregroundColor(.insulin)
  84. Spacer()
  85. Text("❤️" + " \(pulse)")
  86. .fontWeight(.regular)
  87. .font(.system(size: 18)).foregroundColor(Color.white)
  88. }
  89. Spacer()
  90. Spacer()
  91. }.padding()
  92. .onAppear(perform: start)
  93. }
  94. var buttons: some View {
  95. HStack(alignment: .center) {
  96. NavigationLink(isActive: $state.isCarbsViewActive) {
  97. CarbsView()
  98. .environmentObject(state)
  99. } label: {
  100. Image("carbs", bundle: nil)
  101. .renderingMode(.template)
  102. .resizable()
  103. .frame(width: 24, height: 24)
  104. .foregroundColor(.loopGreen)
  105. }
  106. NavigationLink(isActive: $state.isBolusViewActive) {
  107. BolusView()
  108. .environmentObject(state)
  109. } label: {
  110. Image("bolus", bundle: nil)
  111. .renderingMode(.template)
  112. .resizable()
  113. .frame(width: 24, height: 24)
  114. .foregroundColor(.insulin)
  115. }
  116. NavigationLink(isActive: $state.isTempTargetViewActive) {
  117. TempTargetsView()
  118. .environmentObject(state)
  119. } label: {
  120. VStack {
  121. Image("target", bundle: nil)
  122. .renderingMode(.template)
  123. .resizable()
  124. .frame(width: 24, height: 24)
  125. .foregroundColor(.loopYellow)
  126. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  127. Text(until, style: .timer)
  128. .scaledToFill()
  129. .font(.system(size: 8))
  130. }
  131. }
  132. }
  133. }
  134. }
  135. func start() {
  136. autorizeHealthKit()
  137. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  138. }
  139. func autorizeHealthKit() {
  140. let healthKitTypes: Set = [
  141. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  142. ]
  143. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  144. }
  145. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  146. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  147. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  148. _, samples, _, _, _ in
  149. guard let samples = samples as? [HKQuantitySample] else {
  150. return
  151. }
  152. self.process(samples, type: quantityTypeIdentifier)
  153. }
  154. let query = HKAnchoredObjectQuery(
  155. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  156. predicate: devicePredicate,
  157. anchor: nil,
  158. limit: HKObjectQueryNoLimit,
  159. resultsHandler: updateHandler
  160. )
  161. query.updateHandler = updateHandler
  162. healthStore.execute(query)
  163. }
  164. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  165. var lastHeartRate = 0.0
  166. for sample in samples {
  167. if type == .heartRate {
  168. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  169. }
  170. pulse = Int(lastHeartRate)
  171. }
  172. }
  173. private var iobFormatter: NumberFormatter {
  174. let formatter = NumberFormatter()
  175. formatter.maximumFractionDigits = 2
  176. formatter.numberStyle = .decimal
  177. return formatter
  178. }
  179. private var timeString: String {
  180. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  181. if minAgo > 1440 {
  182. return "--"
  183. }
  184. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  185. }
  186. private var color: Color {
  187. guard let lastLoopDate = state.lastLoopDate else {
  188. return .loopGray
  189. }
  190. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  191. if delta <= 5.minutes.timeInterval {
  192. return .loopGreen
  193. } else if delta <= 10.minutes.timeInterval {
  194. return .loopYellow
  195. } else {
  196. return .loopRed
  197. }
  198. }
  199. }
  200. struct ContentView_Previews: PreviewProvider {
  201. static var previews: some View {
  202. let state = WatchStateModel()
  203. state.glucose = "15,8"
  204. state.delta = "+888"
  205. state.iob = 100.38
  206. state.cob = 112.123
  207. state.lastLoopDate = Date().addingTimeInterval(-200)
  208. state
  209. .tempTargets =
  210. [TempTargetWatchPreset(name: "Test", id: "test", description: "", until: Date().addingTimeInterval(3600 * 3))]
  211. return Group {
  212. MainView()
  213. MainView().previewDevice("Apple Watch Series 5 - 40mm")
  214. MainView().previewDevice("Apple Watch Series 3 - 38mm")
  215. }.environmentObject(state)
  216. }
  217. }