MainChartView.swift 38 KB

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