MainChartView2.swift 26 KB

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