MainChartView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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.opacity(0.5)).scaleEffect(x: 1, y: -1)
  148. tempBasalPath.stroke(Color.tempBasal, lineWidth: 1).scaleEffect(x: 1, y: -1)
  149. regularBasalPath.stroke(Color.tempBasal, style: StrokeStyle(lineWidth: 1, dash: [3])).scaleEffect(x: 1, y: -1)
  150. }
  151. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  152. .frame(maxHeight: Config.basalHeight)
  153. .background(Color.secondary.opacity(0.1))
  154. .onChange(of: tempBasals) { _ in
  155. calculateBasalPoints(fullSize: fullSize)
  156. }
  157. .onChange(of: suspensions) { _ in
  158. calculateSuspensions(fullSize: fullSize)
  159. }
  160. .onChange(of: maxBasal) { _ in
  161. calculateBasalPoints(fullSize: fullSize)
  162. }
  163. .onChange(of: autotunedBasalProfile) { _ in
  164. calculateBasalPoints(fullSize: fullSize)
  165. }
  166. .onChange(of: didAppearTrigger) { _ in
  167. calculateBasalPoints(fullSize: fullSize)
  168. }
  169. }
  170. private func mainView(fullSize: CGSize) -> some View {
  171. Group {
  172. VStack {
  173. ZStack {
  174. xGridView(fullSize: fullSize)
  175. carbsView(fullSize: fullSize)
  176. bolusView(fullSize: fullSize)
  177. glucoseView(fullSize: fullSize)
  178. predictionsView(fullSize: fullSize)
  179. }
  180. timeLabelsView(fullSize: fullSize)
  181. }
  182. }
  183. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  184. }
  185. @Environment(\.colorScheme) var colorScheme
  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(colorScheme == .dark ? Color.white : Color.black, // current time as vertical line
  204. style: StrokeStyle(lineWidth: 0.5, dash: [2])
  205. )
  206. }
  207. }
  208. private func timeLabelsView(fullSize: CGSize) -> some View {
  209. ZStack {
  210. // X time labels
  211. ForEach(0 ..< hours + hours) { hour in
  212. Text(dateFormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  213. .font(.caption)
  214. .position(
  215. x: firstHourPosition(viewWidth: fullSize.width) +
  216. oneSecondStep(viewWidth: fullSize.width) *
  217. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  218. y: 10.0
  219. )
  220. .foregroundColor(.secondary)
  221. }
  222. }.frame(maxHeight: 20)
  223. }
  224. private func glucoseView(fullSize: CGSize) -> some View {
  225. Path { path in
  226. for rect in glucoseDots {
  227. path.addEllipse(in: rect)
  228. }
  229. }
  230. .fill(Color.loopGreen)
  231. .onChange(of: glucose) { _ in
  232. update(fullSize: fullSize)
  233. }
  234. .onChange(of: didAppearTrigger) { _ in
  235. update(fullSize: fullSize)
  236. }
  237. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  238. update(fullSize: fullSize)
  239. }
  240. }
  241. private func bolusView(fullSize: CGSize) -> some View {
  242. ZStack {
  243. bolusPath
  244. .fill(Color.insulin)
  245. bolusPath
  246. .stroke(Color.primary, lineWidth: 0.5)
  247. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  248. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  249. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  250. .position(position)
  251. .asAny()
  252. }
  253. }
  254. .onChange(of: boluses) { _ in
  255. calculateBolusDots(fullSize: fullSize)
  256. }
  257. .onChange(of: didAppearTrigger) { _ in
  258. calculateBolusDots(fullSize: fullSize)
  259. }
  260. }
  261. private func carbsView(fullSize: CGSize) -> some View {
  262. ZStack {
  263. carbsPath
  264. .fill(Color.loopYellow)
  265. carbsPath
  266. .stroke(Color.primary, lineWidth: 0.5)
  267. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  268. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  269. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  270. .position(position)
  271. .asAny()
  272. }
  273. }
  274. .onChange(of: carbs) { _ in
  275. calculateCarbsDots(fullSize: fullSize)
  276. }
  277. .onChange(of: didAppearTrigger) { _ in
  278. calculateCarbsDots(fullSize: fullSize)
  279. }
  280. }
  281. private func tempTargetsView(fullSize: CGSize) -> some View {
  282. ZStack {
  283. tempTargetsPath
  284. .fill(Color.tempBasal.opacity(0.5))
  285. }
  286. .onChange(of: glucose) { _ in
  287. calculateTempTargetsRects(fullSize: fullSize)
  288. }
  289. .onChange(of: tempTargets) { _ in
  290. calculateTempTargetsRects(fullSize: fullSize)
  291. }
  292. .onChange(of: didAppearTrigger) { _ in
  293. calculateTempTargetsRects(fullSize: fullSize)
  294. }
  295. }
  296. private func predictionsView(fullSize: CGSize) -> some View {
  297. Group {
  298. Path { path in
  299. for rect in predictionDots[.iob] ?? [] {
  300. path.addEllipse(in: rect)
  301. }
  302. }.fill(Color.insulin)
  303. Path { path in
  304. for rect in predictionDots[.cob] ?? [] {
  305. path.addEllipse(in: rect)
  306. }
  307. }.fill(Color.loopYellow)
  308. Path { path in
  309. for rect in predictionDots[.zt] ?? [] {
  310. path.addEllipse(in: rect)
  311. }
  312. }.fill(Color.zt)
  313. Path { path in
  314. for rect in predictionDots[.uam] ?? [] {
  315. path.addEllipse(in: rect)
  316. }
  317. }.fill(Color.uam)
  318. }
  319. .onChange(of: suggestion) { _ in
  320. update(fullSize: fullSize)
  321. }
  322. }
  323. }
  324. // MARK: - Calculations
  325. extension MainChartView {
  326. private func update(fullSize: CGSize) {
  327. calculatePredictionDots(fullSize: fullSize, type: .iob)
  328. calculatePredictionDots(fullSize: fullSize, type: .cob)
  329. calculatePredictionDots(fullSize: fullSize, type: .zt)
  330. calculatePredictionDots(fullSize: fullSize, type: .uam)
  331. calculateGlucoseDots(fullSize: fullSize)
  332. calculateBolusDots(fullSize: fullSize)
  333. calculateCarbsDots(fullSize: fullSize)
  334. calculateTempTargetsRects(fullSize: fullSize)
  335. calculateTempTargetsRects(fullSize: fullSize)
  336. calculateBasalPoints(fullSize: fullSize)
  337. calculateSuspensions(fullSize: fullSize)
  338. }
  339. private func calculateGlucoseDots(fullSize: CGSize) {
  340. calculationQueue.async {
  341. let dots = glucose.concurrentMap { value -> CGRect in
  342. let position = glucoseToCoordinate(value, fullSize: fullSize)
  343. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  344. }
  345. let range = self.getGlucoseYRange(fullSize: fullSize)
  346. DispatchQueue.main.async {
  347. glucoseYGange = range
  348. glucoseDots = dots
  349. }
  350. }
  351. }
  352. private func calculateBolusDots(fullSize: CGSize) {
  353. calculationQueue.async {
  354. let dots = boluses.map { value -> DotInfo in
  355. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  356. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  357. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  358. return DotInfo(rect: rect, value: value.amount ?? 0)
  359. }
  360. let path = Path { path in
  361. for dot in dots {
  362. path.addEllipse(in: dot.rect)
  363. }
  364. }
  365. DispatchQueue.main.async {
  366. bolusDots = dots
  367. bolusPath = path
  368. }
  369. }
  370. }
  371. private func calculateCarbsDots(fullSize: CGSize) {
  372. calculationQueue.async {
  373. let dots = carbs.map { value -> DotInfo in
  374. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  375. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  376. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  377. return DotInfo(rect: rect, value: value.carbs)
  378. }
  379. let path = Path { path in
  380. for dot in dots {
  381. path.addEllipse(in: dot.rect)
  382. }
  383. }
  384. DispatchQueue.main.async {
  385. carbsDots = dots
  386. carbsPath = path
  387. }
  388. }
  389. }
  390. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  391. calculationQueue.async {
  392. let values: [Int] = { () -> [Int] in
  393. switch type {
  394. case .iob:
  395. return suggestion?.predictions?.iob ?? []
  396. case .cob:
  397. return suggestion?.predictions?.cob ?? []
  398. case .zt:
  399. return suggestion?.predictions?.zt ?? []
  400. case .uam:
  401. return suggestion?.predictions?.uam ?? []
  402. }
  403. }()
  404. var index = 0
  405. let dots = values.map { value -> CGRect in
  406. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  407. index += 1
  408. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  409. }
  410. DispatchQueue.main.async {
  411. predictionDots[type] = dots
  412. }
  413. }
  414. }
  415. private func calculateBasalPoints(fullSize: CGSize) {
  416. calculationQueue.async {
  417. self.cachedMaxBasalRate = nil
  418. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  419. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  420. var lastTimeEnd = firstTempTime
  421. let firstRegularBasalPoints = findRegularBasalPoints(
  422. timeBegin: dayAgoTime,
  423. timeEnd: firstTempTime,
  424. fullSize: fullSize,
  425. autotuned: false
  426. )
  427. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  428. let chunk = Array(chunk)
  429. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  430. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  431. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  432. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  433. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  434. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  435. let regularPoints = findRegularBasalPoints(
  436. timeBegin: lastTimeEnd,
  437. timeEnd: timeBegin,
  438. fullSize: fullSize,
  439. autotuned: false
  440. )
  441. lastTimeEnd = timeEnd
  442. return regularPoints + [CGPoint(x: x0, y: y0)]
  443. }.flatMap { $0 }
  444. let tempBasalPath = Path { path in
  445. var yPoint: CGFloat = Config.basalHeight
  446. path.move(to: CGPoint(x: 0, y: yPoint))
  447. for point in tempBasalPoints {
  448. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  449. path.addLine(to: point)
  450. yPoint = point.y
  451. }
  452. let lastPoint = lastBasalPoint(fullSize: fullSize)
  453. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  454. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  455. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  456. }
  457. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  458. let autotunedBasalPoints = findRegularBasalPoints(
  459. timeBegin: dayAgoTime,
  460. timeEnd: endDateTime,
  461. fullSize: fullSize,
  462. autotuned: true
  463. )
  464. let autotunedBasalPath = Path { path in
  465. var yPoint: CGFloat = Config.basalHeight
  466. path.move(to: CGPoint(x: -50, y: yPoint))
  467. for point in autotunedBasalPoints {
  468. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  469. path.addLine(to: point)
  470. yPoint = point.y
  471. }
  472. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  473. }
  474. DispatchQueue.main.async {
  475. self.tempBasalPath = tempBasalPath
  476. self.regularBasalPath = autotunedBasalPath
  477. }
  478. }
  479. }
  480. private func calculateSuspensions(fullSize: CGSize) {
  481. calculationQueue.async {
  482. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  483. let window = Array(window)
  484. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  485. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  486. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  487. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight)
  488. }
  489. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  490. guard event.type == .pumpResume else { return nil }
  491. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  492. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  493. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  494. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  495. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  496. return CGRect(
  497. x: x0,
  498. y: 0,
  499. width: x1 - x0,
  500. height: Config.basalHeight
  501. )
  502. }
  503. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  504. guard event.type == .pumpSuspend else { return nil }
  505. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  506. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  507. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  508. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  509. .additionalWidth(viewWidth: fullSize.width)
  510. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight)
  511. }
  512. rects.append(firstRec)
  513. rects.append(lastRec)
  514. let path = Path { path in
  515. path.addRects(rects.compactMap { $0 })
  516. }
  517. DispatchQueue.main.async {
  518. suspensionsPath = path
  519. }
  520. }
  521. }
  522. private func maxBasalRate() -> Decimal {
  523. if let cached = cachedMaxBasalRate {
  524. return cached
  525. }
  526. let maxRegularBasalRate = max(
  527. basalProfile.map(\.rate).max() ?? maxBasal,
  528. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  529. )
  530. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  531. if maxTempBasalRate == 0 {
  532. maxTempBasalRate = maxRegularBasalRate
  533. }
  534. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  535. return cachedMaxBasalRate ?? maxBasal
  536. }
  537. private func calculateTempTargetsRects(fullSize: CGSize) {
  538. calculationQueue.async {
  539. var rects = tempTargets.map { tempTarget -> CGRect in
  540. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  541. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  542. let x1 = timeToXCoordinate(
  543. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  544. fullSize: fullSize
  545. )
  546. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  547. return CGRect(
  548. x: x0,
  549. y: y0 - 3,
  550. width: x1 - x0,
  551. height: y1 - y0 + 6
  552. )
  553. }
  554. if rects.count > 1 {
  555. rects = rects.reduce([]) { result, rect -> [CGRect] in
  556. guard var last = result.last else { return [rect] }
  557. if last.origin.x + last.width > rect.origin.x {
  558. last.size.width = rect.origin.x - last.origin.x
  559. }
  560. var res = Array(result.dropLast())
  561. res.append(contentsOf: [last, rect])
  562. return res
  563. }
  564. }
  565. let path = Path { path in
  566. path.addRects(rects)
  567. }
  568. DispatchQueue.main.async {
  569. tempTargetsPath = path
  570. }
  571. }
  572. }
  573. private func findRegularBasalPoints(
  574. timeBegin: TimeInterval,
  575. timeEnd: TimeInterval,
  576. fullSize: CGSize,
  577. autotuned: Bool
  578. ) -> [CGPoint] {
  579. guard timeBegin < timeEnd else {
  580. return []
  581. }
  582. let beginDate = Date(timeIntervalSince1970: timeBegin)
  583. let calendar = Calendar.current
  584. let startOfDay = calendar.startOfDay(for: beginDate)
  585. let profile = autotuned ? autotunedBasalProfile : basalProfile
  586. let basalNormalized = profile.map {
  587. (
  588. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  589. rate: $0.rate
  590. )
  591. } + profile.map {
  592. (
  593. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  594. rate: $0.rate
  595. )
  596. } + profile.map {
  597. (
  598. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  599. rate: $0.rate
  600. )
  601. }
  602. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  603. .compactMap { window -> CGPoint? in
  604. let window = Array(window)
  605. if window[0].time < timeBegin, window[1].time < timeBegin {
  606. return nil
  607. }
  608. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  609. if window[0].time < timeBegin, window[1].time >= timeBegin {
  610. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  611. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  612. return CGPoint(x: x, y: y)
  613. }
  614. if window[0].time >= timeBegin, window[0].time < timeEnd {
  615. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  616. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  617. return CGPoint(x: x, y: y)
  618. }
  619. return nil
  620. }
  621. return basalTruncatedPoints
  622. }
  623. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  624. let lastBasal = Array(tempBasals.suffix(2))
  625. guard lastBasal.count == 2 else {
  626. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  627. }
  628. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  629. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  630. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  631. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  632. return CGPoint(x: x, y: y)
  633. }
  634. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  635. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  636. }
  637. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  638. guard let predictions = suggestion?.predictions,
  639. let deliveredAt = suggestion?.deliverAt,
  640. let last = glucose.last
  641. else {
  642. return Config.minAdditionalWidth
  643. }
  644. let iob = predictions.iob?.count ?? 0
  645. let zt = predictions.zt?.count ?? 0
  646. let cob = predictions.cob?.count ?? 0
  647. let uam = predictions.uam?.count ?? 0
  648. let max = [iob, zt, cob, uam].max() ?? 0
  649. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  650. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  651. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  652. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  653. }
  654. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  655. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  656. }
  657. private func maxPredValue() -> Int? {
  658. [
  659. suggestion?.predictions?.cob ?? [],
  660. suggestion?.predictions?.iob ?? [],
  661. suggestion?.predictions?.zt ?? [],
  662. suggestion?.predictions?.uam ?? []
  663. ]
  664. .flatMap { $0 }
  665. .max()
  666. }
  667. private func minPredValue() -> Int? {
  668. [
  669. suggestion?.predictions?.cob ?? [],
  670. suggestion?.predictions?.iob ?? [],
  671. suggestion?.predictions?.zt ?? [],
  672. suggestion?.predictions?.uam ?? []
  673. ]
  674. .flatMap { $0 }
  675. .min()
  676. }
  677. private func maxTargetValue() -> Int? {
  678. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  679. }
  680. private func minTargetValue() -> Int? {
  681. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  682. }
  683. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  684. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  685. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  686. return CGPoint(x: x, y: y)
  687. }
  688. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  689. guard let deliveredAt = suggestion?.deliverAt else {
  690. return .zero
  691. }
  692. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  693. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  694. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  695. return CGPoint(x: x, y: y)
  696. }
  697. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  698. let xOffset = -(
  699. glucose.first?.dateString.timeIntervalSince1970 ?? Date()
  700. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  701. )
  702. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  703. let x = CGFloat(time + xOffset) * stepXFraction
  704. return x
  705. }
  706. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  707. let topYPaddint = Config.topYPadding + Config.basalHeight
  708. let bottomYPadding = Config.bottomYPadding
  709. let (minValue, maxValue) = minMaxYValues()
  710. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  711. let yOffset = CGFloat(minValue) * stepYFraction
  712. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  713. return y
  714. }
  715. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  716. var nextIndex = 0
  717. for (index, value) in glucose.enumerated() {
  718. if value.dateString.timeIntervalSince1970 > time {
  719. nextIndex = index
  720. break
  721. }
  722. }
  723. let x = timeToXCoordinate(time, fullSize: fullSize)
  724. guard nextIndex > 0 else {
  725. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  726. return CGPoint(x: x, y: lastY)
  727. }
  728. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  729. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  730. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  731. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  732. let delta = nextX - prevX
  733. let fraction = (x - prevX) / delta
  734. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  735. }
  736. private func minMaxYValues() -> (min: Int, max: Int) {
  737. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  738. if let maxPredValue = maxPredValue() {
  739. maxValue = max(maxValue, maxPredValue)
  740. }
  741. if let maxTargetValue = maxTargetValue() {
  742. maxValue = max(maxValue, maxTargetValue)
  743. }
  744. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  745. if let minPredValue = minPredValue() {
  746. minValue = min(minValue, minPredValue)
  747. }
  748. if let minTargetValue = minTargetValue() {
  749. minValue = min(minValue, minTargetValue)
  750. }
  751. return (min: minValue, max: maxValue)
  752. }
  753. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  754. let topYPaddint = Config.topYPadding + Config.basalHeight
  755. let bottomYPadding = Config.bottomYPadding
  756. let (minValue, maxValue) = minMaxYValues()
  757. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  758. let yOffset = CGFloat(minValue) * stepYFraction
  759. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  760. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  761. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  762. }
  763. private func firstHourDate() -> Date {
  764. let firstDate = glucose.first?.dateString ?? Date()
  765. return firstDate.dateTruncated(from: .minute)!
  766. }
  767. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  768. let firstDate = glucose.first?.dateString ?? Date()
  769. let firstHour = firstHourDate()
  770. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  771. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  772. return oneSecondWidth * CGFloat(lastDeltaTime)
  773. }
  774. }