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