MainChartView.swift 31 KB

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