MainChartView2.swift 28 KB

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