MainChartView.swift 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 adjustForOptionalExtraHours = screenHours > 12 ? screenHours - 12 : 0
  609. let endDateTime = dayAgoTime + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  610. .timeInterval + min(max(screenHours - adjustForOptionalExtraHours, 12), 24).hours
  611. .timeInterval
  612. let autotunedBasalPoints = findRegularBasalPoints(
  613. timeBegin: dayAgoTime,
  614. timeEnd: endDateTime,
  615. fullSize: fullSize,
  616. autotuned: true
  617. )
  618. let autotunedBasalPath = Path { path in
  619. var yPoint: CGFloat = Config.basalHeight
  620. path.move(to: CGPoint(x: -50, y: yPoint))
  621. for point in autotunedBasalPoints {
  622. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  623. path.addLine(to: point)
  624. yPoint = point.y
  625. }
  626. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  627. }
  628. DispatchQueue.main.async {
  629. self.tempBasalPath = tempBasalPath
  630. self.regularBasalPath = autotunedBasalPath
  631. }
  632. }
  633. }
  634. private func calculateSuspensions(fullSize: CGSize) {
  635. calculationQueue.async {
  636. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  637. let window = Array(window)
  638. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  639. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  640. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  641. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  642. }
  643. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  644. guard event.type == .pumpResume else { return nil }
  645. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  646. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  647. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  648. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  649. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  650. return CGRect(
  651. x: x0,
  652. y: 0,
  653. width: x1 - x0,
  654. height: Config.basalHeight * 0.7
  655. )
  656. }
  657. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  658. guard event.type == .pumpSuspend else { return nil }
  659. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  660. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  661. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  662. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  663. .additionalWidth(viewWidth: fullSize.width)
  664. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  665. }
  666. rects.append(firstRec)
  667. rects.append(lastRec)
  668. let path = Path { path in
  669. path.addRects(rects.compactMap { $0 })
  670. }
  671. DispatchQueue.main.async {
  672. suspensionsPath = path
  673. }
  674. }
  675. }
  676. private func maxBasalRate() -> Decimal {
  677. if let cached = cachedMaxBasalRate {
  678. return cached
  679. }
  680. let maxRegularBasalRate = max(
  681. basalProfile.map(\.rate).max() ?? maxBasal,
  682. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  683. )
  684. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  685. if maxTempBasalRate == 0 {
  686. maxTempBasalRate = maxRegularBasalRate
  687. }
  688. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  689. return cachedMaxBasalRate ?? maxBasal
  690. }
  691. private func calculateTempTargetsRects(fullSize: CGSize) {
  692. calculationQueue.async {
  693. var rects = tempTargets.map { tempTarget -> CGRect in
  694. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  695. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  696. let x1 = timeToXCoordinate(
  697. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  698. fullSize: fullSize
  699. )
  700. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  701. return CGRect(
  702. x: x0,
  703. y: y0 - 3,
  704. width: x1 - x0,
  705. height: y1 - y0 + 6
  706. )
  707. }
  708. if rects.count > 1 {
  709. rects = rects.reduce([]) { result, rect -> [CGRect] in
  710. guard var last = result.last else { return [rect] }
  711. if last.origin.x + last.width > rect.origin.x {
  712. last.size.width = rect.origin.x - last.origin.x
  713. }
  714. var res = Array(result.dropLast())
  715. res.append(contentsOf: [last, rect])
  716. return res
  717. }
  718. }
  719. let path = Path { path in
  720. path.addRects(rects)
  721. }
  722. DispatchQueue.main.async {
  723. tempTargetsPath = path
  724. }
  725. }
  726. }
  727. private func findRegularBasalPoints(
  728. timeBegin: TimeInterval,
  729. timeEnd: TimeInterval,
  730. fullSize: CGSize,
  731. autotuned: Bool
  732. ) -> [CGPoint] {
  733. guard timeBegin < timeEnd else {
  734. return []
  735. }
  736. let beginDate = Date(timeIntervalSince1970: timeBegin)
  737. let calendar = Calendar.current
  738. let startOfDay = calendar.startOfDay(for: beginDate)
  739. let profile = autotuned ? autotunedBasalProfile : basalProfile
  740. let basalNormalized = profile.map {
  741. (
  742. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  743. rate: $0.rate
  744. )
  745. } + profile.map {
  746. (
  747. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  748. rate: $0.rate
  749. )
  750. } + profile.map {
  751. (
  752. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  753. rate: $0.rate
  754. )
  755. }
  756. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  757. .compactMap { window -> CGPoint? in
  758. let window = Array(window)
  759. if window[0].time < timeBegin, window[1].time < timeBegin {
  760. return nil
  761. }
  762. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  763. if window[0].time < timeBegin, window[1].time >= timeBegin {
  764. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  765. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  766. return CGPoint(x: x, y: y)
  767. }
  768. if window[0].time >= timeBegin, window[0].time < timeEnd {
  769. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  770. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  771. return CGPoint(x: x, y: y)
  772. }
  773. return nil
  774. }
  775. return basalTruncatedPoints
  776. }
  777. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  778. let lastBasal = Array(tempBasals.suffix(2))
  779. guard lastBasal.count == 2 else {
  780. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  781. }
  782. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  783. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  784. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  785. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  786. return CGPoint(x: x, y: y)
  787. }
  788. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  789. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  790. }
  791. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  792. guard let predictions = suggestion?.predictions,
  793. let deliveredAt = suggestion?.deliverAt,
  794. let last = glucose.last
  795. else {
  796. return Config.minAdditionalWidth
  797. }
  798. let iob = predictions.iob?.count ?? 0
  799. let zt = predictions.zt?.count ?? 0
  800. let cob = predictions.cob?.count ?? 0
  801. let uam = predictions.uam?.count ?? 0
  802. let max = [iob, zt, cob, uam].max() ?? 0
  803. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  804. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  805. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  806. return Swift.min(Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth), 275)
  807. }
  808. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  809. viewWidth / (CGFloat(min(max(screenHours, 2), 24)) * CGFloat(1.hours.timeInterval))
  810. }
  811. private func maxPredValue() -> Int? {
  812. [
  813. suggestion?.predictions?.cob ?? [],
  814. suggestion?.predictions?.iob ?? [],
  815. suggestion?.predictions?.zt ?? [],
  816. suggestion?.predictions?.uam ?? []
  817. ]
  818. .flatMap { $0 }
  819. .max()
  820. }
  821. private func minPredValue() -> Int? {
  822. [
  823. suggestion?.predictions?.cob ?? [],
  824. suggestion?.predictions?.iob ?? [],
  825. suggestion?.predictions?.zt ?? [],
  826. suggestion?.predictions?.uam ?? []
  827. ]
  828. .flatMap { $0 }
  829. .min()
  830. }
  831. private func maxTargetValue() -> Int? {
  832. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  833. }
  834. private func minTargetValue() -> Int? {
  835. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  836. }
  837. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  838. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  839. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  840. return CGPoint(x: x, y: y)
  841. }
  842. private func UnSmoothedGlucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  843. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  844. let glucoseValue: Decimal = glucoseEntry.unfiltered ?? Decimal(glucoseEntry.glucose ?? 0)
  845. let y = glucoseToYCoordinate(Int(glucoseValue), fullSize: fullSize)
  846. return CGPoint(x: x, y: y)
  847. }
  848. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  849. guard let deliveredAt = suggestion?.deliverAt else {
  850. return .zero
  851. }
  852. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  853. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  854. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  855. return CGPoint(x: x, y: y)
  856. }
  857. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  858. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  859. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  860. let x = CGFloat(time + xOffset) * stepXFraction
  861. return x
  862. }
  863. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  864. let topYPaddint = Config.topYPadding + Config.basalHeight
  865. let bottomYPadding = Config.bottomYPadding
  866. let (minValue, maxValue) = minMaxYValues()
  867. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  868. let yOffset = CGFloat(minValue) * stepYFraction
  869. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  870. return y
  871. }
  872. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  873. var nextIndex = 0
  874. for (index, value) in glucose.enumerated() {
  875. if value.dateString.timeIntervalSince1970 > time {
  876. nextIndex = index
  877. break
  878. }
  879. }
  880. let x = timeToXCoordinate(time, fullSize: fullSize)
  881. guard nextIndex > 0 else {
  882. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  883. return CGPoint(x: x, y: lastY)
  884. }
  885. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  886. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  887. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  888. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  889. let delta = nextX - prevX
  890. let fraction = (x - prevX) / delta
  891. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  892. }
  893. private func minMaxYValues() -> (min: Int, max: Int) {
  894. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  895. if let maxPredValue = maxPredValue() {
  896. maxValue = max(maxValue, maxPredValue)
  897. }
  898. if let maxTargetValue = maxTargetValue() {
  899. maxValue = max(maxValue, maxTargetValue)
  900. }
  901. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  902. if let minPredValue = minPredValue() {
  903. minValue = min(minValue, minPredValue)
  904. }
  905. if let minTargetValue = minTargetValue() {
  906. minValue = min(minValue, minTargetValue)
  907. }
  908. if minValue == maxValue {
  909. minValue = Config.minGlucose
  910. maxValue = Config.maxGlucose
  911. }
  912. // fix the grah y-axis as long as the min and max BG values are within set borders
  913. if minValue > Config.minGlucose {
  914. minValue = Config.minGlucose
  915. }
  916. if maxValue < Config.maxGlucose {
  917. maxValue = Config.maxGlucose
  918. }
  919. return (min: minValue, max: maxValue)
  920. }
  921. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  922. let topYPaddint = Config.topYPadding + Config.basalHeight
  923. let bottomYPadding = Config.bottomYPadding
  924. let (minValue, maxValue) = minMaxYValues()
  925. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  926. let yOffset = CGFloat(minValue) * stepYFraction
  927. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  928. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  929. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  930. }
  931. private func firstHourDate() -> Date {
  932. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  933. return firstDate.dateTruncated(from: .minute)!
  934. }
  935. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  936. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  937. let firstHour = firstHourDate()
  938. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  939. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  940. return oneSecondWidth * CGFloat(lastDeltaTime)
  941. }
  942. }