MainChartView.swift 41 KB

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