MainChartView.swift 33 KB

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