MainChartView.swift 31 KB

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