MainChartView.swift 34 KB

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