MainChartView.swift 40 KB

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