MainChartView2.swift 26 KB

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