MainChartView2.swift 25 KB

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