MainChartView.swift 34 KB

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