MainView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. @GestureState var isDetectingLongPress = false
  14. @State var completedLongPress = false
  15. @State var completedLongPressOfBG = false
  16. @GestureState var isDetectingLongPressOfBG = false
  17. private var healthStore = HKHealthStore()
  18. let heartRateQuantity = HKUnit(from: "count/min")
  19. var body: some View {
  20. ZStack(alignment: .topLeading) {
  21. if !completedLongPressOfBG {
  22. if state.timerDate.timeIntervalSince(state.lastUpdate) > 10 {
  23. HStack {
  24. withAnimation {
  25. BlinkingView(count: 5, size: 3)
  26. .frame(width: 14, height: 14)
  27. .padding(2)
  28. }
  29. Text("Updating...").font(.caption2).foregroundColor(.secondary)
  30. }
  31. }
  32. }
  33. VStack {
  34. if !completedLongPressOfBG {
  35. header
  36. Spacer()
  37. buttons
  38. } else {
  39. bigHeader
  40. }
  41. }
  42. if state.isConfirmationViewActive {
  43. ConfirmationView(success: $state.confirmationSuccess)
  44. .background(Rectangle().fill(.black))
  45. }
  46. if state.isConfirmationBolusViewActive {
  47. BolusConfirmationView()
  48. .environmentObject(state)
  49. .background(Rectangle().fill(.black))
  50. }
  51. }
  52. .frame(maxHeight: .infinity)
  53. .padding()
  54. .onReceive(state.timer) { date in
  55. state.timerDate = date
  56. state.requestState()
  57. }
  58. .onAppear {
  59. state.requestState()
  60. }
  61. }
  62. var header: some View {
  63. VStack {
  64. HStack(alignment: .top) {
  65. VStack(alignment: .leading) {
  66. HStack {
  67. Text(state.glucose).font(.title)
  68. Text(state.trend)
  69. .scaledToFill()
  70. .minimumScaleFactor(0.5)
  71. }
  72. Text(state.delta).font(.caption2).foregroundColor(.gray)
  73. }
  74. Spacer()
  75. VStack(spacing: 0) {
  76. HStack {
  77. Circle().stroke(color, lineWidth: 5).frame(width: 26, height: 26).padding(10)
  78. }
  79. if state.lastLoopDate != nil {
  80. Text(timeString).font(.caption2).foregroundColor(.gray)
  81. } else {
  82. Text("--").font(.caption2).foregroundColor(.gray)
  83. }
  84. }
  85. }
  86. Spacer()
  87. HStack(alignment: .firstTextBaseline) {
  88. Text(iobFormatter.string(from: (state.cob ?? 0) as NSNumber)!)
  89. .font(.caption2)
  90. .scaledToFill()
  91. .foregroundColor(Color.white)
  92. .minimumScaleFactor(0.5)
  93. Text("g").foregroundColor(.loopGreen)
  94. .font(.caption2)
  95. .scaledToFill()
  96. .foregroundColor(.loopGreen)
  97. .minimumScaleFactor(0.5)
  98. Spacer()
  99. Text(iobFormatter.string(from: (state.iob ?? 0) as NSNumber)!)
  100. .font(.caption2)
  101. .scaledToFill()
  102. .foregroundColor(Color.white)
  103. .minimumScaleFactor(0.5)
  104. Text("U").foregroundColor(.insulin)
  105. .font(.caption2)
  106. .scaledToFill()
  107. .foregroundColor(.loopGreen)
  108. .minimumScaleFactor(0.5)
  109. if state.displayHR {
  110. Spacer()
  111. HStack {
  112. if completedLongPress {
  113. HStack {
  114. Text("❤️" + " \(pulse)")
  115. .fontWeight(.regular)
  116. .font(.custom("activated", size: 20))
  117. .scaledToFill()
  118. .foregroundColor(.white)
  119. .minimumScaleFactor(0.5)
  120. }
  121. .scaleEffect(isDetectingLongPress ? 3 : 1)
  122. .gesture(longPress)
  123. } else {
  124. HStack {
  125. Text("❤️" + " \(pulse)")
  126. .fontWeight(.regular)
  127. .font(.caption2)
  128. .scaledToFill()
  129. .foregroundColor(.white)
  130. .minimumScaleFactor(0.5)
  131. }
  132. .scaleEffect(isDetectingLongPress ? 3 : 1)
  133. .gesture(longPress)
  134. }
  135. }
  136. } else if let eventualBG = state.eventualBG.nonEmpty {
  137. Spacer()
  138. HStack {
  139. Text(eventualBG)
  140. .font(.caption2)
  141. .scaledToFill()
  142. .foregroundColor(.secondary)
  143. .minimumScaleFactor(0.5)
  144. }
  145. }
  146. }
  147. Spacer()
  148. .onAppear(perform: start)
  149. }
  150. .padding()
  151. // .scaleEffect(isDetectingLongPressOfBG ? 3 : 1)
  152. .gesture(longPresBGs)
  153. }
  154. var bigHeader: some View {
  155. VStack(alignment: .center) {
  156. HStack {
  157. Text(state.glucose).font(.custom("Big BG", size: 55))
  158. Text(state.trend != "→" ? state.trend : "")
  159. .scaledToFill()
  160. .minimumScaleFactor(0.5)
  161. }.padding(.bottom, 35)
  162. HStack {
  163. Circle().stroke(color, lineWidth: 5).frame(width: 20, height: 20).padding(10)
  164. }
  165. }
  166. .gesture(longPresBGs)
  167. }
  168. var longPress: some Gesture {
  169. LongPressGesture(minimumDuration: 1)
  170. .updating($isDetectingLongPress) { currentState, gestureState,
  171. _ in
  172. gestureState = currentState
  173. }
  174. .onEnded { _ in
  175. if completedLongPress {
  176. completedLongPress = false
  177. } else { completedLongPress = true }
  178. }
  179. }
  180. var longPresBGs: some Gesture {
  181. LongPressGesture(minimumDuration: 1)
  182. .updating($isDetectingLongPressOfBG) { currentState, gestureState,
  183. _ in
  184. gestureState = currentState
  185. }
  186. .onEnded { _ in
  187. if completedLongPressOfBG {
  188. completedLongPressOfBG = false
  189. } else { completedLongPressOfBG = true }
  190. }
  191. }
  192. var buttons: some View {
  193. HStack(alignment: .center) {
  194. NavigationLink(isActive: $state.isCarbsViewActive) {
  195. CarbsView()
  196. .environmentObject(state)
  197. } label: {
  198. Image("carbs", bundle: nil)
  199. .renderingMode(.template)
  200. .resizable()
  201. .frame(width: 24, height: 24)
  202. .foregroundColor(.loopGreen)
  203. }
  204. NavigationLink(isActive: $state.isTempTargetViewActive) {
  205. TempTargetsView()
  206. .environmentObject(state)
  207. } label: {
  208. VStack {
  209. Image("target", bundle: nil)
  210. .renderingMode(.template)
  211. .resizable()
  212. .frame(width: 24, height: 24)
  213. .foregroundColor(.loopYellow)
  214. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  215. Text(until, style: .timer)
  216. .scaledToFill()
  217. .font(.system(size: 8))
  218. }
  219. }
  220. }
  221. NavigationLink(isActive: $state.isBolusViewActive) {
  222. BolusView()
  223. .environmentObject(state)
  224. } label: {
  225. Image("bolus", bundle: nil)
  226. .renderingMode(.template)
  227. .resizable()
  228. .frame(width: 24, height: 24)
  229. .foregroundColor(.insulin)
  230. }
  231. }
  232. }
  233. func start() {
  234. autorizeHealthKit()
  235. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  236. }
  237. func autorizeHealthKit() {
  238. let healthKitTypes: Set = [
  239. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  240. ]
  241. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  242. }
  243. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  244. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  245. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  246. _, samples, _, _, _ in
  247. guard let samples = samples as? [HKQuantitySample] else {
  248. return
  249. }
  250. self.process(samples, type: quantityTypeIdentifier)
  251. }
  252. let query = HKAnchoredObjectQuery(
  253. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  254. predicate: devicePredicate,
  255. anchor: nil,
  256. limit: HKObjectQueryNoLimit,
  257. resultsHandler: updateHandler
  258. )
  259. query.updateHandler = updateHandler
  260. healthStore.execute(query)
  261. }
  262. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  263. var lastHeartRate = 0.0
  264. for sample in samples {
  265. if type == .heartRate {
  266. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  267. }
  268. pulse = Int(lastHeartRate)
  269. }
  270. }
  271. private var iobFormatter: NumberFormatter {
  272. let formatter = NumberFormatter()
  273. formatter.maximumFractionDigits = 2
  274. formatter.numberStyle = .decimal
  275. return formatter
  276. }
  277. private var timeString: String {
  278. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  279. if minAgo > 1440 {
  280. return "--"
  281. }
  282. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  283. }
  284. private var color: Color {
  285. guard let lastLoopDate = state.lastLoopDate else {
  286. return .loopGray
  287. }
  288. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  289. if delta <= 5.minutes.timeInterval {
  290. return .loopGreen
  291. } else if delta <= 10.minutes.timeInterval {
  292. return .loopYellow
  293. } else {
  294. return .loopRed
  295. }
  296. }
  297. }
  298. struct ContentView_Previews: PreviewProvider {
  299. static var previews: some View {
  300. let state = WatchStateModel()
  301. state.glucose = "15,8"
  302. state.delta = "+888"
  303. state.iob = 100.38
  304. state.cob = 112.123
  305. state.lastLoopDate = Date().addingTimeInterval(-200)
  306. state
  307. .tempTargets =
  308. [TempTargetWatchPreset(name: "Test", id: "test", description: "", until: Date().addingTimeInterval(3600 * 3))]
  309. return Group {
  310. MainView()
  311. MainView().previewDevice("Apple Watch Series 5 - 40mm")
  312. MainView().previewDevice("Apple Watch Series 3 - 38mm")
  313. }.environmentObject(state)
  314. }
  315. }