MainView.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. Text(state.delta).font(.caption2).foregroundColor(.gray)
  74. }
  75. Spacer()
  76. VStack(spacing: 0) {
  77. HStack {
  78. Circle().stroke(color, lineWidth: 5).frame(width: 26, height: 26).padding(10)
  79. }
  80. if state.lastLoopDate != nil {
  81. Text(timeString).font(.caption2).foregroundColor(.gray)
  82. } else {
  83. Text("--").font(.caption2).foregroundColor(.gray)
  84. }
  85. }
  86. }
  87. Spacer()
  88. HStack(alignment: .firstTextBaseline) {
  89. Text(iobFormatter.string(from: (state.cob ?? 0) as NSNumber)!)
  90. .font(.caption2)
  91. .scaledToFill()
  92. .foregroundColor(Color.white)
  93. .minimumScaleFactor(0.5)
  94. Text("g").foregroundColor(.loopYellow)
  95. .font(.caption2)
  96. .scaledToFill()
  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. .minimumScaleFactor(0.5)
  108. switch state.displayOnWatch {
  109. case .HR:
  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. case .BGTarget:
  137. if let eventualBG = state.eventualBG.nonEmpty {
  138. Spacer()
  139. HStack {
  140. Text(eventualBG)
  141. .font(.caption2)
  142. .scaledToFill()
  143. .foregroundColor(.secondary)
  144. .minimumScaleFactor(0.5)
  145. }
  146. }
  147. case .steps:
  148. Spacer()
  149. HStack {
  150. Text("🦶" + " \(steps)")
  151. .fontWeight(.regular)
  152. .font(.caption2)
  153. .scaledToFill()
  154. .foregroundColor(.white)
  155. .minimumScaleFactor(0.5)
  156. }
  157. case .isf:
  158. Spacer()
  159. let isf: String = state.isf != nil ? "\(state.isf ?? 0)" : "-"
  160. HStack {
  161. Image(systemName: "arrow.up.arrow.down")
  162. .renderingMode(.template)
  163. .resizable()
  164. .frame(width: 16, height: 16)
  165. .foregroundColor(.blue)
  166. Text("\(isf)")
  167. .fontWeight(.regular)
  168. .font(.caption2)
  169. .scaledToFill()
  170. .foregroundColor(.white)
  171. .minimumScaleFactor(0.5)
  172. }
  173. }
  174. }
  175. Spacer()
  176. .onAppear(perform: start)
  177. }
  178. .padding()
  179. // .scaleEffect(isDetectingLongPressOfBG ? 3 : 1)
  180. .gesture(longPresBGs)
  181. }
  182. var bigHeader: some View {
  183. VStack(alignment: .center) {
  184. HStack {
  185. Text(state.glucose).font(.custom("Big BG", size: 55))
  186. Text(state.trend != "→" ? state.trend : "")
  187. .scaledToFill()
  188. .minimumScaleFactor(0.5)
  189. }.padding(.bottom, 35)
  190. HStack {
  191. Circle().stroke(color, lineWidth: 5).frame(width: 20, height: 20).padding(10)
  192. }
  193. }
  194. .gesture(longPresBGs)
  195. }
  196. var longPress: some Gesture {
  197. LongPressGesture(minimumDuration: 1)
  198. .updating($isDetectingLongPress) { currentState, gestureState,
  199. _ in
  200. gestureState = currentState
  201. }
  202. .onEnded { _ in
  203. if completedLongPress {
  204. completedLongPress = false
  205. } else { completedLongPress = true }
  206. }
  207. }
  208. var longPresBGs: some Gesture {
  209. LongPressGesture(minimumDuration: 1)
  210. .updating($isDetectingLongPressOfBG) { currentState, gestureState,
  211. _ in
  212. gestureState = currentState
  213. }
  214. .onEnded { _ in
  215. if completedLongPressOfBG {
  216. completedLongPressOfBG = false
  217. } else { completedLongPressOfBG = true }
  218. }
  219. }
  220. var buttons: some View {
  221. HStack(alignment: .center) {
  222. NavigationLink(isActive: $state.isCarbsViewActive) {
  223. CarbsView()
  224. .environmentObject(state)
  225. } label: {
  226. Image("carbs", bundle: nil)
  227. .renderingMode(.template)
  228. .resizable()
  229. .frame(width: 24, height: 24)
  230. .foregroundColor(.loopYellow)
  231. }
  232. NavigationLink(isActive: $state.isTempTargetViewActive) {
  233. TempTargetsView()
  234. .environmentObject(state)
  235. } label: {
  236. VStack {
  237. Image("target", bundle: nil)
  238. .renderingMode(.template)
  239. .resizable()
  240. .frame(width: 24, height: 24)
  241. .foregroundColor(.loopGreen)
  242. if let until = state.tempTargets.compactMap(\.until).first, until > Date() {
  243. Text(until, style: .timer)
  244. .scaledToFill()
  245. .font(.system(size: 8))
  246. }
  247. }
  248. }
  249. NavigationLink(isActive: $state.isBolusViewActive) {
  250. BolusView()
  251. .environmentObject(state)
  252. } label: {
  253. Image("bolus", bundle: nil)
  254. .renderingMode(.template)
  255. .resizable()
  256. .frame(width: 24, height: 24)
  257. .foregroundColor(.insulin)
  258. }
  259. }
  260. }
  261. func start() {
  262. autorizeHealthKit()
  263. startHeartRateQuery(quantityTypeIdentifier: .heartRate)
  264. startStepsQuery(quantityTypeIdentifier: .stepCount)
  265. }
  266. func autorizeHealthKit() {
  267. let healthKitTypes: Set = [
  268. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!,
  269. HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
  270. ]
  271. healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { _, _ in }
  272. }
  273. private func startStepsQuery(quantityTypeIdentifier _: HKQuantityTypeIdentifier) {
  274. let type = HKQuantityType.quantityType(forIdentifier: .stepCount)!
  275. let now = Date()
  276. let startOfDay = Calendar.current.startOfDay(for: now)
  277. var interval = DateComponents()
  278. interval.day = 1
  279. let query = HKStatisticsCollectionQuery(
  280. quantityType: type,
  281. quantitySamplePredicate: nil,
  282. options: [.cumulativeSum],
  283. anchorDate: startOfDay,
  284. intervalComponents: interval
  285. )
  286. query.initialResultsHandler = { _, result, _ in
  287. var resultCount = 0.0
  288. guard let result = result else {
  289. self.steps = 0
  290. return
  291. }
  292. result.enumerateStatistics(from: startOfDay, to: now) { statistics, _ in
  293. if let sum = statistics.sumQuantity() {
  294. // Get steps (they are of double type)
  295. resultCount = sum.doubleValue(for: HKUnit.count())
  296. } // end if
  297. // Return
  298. self.steps = Int(resultCount)
  299. }
  300. }
  301. query.statisticsUpdateHandler = {
  302. _, statistics, _, _ in
  303. // If new statistics are available
  304. if let sum = statistics?.sumQuantity() {
  305. let resultCount = sum.doubleValue(for: HKUnit.count())
  306. // Return
  307. self.steps = Int(resultCount)
  308. } // end if
  309. }
  310. healthStore.execute(query)
  311. }
  312. private func startHeartRateQuery(quantityTypeIdentifier: HKQuantityTypeIdentifier) {
  313. let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
  314. let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = {
  315. _, samples, _, _, _ in
  316. guard let samples = samples as? [HKQuantitySample] else {
  317. return
  318. }
  319. self.process(samples, type: quantityTypeIdentifier)
  320. }
  321. let query = HKAnchoredObjectQuery(
  322. type: HKObjectType.quantityType(forIdentifier: quantityTypeIdentifier)!,
  323. predicate: devicePredicate,
  324. anchor: nil,
  325. limit: HKObjectQueryNoLimit,
  326. resultsHandler: updateHandler
  327. )
  328. query.updateHandler = updateHandler
  329. healthStore.execute(query)
  330. }
  331. private func process(_ samples: [HKQuantitySample], type: HKQuantityTypeIdentifier) {
  332. var lastHeartRate = 0.0
  333. for sample in samples {
  334. if type == .heartRate {
  335. lastHeartRate = sample.quantity.doubleValue(for: heartRateQuantity)
  336. }
  337. pulse = Int(lastHeartRate)
  338. }
  339. }
  340. private var iobFormatter: NumberFormatter {
  341. let formatter = NumberFormatter()
  342. formatter.maximumFractionDigits = 2
  343. formatter.numberStyle = .decimal
  344. return formatter
  345. }
  346. private var timeString: String {
  347. let minAgo = Int((Date().timeIntervalSince(state.lastLoopDate ?? .distantPast) - Config.lag) / 60) + 1
  348. if minAgo > 1440 {
  349. return "--"
  350. }
  351. return "\(minAgo) " + NSLocalizedString("min", comment: "Minutes ago since last loop")
  352. }
  353. private var color: Color {
  354. guard let lastLoopDate = state.lastLoopDate else {
  355. return .loopGray
  356. }
  357. let delta = Date().timeIntervalSince(lastLoopDate) - Config.lag
  358. if delta <= 5.minutes.timeInterval {
  359. return .loopGreen
  360. } else if delta <= 10.minutes.timeInterval {
  361. return .loopYellow
  362. } else {
  363. return .loopRed
  364. }
  365. }
  366. }
  367. struct ContentView_Previews: PreviewProvider {
  368. static var previews: some View {
  369. let state = WatchStateModel()
  370. state.glucose = "15,8"
  371. state.delta = "+888"
  372. state.iob = 100.38
  373. state.cob = 112.123
  374. state.lastLoopDate = Date().addingTimeInterval(-200)
  375. state
  376. .tempTargets =
  377. [TempTargetWatchPreset(name: "Test", id: "test", description: "", until: Date().addingTimeInterval(3600 * 3))]
  378. return Group {
  379. MainView()
  380. MainView().previewDevice("Apple Watch Series 5 - 40mm")
  381. MainView().previewDevice("Apple Watch Series 3 - 38mm")
  382. }.environmentObject(state)
  383. }
  384. }