MainChartView.swift 31 KB

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