MainView.swift 12 KB

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