MainView.swift 12 KB

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