MainChartView.swift 36 KB

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