MainChartView.swift 39 KB

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