MainChartView2.swift 29 KB

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