MainChartView.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 = 70
  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 = 2.5
  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. @Binding var 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 dateFormatter: 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(dateFormatter.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 tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  495. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  496. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  497. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  498. .additionalWidth(viewWidth: fullSize.width)
  499. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight)
  500. }
  501. rects.append(firstRec)
  502. rects.append(lastRec)
  503. let path = Path { path in
  504. path.addRects(rects.compactMap { $0 })
  505. }
  506. DispatchQueue.main.async {
  507. suspensionsPath = path
  508. }
  509. }
  510. }
  511. private func maxBasalRate() -> Decimal {
  512. if let cached = cachedMaxBasalRate {
  513. return cached
  514. }
  515. let maxRegularBasalRate = max(
  516. basalProfile.map(\.rate).max() ?? maxBasal,
  517. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  518. )
  519. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  520. if maxTempBasalRate == 0 {
  521. maxTempBasalRate = maxRegularBasalRate
  522. }
  523. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  524. return cachedMaxBasalRate!
  525. }
  526. private func calculateTempTargetsRects(fullSize: CGSize) {
  527. calculationQueue.async {
  528. var rects = tempTargets.map { tempTarget -> CGRect in
  529. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  530. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  531. let x1 = timeToXCoordinate(
  532. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  533. fullSize: fullSize
  534. )
  535. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  536. return CGRect(
  537. x: x0,
  538. y: y0 - 3,
  539. width: x1 - x0,
  540. height: y1 - y0 + 6
  541. )
  542. }
  543. if rects.count > 1 {
  544. rects = rects.reduce([]) { result, rect -> [CGRect] in
  545. guard var last = result.last else { return [rect] }
  546. if last.origin.x + last.width > rect.origin.x {
  547. last.size.width = rect.origin.x - last.origin.x
  548. }
  549. var res = Array(result.dropLast())
  550. res.append(contentsOf: [last, rect])
  551. return res
  552. }
  553. }
  554. let path = Path { path in
  555. path.addRects(rects)
  556. }
  557. DispatchQueue.main.async {
  558. tempTargetsPath = path
  559. }
  560. }
  561. }
  562. private func findRegularBasalPoints(
  563. timeBegin: TimeInterval,
  564. timeEnd: TimeInterval,
  565. fullSize: CGSize,
  566. autotuned: Bool
  567. ) -> [CGPoint] {
  568. guard timeBegin < timeEnd else {
  569. return []
  570. }
  571. let beginDate = Date(timeIntervalSince1970: timeBegin)
  572. let calendar = Calendar.current
  573. let startOfDay = calendar.startOfDay(for: beginDate)
  574. let profile = autotuned ? autotunedBasalProfile : basalProfile
  575. let basalNormalized = profile.map {
  576. (
  577. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  578. rate: $0.rate
  579. )
  580. } + profile.map {
  581. (
  582. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  583. rate: $0.rate
  584. )
  585. } + profile.map {
  586. (
  587. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  588. rate: $0.rate
  589. )
  590. }
  591. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  592. .compactMap { window -> CGPoint? in
  593. let window = Array(window)
  594. if window[0].time < timeBegin, window[1].time < timeBegin {
  595. return nil
  596. }
  597. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  598. if window[0].time < timeBegin, window[1].time >= timeBegin {
  599. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  600. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  601. return CGPoint(x: x, y: y)
  602. }
  603. if window[0].time >= timeBegin, window[0].time < timeEnd {
  604. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  605. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  606. return CGPoint(x: x, y: y)
  607. }
  608. return nil
  609. }
  610. return basalTruncatedPoints
  611. }
  612. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  613. let lastBasal = Array(tempBasals.suffix(2))
  614. guard lastBasal.count == 2 else {
  615. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  616. }
  617. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  618. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  619. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  620. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  621. return CGPoint(x: x, y: y)
  622. }
  623. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  624. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  625. }
  626. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  627. guard let predictions = suggestion?.predictions,
  628. let deliveredAt = suggestion?.deliverAt,
  629. let last = glucose.last
  630. else {
  631. return Config.minAdditionalWidth
  632. }
  633. let iob = predictions.iob?.count ?? 0
  634. let zt = predictions.zt?.count ?? 0
  635. let cob = predictions.cob?.count ?? 0
  636. let uam = predictions.uam?.count ?? 0
  637. let max = [iob, zt, cob, uam].max() ?? 0
  638. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  639. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  640. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  641. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  642. }
  643. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  644. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  645. }
  646. private func maxPredValue() -> Int? {
  647. [
  648. suggestion?.predictions?.cob ?? [],
  649. suggestion?.predictions?.iob ?? [],
  650. suggestion?.predictions?.zt ?? [],
  651. suggestion?.predictions?.uam ?? []
  652. ]
  653. .flatMap { $0 }
  654. .max()
  655. }
  656. private func minPredValue() -> Int? {
  657. [
  658. suggestion?.predictions?.cob ?? [],
  659. suggestion?.predictions?.iob ?? [],
  660. suggestion?.predictions?.zt ?? [],
  661. suggestion?.predictions?.uam ?? []
  662. ]
  663. .flatMap { $0 }
  664. .min()
  665. }
  666. private func maxTargetValue() -> Int? {
  667. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  668. }
  669. private func minTargetValue() -> Int? {
  670. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  671. }
  672. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  673. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  674. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  675. return CGPoint(x: x, y: y)
  676. }
  677. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  678. guard let deliveredAt = suggestion?.deliverAt else {
  679. return .zero
  680. }
  681. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  682. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  683. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  684. return CGPoint(x: x, y: y)
  685. }
  686. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  687. let xOffset = -(
  688. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  689. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  690. )
  691. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  692. let x = CGFloat(time + xOffset) * stepXFraction
  693. return x
  694. }
  695. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  696. let topYPaddint = Config.topYPadding + Config.basalHeight
  697. let bottomYPadding = Config.bottomYPadding
  698. let (minValue, maxValue) = minMaxYValues()
  699. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  700. let yOffset = CGFloat(minValue) * stepYFraction
  701. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  702. return y
  703. }
  704. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  705. var nextIndex = 0
  706. for (index, value) in glucose.enumerated() {
  707. if value.dateString.timeIntervalSince1970 > time {
  708. nextIndex = index
  709. break
  710. }
  711. }
  712. let x = timeToXCoordinate(time, fullSize: fullSize)
  713. guard nextIndex > 0 else {
  714. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  715. return CGPoint(x: x, y: lastY)
  716. }
  717. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  718. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  719. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  720. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  721. let delta = nextX - prevX
  722. let fraction = (x - prevX) / delta
  723. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  724. }
  725. private func minMaxYValues() -> (min: Int, max: Int) {
  726. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  727. if let maxPredValue = maxPredValue() {
  728. maxValue = max(maxValue, maxPredValue)
  729. }
  730. if let maxTargetValue = maxTargetValue() {
  731. maxValue = max(maxValue, maxTargetValue)
  732. }
  733. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  734. if let minPredValue = minPredValue() {
  735. minValue = min(minValue, minPredValue)
  736. }
  737. if let minTargetValue = minTargetValue() {
  738. minValue = min(minValue, minTargetValue)
  739. }
  740. return (min: minValue, max: maxValue)
  741. }
  742. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  743. let topYPaddint = Config.topYPadding + Config.basalHeight
  744. let bottomYPadding = Config.bottomYPadding
  745. let (minValue, maxValue) = minMaxYValues()
  746. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  747. let yOffset = CGFloat(minValue) * stepYFraction
  748. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  749. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  750. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  751. }
  752. private func firstHourDate() -> Date {
  753. let firstDate = glucose.first?.dateString ?? Date()
  754. return firstDate.dateTruncated(from: .minute)!
  755. }
  756. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  757. let firstDate = glucose.first?.dateString ?? Date()
  758. let firstHour = firstHourDate()
  759. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  760. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  761. return oneSecondWidth * CGFloat(lastDeltaTime)
  762. }
  763. }