Graphs.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. //
  2. // Graphs.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/16/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import Charts
  10. import UIKit
  11. let ScaleXMax:Float = 150.0
  12. extension MainViewController {
  13. func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
  14. if chartView == BGChartFull {
  15. BGChart.moveViewToX(entry.x)
  16. }
  17. if entry.data as? String == "hide"{
  18. BGChart.highlightValue(nil, callDelegate: false)
  19. }
  20. }
  21. func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) {
  22. if chartView == BGChart {
  23. let currentMatrix = chartView.viewPortHandler.touchMatrix
  24. //BGChartFull.viewPortHandler.refresh(newMatrix: currentMatrix, chart: BGChartFull, invalidate: true)
  25. //BGChartFull.highlightValue(x: Double(currentMatrix.tx), y: Double(currentMatrix.ty), dataSetIndex: 0)
  26. }
  27. }
  28. func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) {
  29. print("Chart Scaled: \(BGChart.scaleX), \(BGChart.scaleY)")
  30. // dont store huge values
  31. var scale: Float = Float(BGChart.scaleX)
  32. if(scale > ScaleXMax ) {
  33. scale = ScaleXMax
  34. }
  35. UserDefaultsRepository.chartScaleX.value = Float(scale)
  36. }
  37. func createGraph(){
  38. self.BGChart.clear()
  39. // Create the BG Graph Data
  40. let entries = bgData
  41. var bgChartEntry = [ChartDataEntry]()
  42. var colors = [NSUIColor]()
  43. var maxBG: Float = UserDefaultsRepository.minBGScale.value
  44. // Setup BG line details
  45. let lineBG = LineChartDataSet(entries:bgChartEntry, label: "")
  46. lineBG.circleRadius = CGFloat(globalVariables.dotBG)
  47. lineBG.circleColors = [NSUIColor.systemGreen]
  48. lineBG.drawCircleHoleEnabled = false
  49. lineBG.axisDependency = YAxis.AxisDependency.right
  50. lineBG.highlightEnabled = true
  51. lineBG.drawValuesEnabled = false
  52. if UserDefaultsRepository.showLines.value {
  53. lineBG.lineWidth = 2
  54. } else {
  55. lineBG.lineWidth = 0
  56. }
  57. if UserDefaultsRepository.showDots.value {
  58. lineBG.drawCirclesEnabled = true
  59. } else {
  60. lineBG.drawCirclesEnabled = false
  61. }
  62. lineBG.setDrawHighlightIndicators(false)
  63. lineBG.valueFont.withSize(50)
  64. // Setup Prediction line details
  65. var predictionChartEntry = [ChartDataEntry]()
  66. let linePrediction = LineChartDataSet(entries:predictionChartEntry, label: "")
  67. linePrediction.circleRadius = CGFloat(globalVariables.dotBG)
  68. linePrediction.circleColors = [NSUIColor.systemPurple]
  69. linePrediction.colors = [NSUIColor.systemPurple]
  70. linePrediction.drawCircleHoleEnabled = false
  71. linePrediction.axisDependency = YAxis.AxisDependency.right
  72. linePrediction.highlightEnabled = true
  73. linePrediction.drawValuesEnabled = false
  74. if UserDefaultsRepository.showLines.value {
  75. linePrediction.lineWidth = 2
  76. } else {
  77. linePrediction.lineWidth = 0
  78. }
  79. if UserDefaultsRepository.showDots.value {
  80. linePrediction.drawCirclesEnabled = true
  81. } else {
  82. linePrediction.drawCirclesEnabled = false
  83. }
  84. linePrediction.setDrawHighlightIndicators(false)
  85. linePrediction.valueFont.withSize(50)
  86. // create Basal graph data
  87. var chartEntry = [ChartDataEntry]()
  88. var maxBasal = UserDefaultsRepository.minBasalScale.value
  89. let lineBasal = LineChartDataSet(entries:chartEntry, label: "")
  90. lineBasal.setDrawHighlightIndicators(false)
  91. lineBasal.setColor(NSUIColor.systemBlue, alpha: 0.5)
  92. lineBasal.lineWidth = 0
  93. lineBasal.drawFilledEnabled = true
  94. lineBasal.fillColor = NSUIColor.systemBlue
  95. lineBasal.fillAlpha = 0.5
  96. lineBasal.drawCirclesEnabled = false
  97. lineBasal.axisDependency = YAxis.AxisDependency.left
  98. lineBasal.highlightEnabled = true
  99. lineBasal.drawValuesEnabled = false
  100. lineBasal.fillFormatter = basalFillFormatter()
  101. // Boluses
  102. var chartEntryBolus = [ChartDataEntry]()
  103. let lineBolus = LineChartDataSet(entries:chartEntryBolus, label: "")
  104. lineBolus.circleRadius = CGFloat(globalVariables.dotBolus)
  105. lineBolus.circleColors = [NSUIColor.systemBlue.withAlphaComponent(0.75)]
  106. lineBolus.drawCircleHoleEnabled = false
  107. lineBolus.setDrawHighlightIndicators(false)
  108. lineBolus.setColor(NSUIColor.systemBlue, alpha: 1.0)
  109. lineBolus.lineWidth = 0
  110. lineBolus.axisDependency = YAxis.AxisDependency.right
  111. lineBolus.valueFormatter = ChartYDataValueFormatter()
  112. lineBolus.valueTextColor = NSUIColor.label
  113. lineBolus.fillFormatter = BolusFillFormatter()
  114. lineBolus.fillColor = NSUIColor.systemBlue
  115. lineBolus.fillAlpha = 0.6
  116. lineBolus.drawCirclesEnabled = true
  117. lineBolus.drawFilledEnabled = false
  118. if UserDefaultsRepository.showValues.value {
  119. lineBolus.drawValuesEnabled = true
  120. lineBolus.highlightEnabled = false
  121. } else {
  122. lineBolus.drawValuesEnabled = false
  123. lineBolus.highlightEnabled = true
  124. }
  125. // Carbs
  126. var chartEntryCarbs = [ChartDataEntry]()
  127. let lineCarbs = LineChartDataSet(entries:chartEntryCarbs, label: "")
  128. lineCarbs.circleRadius = CGFloat(globalVariables.dotCarb)
  129. lineCarbs.circleColors = [NSUIColor.systemOrange.withAlphaComponent(0.75)]
  130. lineCarbs.drawCircleHoleEnabled = false
  131. lineCarbs.setDrawHighlightIndicators(false)
  132. lineCarbs.setColor(NSUIColor.systemBlue, alpha: 1.0)
  133. lineCarbs.lineWidth = 0
  134. lineCarbs.axisDependency = YAxis.AxisDependency.right
  135. lineCarbs.valueFormatter = ChartYDataValueFormatter()
  136. lineCarbs.valueTextColor = NSUIColor.label
  137. lineCarbs.fillFormatter = CarbFillFormatter()
  138. lineCarbs.fillColor = NSUIColor.systemOrange
  139. lineCarbs.fillAlpha = 0.6
  140. lineCarbs.drawCirclesEnabled = true
  141. lineCarbs.drawFilledEnabled = false
  142. if UserDefaultsRepository.showValues.value {
  143. lineCarbs.drawValuesEnabled = true
  144. lineCarbs.highlightEnabled = false
  145. } else {
  146. lineCarbs.drawValuesEnabled = false
  147. lineCarbs.highlightEnabled = true
  148. }
  149. // create Scheduled Basal graph data
  150. var chartBasalScheduledEntry = [ChartDataEntry]()
  151. let lineBasalScheduled = LineChartDataSet(entries:chartBasalScheduledEntry, label: "")
  152. lineBasalScheduled.setDrawHighlightIndicators(false)
  153. lineBasalScheduled.setColor(NSUIColor.systemBlue, alpha: 0.8)
  154. lineBasalScheduled.lineWidth = 2
  155. lineBasalScheduled.drawFilledEnabled = false
  156. lineBasalScheduled.drawCirclesEnabled = false
  157. lineBasalScheduled.axisDependency = YAxis.AxisDependency.left
  158. lineBasalScheduled.highlightEnabled = false
  159. lineBasalScheduled.drawValuesEnabled = false
  160. lineBasalScheduled.lineDashLengths = [10.0, 5.0]
  161. // create Override graph data
  162. var chartOverrideEntry = [ChartDataEntry]()
  163. let lineOverride = LineChartDataSet(entries:chartOverrideEntry, label: "")
  164. lineOverride.setDrawHighlightIndicators(false)
  165. lineOverride.lineWidth = 0
  166. lineOverride.drawFilledEnabled = true
  167. lineOverride.fillFormatter = OverrideFillFormatter()
  168. lineOverride.fillColor = NSUIColor.systemGreen
  169. lineOverride.fillAlpha = 0.6
  170. lineOverride.drawCirclesEnabled = false
  171. lineOverride.axisDependency = YAxis.AxisDependency.right
  172. lineOverride.highlightEnabled = true
  173. lineOverride.drawValuesEnabled = false
  174. // BG Check
  175. var chartEntryBGCheck = [ChartDataEntry]()
  176. let lineBGCheck = LineChartDataSet(entries:chartEntryBGCheck, label: "")
  177. lineBGCheck.circleRadius = CGFloat(globalVariables.dotOther)
  178. lineBGCheck.circleColors = [NSUIColor.systemRed.withAlphaComponent(0.75)]
  179. lineBGCheck.drawCircleHoleEnabled = false
  180. lineBGCheck.setDrawHighlightIndicators(false)
  181. lineBGCheck.setColor(NSUIColor.systemRed, alpha: 1.0)
  182. lineBGCheck.drawCirclesEnabled = true
  183. lineBGCheck.lineWidth = 0
  184. lineBGCheck.highlightEnabled = true
  185. lineBGCheck.axisDependency = YAxis.AxisDependency.right
  186. lineBGCheck.valueFormatter = ChartYDataValueFormatter()
  187. lineBGCheck.drawValuesEnabled = false
  188. // Suspend Pump
  189. var chartEntrySuspend = [ChartDataEntry]()
  190. let lineSuspend = LineChartDataSet(entries:chartEntrySuspend, label: "")
  191. lineSuspend.circleRadius = CGFloat(globalVariables.dotOther)
  192. lineSuspend.circleColors = [NSUIColor.systemTeal.withAlphaComponent(0.75)]
  193. lineSuspend.drawCircleHoleEnabled = false
  194. lineSuspend.setDrawHighlightIndicators(false)
  195. lineSuspend.setColor(NSUIColor.systemGray2, alpha: 1.0)
  196. lineSuspend.drawCirclesEnabled = true
  197. lineSuspend.lineWidth = 0
  198. lineSuspend.highlightEnabled = true
  199. lineSuspend.axisDependency = YAxis.AxisDependency.right
  200. lineSuspend.valueFormatter = ChartYDataValueFormatter()
  201. lineSuspend.drawValuesEnabled = false
  202. // Resume Pump
  203. var chartEntryResume = [ChartDataEntry]()
  204. let lineResume = LineChartDataSet(entries:chartEntryResume, label: "")
  205. lineResume.circleRadius = CGFloat(globalVariables.dotOther)
  206. lineResume.circleColors = [NSUIColor.systemTeal.withAlphaComponent(0.75)]
  207. lineResume.drawCircleHoleEnabled = false
  208. lineResume.setDrawHighlightIndicators(false)
  209. lineResume.setColor(NSUIColor.systemGray4, alpha: 1.0)
  210. lineResume.drawCirclesEnabled = true
  211. lineResume.lineWidth = 0
  212. lineResume.highlightEnabled = true
  213. lineResume.axisDependency = YAxis.AxisDependency.right
  214. lineResume.valueFormatter = ChartYDataValueFormatter()
  215. lineResume.drawValuesEnabled = false
  216. // Sensor Start
  217. var chartEntrySensor = [ChartDataEntry]()
  218. let lineSensor = LineChartDataSet(entries:chartEntrySensor, label: "")
  219. lineSensor.circleRadius = CGFloat(globalVariables.dotOther)
  220. lineSensor.circleColors = [NSUIColor.systemIndigo.withAlphaComponent(0.75)]
  221. lineSensor.drawCircleHoleEnabled = false
  222. lineSensor.setDrawHighlightIndicators(false)
  223. lineSensor.setColor(NSUIColor.systemGray3, alpha: 1.0)
  224. lineSensor.drawCirclesEnabled = true
  225. lineSensor.lineWidth = 0
  226. lineSensor.highlightEnabled = true
  227. lineSensor.axisDependency = YAxis.AxisDependency.right
  228. lineSensor.valueFormatter = ChartYDataValueFormatter()
  229. lineSensor.drawValuesEnabled = false
  230. // Notes
  231. var chartEntryNote = [ChartDataEntry]()
  232. let lineNote = LineChartDataSet(entries:chartEntryNote, label: "")
  233. lineNote.circleRadius = CGFloat(globalVariables.dotOther)
  234. lineNote.circleColors = [NSUIColor.systemGray.withAlphaComponent(0.75)]
  235. lineNote.drawCircleHoleEnabled = false
  236. lineNote.setDrawHighlightIndicators(false)
  237. lineNote.setColor(NSUIColor.systemGray3, alpha: 1.0)
  238. lineNote.drawCirclesEnabled = true
  239. lineNote.lineWidth = 0
  240. lineNote.highlightEnabled = true
  241. lineNote.axisDependency = YAxis.AxisDependency.right
  242. lineNote.valueFormatter = ChartYDataValueFormatter()
  243. lineNote.drawValuesEnabled = false
  244. // Setup the chart data of all lines
  245. let data = LineChartData()
  246. data.addDataSet(lineBG) // Dataset 0
  247. data.addDataSet(linePrediction) // Dataset 1
  248. data.addDataSet(lineBasal) // Dataset 2
  249. data.addDataSet(lineBolus) // Dataset 3
  250. data.addDataSet(lineCarbs) // Dataset 4
  251. data.addDataSet(lineBasalScheduled) // Dataset 5
  252. data.addDataSet(lineOverride) // Dataset 6
  253. data.addDataSet(lineBGCheck) // Dataset 7
  254. data.addDataSet(lineSuspend) // Dataset 8
  255. data.addDataSet(lineResume) // Dataset 9
  256. data.addDataSet(lineSensor) // Dataset 10
  257. data.addDataSet(lineNote) // Dataset 11
  258. data.setValueFont(UIFont.systemFont(ofSize: 12))
  259. // Add marker popups for bolus and carbs
  260. let marker = PillMarker(color: .secondarySystemBackground, font: UIFont.boldSystemFont(ofSize: 14), textColor: .label)
  261. BGChart.marker = marker
  262. // Clear limit lines so they don't add multiples when changing the settings
  263. BGChart.rightAxis.removeAllLimitLines()
  264. //Add lower red line based on low alert value
  265. let ll = ChartLimitLine()
  266. ll.limit = Double(UserDefaultsRepository.lowLine.value)
  267. ll.lineColor = NSUIColor.systemRed.withAlphaComponent(0.5)
  268. BGChart.rightAxis.addLimitLine(ll)
  269. //Add upper yellow line based on low alert value
  270. let ul = ChartLimitLine()
  271. ul.limit = Double(UserDefaultsRepository.highLine.value)
  272. ul.lineColor = NSUIColor.systemYellow.withAlphaComponent(0.5)
  273. BGChart.rightAxis.addLimitLine(ul)
  274. // Add Now Line
  275. createNowLine()
  276. startGraphNowTimer()
  277. // Setup the main graph overall details
  278. BGChart.xAxis.valueFormatter = ChartXValueFormatter()
  279. BGChart.xAxis.granularity = 1800
  280. BGChart.xAxis.labelTextColor = NSUIColor.label
  281. BGChart.xAxis.labelPosition = XAxis.LabelPosition.bottom
  282. BGChart.xAxis.drawGridLinesEnabled = false
  283. BGChart.leftAxis.enabled = true
  284. BGChart.leftAxis.labelPosition = YAxis.LabelPosition.insideChart
  285. BGChart.leftAxis.axisMaximum = maxBasal
  286. BGChart.leftAxis.axisMinimum = 0
  287. BGChart.leftAxis.drawGridLinesEnabled = false
  288. BGChart.leftAxis.granularityEnabled = true
  289. BGChart.leftAxis.granularity = 0.5
  290. //BGChart.leftAxis.inverted = true
  291. BGChart.rightAxis.labelTextColor = NSUIColor.label
  292. BGChart.rightAxis.labelPosition = YAxis.LabelPosition.insideChart
  293. BGChart.rightAxis.axisMinimum = 0.0
  294. BGChart.rightAxis.axisMaximum = Double(maxBG)
  295. BGChart.rightAxis.gridLineDashLengths = [5.0, 5.0]
  296. BGChart.rightAxis.drawGridLinesEnabled = false
  297. BGChart.rightAxis.valueFormatter = ChartYMMOLValueFormatter()
  298. BGChart.rightAxis.granularityEnabled = true
  299. BGChart.rightAxis.granularity = 50
  300. BGChart.legend.enabled = false
  301. BGChart.scaleYEnabled = false
  302. BGChart.drawGridBackgroundEnabled = true
  303. BGChart.gridBackgroundColor = NSUIColor.secondarySystemBackground
  304. BGChart.highlightValue(nil, callDelegate: false)
  305. BGChart.data = data
  306. BGChart.setExtraOffsets(left: 10, top: 10, right: 10, bottom: 10)
  307. }
  308. func createNowLine() {
  309. BGChart.xAxis.removeAllLimitLines()
  310. let ul = ChartLimitLine()
  311. ul.limit = Double(dateTimeUtils.getNowTimeIntervalUTC())
  312. ul.lineColor = NSUIColor.systemGray.withAlphaComponent(0.5)
  313. ul.lineWidth = 1
  314. BGChart.xAxis.addLimitLine(ul)
  315. }
  316. func updateBGGraphSettings() {
  317. let dataIndex = 0
  318. let dataIndexPrediction = 1
  319. let lineBG = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  320. let linePrediction = BGChart.lineData!.dataSets[dataIndexPrediction] as! LineChartDataSet
  321. if UserDefaultsRepository.showLines.value {
  322. lineBG.lineWidth = 2
  323. linePrediction.lineWidth = 2
  324. } else {
  325. lineBG.lineWidth = 0
  326. linePrediction.lineWidth = 0
  327. }
  328. if UserDefaultsRepository.showDots.value {
  329. lineBG.drawCirclesEnabled = true
  330. linePrediction.drawCirclesEnabled = true
  331. } else {
  332. lineBG.drawCirclesEnabled = false
  333. linePrediction.drawCirclesEnabled = false
  334. }
  335. BGChart.rightAxis.axisMinimum = 0
  336. // Clear limit lines so they don't add multiples when changing the settings
  337. BGChart.rightAxis.removeAllLimitLines()
  338. //Add lower red line based on low alert value
  339. let ll = ChartLimitLine()
  340. ll.limit = Double(UserDefaultsRepository.lowLine.value)
  341. ll.lineColor = NSUIColor.systemRed.withAlphaComponent(0.5)
  342. BGChart.rightAxis.addLimitLine(ll)
  343. //Add upper yellow line based on low alert value
  344. let ul = ChartLimitLine()
  345. ul.limit = Double(UserDefaultsRepository.highLine.value)
  346. ul.lineColor = NSUIColor.systemYellow.withAlphaComponent(0.5)
  347. BGChart.rightAxis.addLimitLine(ul)
  348. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  349. BGChart.data?.notifyDataChanged()
  350. BGChart.notifyDataSetChanged()
  351. }
  352. func updateBGGraph() {
  353. let dataIndex = 0
  354. let entries = bgData
  355. var mainChart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  356. var smallChart = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
  357. mainChart.clear()
  358. smallChart.clear()
  359. var maxBGOffset: Float = 50
  360. var colors = [NSUIColor]()
  361. for i in 0..<entries.count{
  362. if Float(entries[i].sgv) > topBG - maxBGOffset {
  363. topBG = Float(entries[i].sgv) + maxBGOffset
  364. }
  365. let value = ChartDataEntry(x: Double(entries[i].date), y: Double(entries[i].sgv), data: formatPillText(line1: bgUnits.toDisplayUnits(String(entries[i].sgv)), time: entries[i].date))
  366. mainChart.addEntry(value)
  367. smallChart.addEntry(value)
  368. if Double(entries[i].sgv) >= Double(UserDefaultsRepository.highLine.value) {
  369. colors.append(NSUIColor.systemYellow)
  370. } else if Double(entries[i].sgv) <= Double(UserDefaultsRepository.lowLine.value) {
  371. colors.append(NSUIColor.systemRed)
  372. } else {
  373. colors.append(NSUIColor.systemGreen)
  374. }
  375. }
  376. // Set Colors
  377. let lineBG = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  378. let lineBGSmall = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
  379. lineBG.colors.removeAll()
  380. lineBG.circleColors.removeAll()
  381. lineBGSmall.colors.removeAll()
  382. lineBGSmall.circleColors.removeAll()
  383. if colors.count > 0 {
  384. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Graph: colors") }
  385. for i in 0..<colors.count{
  386. mainChart.addColor(colors[i])
  387. mainChart.circleColors.append(colors[i])
  388. smallChart.addColor(colors[i])
  389. smallChart.circleColors.append(colors[i])
  390. }
  391. }
  392. BGChart.rightAxis.axisMaximum = Double(topBG)
  393. BGChart.setVisibleXRangeMinimum(600)
  394. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  395. BGChart.data?.notifyDataChanged()
  396. BGChart.notifyDataSetChanged()
  397. BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
  398. BGChartFull.data?.notifyDataChanged()
  399. BGChartFull.notifyDataSetChanged()
  400. if firstGraphLoad {
  401. var scaleX = CGFloat(UserDefaultsRepository.chartScaleX.value)
  402. print("Scale: \(scaleX)")
  403. if( scaleX > CGFloat(ScaleXMax) ) {
  404. scaleX = CGFloat(ScaleXMax)
  405. UserDefaultsRepository.chartScaleX.value = ScaleXMax
  406. }
  407. BGChart.zoom(scaleX: scaleX, scaleY: 1, x: 1, y: 1)
  408. firstGraphLoad = false
  409. }
  410. if BGChart.chartXMax > dateTimeUtils.getNowTimeIntervalUTC() {
  411. BGChart.moveViewToAnimated(xValue: dateTimeUtils.getNowTimeIntervalUTC() - (BGChart.visibleXRange * 0.7), yValue: 0.0, axis: .right, duration: 1, easingOption: .easeInBack)
  412. }
  413. }
  414. func updatePredictionGraph() {
  415. let dataIndex = 1
  416. var mainChart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  417. var smallChart = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
  418. mainChart.clear()
  419. smallChart.clear()
  420. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Graph: print prediction") }
  421. var colors = [NSUIColor]()
  422. let maxBGOffset: Float = 20
  423. for i in 0..<predictionData.count {
  424. var predictionVal = Double(predictionData[i].sgv)
  425. if Float(predictionVal) > topBG - maxBGOffset {
  426. topBG = Float(predictionVal) + maxBGOffset
  427. }
  428. if i == 0 {
  429. if UserDefaultsRepository.showDots.value {
  430. colors.append(NSUIColor.systemPurple.withAlphaComponent(0.0))
  431. } else {
  432. colors.append(NSUIColor.systemPurple.withAlphaComponent(1.0))
  433. }
  434. } else if predictionVal > 400 {
  435. predictionVal = 400
  436. colors.append(NSUIColor.systemYellow)
  437. } else if predictionVal < 0 {
  438. predictionVal = 0
  439. colors.append(NSUIColor.systemRed)
  440. } else {
  441. colors.append(NSUIColor.systemPurple)
  442. }
  443. let value = ChartDataEntry(x: predictionData[i].date, y: predictionVal, data: formatPillText(line1: bgUnits.toDisplayUnits(String(predictionData[i].sgv)), time: predictionData[i].date))
  444. mainChart.addEntry(value)
  445. smallChart.addEntry(value)
  446. }
  447. smallChart.circleColors.removeAll()
  448. smallChart.colors.removeAll()
  449. mainChart.colors.removeAll()
  450. mainChart.circleColors.removeAll()
  451. if colors.count > 0 {
  452. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Graph: prediction colors") }
  453. for i in 0..<colors.count{
  454. mainChart.addColor(colors[i])
  455. mainChart.circleColors.append(colors[i])
  456. smallChart.addColor(colors[i])
  457. smallChart.circleColors.append(colors[i])
  458. }
  459. }
  460. BGChart.rightAxis.axisMaximum = Double(topBG)
  461. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  462. BGChart.data?.notifyDataChanged()
  463. BGChart.notifyDataSetChanged()
  464. BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
  465. BGChartFull.data?.notifyDataChanged()
  466. BGChartFull.notifyDataSetChanged()
  467. }
  468. func updateBasalGraph() {
  469. var dataIndex = 2
  470. BGChart.lineData?.dataSets[dataIndex].clear()
  471. var maxBasal = UserDefaultsRepository.minBasalScale.value
  472. for i in 0..<basalData.count{
  473. let value = ChartDataEntry(x: Double(basalData[i].date), y: Double(basalData[i].basalRate), data: formatPillText(line1: String(basalData[i].basalRate), time: basalData[i].date))
  474. BGChart.data?.dataSets[dataIndex].addEntry(value)
  475. if basalData[i].basalRate > maxBasal {
  476. maxBasal = basalData[i].basalRate
  477. }
  478. }
  479. BGChart.leftAxis.axisMaximum = maxBasal
  480. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  481. BGChart.data?.notifyDataChanged()
  482. BGChart.notifyDataSetChanged()
  483. }
  484. func updateBasalScheduledGraph() {
  485. var dataIndex = 5
  486. BGChart.lineData?.dataSets[dataIndex].clear()
  487. for i in 0..<basalScheduleData.count{
  488. let value = ChartDataEntry(x: Double(basalScheduleData[i].date), y: Double(basalScheduleData[i].basalRate))
  489. BGChart.data?.dataSets[dataIndex].addEntry(value)
  490. }
  491. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  492. BGChart.data?.notifyDataChanged()
  493. BGChart.notifyDataSetChanged()
  494. }
  495. func updateBolusGraph() {
  496. var dataIndex = 3
  497. var yTop: Double = 370
  498. var yBottom: Double = 345
  499. BGChart.lineData?.dataSets[dataIndex].clear()
  500. for i in 0..<bolusData.count{
  501. let formatter = NumberFormatter()
  502. formatter.minimumFractionDigits = 0
  503. formatter.maximumFractionDigits = 2
  504. formatter.minimumIntegerDigits = 0
  505. // Check overlapping carbs to shift left if needed
  506. let bolusShift = findNextBolusTime(timeWithin: 240, needle: bolusData[i].date, haystack: bolusData, startingIndex: i)
  507. var dateTimeStamp = bolusData[i].date
  508. if bolusShift {
  509. // Move it half the distance between BG readings
  510. dateTimeStamp = dateTimeStamp - 150
  511. }
  512. // skip if > 24 hours old
  513. if dateTimeStamp < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  514. let dot = ChartDataEntry(x: Double(dateTimeStamp), y: Double(bolusData[i].sgv), data: formatter.string(from: NSNumber(value: bolusData[i].value)))
  515. BGChart.data?.dataSets[dataIndex].addEntry(dot)
  516. }
  517. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  518. BGChart.data?.notifyDataChanged()
  519. BGChart.notifyDataSetChanged()
  520. }
  521. func updateCarbGraph() {
  522. var dataIndex = 4
  523. BGChart.lineData?.dataSets[dataIndex].clear()
  524. for i in 0..<carbData.count{
  525. let formatter = NumberFormatter()
  526. formatter.minimumFractionDigits = 0
  527. formatter.maximumFractionDigits = 2
  528. formatter.minimumIntegerDigits = 1
  529. var valueString: String = formatter.string(from: NSNumber(value: carbData[i].value))!
  530. if carbData[i].absorptionTime > 0 && UserDefaultsRepository.showAbsorption.value {
  531. let hours = carbData[i].absorptionTime / 60
  532. valueString += " " + String(hours) + "h"
  533. }
  534. // Check overlapping carbs to shift left if needed
  535. let carbShift = findNextCarbTime(timeWithin: 250, needle: carbData[i].date, haystack: carbData, startingIndex: i)
  536. var dateTimeStamp = carbData[i].date
  537. // skip if > 24 hours old
  538. if dateTimeStamp < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  539. if carbShift {
  540. dateTimeStamp = dateTimeStamp - 250
  541. }
  542. let dot = ChartDataEntry(x: Double(dateTimeStamp), y: Double(carbData[i].sgv), data: valueString)
  543. BGChart.data?.dataSets[dataIndex].addEntry(dot)
  544. }
  545. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  546. BGChart.data?.notifyDataChanged()
  547. BGChart.notifyDataSetChanged()
  548. }
  549. func updateBGCheckGraph() {
  550. var dataIndex = 7
  551. BGChart.lineData?.dataSets[dataIndex].clear()
  552. for i in 0..<bgCheckData.count{
  553. let formatter = NumberFormatter()
  554. formatter.minimumFractionDigits = 0
  555. formatter.maximumFractionDigits = 2
  556. formatter.minimumIntegerDigits = 1
  557. // skip if > 24 hours old
  558. if bgCheckData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  559. let value = ChartDataEntry(x: Double(bgCheckData[i].date), y: Double(bgCheckData[i].sgv), data: formatPillText(line1: bgUnits.toDisplayUnits(String(bgCheckData[i].sgv)), time: bgCheckData[i].date))
  560. BGChart.data?.dataSets[dataIndex].addEntry(value)
  561. }
  562. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  563. BGChart.data?.notifyDataChanged()
  564. BGChart.notifyDataSetChanged()
  565. }
  566. func updateSuspendGraph() {
  567. var dataIndex = 8
  568. BGChart.lineData?.dataSets[dataIndex].clear()
  569. let thisData = suspendGraphData
  570. for i in 0..<thisData.count{
  571. // skip if > 24 hours old
  572. if thisData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  573. let value = ChartDataEntry(x: Double(thisData[i].date), y: Double(thisData[i].sgv), data: formatPillText(line1: "Suspend Pump", time: thisData[i].date))
  574. BGChart.data?.dataSets[dataIndex].addEntry(value)
  575. }
  576. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  577. BGChart.data?.notifyDataChanged()
  578. BGChart.notifyDataSetChanged()
  579. }
  580. func updateResumeGraph() {
  581. var dataIndex = 9
  582. BGChart.lineData?.dataSets[dataIndex].clear()
  583. let thisData = resumeGraphData
  584. for i in 0..<thisData.count{
  585. // skip if > 24 hours old
  586. if thisData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  587. let value = ChartDataEntry(x: Double(thisData[i].date), y: Double(thisData[i].sgv), data: formatPillText(line1: "Resume Pump", time: thisData[i].date))
  588. BGChart.data?.dataSets[dataIndex].addEntry(value)
  589. }
  590. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  591. BGChart.data?.notifyDataChanged()
  592. BGChart.notifyDataSetChanged()
  593. }
  594. func updateSensorStart() {
  595. var dataIndex = 10
  596. BGChart.lineData?.dataSets[dataIndex].clear()
  597. let thisData = sensorStartGraphData
  598. for i in 0..<thisData.count{
  599. // skip if > 24 hours old
  600. if thisData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  601. let value = ChartDataEntry(x: Double(thisData[i].date), y: Double(thisData[i].sgv), data: formatPillText(line1: "Start Sensor", time: thisData[i].date))
  602. BGChart.data?.dataSets[dataIndex].addEntry(value)
  603. }
  604. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  605. BGChart.data?.notifyDataChanged()
  606. BGChart.notifyDataSetChanged()
  607. }
  608. func updateNotes() {
  609. var dataIndex = 11
  610. BGChart.lineData?.dataSets[dataIndex].clear()
  611. let thisData = noteGraphData
  612. for i in 0..<thisData.count{
  613. // skip if > 24 hours old
  614. if thisData[i].date < dateTimeUtils.getTimeInterval24HoursAgo() { continue }
  615. let value = ChartDataEntry(x: Double(thisData[i].date), y: Double(thisData[i].sgv), data: formatPillText(line1: thisData[i].note, time: thisData[i].date))
  616. BGChart.data?.dataSets[dataIndex].addEntry(value)
  617. }
  618. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  619. BGChart.data?.notifyDataChanged()
  620. BGChart.notifyDataSetChanged()
  621. }
  622. func createSmallBGGraph(){
  623. let entries = bgData
  624. var bgChartEntry = [ChartDataEntry]()
  625. var colors = [NSUIColor]()
  626. let lineBG = LineChartDataSet(entries:bgChartEntry, label: "")
  627. lineBG.drawCirclesEnabled = false
  628. //line2.setDrawHighlightIndicators(false)
  629. lineBG.highlightEnabled = true
  630. lineBG.drawHorizontalHighlightIndicatorEnabled = false
  631. lineBG.drawVerticalHighlightIndicatorEnabled = false
  632. lineBG.highlightColor = NSUIColor.label
  633. lineBG.drawValuesEnabled = false
  634. lineBG.lineWidth = 2
  635. // Setup Prediction line details
  636. var predictionChartEntry = [ChartDataEntry]()
  637. let linePrediction = LineChartDataSet(entries:predictionChartEntry, label: "")
  638. linePrediction.drawCirclesEnabled = false
  639. //line2.setDrawHighlightIndicators(false)
  640. linePrediction.setColor(NSUIColor.systemPurple)
  641. linePrediction.highlightEnabled = true
  642. linePrediction.drawHorizontalHighlightIndicatorEnabled = false
  643. linePrediction.drawVerticalHighlightIndicatorEnabled = false
  644. linePrediction.highlightColor = NSUIColor.label
  645. linePrediction.drawValuesEnabled = false
  646. linePrediction.lineWidth = 2
  647. let data = LineChartData()
  648. data.addDataSet(lineBG)
  649. data.addDataSet(linePrediction)
  650. BGChartFull.highlightPerDragEnabled = true
  651. BGChartFull.leftAxis.enabled = false
  652. BGChartFull.rightAxis.enabled = false
  653. BGChartFull.xAxis.enabled = false
  654. BGChartFull.legend.enabled = false
  655. BGChartFull.scaleYEnabled = false
  656. BGChartFull.scaleXEnabled = false
  657. BGChartFull.drawGridBackgroundEnabled = false
  658. BGChartFull.data = data
  659. }
  660. func updateOverrideGraph() {
  661. var dataIndex = 6
  662. var yTop: Double = Double(topBG - 1)
  663. var yBottom: Double = Double(topBG - 25)
  664. var chart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  665. chart.clear()
  666. let thisData = overrideGraphData
  667. var colors = [NSUIColor]()
  668. for i in 0..<thisData.count{
  669. let thisItem = thisData[i]
  670. let multiplier = thisItem.insulNeedsScaleFactor as! Double * 100.0
  671. //let labelText = String(format: "%.0f%%", multiplier)
  672. var labelText = thisItem.reason + "\r\n"
  673. labelText += String(Int(thisItem.insulNeedsScaleFactor * 100)) + "% "
  674. if thisItem.correctionRange.count == 2 {
  675. labelText += String(thisItem.correctionRange[0]) + "-" + String(thisItem.correctionRange[1])
  676. }
  677. // Start Dot
  678. // Shift dots 30 seconds to create an empty 0 space between consecutive temps
  679. let preStartDot = ChartDataEntry(x: Double(thisItem.date), y: yBottom, data: "hide")
  680. BGChart.data?.dataSets[dataIndex].addEntry(preStartDot)
  681. let value = ChartDataEntry(x: Double(thisItem.date + 1), y: yTop, data: labelText)
  682. BGChart.data?.dataSets[dataIndex].addEntry(value)
  683. if Double(thisItem.insulNeedsScaleFactor) == 1.0 {
  684. colors.append(NSUIColor.systemGray.withAlphaComponent(0.0))
  685. } else if i >= overrideGraphData.count - 2 {
  686. colors.append(NSUIColor.systemGreen)
  687. } else {
  688. colors.append(NSUIColor.systemGray.withAlphaComponent(CGFloat(thisItem.insulNeedsScaleFactor / 2)))
  689. }
  690. // End Dot
  691. let endDot = ChartDataEntry(x: Double(thisItem.endDate - 1), y: yTop, data: labelText)
  692. BGChart.data?.dataSets[dataIndex].addEntry(endDot)
  693. // Post end dot
  694. let postEndDot = ChartDataEntry(x: Double(thisItem.endDate), y: yBottom, data: "hide")
  695. BGChart.data?.dataSets[dataIndex].addEntry(postEndDot)
  696. if Double(thisItem.insulNeedsScaleFactor) == 1.0 {
  697. colors.append(NSUIColor.systemGray.withAlphaComponent(0.0))
  698. } else if i >= overrideGraphData.count - 2 {
  699. colors.append(NSUIColor.systemGreen)
  700. } else {
  701. colors.append(NSUIColor.systemGray.withAlphaComponent(CGFloat(thisItem.insulNeedsScaleFactor / 2)))
  702. }
  703. }
  704. // Set Colors
  705. let line = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
  706. line.colors.removeAll()
  707. line.circleColors.removeAll()
  708. if colors.count > 0 {
  709. for i in 0..<colors.count{
  710. chart.addColor(colors[i])
  711. chart.circleColors.append(colors[i])
  712. }
  713. }
  714. BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
  715. BGChart.data?.notifyDataChanged()
  716. BGChart.notifyDataSetChanged()
  717. }
  718. func formatPillText(line1: String, time: TimeInterval) -> String {
  719. let dateFormatter = DateFormatter()
  720. //let timezoneOffset = TimeZone.current.secondsFromGMT()
  721. //let epochTimezoneOffset = value + Double(timezoneOffset)
  722. if dateTimeUtils.is24Hour() {
  723. dateFormatter.setLocalizedDateFormatFromTemplate("HH:mm")
  724. } else {
  725. dateFormatter.setLocalizedDateFormatFromTemplate("hh:mm")
  726. }
  727. //let date = Date(timeIntervalSince1970: epochTimezoneOffset)
  728. let date = Date(timeIntervalSince1970: time)
  729. let formattedDate = dateFormatter.string(from: date)
  730. return line1 + "\r\n" + formattedDate
  731. }
  732. }