MainChartView.swift 38 KB

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