MainChartView.swift 34 KB

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