MainView.swift 15 KB

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