MainChartView.swift 36 KB

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