MainChartView.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. import Algorithms
  2. import SwiftDate
  3. import SwiftUI
  4. private enum PredictionType: Hashable {
  5. case iob
  6. case cob
  7. case zt
  8. case uam
  9. }
  10. struct DotInfo {
  11. let rect: CGRect
  12. let value: Decimal
  13. }
  14. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  15. struct MainChartView: View {
  16. private enum Config {
  17. static let endID = "End"
  18. static let screenHours = 6
  19. static let basalHeight: CGFloat = 80
  20. static let topYPadding: CGFloat = 20
  21. static let bottomYPadding: CGFloat = 50
  22. static let minAdditionalWidth: CGFloat = 150
  23. static let maxGlucose = 250
  24. static let minGlucose = 50
  25. static let yLinesCount = 5
  26. static let glucoseScale: CGFloat = 2 // default 2
  27. static let bolusSize: CGFloat = 8
  28. static let bolusScale: CGFloat = 2.5
  29. static let carbsSize: CGFloat = 10
  30. static let carbsScale: CGFloat = 0.3
  31. static let upperTarget: CGFloat = 180
  32. static let lowerTarget: CGFloat = 70
  33. }
  34. @Binding var glucose: [BloodGlucose]
  35. @Binding var suggestion: Suggestion?
  36. @Binding var statistcs: Statistics?
  37. @Binding var tempBasals: [PumpHistoryEvent]
  38. @Binding var boluses: [PumpHistoryEvent]
  39. @Binding var suspensions: [PumpHistoryEvent]
  40. @Binding var hours: Int
  41. @Binding var maxBasal: Decimal
  42. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  43. @Binding var basalProfile: [BasalProfileEntry]
  44. @Binding var tempTargets: [TempTarget]
  45. @Binding var carbs: [CarbsEntry]
  46. @Binding var timerDate: Date
  47. @Binding var units: GlucoseUnits
  48. @State var didAppearTrigger = false
  49. @State private var glucoseDots: [CGRect] = []
  50. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  51. @State private var bolusDots: [DotInfo] = []
  52. @State private var bolusPath = Path()
  53. @State private var tempBasalPath = Path()
  54. @State private var regularBasalPath = Path()
  55. @State private var tempTargetsPath = Path()
  56. @State private var suspensionsPath = Path()
  57. @State private var carbsDots: [DotInfo] = []
  58. @State private var carbsPath = Path()
  59. @State private var fpuDots: [DotInfo] = []
  60. @State private var fpuPath = Path()
  61. @State private var glucoseYGange: GlucoseYRange = (0, 0, 0, 0)
  62. @State private var offset: CGFloat = 0
  63. @State private var cachedMaxBasalRate: Decimal?
  64. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  65. private var dateFormatter: DateFormatter {
  66. let formatter = DateFormatter()
  67. formatter.timeStyle = .short
  68. return formatter
  69. }
  70. private var glucoseFormatter: NumberFormatter {
  71. let formatter = NumberFormatter()
  72. formatter.numberStyle = .decimal
  73. formatter.maximumFractionDigits = 1
  74. return formatter
  75. }
  76. private var bolusFormatter: NumberFormatter {
  77. let formatter = NumberFormatter()
  78. formatter.numberStyle = .decimal
  79. formatter.minimumIntegerDigits = 0
  80. formatter.maximumFractionDigits = 2
  81. formatter.decimalSeparator = "."
  82. return formatter
  83. }
  84. private var carbsFormatter: NumberFormatter {
  85. let formatter = NumberFormatter()
  86. formatter.numberStyle = .decimal
  87. formatter.maximumFractionDigits = 0
  88. return formatter
  89. }
  90. private var fpuFormatter: NumberFormatter {
  91. let formatter = NumberFormatter()
  92. formatter.numberStyle = .decimal
  93. formatter.maximumFractionDigits = 1
  94. formatter.decimalSeparator = "."
  95. formatter.minimumIntegerDigits = 0
  96. return formatter
  97. }
  98. @Environment(\.horizontalSizeClass) var hSizeClass
  99. @Environment(\.verticalSizeClass) var vSizeClass
  100. // MARK: - Views
  101. var body: some View {
  102. GeometryReader { geo in
  103. ZStack(alignment: .leading) {
  104. yGridView(fullSize: geo.size)
  105. mainScrollView(fullSize: geo.size)
  106. glucoseLabelsView(fullSize: geo.size)
  107. }
  108. .onChange(of: hSizeClass) { _ in
  109. update(fullSize: geo.size)
  110. }
  111. .onChange(of: vSizeClass) { _ in
  112. update(fullSize: geo.size)
  113. }
  114. .onReceive(
  115. Foundation.NotificationCenter.default
  116. .publisher(for: UIDevice.orientationDidChangeNotification)
  117. ) { _ in
  118. update(fullSize: geo.size)
  119. }
  120. }
  121. }
  122. private func mainScrollView(fullSize: CGSize) -> some View {
  123. ScrollView(.horizontal, showsIndicators: false) {
  124. ScrollViewReader { scroll in
  125. ZStack(alignment: .top) {
  126. tempTargetsView(fullSize: fullSize).drawingGroup()
  127. basalView(fullSize: fullSize).drawingGroup()
  128. mainView(fullSize: fullSize).id(Config.endID)
  129. .drawingGroup()
  130. .onChange(of: glucose) { _ in
  131. scroll.scrollTo(Config.endID, anchor: .trailing)
  132. }
  133. .onChange(of: suggestion) { _ in
  134. scroll.scrollTo(Config.endID, anchor: .trailing)
  135. }
  136. .onChange(of: tempBasals) { _ in
  137. scroll.scrollTo(Config.endID, anchor: .trailing)
  138. }
  139. .onAppear {
  140. // add trigger to the end of main queue
  141. DispatchQueue.main.async {
  142. scroll.scrollTo(Config.endID, anchor: .trailing)
  143. didAppearTrigger = true
  144. }
  145. }
  146. }
  147. }
  148. }
  149. }
  150. private func yGridView(fullSize: CGSize) -> some View {
  151. ZStack {
  152. Path { path in
  153. let range = glucoseYGange
  154. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  155. for line in 0 ... Config.yLinesCount {
  156. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  157. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  158. }
  159. }.stroke(Color.secondary, lineWidth: 0.2)
  160. // horizontal limits
  161. let range = glucoseYGange
  162. let topstep = (range.maxY - range.minY) / CGFloat(range.maxValue - range.minValue) *
  163. (CGFloat(range.maxValue) - Config.upperTarget)
  164. if CGFloat(range.maxValue) > Config.upperTarget {
  165. Path { path in
  166. path.move(to: CGPoint(x: 0, y: range.minY + topstep))
  167. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + topstep))
  168. }.stroke(Color.loopYellow, lineWidth: 0.5)
  169. }
  170. let yrange = glucoseYGange
  171. let bottomstep = (yrange.maxY - yrange.minY) / CGFloat(yrange.maxValue - yrange.minValue) *
  172. (CGFloat(yrange.maxValue) - Config.lowerTarget)
  173. if CGFloat(yrange.minValue) < Config.lowerTarget {
  174. Path { path in
  175. path.move(to: CGPoint(x: 0, y: yrange.minY + bottomstep))
  176. path.addLine(to: CGPoint(x: fullSize.width, y: yrange.minY + bottomstep))
  177. }.stroke(Color.loopRed, lineWidth: 0.5)
  178. }
  179. }
  180. }
  181. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  182. ForEach(0 ..< Config.yLinesCount + 1, id: \.self) { line -> AnyView in
  183. let range = glucoseYGange
  184. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  185. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  186. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  187. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  188. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  189. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  190. .font(.caption2)
  191. .asAny()
  192. }
  193. }
  194. private func basalView(fullSize: CGSize) -> some View {
  195. ZStack {
  196. tempBasalPath.fill(Color.basal.opacity(0.5))
  197. tempBasalPath.stroke(Color.insulin, lineWidth: 1)
  198. regularBasalPath.stroke(Color.insulin, style: StrokeStyle(lineWidth: 0.7, dash: [4]))
  199. suspensionsPath.stroke(Color.loopGray.opacity(0.7), style: StrokeStyle(lineWidth: 0.7)).scaleEffect(x: 1, y: -1)
  200. suspensionsPath.fill(Color.loopGray.opacity(0.2)).scaleEffect(x: 1, y: -1)
  201. }
  202. .scaleEffect(x: 1, y: -1)
  203. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  204. .frame(maxHeight: Config.basalHeight)
  205. .background(Color.secondary.opacity(0.1))
  206. .onChange(of: tempBasals) { _ in
  207. calculateBasalPoints(fullSize: fullSize)
  208. }
  209. .onChange(of: suspensions) { _ in
  210. calculateSuspensions(fullSize: fullSize)
  211. }
  212. .onChange(of: maxBasal) { _ in
  213. calculateBasalPoints(fullSize: fullSize)
  214. }
  215. .onChange(of: autotunedBasalProfile) { _ in
  216. calculateBasalPoints(fullSize: fullSize)
  217. }
  218. .onChange(of: didAppearTrigger) { _ in
  219. calculateBasalPoints(fullSize: fullSize)
  220. }
  221. }
  222. private func mainView(fullSize: CGSize) -> some View {
  223. Group {
  224. VStack {
  225. ZStack {
  226. xGridView(fullSize: fullSize)
  227. carbsView(fullSize: fullSize)
  228. fpuView(fullSize: fullSize)
  229. bolusView(fullSize: fullSize)
  230. glucoseView(fullSize: fullSize)
  231. predictionsView(fullSize: fullSize)
  232. }
  233. timeLabelsView(fullSize: fullSize)
  234. }
  235. }
  236. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  237. }
  238. @Environment(\.colorScheme) var colorScheme
  239. private func xGridView(fullSize: CGSize) -> some View {
  240. ZStack {
  241. Path { path in
  242. for hour in 0 ..< hours + hours {
  243. let x = firstHourPosition(viewWidth: fullSize.width) +
  244. oneSecondStep(viewWidth: fullSize.width) *
  245. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  246. path.move(to: CGPoint(x: x, y: 0))
  247. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  248. }
  249. }
  250. .stroke(Color.secondary, lineWidth: 0.2)
  251. Path { path in // vertical timeline
  252. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize)
  253. path.move(to: CGPoint(x: x, y: 0))
  254. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  255. }
  256. .stroke(
  257. colorScheme == .dark ? Color.white : Color.black,
  258. style: StrokeStyle(lineWidth: 0.5, dash: [5])
  259. )
  260. }
  261. }
  262. private func timeLabelsView(fullSize: CGSize) -> some View {
  263. ZStack {
  264. // X time labels
  265. ForEach(0 ..< hours + hours) { hour in
  266. Text(dateFormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  267. .font(.caption)
  268. .position(
  269. x: firstHourPosition(viewWidth: fullSize.width) +
  270. oneSecondStep(viewWidth: fullSize.width) *
  271. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  272. y: 10.0
  273. )
  274. .foregroundColor(.secondary)
  275. }
  276. }.frame(maxHeight: 20)
  277. }
  278. private func glucoseView(fullSize: CGSize) -> some View {
  279. Path { path in
  280. for rect in glucoseDots {
  281. path.addEllipse(in: rect)
  282. }
  283. }
  284. .fill(Color.loopGreen)
  285. .onChange(of: glucose) { _ in
  286. update(fullSize: fullSize)
  287. }
  288. .onChange(of: didAppearTrigger) { _ in
  289. update(fullSize: fullSize)
  290. }
  291. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  292. update(fullSize: fullSize)
  293. }
  294. }
  295. private func bolusView(fullSize: CGSize) -> some View {
  296. ZStack {
  297. bolusPath
  298. .fill(Color.insulin)
  299. bolusPath
  300. .stroke(Color.primary, lineWidth: 0.5)
  301. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  302. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  303. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  304. .position(position)
  305. .asAny()
  306. }
  307. }
  308. .onChange(of: boluses) { _ in
  309. calculateBolusDots(fullSize: fullSize)
  310. }
  311. .onChange(of: didAppearTrigger) { _ in
  312. calculateBolusDots(fullSize: fullSize)
  313. }
  314. }
  315. private func carbsView(fullSize: CGSize) -> some View {
  316. ZStack {
  317. carbsPath
  318. .fill(Color.loopYellow)
  319. carbsPath
  320. .stroke(Color.primary, lineWidth: 0.5)
  321. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  322. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  323. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  324. .position(position)
  325. .asAny()
  326. }
  327. }
  328. .onChange(of: carbs) { _ in
  329. calculateCarbsDots(fullSize: fullSize)
  330. }
  331. .onChange(of: didAppearTrigger) { _ in
  332. calculateCarbsDots(fullSize: fullSize)
  333. }
  334. }
  335. private func fpuView(fullSize: CGSize) -> some View {
  336. ZStack {
  337. fpuPath
  338. .fill(Color.red)
  339. fpuPath
  340. .stroke(Color.primary, lineWidth: 0.5)
  341. ForEach(fpuDots, id: \.rect.minX) { info -> AnyView in
  342. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  343. return Text(fpuFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  344. .position(position)
  345. .asAny()
  346. }
  347. }
  348. .onChange(of: carbs) { _ in
  349. calculateFPUsDots(fullSize: fullSize)
  350. }
  351. .onChange(of: didAppearTrigger) { _ in
  352. calculateFPUsDots(fullSize: fullSize)
  353. }
  354. }
  355. private func tempTargetsView(fullSize: CGSize) -> some View {
  356. ZStack {
  357. tempTargetsPath
  358. .fill(Color.tempBasal.opacity(0.5))
  359. tempTargetsPath
  360. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  361. }
  362. .onChange(of: glucose) { _ in
  363. calculateTempTargetsRects(fullSize: fullSize)
  364. }
  365. .onChange(of: tempTargets) { _ in
  366. calculateTempTargetsRects(fullSize: fullSize)
  367. }
  368. .onChange(of: didAppearTrigger) { _ in
  369. calculateTempTargetsRects(fullSize: fullSize)
  370. }
  371. }
  372. private func predictionsView(fullSize: CGSize) -> some View {
  373. Group {
  374. Path { path in
  375. for rect in predictionDots[.iob] ?? [] {
  376. path.addEllipse(in: rect)
  377. }
  378. }.fill(Color.insulin)
  379. Path { path in
  380. for rect in predictionDots[.cob] ?? [] {
  381. path.addEllipse(in: rect)
  382. }
  383. }.fill(Color.loopYellow)
  384. Path { path in
  385. for rect in predictionDots[.zt] ?? [] {
  386. path.addEllipse(in: rect)
  387. }
  388. }.fill(Color.zt)
  389. Path { path in
  390. for rect in predictionDots[.uam] ?? [] {
  391. path.addEllipse(in: rect)
  392. }
  393. }.fill(Color.uam)
  394. }
  395. .onChange(of: suggestion) { _ in
  396. update(fullSize: fullSize)
  397. }
  398. }
  399. }
  400. // MARK: - Calculations
  401. extension MainChartView {
  402. private func update(fullSize: CGSize) {
  403. calculatePredictionDots(fullSize: fullSize, type: .iob)
  404. calculatePredictionDots(fullSize: fullSize, type: .cob)
  405. calculatePredictionDots(fullSize: fullSize, type: .zt)
  406. calculatePredictionDots(fullSize: fullSize, type: .uam)
  407. calculateGlucoseDots(fullSize: fullSize)
  408. calculateBolusDots(fullSize: fullSize)
  409. calculateCarbsDots(fullSize: fullSize)
  410. calculateFPUsDots(fullSize: fullSize)
  411. calculateTempTargetsRects(fullSize: fullSize)
  412. calculateBasalPoints(fullSize: fullSize)
  413. calculateSuspensions(fullSize: fullSize)
  414. }
  415. private func calculateGlucoseDots(fullSize: CGSize) {
  416. calculationQueue.async {
  417. let dots = glucose.concurrentMap { value -> CGRect in
  418. let position = glucoseToCoordinate(value, fullSize: fullSize)
  419. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  420. }
  421. let range = self.getGlucoseYRange(fullSize: fullSize)
  422. DispatchQueue.main.async {
  423. glucoseYGange = range
  424. glucoseDots = dots
  425. }
  426. }
  427. }
  428. private func calculateBolusDots(fullSize: CGSize) {
  429. calculationQueue.async {
  430. let dots = boluses.map { value -> DotInfo in
  431. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  432. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  433. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  434. return DotInfo(rect: rect, value: value.amount ?? 0)
  435. }
  436. let path = Path { path in
  437. for dot in dots {
  438. path.addEllipse(in: dot.rect)
  439. }
  440. }
  441. DispatchQueue.main.async {
  442. bolusDots = dots
  443. bolusPath = path
  444. }
  445. }
  446. }
  447. private func calculateCarbsDots(fullSize: CGSize) {
  448. calculationQueue.async {
  449. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  450. let dots = realCarbs.map { value -> DotInfo in
  451. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  452. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  453. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  454. return DotInfo(rect: rect, value: value.carbs)
  455. }
  456. let path = Path { path in
  457. for dot in dots {
  458. path.addEllipse(in: dot.rect)
  459. }
  460. }
  461. DispatchQueue.main.async {
  462. carbsDots = dots
  463. carbsPath = path
  464. }
  465. }
  466. }
  467. private func calculateFPUsDots(fullSize: CGSize) {
  468. calculationQueue.async {
  469. let fpus = carbs.filter { $0.isFPU ?? false }
  470. let dots = fpus.map { value -> DotInfo in
  471. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  472. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  473. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  474. return DotInfo(rect: rect, value: value.carbs)
  475. }
  476. let path = Path { path in
  477. for dot in dots {
  478. path.addEllipse(in: dot.rect)
  479. }
  480. }
  481. DispatchQueue.main.async {
  482. fpuDots = dots
  483. fpuPath = path
  484. }
  485. }
  486. }
  487. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  488. calculationQueue.async {
  489. let values: [Int] = { () -> [Int] in
  490. switch type {
  491. case .iob:
  492. return suggestion?.predictions?.iob ?? []
  493. case .cob:
  494. return suggestion?.predictions?.cob ?? []
  495. case .zt:
  496. return suggestion?.predictions?.zt ?? []
  497. case .uam:
  498. return suggestion?.predictions?.uam ?? []
  499. }
  500. }()
  501. var index = 0
  502. let dots = values.map { value -> CGRect in
  503. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  504. index += 1
  505. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  506. }
  507. DispatchQueue.main.async {
  508. predictionDots[type] = dots
  509. }
  510. }
  511. }
  512. private func calculateBasalPoints(fullSize: CGSize) {
  513. calculationQueue.async {
  514. self.cachedMaxBasalRate = nil
  515. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  516. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  517. var lastTimeEnd = firstTempTime
  518. let firstRegularBasalPoints = findRegularBasalPoints(
  519. timeBegin: dayAgoTime,
  520. timeEnd: firstTempTime,
  521. fullSize: fullSize,
  522. autotuned: false
  523. )
  524. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  525. let chunk = Array(chunk)
  526. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  527. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  528. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  529. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  530. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  531. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  532. let regularPoints = findRegularBasalPoints(
  533. timeBegin: lastTimeEnd,
  534. timeEnd: timeBegin,
  535. fullSize: fullSize,
  536. autotuned: false
  537. )
  538. lastTimeEnd = timeEnd
  539. return regularPoints + [CGPoint(x: x0, y: y0)]
  540. }.flatMap { $0 }
  541. let tempBasalPath = Path { path in
  542. var yPoint: CGFloat = Config.basalHeight
  543. path.move(to: CGPoint(x: 0, y: yPoint))
  544. for point in tempBasalPoints {
  545. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  546. path.addLine(to: point)
  547. yPoint = point.y
  548. }
  549. let lastPoint = lastBasalPoint(fullSize: fullSize)
  550. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  551. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  552. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  553. }
  554. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  555. let autotunedBasalPoints = findRegularBasalPoints(
  556. timeBegin: dayAgoTime,
  557. timeEnd: endDateTime,
  558. fullSize: fullSize,
  559. autotuned: true
  560. )
  561. let autotunedBasalPath = Path { path in
  562. var yPoint: CGFloat = Config.basalHeight
  563. path.move(to: CGPoint(x: -50, y: yPoint))
  564. for point in autotunedBasalPoints {
  565. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  566. path.addLine(to: point)
  567. yPoint = point.y
  568. }
  569. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  570. }
  571. DispatchQueue.main.async {
  572. self.tempBasalPath = tempBasalPath
  573. self.regularBasalPath = autotunedBasalPath
  574. }
  575. }
  576. }
  577. private func calculateSuspensions(fullSize: CGSize) {
  578. calculationQueue.async {
  579. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  580. let window = Array(window)
  581. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  582. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  583. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  584. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  585. }
  586. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  587. guard event.type == .pumpResume else { return nil }
  588. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  589. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  590. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  591. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  592. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  593. return CGRect(
  594. x: x0,
  595. y: 0,
  596. width: x1 - x0,
  597. height: Config.basalHeight * 0.7
  598. )
  599. }
  600. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  601. guard event.type == .pumpSuspend else { return nil }
  602. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  603. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  604. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  605. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  606. .additionalWidth(viewWidth: fullSize.width)
  607. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  608. }
  609. rects.append(firstRec)
  610. rects.append(lastRec)
  611. let path = Path { path in
  612. path.addRects(rects.compactMap { $0 })
  613. }
  614. DispatchQueue.main.async {
  615. suspensionsPath = path
  616. }
  617. }
  618. }
  619. private func maxBasalRate() -> Decimal {
  620. if let cached = cachedMaxBasalRate {
  621. return cached
  622. }
  623. let maxRegularBasalRate = max(
  624. basalProfile.map(\.rate).max() ?? maxBasal,
  625. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  626. )
  627. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  628. if maxTempBasalRate == 0 {
  629. maxTempBasalRate = maxRegularBasalRate
  630. }
  631. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  632. return cachedMaxBasalRate ?? maxBasal
  633. }
  634. private func calculateTempTargetsRects(fullSize: CGSize) {
  635. calculationQueue.async {
  636. var rects = tempTargets.map { tempTarget -> CGRect in
  637. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  638. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  639. let x1 = timeToXCoordinate(
  640. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  641. fullSize: fullSize
  642. )
  643. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  644. return CGRect(
  645. x: x0,
  646. y: y0 - 3,
  647. width: x1 - x0,
  648. height: y1 - y0 + 6
  649. )
  650. }
  651. if rects.count > 1 {
  652. rects = rects.reduce([]) { result, rect -> [CGRect] in
  653. guard var last = result.last else { return [rect] }
  654. if last.origin.x + last.width > rect.origin.x {
  655. last.size.width = rect.origin.x - last.origin.x
  656. }
  657. var res = Array(result.dropLast())
  658. res.append(contentsOf: [last, rect])
  659. return res
  660. }
  661. }
  662. let path = Path { path in
  663. path.addRects(rects)
  664. }
  665. DispatchQueue.main.async {
  666. tempTargetsPath = path
  667. }
  668. }
  669. }
  670. private func findRegularBasalPoints(
  671. timeBegin: TimeInterval,
  672. timeEnd: TimeInterval,
  673. fullSize: CGSize,
  674. autotuned: Bool
  675. ) -> [CGPoint] {
  676. guard timeBegin < timeEnd else {
  677. return []
  678. }
  679. let beginDate = Date(timeIntervalSince1970: timeBegin)
  680. let calendar = Calendar.current
  681. let startOfDay = calendar.startOfDay(for: beginDate)
  682. let profile = autotuned ? autotunedBasalProfile : basalProfile
  683. let basalNormalized = profile.map {
  684. (
  685. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  686. rate: $0.rate
  687. )
  688. } + profile.map {
  689. (
  690. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  691. rate: $0.rate
  692. )
  693. } + profile.map {
  694. (
  695. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  696. rate: $0.rate
  697. )
  698. }
  699. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  700. .compactMap { window -> CGPoint? in
  701. let window = Array(window)
  702. if window[0].time < timeBegin, window[1].time < timeBegin {
  703. return nil
  704. }
  705. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  706. if window[0].time < timeBegin, window[1].time >= timeBegin {
  707. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  708. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  709. return CGPoint(x: x, y: y)
  710. }
  711. if window[0].time >= timeBegin, window[0].time < timeEnd {
  712. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  713. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  714. return CGPoint(x: x, y: y)
  715. }
  716. return nil
  717. }
  718. return basalTruncatedPoints
  719. }
  720. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  721. let lastBasal = Array(tempBasals.suffix(2))
  722. guard lastBasal.count == 2 else {
  723. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  724. }
  725. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  726. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  727. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  728. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  729. return CGPoint(x: x, y: y)
  730. }
  731. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  732. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  733. }
  734. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  735. guard let predictions = suggestion?.predictions,
  736. let deliveredAt = suggestion?.deliverAt,
  737. let last = glucose.last
  738. else {
  739. return Config.minAdditionalWidth
  740. }
  741. let iob = predictions.iob?.count ?? 0
  742. let zt = predictions.zt?.count ?? 0
  743. let cob = predictions.cob?.count ?? 0
  744. let uam = predictions.uam?.count ?? 0
  745. let max = [iob, zt, cob, uam].max() ?? 0
  746. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  747. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  748. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  749. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  750. }
  751. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  752. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  753. }
  754. private func maxPredValue() -> Int? {
  755. [
  756. suggestion?.predictions?.cob ?? [],
  757. suggestion?.predictions?.iob ?? [],
  758. suggestion?.predictions?.zt ?? [],
  759. suggestion?.predictions?.uam ?? []
  760. ]
  761. .flatMap { $0 }
  762. .max()
  763. }
  764. private func minPredValue() -> Int? {
  765. [
  766. suggestion?.predictions?.cob ?? [],
  767. suggestion?.predictions?.iob ?? [],
  768. suggestion?.predictions?.zt ?? [],
  769. suggestion?.predictions?.uam ?? []
  770. ]
  771. .flatMap { $0 }
  772. .min()
  773. }
  774. private func maxTargetValue() -> Int? {
  775. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  776. }
  777. private func minTargetValue() -> Int? {
  778. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  779. }
  780. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  781. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  782. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  783. return CGPoint(x: x, y: y)
  784. }
  785. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  786. guard let deliveredAt = suggestion?.deliverAt else {
  787. return .zero
  788. }
  789. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  790. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  791. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  792. return CGPoint(x: x, y: y)
  793. }
  794. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  795. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  796. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  797. let x = CGFloat(time + xOffset) * stepXFraction
  798. return x
  799. }
  800. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  801. let topYPaddint = Config.topYPadding + Config.basalHeight
  802. let bottomYPadding = Config.bottomYPadding
  803. let (minValue, maxValue) = minMaxYValues()
  804. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  805. let yOffset = CGFloat(minValue) * stepYFraction
  806. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  807. return y
  808. }
  809. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  810. var nextIndex = 0
  811. for (index, value) in glucose.enumerated() {
  812. if value.dateString.timeIntervalSince1970 > time {
  813. nextIndex = index
  814. break
  815. }
  816. }
  817. let x = timeToXCoordinate(time, fullSize: fullSize)
  818. guard nextIndex > 0 else {
  819. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  820. return CGPoint(x: x, y: lastY)
  821. }
  822. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  823. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  824. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  825. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  826. let delta = nextX - prevX
  827. let fraction = (x - prevX) / delta
  828. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  829. }
  830. private func minMaxYValues() -> (min: Int, max: Int) {
  831. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  832. if let maxPredValue = maxPredValue() {
  833. maxValue = max(maxValue, maxPredValue)
  834. }
  835. if let maxTargetValue = maxTargetValue() {
  836. maxValue = max(maxValue, maxTargetValue)
  837. }
  838. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  839. if let minPredValue = minPredValue() {
  840. minValue = min(minValue, minPredValue)
  841. }
  842. if let minTargetValue = minTargetValue() {
  843. minValue = min(minValue, minTargetValue)
  844. }
  845. if minValue == maxValue {
  846. minValue = Config.minGlucose
  847. maxValue = Config.maxGlucose
  848. }
  849. // fix the grah y-axis as long as the min and max BG values are within set borders
  850. if minValue > Config.minGlucose {
  851. minValue = Config.minGlucose
  852. }
  853. if maxValue < Config.maxGlucose {
  854. maxValue = Config.maxGlucose
  855. }
  856. return (min: minValue, max: maxValue)
  857. }
  858. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  859. let topYPaddint = Config.topYPadding + Config.basalHeight
  860. let bottomYPadding = Config.bottomYPadding
  861. let (minValue, maxValue) = minMaxYValues()
  862. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  863. let yOffset = CGFloat(minValue) * stepYFraction
  864. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  865. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  866. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  867. }
  868. private func firstHourDate() -> Date {
  869. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  870. return firstDate.dateTruncated(from: .minute)!
  871. }
  872. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  873. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  874. let firstHour = firstHourDate()
  875. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  876. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  877. return oneSecondWidth * CGFloat(lastDeltaTime)
  878. }
  879. }