MainView.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. @State private var steps = 0
  14. @GestureState var isDetectingLongPress = false
  15. @State var completedLongPress = false
  16. @State var completedLongPressOfBG = false
  17. @GestureState var isDetectingLongPressOfBG = false
  18. private var healthStore = HKHealthStore()
  19. let heartRateQuantity = HKUnit(from: "count/min")
  20. var body: some View {
  21. ZStack(alignment: .topLeading) {
  22. if !completedLongPressOfBG {
  23. if state.timerDate.timeIntervalSince(state.lastUpdate) > 10 {
  24. HStack {
  25. withAnimation {
  26. BlinkingView(count: 5, size: 3)
  27. .frame(width: 14, height: 14)
  28. .padding(2)
  29. }
  30. Text("Updating...").font(.caption2).foregroundColor(.secondary)
  31. }
  32. }
  33. }
  34. VStack {
  35. if !completedLongPressOfBG {
  36. header
  37. Spacer()
  38. buttons
  39. } else {
  40. bigHeader
  41. }
  42. }
  43. if state.isConfirmationViewActive {
  44. ConfirmationView(success: $state.confirmationSuccess)
  45. .background(Rectangle().fill(.black))
  46. }
  47. if state.isConfirmationBolusViewActive {
  48. BolusConfirmationView()
  49. .environmentObject(state)
  50. .background(Rectangle().fill(.black))
  51. }
  52. }
  53. .frame(maxHeight: .infinity)
  54. .padding()
  55. .onReceive(state.timer) { date in
  56. state.timerDate = date
  57. state.requestState()
  58. }
  59. .onAppear {
  60. state.requestState()
  61. }
  62. }
  63. var header: some View {
  64. VStack {
  65. HStack(alignment: .top) {
  66. VStack(alignment: .leading) {
  67. HStack {
  68. Text(state.glucose).font(.title)
  69. Text(state.trend)
  70. .scaledToFill()
  71. .minimumScaleFactor(0.5)
  72. }
  73. /* IF YOU WANT TO DISPLAY MINUTES AGO, UNCOMMENT the gray code below
  74. let minutesAgo: TimeInterval = -1 * (state.glucoseDate ?? .distantPast).timeIntervalSinceNow / 60
  75. let minuteString = minutesAgo.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))
  76. */
  77. HStack {
  78. /* if minutesAgo > 0 {
  79. Text(minuteString)
  80. Text("min")
  81. } */
  82. Text(state.delta)
  83. }
  84. .font(.caption2).foregroundColor(.gray)
  85. }
  86. Spacer()
  87. VStack(spacing: 0) {
  88. HStack {
  89. Circle().stroke(color, lineWidth: 5).frame(width: 26, height: 26).padding(10)
  90. }
  91. if state.lastLoopDate != nil {
  92. Text(timeString).font(.caption2).foregroundColor(.gray)
  93. } else {
  94. Text("--").font(.caption2).foregroundColor(.gray)
  95. }
  96. }
  97. }
  98. Spacer()
  99. HStack(alignment: .firstTextBaseline) {
  100. Text(iobFormatter.string(from: (state.cob ?? 0) as NSNumber)!)
  101. .font(.caption2)
  102. .scaledToFill()
  103. .foregroundColor(Color.white)
  104. .minimumScaleFactor(0.5)
  105. Text("g").foregroundColor(.loopYellow)
  106. .font(.caption2)
  107. .scaledToFill()
  108. .minimumScaleFactor(0.5)
  109. Spacer()
  110. Text(iobFormatter.string(from: (state.iob ?? 0) as NSNumber)!)
  111. .font(.caption2)
  112. .scaledToFill()
  113. .foregroundColor(Color.white)
  114. .minimumScaleFactor(0.5)
  115. Text("U").foregroundColor(.insulin)
  116. .font(.caption2)
  117. .scaledToFill()
  118. .minimumScaleFactor(0.5)
  119. switch state.displayOnWatch {
  120. case .HR:
  121. Spacer()
  122. HStack {
  123. if completedLongPress {
  124. HStack {
  125. Text("❤️" + " \(pulse)")
  126. .fontWeight(.regular)
  127. .font(.custom("activated", size: 20))
  128. .scaledToFill()
  129. .foregroundColor(.white)
  130. .minimumScaleFactor(0.5)
  131. }
  132. .scaleEffect(isDetectingLongPress ? 3 : 1)
  133. .gesture(longPress)
  134. } else {
  135. HStack {
  136. Text("❤️" + " \(pulse)")
  137. .fontWeight(.regular)
  138. .font(.caption2)
  139. .scaledToFill()
  140. .foregroundColor(.white)
  141. .minimumScaleFactor(0.5)
  142. }
  143. .scaleEffect(isDetectingLongPress ? 3 : 1)
  144. .gesture(longPress)
  145. }
  146. }
  147. case .BGTarget:
  148. if let eventualBG = state.eventualBG.nonEmpty {
  149. Spacer()
  150. HStack {
  151. Text(eventualBG)
  152. .font(.caption2)
  153. .scaledToFill()
  154. .foregroundColor(.secondary)
  155. .minimumScaleFactor(0.5)
  156. }
  157. }
  158. case .steps:
  159. Spacer()
  160. HStack {
  161. Text("🦶" + " \(steps)")
  162. .fontWeight(.regular)
  163. .font(.caption2)
  164. .scaledToFill()
  165. .foregroundColor(.white)
  166. .minimumScaleFactor(0.5)
  167. }
  168. case .isf:
  169. Spacer()
  170. let isf: String = state.isf != nil ? "\(state.isf ?? 0)" : "-"
  171. HStack {
  172. Image(systemName: "arrow.up.arrow.down")
  173. .renderingMode(.template)
  174. .resizable()
  175. .frame(width: 12, height: 12)
  176. .foregroundColor(.loopGreen)
  177. Text("\(isf)")
  178. .fontWeight(.regular)
  179. .font(.caption2)
  180. .scaledToFill()
  181. .foregroundColor(.white)
  182. .minimumScaleFactor(0.5)
  183. }
  184. case .override:
  185. Spacer()
  186. let override: String = state.override != nil ? state.override! : "-"
  187. HStack {
  188. Text("👤 \(override)")
  189. .fontWeight(.regular)
  190. .font(.caption2)
  191. .scaledToFill()
  192. .foregroundColor(.white)
  193. .minimumScaleFactor(0.5)
  194. }
  195. }
  196. }
  197. Spacer()
  198. .onAppear(perform: start)
  199. }
  200. .padding()
  201. // .scaleEffect(isDetectingLongPressOfBG ? 3 : 1)
  202. .gesture(longPresBGs)
  203. }
  204. var bigHeader: some View {
  205. VStack(alignment: .center) {
  206. HStack {
  207. Text(state.glucose).font(.custom("Big BG", size: 55))
  208. Text(state.trend != "→" ? state.trend : "")
  209. .scaledToFill()
  210. .minimumScaleFactor(0.5)
  211. }.padding(.bottom, 35)
  212. HStack {
  213. Circle().stroke(color, lineWidth: 5).frame(width: 20, height: 20).padding(10)
  214. }
  215. }
  216. .gesture(longPresBGs)
  217. }
  218. var longPress: some Gesture {
  219. LongPressGesture(minimumDuration: 1)
  220. .updating($isDetectingLongPress) { currentState, gestureState,
  221. _ in
  222. gestureState = currentState
  223. }
  224. .onEnded { _ in
  225. if completedLongPress {
  226. completedLongPress = false
  227. } else { completedLongPress = true }
  228. }
  229. }
  230. var longPresBGs: some Gesture {
  231. LongPressGesture(minimumDuration: 1)
  232. .updating($isDetectingLongPressOfBG) { currentState, gestureState,
  233. _ in
  234. gestureState = currentState
  235. }
  236. .onEnded { _ in
  237. if completedLongPressOfBG {
  238. completedLongPressOfBG = false
  239. } else { completedLongPressOfBG = true }
  240. }
  241. }
  242. var buttons: some View {
  243. HStack(alignment: .center) {
  244. NavigationLink(isActive: $state.isCarbsViewActive) {
  245. CarbsView()
  246. .environmentObject(state)
  247. } label: {
  248. Image("carbs", bundle: nil)
  249. .renderingMode(.template)
  250. .resizable()
  251. .frame(width: 24, height: 24)
  252. .foregroundColor(.loopYellow)
  253. }
  254. NavigationLink(isActive: $state.isTempTargetViewActive) {
  255. TempTargetsView()
  256. .environmentObject(state)
  257. } label: {
  258. VStack {
  259. Image("target", bundle: nil)
  260. .renderingMode(.template)
  261. .resizable()
  262. .frame(width: 24, height: 24)
  263. .foregroundColor(.loopGreen)
  264. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  265. Text(until, style: .timer)
  266. .scaledToFill()
  267. .font(.system(size: 8))
  268. }
  269. }
  270. }
  271. NavigationLink(isActive: $state.isBolusViewActive) {
  272. BolusView()
  273. .environmentObject(state)
  274. } label: {
  275. Image("bolus", bundle: nil)
  276. .renderingMode(.template)
  277. .resizable()
  278. .frame(width: 24, height: 24)
  279. .foregroundColor(.insulin)
  280. }
  281. }
  282. }
  283. func start() {
  284. autorizeHealthKit()
  285. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  286. startStepsQuery(quantityTypeIdentifier: .stepCount)
  287. }
  288. func autorizeHealthKit() {
  289. let healthKitTypes: Set = [
  290. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
  291. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  292. ]
  293. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  294. }
  295. private func startStepsQuery(quantityTypeIdentifier _: HKQuantityTypeIdentifier) {
  296. let type = HKQuantityType.quantityType(forIdentifier: .stepCount)!
  297. let now = Date()
  298. let startOfDay = Calendar.current.startOfDay(for: now)
  299. var interval = DateComponents()
  300. interval.day = 1
  301. let query = HKStatisticsCollectionQuery(
  302. quantityType: type,
  303. quantitySamplePredicate: nil,
  304. options: [.cumulativeSum],
  305. anchorDate: startOfDay,
  306. intervalComponents: interval
  307. )
  308. query.initialResultsHandler = { _, result, _ in
  309. var resultCount = 0.0
  310. guard let result = result else {
  311. self.steps = 0
  312. return
  313. }
  314. result.enumerateStatistics(from: startOfDay, to: now) { statistics, _ in
  315. if let sum = statistics.sumQuantity() {
  316. // Get steps (they are of double type)
  317. resultCount = sum.doubleValue(for: HKUnit.count())
  318. } // end if
  319. // Return
  320. self.steps = Int(resultCount)
  321. }
  322. }
  323. query.statisticsUpdateHandler = {
  324. _, statistics, _, _ in
  325. // If new statistics are available
  326. if let sum = statistics?.sumQuantity() {
  327. let resultCount = sum.doubleValue(for: HKUnit.count())
  328. // Return
  329. self.steps = Int(resultCount)
  330. } // end if
  331. }
  332. healthStore.execute(query)
  333. }
  334. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  335. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  336. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  337. _, samples, _, _, _ in
  338. guard let samples = samples as? [HKQuantitySample] else {
  339. return
  340. }
  341. self.process(samples, type: quantityTypeIdentifier)
  342. }
  343. let query = HKAnchoredObjectQuery(
  344. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  345. predicate: devicePredicate,
  346. anchor: nil,
  347. limit: HKObjectQueryNoLimit,
  348. resultsHandler: updateHandler
  349. )
  350. query.updateHandler = updateHandler
  351. healthStore.execute(query)
  352. }
  353. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  354. var lastHeartRate = 0.0
  355. for sample in samples {
  356. if type == .heartRate {
  357. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  358. }
  359. pulse = Int(lastHeartRate)
  360. }
  361. }
  362. private var iobFormatter: NumberFormatter {
  363. let formatter = NumberFormatter()
  364. formatter.maximumFractionDigits = 2
  365. formatter.numberStyle = .decimal
  366. return formatter
  367. }
  368. private var timeString: String {
  369. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  370. if minAgo > 1440 {
  371. return "--"
  372. }
  373. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  374. }
  375. private var color: Color {
  376. guard let lastLoopDate = state.lastLoopDate else {
  377. return .loopGray
  378. }
  379. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  380. if delta <= 5.minutes.timeInterval {
  381. return .loopGreen
  382. } else if delta <= 10.minutes.timeInterval {
  383. return .loopYellow
  384. } else {
  385. return .loopRed
  386. }
  387. }
  388. }
  389. struct ContentView_Previews: PreviewProvider {
  390. static var previews: some View {
  391. let state = WatchStateModel()
  392. state.glucose = "15,8"
  393. state.delta = "+888"
  394. state.iob = 100.38
  395. state.cob = 112.123
  396. state.lastLoopDate = Date().addingTimeInterval(-200)
  397. state
  398. .tempTargets =
  399. [TempTargetWatchPreset(name: "Test", id: "test", description: "", until: Date().addingTimeInterval(3600 * 3))]
  400. return Group {
  401. MainView()
  402. MainView().previewDevice("Apple Watch Series 5 - 40mm")
  403. MainView().previewDevice("Apple Watch Series 3 - 38mm")
  404. }.environmentObject(state)
  405. }
  406. }