MainView.swift 9.2 KB

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