MainChartView.swift 38 KB

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