MainChartView.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. import Charts
  2. import SwiftUI
  3. let screenSize: CGRect = UIScreen.main.bounds
  4. let calendar = Calendar.current
  5. private struct BasalProfile: Hashable {
  6. let amount: Double
  7. var isOverwritten: Bool
  8. let startDate: Date
  9. let endDate: Date?
  10. init(amount: Double, isOverwritten: Bool, startDate: Date, endDate: Date? = nil) {
  11. self.amount = amount
  12. self.isOverwritten = isOverwritten
  13. self.startDate = startDate
  14. self.endDate = endDate
  15. }
  16. }
  17. private struct Prediction: Hashable {
  18. let amount: Int
  19. let timestamp: Date
  20. let type: PredictionType
  21. }
  22. private struct Carb: Hashable {
  23. let amount: Decimal
  24. let timestamp: Date
  25. let nearestGlucose: BloodGlucose
  26. }
  27. private struct ChartBolus: Hashable {
  28. let amount: Decimal
  29. let timestamp: Date
  30. let nearestGlucose: BloodGlucose
  31. let yPosition: Int
  32. }
  33. private struct ChartTempTarget: Hashable {
  34. let amount: Decimal
  35. let start: Date
  36. let end: Date
  37. }
  38. private enum PredictionType: Hashable {
  39. case iob
  40. case cob
  41. case zt
  42. case uam
  43. }
  44. struct MainChartView: View {
  45. private enum Config {
  46. static let bolusSize: CGFloat = 5
  47. static let bolusScale: CGFloat = 1
  48. static let carbsSize: CGFloat = 5
  49. static let carbsScale: CGFloat = 0.3
  50. static let fpuSize: CGFloat = 10
  51. static let maxGlucose = 270
  52. static let minGlucose = 45
  53. }
  54. @Binding var glucose: [BloodGlucose]
  55. @Binding var units: GlucoseUnits
  56. @Binding var eventualBG: Int?
  57. @Binding var suggestion: Suggestion?
  58. @Binding var tempBasals: [PumpHistoryEvent]
  59. @Binding var boluses: [PumpHistoryEvent]
  60. @Binding var suspensions: [PumpHistoryEvent]
  61. @Binding var announcement: [Announcement]
  62. @Binding var hours: Int
  63. @Binding var maxBasal: Decimal
  64. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  65. @Binding var basalProfile: [BasalProfileEntry]
  66. @Binding var tempTargets: [TempTarget]
  67. @Binding var carbs: [CarbsEntry]
  68. @Binding var smooth: Bool
  69. @Binding var highGlucose: Decimal
  70. @Binding var lowGlucose: Decimal
  71. @Binding var screenHours: Int16
  72. @Binding var displayXgridLines: Bool
  73. @Binding var displayYgridLines: Bool
  74. @Binding var thresholdLines: Bool
  75. @Binding var isTempTargetActive: Bool
  76. @State var didAppearTrigger = false
  77. @State private var BasalProfiles: [BasalProfile] = []
  78. @State private var TempBasals: [PumpHistoryEvent] = []
  79. @State private var ChartTempTargets: [ChartTempTarget] = []
  80. @State private var Predictions: [Prediction] = []
  81. @State private var ChartCarbs: [Carb] = []
  82. @State private var ChartFpus: [Carb] = []
  83. @State private var ChartBoluses: [ChartBolus] = []
  84. @State private var count: Decimal = 1
  85. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  86. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  87. @State private var glucoseUpdateCount = 0
  88. @State private var maxUpdateCount = 12
  89. @State private var minValue: Int = 45
  90. @State private var maxValue: Int = 270
  91. private var bolusFormatter: NumberFormatter {
  92. let formatter = NumberFormatter()
  93. formatter.numberStyle = .decimal
  94. formatter.minimumIntegerDigits = 0
  95. formatter.maximumFractionDigits = 2
  96. formatter.decimalSeparator = "."
  97. return formatter
  98. }
  99. private var carbsFormatter: NumberFormatter {
  100. let formatter = NumberFormatter()
  101. formatter.numberStyle = .decimal
  102. formatter.maximumFractionDigits = 0
  103. return formatter
  104. }
  105. var body: some View {
  106. VStack {
  107. ScrollViewReader { scroller in
  108. ScrollView(.horizontal, showsIndicators: false) {
  109. VStack(spacing: -0.00002) {
  110. BasalChart()
  111. MainChart()
  112. }.onChange(of: screenHours) { _ in
  113. updateStartEndMarkers()
  114. scroller.scrollTo("MainChart", anchor: .trailing)
  115. }.onChange(of: glucose) { _ in
  116. updateStartEndMarkers()
  117. scroller.scrollTo("MainChart", anchor: .trailing)
  118. }
  119. .onChange(of: suggestion) { _ in
  120. updateStartEndMarkers()
  121. scroller.scrollTo("MainChart", anchor: .trailing)
  122. }
  123. .onChange(of: tempBasals) { _ in
  124. updateStartEndMarkers()
  125. scroller.scrollTo("MainChart", anchor: .trailing)
  126. }
  127. .onAppear {
  128. updateStartEndMarkers()
  129. scroller.scrollTo("MainChart", anchor: .trailing)
  130. }
  131. }
  132. }
  133. legendPanel.padding(.top, 8)
  134. }
  135. }
  136. }
  137. // MARK: Components
  138. extension MainChartView {
  139. private func MainChart() -> some View {
  140. VStack {
  141. Chart {
  142. /// high and low treshold lines
  143. if thresholdLines {
  144. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  145. .lineStyle(.init(lineWidth: 2, dash: [2]))
  146. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  147. .lineStyle(.init(lineWidth: 2, dash: [2]))
  148. }
  149. RuleMark(
  150. x: .value(
  151. "",
  152. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  153. unit: .second
  154. )
  155. ).lineStyle(.init(lineWidth: 2, dash: [2])).foregroundStyle(Color.insulin)
  156. RuleMark(
  157. x: .value(
  158. "",
  159. startMarker,
  160. unit: .second
  161. )
  162. ).foregroundStyle(Color.clear)
  163. RuleMark(
  164. x: .value(
  165. "",
  166. endMarker,
  167. unit: .second
  168. )
  169. ).foregroundStyle(Color.clear)
  170. /// carbs
  171. ForEach(ChartCarbs, id: \.self) { carb in
  172. let carbAmount = carb.amount
  173. PointMark(
  174. x: .value("Time", carb.timestamp, unit: .second),
  175. y: .value("Value", 60)
  176. )
  177. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  178. .foregroundStyle(Color.orange)
  179. .annotation(position: .bottom) {
  180. Text(carbsFormatter.string(from: carbAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.orange)
  181. }
  182. }
  183. /// fpus
  184. ForEach(ChartFpus, id: \.self) { fpu in
  185. let fpuAmount = fpu.amount
  186. let size = (Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 1.8
  187. PointMark(
  188. x: .value("Time", fpu.timestamp, unit: .second),
  189. y: .value("Value", 60)
  190. )
  191. .symbolSize(size)
  192. .foregroundStyle(Color.brown)
  193. }
  194. /// smbs in triangle form
  195. ForEach(ChartBoluses, id: \.self) { bolus in
  196. let bolusAmount = bolus.amount
  197. let size = (Config.bolusSize + CGFloat(bolusAmount) * Config.bolusScale) * 1.8
  198. PointMark(
  199. x: .value("Time", bolus.timestamp, unit: .second),
  200. y: .value("Value", bolus.yPosition)
  201. )
  202. .symbol {
  203. Image(systemName: "arrowtriangle.down.fill").font(.system(size: size))
  204. }
  205. .foregroundStyle(Color.insulin)
  206. .annotation(position: .top) {
  207. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2).foregroundStyle(Color.insulin)
  208. }
  209. }
  210. /// temp targets
  211. ForEach(ChartTempTargets, id: \.self) { target in
  212. RuleMark(
  213. xStart: .value("Start", target.start),
  214. xEnd: .value("End", target.end),
  215. y: .value("Value", target.amount)
  216. )
  217. .foregroundStyle(Color.purple.opacity(0.5)).lineStyle(.init(lineWidth: 8))
  218. }
  219. /// predictions
  220. ForEach(Predictions, id: \.self) { info in
  221. /// ensure that there are no values below 0 in the chart
  222. let yValue = max(info.amount, 0)
  223. if info.type == .uam {
  224. LineMark(
  225. x: .value("Time", info.timestamp, unit: .second),
  226. y: .value("Value", yValue),
  227. series: .value("uam", "uam")
  228. ).foregroundStyle(Color.uam).symbolSize(16)
  229. }
  230. if info.type == .cob {
  231. LineMark(
  232. x: .value("Time", info.timestamp, unit: .second),
  233. y: .value("Value", yValue),
  234. series: .value("cob", "cob")
  235. ).foregroundStyle(Color.orange).symbolSize(16)
  236. }
  237. if info.type == .iob {
  238. LineMark(
  239. x: .value("Time", info.timestamp, unit: .second),
  240. y: .value("Value", yValue),
  241. series: .value("iob", "iob")
  242. ).foregroundStyle(Color.insulin).symbolSize(16)
  243. }
  244. if info.type == .zt {
  245. LineMark(
  246. x: .value("Time", info.timestamp, unit: .second),
  247. y: .value("Value", yValue),
  248. series: .value("zt", "zt")
  249. ).foregroundStyle(Color.zt).symbolSize(16)
  250. }
  251. }
  252. /// glucose point mark
  253. ForEach(glucose) {
  254. if let sgv = $0.sgv {
  255. PointMark(
  256. x: .value("Time", $0.dateString, unit: .second),
  257. y: .value("Value", sgv)
  258. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  259. if smooth {
  260. LineMark(
  261. x: .value("Time", $0.dateString, unit: .second),
  262. y: .value("Value", sgv)
  263. ).foregroundStyle(Color.green.gradient).symbolSize(25)
  264. .interpolationMethod(.cardinal)
  265. }
  266. }
  267. }
  268. }.id("MainChart")
  269. .onChange(of: glucose) { _ in
  270. calculatePredictions()
  271. calculateFpus()
  272. counter()
  273. }
  274. .onChange(of: carbs) { _ in
  275. calculateCarbs()
  276. calculateFpus()
  277. }
  278. .onChange(of: boluses) { _ in
  279. calculateBoluses()
  280. }
  281. .onChange(of: tempTargets) { _ in
  282. calculateTTs()
  283. }
  284. .onChange(of: didAppearTrigger) { _ in
  285. calculatePredictions()
  286. calculateTTs()
  287. }.onChange(of: suggestion) { _ in
  288. calculatePredictions()
  289. }
  290. .onReceive(
  291. Foundation.NotificationCenter.default
  292. .publisher(for: UIApplication.willEnterForegroundNotification)
  293. ) { _ in
  294. calculatePredictions()
  295. }
  296. .frame(
  297. minHeight: UIScreen.main.bounds.height / 3
  298. )
  299. .frame(width: fullWidth(viewWidth: screenSize.width))
  300. .chartYScale(domain: minValue ... maxValue)
  301. .chartXScale(domain: startMarker ... endMarker)
  302. .chartXAxis {
  303. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  304. if displayXgridLines {
  305. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  306. } else {
  307. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  308. }
  309. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  310. }
  311. }
  312. .chartYAxis {
  313. AxisMarks { _ in
  314. if displayYgridLines {
  315. AxisGridLine(stroke: .init(lineWidth: 0.3, dash: [2, 3]))
  316. } else {
  317. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  318. }
  319. AxisValueLabel()
  320. }
  321. }
  322. }
  323. }
  324. func BasalChart() -> some View {
  325. VStack {
  326. Chart {
  327. RuleMark(
  328. x: .value(
  329. "",
  330. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  331. unit: .second
  332. )
  333. ).lineStyle(.init(lineWidth: 2, dash: [2])).foregroundStyle(Color.insulin)
  334. RuleMark(
  335. x: .value(
  336. "",
  337. startMarker,
  338. unit: .second
  339. )
  340. ).foregroundStyle(Color.clear)
  341. RuleMark(
  342. x: .value(
  343. "",
  344. endMarker,
  345. unit: .second
  346. )
  347. ).foregroundStyle(Color.clear)
  348. ForEach(TempBasals) {
  349. BarMark(
  350. x: .value("Time", $0.timestamp),
  351. y: .value("Rate", $0.rate ?? 0)
  352. ).foregroundStyle(Color.insulin)
  353. }
  354. ForEach(BasalProfiles, id: \.self) { profile in
  355. LineMark(
  356. x: .value("Start Date", profile.startDate),
  357. y: .value("Amount", profile.amount),
  358. series: .value("profile", "profile")
  359. ).lineStyle(.init(lineWidth: 2, dash: [2, 3])).foregroundStyle(Color.insulin)
  360. LineMark(
  361. x: .value("End Date", profile.endDate ?? endMarker),
  362. y: .value("Amount", profile.amount),
  363. series: .value("profile", "profile")
  364. ).lineStyle(.init(lineWidth: 2.5, dash: [2, 3])).foregroundStyle(Color.insulin)
  365. }
  366. }.onChange(of: tempBasals) { _ in
  367. calculateBasals()
  368. calculateTempBasals()
  369. }
  370. .onChange(of: maxBasal) { _ in
  371. calculateBasals()
  372. calculateTempBasals()
  373. }
  374. .onChange(of: autotunedBasalProfile) { _ in
  375. calculateBasals()
  376. calculateTempBasals()
  377. }
  378. .onChange(of: didAppearTrigger) { _ in
  379. calculateBasals()
  380. calculateTempBasals()
  381. }.onChange(of: basalProfile) { _ in
  382. calculateTempBasals()
  383. }
  384. .frame(
  385. minHeight: UIScreen.main.bounds.height / 10
  386. )
  387. .frame(width: fullWidth(viewWidth: screenSize.width))
  388. .rotationEffect(.degrees(180))
  389. .scaleEffect(x: -1, y: 1)
  390. .chartXScale(domain: startMarker ... endMarker)
  391. .chartXAxis(.hidden)
  392. .chartXAxis {
  393. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  394. }
  395. }
  396. .chartYAxis {
  397. AxisMarks(position: .trailing) { _ in
  398. AxisTick(length: 25, stroke: .init(lineWidth: 4))
  399. .foregroundStyle(Color.clear)
  400. }
  401. }
  402. }
  403. }
  404. var legendPanel: some View {
  405. ZStack {
  406. HStack(alignment: .center) {
  407. Spacer()
  408. Group {
  409. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  410. Text("BG")
  411. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopGreen)
  412. }
  413. Group {
  414. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  415. .padding(.leading, 8)
  416. Text("IOB")
  417. .font(.system(size: 10, weight: .bold)).foregroundColor(.insulin)
  418. }
  419. Group {
  420. Circle().fill(Color.zt).frame(width: 8, height: 8)
  421. .padding(.leading, 8)
  422. Text("ZT")
  423. .font(.system(size: 10, weight: .bold)).foregroundColor(.zt)
  424. }
  425. Group {
  426. Circle().fill(Color.loopYellow).frame(width: 8, height: 8).padding(.leading, 8)
  427. Text("COB")
  428. .font(.system(size: 10, weight: .bold)).foregroundColor(.loopYellow)
  429. }
  430. Group {
  431. Circle().fill(Color.uam).frame(width: 8, height: 8)
  432. .padding(.leading, 8)
  433. Text("UAM")
  434. .font(.system(size: 10, weight: .bold)).foregroundColor(.uam)
  435. }
  436. Spacer()
  437. }
  438. .padding(.horizontal, 10)
  439. .frame(maxWidth: .infinity)
  440. }
  441. }
  442. }
  443. // MARK: Calculations
  444. /// calculates the glucose value thats the nearest to parameter 'time'
  445. /// if time is later than all the arrays values return the last element of BloodGlucose
  446. extension MainChartView {
  447. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  448. var nextIndex = 0
  449. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  450. return glucose.last ?? BloodGlucose(
  451. date: 0,
  452. dateString: Date(),
  453. unfiltered: nil,
  454. filtered: nil,
  455. noise: nil,
  456. type: nil
  457. )
  458. }
  459. for (index, value) in glucose.enumerated() {
  460. if value.dateString.timeIntervalSince1970 > time {
  461. nextIndex = index
  462. print("Break", value.dateString.timeIntervalSince1970, time)
  463. break
  464. }
  465. }
  466. return glucose[nextIndex]
  467. }
  468. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  469. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  470. }
  471. private func calculateCarbs() {
  472. var calculatedCarbs: [Carb] = []
  473. /// check if carbs are not fpus before adding them to the chart
  474. /// this solves the problem of a first CARB entry with the amount of the single fpu entries that was made at current time when adding ONLY fpus
  475. let realCarbs = carbs.filter { !($0.isFPU ?? false) }
  476. realCarbs.forEach { carb in
  477. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  478. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg))
  479. }
  480. ChartCarbs = calculatedCarbs
  481. }
  482. private func calculateFpus() {
  483. var calculatedFpus: [Carb] = []
  484. /// check for only fpus
  485. let fpus = carbs.filter { $0.isFPU ?? false }
  486. fpus.forEach { fpu in
  487. let bg = timeToNearestGlucose(
  488. time: TimeInterval(rawValue: (fpu.actualDate?.timeIntervalSince1970)!) ?? fpu.createdAt
  489. .timeIntervalSince1970
  490. )
  491. calculatedFpus
  492. .append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg))
  493. }
  494. ChartFpus = calculatedFpus
  495. }
  496. private func calculateBoluses() {
  497. var calculatedBoluses: [ChartBolus] = []
  498. boluses.forEach { bolus in
  499. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  500. let yPosition = (bg.sgv ?? 120) + 30
  501. calculatedBoluses
  502. .append(ChartBolus(
  503. amount: bolus.amount ?? 0,
  504. timestamp: bolus.timestamp,
  505. nearestGlucose: bg,
  506. yPosition: yPosition
  507. ))
  508. }
  509. ChartBoluses = calculatedBoluses
  510. }
  511. /// calculations for temp target bar mark
  512. private func calculateTTs() {
  513. var groupedPackages: [[TempTarget]] = []
  514. var currentPackage: [TempTarget] = []
  515. var calculatedTTs: [ChartTempTarget] = []
  516. for target in tempTargets {
  517. if target.duration > 0 {
  518. if !currentPackage.isEmpty {
  519. groupedPackages.append(currentPackage)
  520. currentPackage = []
  521. }
  522. currentPackage.append(target)
  523. } else {
  524. if let lastNonZeroTempTarget = currentPackage.last(where: { $0.duration > 0 }) {
  525. if target.createdAt >= lastNonZeroTempTarget.createdAt,
  526. target.createdAt <= lastNonZeroTempTarget.createdAt
  527. .addingTimeInterval(TimeInterval(lastNonZeroTempTarget.duration * 60))
  528. {
  529. currentPackage.append(target)
  530. }
  531. }
  532. }
  533. }
  534. // appends last package, if exists
  535. if !currentPackage.isEmpty {
  536. groupedPackages.append(currentPackage)
  537. }
  538. for package in groupedPackages {
  539. guard let firstNonZeroTarget = package.first(where: { $0.duration > 0 }) else {
  540. continue
  541. }
  542. var end = firstNonZeroTarget.createdAt.addingTimeInterval(TimeInterval(firstNonZeroTarget.duration * 60))
  543. let earliestCancelTarget = package.filter({ $0.duration == 0 }).min(by: { $0.createdAt < $1.createdAt })
  544. if let earliestCancelTarget = earliestCancelTarget {
  545. end = min(earliestCancelTarget.createdAt, end)
  546. }
  547. let now = Date()
  548. isTempTargetActive = firstNonZeroTarget.createdAt <= now && now <= end
  549. if firstNonZeroTarget.targetTop != nil {
  550. calculatedTTs
  551. .append(ChartTempTarget(
  552. amount: firstNonZeroTarget.targetTop ?? 0,
  553. start: firstNonZeroTarget.createdAt,
  554. end: end
  555. ))
  556. }
  557. }
  558. ChartTempTargets = calculatedTTs
  559. }
  560. private func calculatePredictions() {
  561. var calculatedPredictions: [Prediction] = []
  562. let uam = suggestion?.predictions?.uam ?? []
  563. let iob = suggestion?.predictions?.iob ?? []
  564. let cob = suggestion?.predictions?.cob ?? []
  565. let zt = suggestion?.predictions?.zt ?? []
  566. guard let deliveredAt = suggestion?.deliverAt else {
  567. return
  568. }
  569. uam.indices.forEach { index in
  570. let predTime = Date(
  571. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  572. .timeInterval
  573. )
  574. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  575. calculatedPredictions.append(
  576. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  577. )
  578. }
  579. }
  580. iob.indices.forEach { index in
  581. let predTime = Date(
  582. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  583. .timeInterval
  584. )
  585. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  586. calculatedPredictions.append(
  587. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  588. )
  589. }
  590. }
  591. cob.indices.forEach { index in
  592. let predTime = Date(
  593. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  594. .timeInterval
  595. )
  596. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  597. calculatedPredictions.append(
  598. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  599. )
  600. }
  601. }
  602. zt.indices.forEach { index in
  603. let predTime = Date(
  604. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  605. .timeInterval
  606. )
  607. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  608. calculatedPredictions.append(
  609. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  610. )
  611. }
  612. }
  613. Predictions = calculatedPredictions
  614. }
  615. private func getLastUam() -> Int {
  616. let uam = suggestion?.predictions?.uam ?? []
  617. return uam.last ?? 0
  618. }
  619. private func calculateTempBasals() {
  620. var basals = tempBasals
  621. var returnTempBasalRates: [PumpHistoryEvent] = []
  622. var finished: [Int: Bool] = [:]
  623. basals.indices.forEach { i in
  624. basals.indices.forEach { j in
  625. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  626. let rate = basals[i].rate ?? basals[j].rate
  627. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  628. finished[i] = true
  629. if rate != 0 || durationMin != 0 {
  630. returnTempBasalRates.append(
  631. PumpHistoryEvent(
  632. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  633. timestamp: basals[i].timestamp,
  634. durationMin: durationMin,
  635. rate: rate
  636. )
  637. )
  638. }
  639. }
  640. }
  641. }
  642. TempBasals = returnTempBasalRates
  643. }
  644. private func findRegularBasalPoints(
  645. timeBegin: TimeInterval,
  646. timeEnd: TimeInterval,
  647. autotuned: Bool
  648. ) -> [BasalProfile] {
  649. guard timeBegin < timeEnd else {
  650. return []
  651. }
  652. let beginDate = Date(timeIntervalSince1970: timeBegin)
  653. let calendar = Calendar.current
  654. let startOfDay = calendar.startOfDay(for: beginDate)
  655. let profile = autotuned ? autotunedBasalProfile : basalProfile
  656. let basalNormalized = profile.map {
  657. (
  658. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  659. rate: $0.rate
  660. )
  661. } + profile.map {
  662. (
  663. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  664. .timeIntervalSince1970,
  665. rate: $0.rate
  666. )
  667. } + profile.map {
  668. (
  669. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  670. .timeIntervalSince1970,
  671. rate: $0.rate
  672. )
  673. }
  674. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  675. .compactMap { window -> BasalProfile? in
  676. let window = Array(window)
  677. if window[0].time < timeBegin, window[1].time < timeBegin {
  678. return nil
  679. }
  680. if window[0].time < timeBegin, window[1].time >= timeBegin {
  681. let startDate = Date(timeIntervalSince1970: timeBegin)
  682. let rate = window[0].rate
  683. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  684. }
  685. if window[0].time >= timeBegin, window[0].time < timeEnd {
  686. let startDate = Date(timeIntervalSince1970: window[0].time)
  687. let rate = window[0].rate
  688. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  689. }
  690. return nil
  691. }
  692. return basalTruncatedPoints
  693. }
  694. /// update start and end marker to fix scroll update problem with x axis
  695. private func updateStartEndMarkers() {
  696. startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  697. endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  698. }
  699. /// get y axis scale
  700. /// but only call the function every 60min, i.e. every 12th glucose value
  701. private func counter() {
  702. glucoseUpdateCount += 1
  703. if glucoseUpdateCount >= maxUpdateCount {
  704. maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  705. if let maxPredValue = maxPredValue() {
  706. maxValue = max(maxValue, maxPredValue)
  707. }
  708. minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  709. if let minPredValue = minPredValue() {
  710. minValue = min(minValue, minPredValue)
  711. }
  712. if minValue > Config.minGlucose {
  713. minValue = Config.minGlucose
  714. }
  715. if maxValue < Config.maxGlucose {
  716. maxValue = Config.maxGlucose
  717. }
  718. glucoseUpdateCount = 0
  719. }
  720. }
  721. private func maxPredValue() -> Int? {
  722. [
  723. suggestion?.predictions?.cob ?? [],
  724. suggestion?.predictions?.iob ?? [],
  725. suggestion?.predictions?.zt ?? [],
  726. suggestion?.predictions?.uam ?? []
  727. ].flatMap {
  728. $0
  729. }.max()
  730. }
  731. private func minPredValue() -> Int? {
  732. [
  733. suggestion?.predictions?.cob ?? [],
  734. suggestion?.predictions?.iob ?? [],
  735. suggestion?.predictions?.zt ?? [],
  736. suggestion?.predictions?.uam ?? []
  737. ].flatMap {
  738. $0
  739. }.min()
  740. }
  741. /* private func generateYAxisValues(maxYLabel: Int) -> [Int] {
  742. var yAxisValues = [50, 100, 150]
  743. if maxYLabel > 170, maxYLabel < 200 {
  744. yAxisValues.append(maxYLabel)
  745. } else if maxYLabel > 200, maxYLabel < 250 {
  746. yAxisValues += [200, maxYLabel]
  747. } else if maxYLabel > 250, maxYLabel < 350 {
  748. yAxisValues += [200, 250, maxYLabel]
  749. } else if maxYLabel > 350 {
  750. yAxisValues += [200, 250, 300, maxYLabel]
  751. } else if maxYLabel == 400 {
  752. yAxisValues += [200, 250, 300, 350, 400]
  753. }
  754. return yAxisValues
  755. } */
  756. private func calculateBasals() {
  757. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  758. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  759. let regularPoints = findRegularBasalPoints(
  760. timeBegin: dayAgoTime,
  761. timeEnd: endMarker.timeIntervalSince1970,
  762. autotuned: false
  763. )
  764. let autotunedBasalPoints = findRegularBasalPoints(
  765. timeBegin: dayAgoTime,
  766. timeEnd: endMarker.timeIntervalSince1970,
  767. autotuned: true
  768. )
  769. var totalBasal = regularPoints + autotunedBasalPoints
  770. totalBasal.sort {
  771. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  772. }
  773. var basals: [BasalProfile] = []
  774. totalBasal.indices.forEach { index in
  775. basals.append(BasalProfile(
  776. amount: totalBasal[index].amount,
  777. isOverwritten: totalBasal[index].isOverwritten,
  778. startDate: totalBasal[index].startDate,
  779. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  780. ))
  781. print(
  782. "Basal",
  783. totalBasal[index].startDate,
  784. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  785. totalBasal[index].amount,
  786. totalBasal[index].isOverwritten
  787. )
  788. }
  789. BasalProfiles = basals
  790. }
  791. }