MainChartView.swift 41 KB

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