MainChartView.swift 37 KB

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