-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathGraphs.swift
More file actions
1986 lines (1741 loc) · 81.3 KB
/
Graphs.swift
File metadata and controls
1986 lines (1741 loc) · 81.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// LoopFollow
// Graphs.swift
import Charts
import Foundation
import UIKit
import Charts
enum GraphDataIndex: Int {
case bg = 0
case prediction = 1
case basal = 2
case bolus = 3
case carbs = 4
case basalScheduled = 5
case override = 6
case bgCheck = 7
case suspend = 8
case resumePump = 9
case sensorStart = 10
case note = 11
case ztPrediction = 12
case iobPrediction = 13
case cobPrediction = 14
case uamPrediction = 15
case smb = 16
case tempTarget = 17
}
extension GraphDataIndex {
var description: String {
switch self {
case .bg: return "BG"
case .prediction: return "Prediction"
case .basal: return "Basal"
case .bolus: return "Bolus"
case .carbs: return "Carbs"
case .basalScheduled: return "Basal Scheduled"
case .override: return "Override"
case .bgCheck: return "BG Check"
case .suspend: return "Suspend"
case .resumePump: return "Resume Pump"
case .sensorStart: return "Sensor Start"
case .note: return "Note"
case .ztPrediction: return "ZT Prediction"
case .iobPrediction: return "IOB Prediction"
case .cobPrediction: return "COB Prediction"
case .uamPrediction: return "UAM Prediction"
case .smb: return "SMB"
case .tempTarget: return "Temp Target"
}
}
}
class CompositeRenderer: LineChartRenderer {
let tempTargetRenderer: TempTargetRenderer
let triangleRenderer: TriangleRenderer
init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?, tempTargetDataSetIndex: Int, smbDataSetIndex: Int) {
tempTargetRenderer = TempTargetRenderer(
dataProvider: dataProvider,
animator: animator,
viewPortHandler: viewPortHandler,
tempTargetDataSetIndex: tempTargetDataSetIndex
)
triangleRenderer = TriangleRenderer(
dataProvider: dataProvider,
animator: animator,
viewPortHandler: viewPortHandler,
smbDataSetIndex: smbDataSetIndex
)
super.init(dataProvider: dataProvider!, animator: animator!, viewPortHandler: viewPortHandler!)
}
override func drawExtras(context: CGContext) {
super.drawExtras(context: context)
tempTargetRenderer.drawExtras(context: context)
triangleRenderer.drawExtras(context: context)
}
}
class TriangleRenderer: LineChartRenderer {
let smbDataSetIndex: Int
init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?, smbDataSetIndex: Int) {
self.smbDataSetIndex = smbDataSetIndex
super.init(dataProvider: dataProvider!, animator: animator!, viewPortHandler: viewPortHandler!)
}
override func drawExtras(context: CGContext) {
super.drawExtras(context: context)
guard let dataProvider = dataProvider else { return }
if dataProvider.lineData?.dataSets.count ?? 0 > smbDataSetIndex, let lineDataSet = dataProvider.lineData?.dataSets[smbDataSetIndex] as? LineChartDataSet {
let trans = dataProvider.getTransformer(forAxis: lineDataSet.axisDependency)
let phaseY = animator.phaseY
for j in 0 ..< lineDataSet.entryCount {
guard let e = lineDataSet.entryForIndex(j) else { continue }
let pt = trans.pixelForValues(x: e.x, y: e.y * phaseY)
context.saveGState()
context.beginPath()
context.move(to: CGPoint(x: pt.x, y: pt.y + 9))
context.addLine(to: CGPoint(x: pt.x - 5, y: pt.y - 1))
context.addLine(to: CGPoint(x: pt.x + 5, y: pt.y - 1))
context.closePath()
context.setFillColor(lineDataSet.circleColors.first!.cgColor)
context.fillPath()
context.restoreGState()
}
}
}
}
class TempTargetChartDataEntry: ChartDataEntry {
var xStart: Double = 0.0
var xEnd: Double = 0.0
var yTop: Double = 0.0
var yBottom: Double = 0.0
required init() {
super.init()
}
init(xStart: Double, xEnd: Double, yTop: Double, yBottom: Double, data: Any?) {
self.xStart = xStart
self.xEnd = xEnd
self.yTop = yTop
self.yBottom = yBottom
super.init(x: xStart, y: yTop)
self.data = data
}
override func copy(with _: NSZone? = nil) -> Any {
let copy = TempTargetChartDataEntry(
xStart: xStart,
xEnd: xEnd,
yTop: yTop,
yBottom: yBottom,
data: data
)
return copy
}
}
class TempTargetRenderer: LineChartRenderer {
let tempTargetDataSetIndex: Int
init(dataProvider: LineChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?, tempTargetDataSetIndex: Int) {
self.tempTargetDataSetIndex = tempTargetDataSetIndex
super.init(dataProvider: dataProvider!, animator: animator!, viewPortHandler: viewPortHandler!)
}
override func drawExtras(context: CGContext) {
super.drawExtras(context: context)
guard let dataProvider = dataProvider else { return }
if dataProvider.lineData?.dataSets.count ?? 0 > tempTargetDataSetIndex,
let lineDataSet = dataProvider.lineData?.dataSets[tempTargetDataSetIndex] as? LineChartDataSet
{
let trans = dataProvider.getTransformer(forAxis: lineDataSet.axisDependency)
let phaseY = animator.phaseY
for i in 0 ..< lineDataSet.entryCount {
guard let entry = lineDataSet.entryForIndex(i) as? TempTargetChartDataEntry else { continue }
let xStart = entry.xStart
let xEnd = entry.xEnd
let yTop = entry.yTop * phaseY
let yBottom = entry.yBottom * phaseY
let leftTop = trans.pixelForValues(x: xStart, y: yTop)
let rightBottom = trans.pixelForValues(x: xEnd, y: yBottom)
var rect = CGRect(x: leftTop.x, y: leftTop.y, width: rightBottom.x - leftTop.x, height: rightBottom.y - leftTop.y)
if rect.width < 0 {
rect.origin.x += rect.width
rect.size.width = abs(rect.width)
}
if rect.height < 0 {
rect.origin.y += rect.height
rect.size.height = abs(rect.height)
}
context.saveGState()
context.setFillColor(NSUIColor.systemPurple.withAlphaComponent(0.5).cgColor)
context.fill(rect)
context.restoreGState()
}
}
}
}
let ScaleXMax: Double = 150.0
extension MainViewController {
private func graphRangeThresholds() -> (low: Double, high: Double) {
let low = 70.0
let high = UnitSettingsStore.shared.timeInRangeMode == .titr ? 140.0 : 180.0
return (low, high)
}
func updateChartRenderers() {
let tempTargetDataIndex = GraphDataIndex.tempTarget.rawValue
let smbDataIndex = GraphDataIndex.smb.rawValue
let compositeRenderer = CompositeRenderer(
dataProvider: BGChart,
animator: BGChart.chartAnimator,
viewPortHandler: BGChart.viewPortHandler,
tempTargetDataSetIndex: tempTargetDataIndex,
smbDataSetIndex: smbDataIndex
)
BGChart.renderer = compositeRenderer
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight _: Highlight) {
if chartView == BGChartFull {
BGChart.moveViewToX(entry.x)
}
if entry.data as? String == "hide" {
BGChart.highlightValue(nil, callDelegate: false)
}
}
func chartScaled(_: ChartViewBase, scaleX _: CGFloat, scaleY _: CGFloat) {
// dont store huge values
var scale = Double(BGChart.scaleX)
if scale > ScaleXMax {
scale = ScaleXMax
}
Storage.shared.chartScaleX.value = scale
}
func createGraph() {
// Create the BG Graph Data
let bgChartEntry = [ChartDataEntry]()
let maxBG = Storage.shared.minBGScale.value
// Setup BG line details
let lineBG = LineChartDataSet(entries: bgChartEntry, label: "")
lineBG.circleRadius = CGFloat(globalVariables.dotBG)
lineBG.circleColors = [NSUIColor.systemGreen]
lineBG.drawCircleHoleEnabled = false
lineBG.axisDependency = YAxis.AxisDependency.right
lineBG.highlightEnabled = true
lineBG.drawValuesEnabled = false
if Storage.shared.showLines.value {
lineBG.lineWidth = 2
} else {
lineBG.lineWidth = 0
}
if Storage.shared.showDots.value {
lineBG.drawCirclesEnabled = true
} else {
lineBG.drawCirclesEnabled = false
}
lineBG.setDrawHighlightIndicators(false)
lineBG.valueFont.withSize(50)
// Setup Prediction line details
let predictionChartEntry = [ChartDataEntry]()
let linePrediction = LineChartDataSet(entries: predictionChartEntry, label: "")
linePrediction.circleRadius = CGFloat(globalVariables.dotBG)
linePrediction.circleColors = [NSUIColor.systemPurple]
linePrediction.colors = [NSUIColor.systemPurple]
linePrediction.drawCircleHoleEnabled = false
linePrediction.axisDependency = YAxis.AxisDependency.right
linePrediction.highlightEnabled = true
linePrediction.drawValuesEnabled = false
if Storage.shared.showLines.value {
linePrediction.lineWidth = 2
} else {
linePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
linePrediction.drawCirclesEnabled = true
} else {
linePrediction.drawCirclesEnabled = false
}
linePrediction.setDrawHighlightIndicators(false)
linePrediction.valueFont.withSize(50)
// create Basal graph data
let chartEntry = [ChartDataEntry]()
let maxBasal = Storage.shared.minBasalScale.value
let lineBasal = LineChartDataSet(entries: chartEntry, label: "")
lineBasal.setDrawHighlightIndicators(false)
lineBasal.setColor(NSUIColor.systemBlue, alpha: 0.5)
lineBasal.lineWidth = 0
lineBasal.drawFilledEnabled = true
lineBasal.fillColor = NSUIColor.systemBlue
lineBasal.fillAlpha = 0.5
lineBasal.drawCirclesEnabled = false
lineBasal.axisDependency = YAxis.AxisDependency.left
lineBasal.highlightEnabled = true
lineBasal.drawValuesEnabled = false
lineBasal.fillFormatter = basalFillFormatter()
// Boluses
let chartEntryBolus = [ChartDataEntry]()
let lineBolus = LineChartDataSet(entries: chartEntryBolus, label: "")
lineBolus.circleRadius = CGFloat(globalVariables.dotBolus)
lineBolus.circleColors = [NSUIColor.systemBlue.withAlphaComponent(0.75)]
lineBolus.drawCircleHoleEnabled = false
lineBolus.setDrawHighlightIndicators(false)
lineBolus.setColor(NSUIColor.systemBlue, alpha: 1.0)
lineBolus.lineWidth = 0
lineBolus.axisDependency = YAxis.AxisDependency.right
lineBolus.valueFormatter = ChartYDataValueFormatter()
lineBolus.valueTextColor = NSUIColor.label
lineBolus.fillColor = NSUIColor.systemBlue
lineBolus.fillAlpha = 0.6
lineBolus.drawCirclesEnabled = true
lineBolus.drawFilledEnabled = false
if Storage.shared.showValues.value {
lineBolus.drawValuesEnabled = true
lineBolus.highlightEnabled = false
} else {
lineBolus.drawValuesEnabled = false
lineBolus.highlightEnabled = true
}
// Carbs
let chartEntryCarbs = [ChartDataEntry]()
let lineCarbs = LineChartDataSet(entries: chartEntryCarbs, label: "")
lineCarbs.circleRadius = CGFloat(globalVariables.dotCarb)
lineCarbs.circleColors = [NSUIColor.systemOrange.withAlphaComponent(0.75)]
lineCarbs.drawCircleHoleEnabled = false
lineCarbs.setDrawHighlightIndicators(false)
lineCarbs.setColor(NSUIColor.systemBlue, alpha: 1.0)
lineCarbs.lineWidth = 0
lineCarbs.axisDependency = YAxis.AxisDependency.right
lineCarbs.valueFormatter = ChartYDataValueFormatter()
lineCarbs.valueTextColor = NSUIColor.label
lineCarbs.fillColor = NSUIColor.systemOrange
lineCarbs.fillAlpha = 0.6
lineCarbs.drawCirclesEnabled = true
lineCarbs.drawFilledEnabled = false
if Storage.shared.showValues.value {
lineCarbs.drawValuesEnabled = true
lineCarbs.highlightEnabled = false
} else {
lineCarbs.drawValuesEnabled = false
lineCarbs.highlightEnabled = true
}
// create Scheduled Basal graph data
let chartBasalScheduledEntry = [ChartDataEntry]()
let lineBasalScheduled = LineChartDataSet(entries: chartBasalScheduledEntry, label: "")
lineBasalScheduled.setDrawHighlightIndicators(false)
lineBasalScheduled.setColor(NSUIColor.systemBlue, alpha: 0.8)
lineBasalScheduled.lineWidth = 2
lineBasalScheduled.drawFilledEnabled = false
lineBasalScheduled.drawCirclesEnabled = false
lineBasalScheduled.axisDependency = YAxis.AxisDependency.left
lineBasalScheduled.highlightEnabled = false
lineBasalScheduled.drawValuesEnabled = false
lineBasalScheduled.lineDashLengths = [10.0, 5.0]
// create Override graph data
let chartOverrideEntry = [ChartDataEntry]()
let lineOverride = LineChartDataSet(entries: chartOverrideEntry, label: "")
lineOverride.setDrawHighlightIndicators(false)
lineOverride.lineWidth = 0
lineOverride.drawFilledEnabled = true
lineOverride.fillFormatter = OverrideFillFormatter()
lineOverride.fillColor = NSUIColor.systemGreen
lineOverride.fillAlpha = 0.6
lineOverride.drawCirclesEnabled = false
lineOverride.axisDependency = YAxis.AxisDependency.right
lineOverride.highlightEnabled = true
lineOverride.drawValuesEnabled = false
// BG Check
let chartEntryBGCheck = [ChartDataEntry]()
let lineBGCheck = LineChartDataSet(entries: chartEntryBGCheck, label: "")
lineBGCheck.circleRadius = CGFloat(globalVariables.dotOther)
lineBGCheck.circleColors = [NSUIColor.systemRed.withAlphaComponent(0.75)]
lineBGCheck.drawCircleHoleEnabled = false
lineBGCheck.setDrawHighlightIndicators(false)
lineBGCheck.setColor(NSUIColor.systemRed, alpha: 1.0)
lineBGCheck.drawCirclesEnabled = true
lineBGCheck.lineWidth = 0
lineBGCheck.highlightEnabled = true
lineBGCheck.axisDependency = YAxis.AxisDependency.right
lineBGCheck.valueFormatter = ChartYDataValueFormatter()
lineBGCheck.drawValuesEnabled = false
// Suspend Pump
let chartEntrySuspend = [ChartDataEntry]()
let lineSuspend = LineChartDataSet(entries: chartEntrySuspend, label: "")
lineSuspend.circleRadius = CGFloat(globalVariables.dotOther)
lineSuspend.circleColors = [NSUIColor.systemTeal.withAlphaComponent(0.75)]
lineSuspend.drawCircleHoleEnabled = false
lineSuspend.setDrawHighlightIndicators(false)
lineSuspend.setColor(NSUIColor.systemGray2, alpha: 1.0)
lineSuspend.drawCirclesEnabled = true
lineSuspend.lineWidth = 0
lineSuspend.highlightEnabled = true
lineSuspend.axisDependency = YAxis.AxisDependency.right
lineSuspend.valueFormatter = ChartYDataValueFormatter()
lineSuspend.drawValuesEnabled = false
// Resume Pump
let chartEntryResume = [ChartDataEntry]()
let lineResume = LineChartDataSet(entries: chartEntryResume, label: "")
lineResume.circleRadius = CGFloat(globalVariables.dotOther)
lineResume.circleColors = [NSUIColor.systemTeal.withAlphaComponent(0.75)]
lineResume.drawCircleHoleEnabled = false
lineResume.setDrawHighlightIndicators(false)
lineResume.setColor(NSUIColor.systemGray4, alpha: 1.0)
lineResume.drawCirclesEnabled = true
lineResume.lineWidth = 0
lineResume.highlightEnabled = true
lineResume.axisDependency = YAxis.AxisDependency.right
lineResume.valueFormatter = ChartYDataValueFormatter()
lineResume.drawValuesEnabled = false
// Sensor Start
let chartEntrySensor = [ChartDataEntry]()
let lineSensor = LineChartDataSet(entries: chartEntrySensor, label: "")
lineSensor.circleRadius = CGFloat(globalVariables.dotOther)
lineSensor.circleColors = [NSUIColor.systemIndigo.withAlphaComponent(0.75)]
lineSensor.drawCircleHoleEnabled = false
lineSensor.setDrawHighlightIndicators(false)
lineSensor.setColor(NSUIColor.systemGray3, alpha: 1.0)
lineSensor.drawCirclesEnabled = true
lineSensor.lineWidth = 0
lineSensor.highlightEnabled = true
lineSensor.axisDependency = YAxis.AxisDependency.right
lineSensor.valueFormatter = ChartYDataValueFormatter()
lineSensor.drawValuesEnabled = false
// Notes
let chartEntryNote = [ChartDataEntry]()
let lineNote = LineChartDataSet(entries: chartEntryNote, label: "")
lineNote.circleRadius = CGFloat(globalVariables.dotOther)
lineNote.circleColors = [NSUIColor.systemGray.withAlphaComponent(0.75)]
lineNote.drawCircleHoleEnabled = false
lineNote.setDrawHighlightIndicators(false)
lineNote.setColor(NSUIColor.systemGray3, alpha: 1.0)
lineNote.drawCirclesEnabled = true
lineNote.lineWidth = 0
lineNote.highlightEnabled = true
lineNote.axisDependency = YAxis.AxisDependency.right
lineNote.valueFormatter = ChartYDataValueFormatter()
lineNote.drawValuesEnabled = false
// Setup COB Prediction line details
let COBpredictionChartEntry = [ChartDataEntry]()
let COBlinePrediction = LineChartDataSet(entries: COBpredictionChartEntry, label: "")
COBlinePrediction.circleRadius = CGFloat(globalVariables.dotBG)
COBlinePrediction.circleColors = [NSUIColor.systemPurple]
COBlinePrediction.colors = [NSUIColor.systemPurple]
COBlinePrediction.drawCircleHoleEnabled = false
COBlinePrediction.axisDependency = YAxis.AxisDependency.right
COBlinePrediction.highlightEnabled = true
COBlinePrediction.drawValuesEnabled = false
if Storage.shared.showLines.value {
COBlinePrediction.lineWidth = 2
} else {
COBlinePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
COBlinePrediction.drawCirclesEnabled = true
} else {
COBlinePrediction.drawCirclesEnabled = false
}
COBlinePrediction.setDrawHighlightIndicators(false)
COBlinePrediction.valueFont.withSize(50)
// Setup IOB Prediction line details
let IOBpredictionChartEntry = [ChartDataEntry]()
let IOBlinePrediction = LineChartDataSet(entries: IOBpredictionChartEntry, label: "")
IOBlinePrediction.circleRadius = CGFloat(globalVariables.dotBG)
IOBlinePrediction.circleColors = [NSUIColor.systemPurple]
IOBlinePrediction.colors = [NSUIColor.systemPurple]
IOBlinePrediction.drawCircleHoleEnabled = false
IOBlinePrediction.axisDependency = YAxis.AxisDependency.right
IOBlinePrediction.highlightEnabled = true
IOBlinePrediction.drawValuesEnabled = false
if Storage.shared.showLines.value {
IOBlinePrediction.lineWidth = 2
} else {
IOBlinePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
IOBlinePrediction.drawCirclesEnabled = true
} else {
IOBlinePrediction.drawCirclesEnabled = false
}
IOBlinePrediction.setDrawHighlightIndicators(false)
IOBlinePrediction.valueFont.withSize(50)
// Setup UAM Prediction line details
let UAMpredictionChartEntry = [ChartDataEntry]()
let UAMlinePrediction = LineChartDataSet(entries: UAMpredictionChartEntry, label: "")
UAMlinePrediction.circleRadius = CGFloat(globalVariables.dotBG)
UAMlinePrediction.circleColors = [NSUIColor.systemPurple]
UAMlinePrediction.colors = [NSUIColor.systemPurple]
UAMlinePrediction.drawCircleHoleEnabled = false
UAMlinePrediction.axisDependency = YAxis.AxisDependency.right
UAMlinePrediction.highlightEnabled = true
UAMlinePrediction.drawValuesEnabled = false
if Storage.shared.showLines.value {
UAMlinePrediction.lineWidth = 2
} else {
UAMlinePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
UAMlinePrediction.drawCirclesEnabled = true
} else {
UAMlinePrediction.drawCirclesEnabled = false
}
linePrediction.setDrawHighlightIndicators(false)
linePrediction.valueFont.withSize(50)
// Setup ZT Prediction line details
let ZTpredictionChartEntry = [ChartDataEntry]()
let ZTlinePrediction = LineChartDataSet(entries: ZTpredictionChartEntry, label: "")
ZTlinePrediction.circleRadius = CGFloat(globalVariables.dotBG)
ZTlinePrediction.circleColors = [NSUIColor.systemPurple]
ZTlinePrediction.colors = [NSUIColor.systemPurple]
ZTlinePrediction.drawCircleHoleEnabled = false
ZTlinePrediction.axisDependency = YAxis.AxisDependency.right
ZTlinePrediction.highlightEnabled = true
ZTlinePrediction.drawValuesEnabled = false
if Storage.shared.showLines.value {
ZTlinePrediction.lineWidth = 2
} else {
ZTlinePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
ZTlinePrediction.drawCirclesEnabled = true
} else {
ZTlinePrediction.drawCirclesEnabled = false
}
ZTlinePrediction.setDrawHighlightIndicators(false)
ZTlinePrediction.valueFont.withSize(50)
// SMB
let chartEntrySmb = [ChartDataEntry]()
let lineSmb = LineChartDataSet(entries: chartEntrySmb, label: "")
lineSmb.circleRadius = CGFloat(globalVariables.dotBolus)
lineSmb.circleColors = [NSUIColor.systemBlue.withAlphaComponent(1.0)]
lineSmb.drawCircleHoleEnabled = false
lineSmb.setDrawHighlightIndicators(false)
lineSmb.setColor(NSUIColor.red, alpha: 1.0)
lineSmb.lineWidth = 0
lineSmb.axisDependency = YAxis.AxisDependency.right
lineSmb.valueFormatter = ChartYDataValueFormatter()
lineSmb.valueTextColor = NSUIColor.label
lineSmb.drawCirclesEnabled = false
lineSmb.drawFilledEnabled = false
if Storage.shared.showValues.value {
lineSmb.drawValuesEnabled = true
lineSmb.highlightEnabled = false
} else {
lineSmb.drawValuesEnabled = false
lineSmb.highlightEnabled = true
}
// TempTarget graph data
let chartTempTargetEntry = [ChartDataEntry]()
let lineTempTarget = LineChartDataSet(entries: chartTempTargetEntry, label: "")
lineTempTarget.setDrawHighlightIndicators(false)
lineTempTarget.lineWidth = 0
lineTempTarget.drawFilledEnabled = false
lineTempTarget.fillColor = NSUIColor.systemPurple
lineTempTarget.fillAlpha = 0.6
lineTempTarget.drawCirclesEnabled = false
lineTempTarget.axisDependency = YAxis.AxisDependency.right
lineTempTarget.highlightEnabled = true
lineTempTarget.drawValuesEnabled = false
// Setup the chart data of all lines
let data = LineChartData()
data.append(lineBG) // Dataset 0
data.append(linePrediction) // Dataset 1
data.append(lineBasal) // Dataset 2
data.append(lineBolus) // Dataset 3
data.append(lineCarbs) // Dataset 4
data.append(lineBasalScheduled) // Dataset 5
data.append(lineOverride) // Dataset 6
data.append(lineBGCheck) // Dataset 7
data.append(lineSuspend) // Dataset 8
data.append(lineResume) // Dataset 9
data.append(lineSensor) // Dataset 10
data.append(lineNote) // Dataset 11
data.append(ZTlinePrediction) // Dataset 12
data.append(IOBlinePrediction) // Dataset 13
data.append(COBlinePrediction) // Dataset 14
data.append(UAMlinePrediction) // Dataset 15
data.append(lineSmb) // Dataset 16
data.append(lineTempTarget)
data.setValueFont(UIFont.systemFont(ofSize: 12))
// Add marker popups for bolus and carbs
let marker = PillMarker(color: .secondarySystemBackground, font: UIFont.boldSystemFont(ofSize: 14), textColor: .label)
BGChart.marker = marker
// Clear limit lines so they don't add multiples when changing the settings
BGChart.rightAxis.removeAllLimitLines()
let thresholds = graphRangeThresholds()
// Add lower red line based on low alert value
let ll = ChartLimitLine()
ll.limit = thresholds.low
ll.lineColor = NSUIColor.systemRed.withAlphaComponent(0.5)
BGChart.rightAxis.addLimitLine(ll)
// Add upper yellow line based on low alert value
let ul = ChartLimitLine()
ul.limit = thresholds.high
ul.lineColor = NSUIColor.systemYellow.withAlphaComponent(0.5)
BGChart.rightAxis.addLimitLine(ul)
// Add vertical lines as configured
createVerticalLines()
startGraphNowTimer()
// Setup the main graph overall details
BGChart.xAxis.valueFormatter = ChartXValueFormatter()
BGChart.xAxis.granularity = 1800
BGChart.xAxis.labelTextColor = NSUIColor.label
BGChart.xAxis.labelPosition = XAxis.LabelPosition.bottom
BGChart.xAxis.drawGridLinesEnabled = false
BGChart.leftAxis.enabled = true
BGChart.leftAxis.labelPosition = YAxis.LabelPosition.insideChart
BGChart.leftAxis.axisMaximum = maxBasal
BGChart.leftAxis.axisMinimum = 0
BGChart.leftAxis.drawGridLinesEnabled = false
BGChart.leftAxis.granularityEnabled = true
BGChart.leftAxis.granularity = 0.5
BGChart.rightAxis.labelTextColor = NSUIColor.label
BGChart.rightAxis.labelPosition = YAxis.LabelPosition.insideChart
BGChart.rightAxis.axisMinimum = 0.0
BGChart.rightAxis.axisMaximum = Double(maxBG)
BGChart.rightAxis.gridLineDashLengths = [5.0, 5.0]
BGChart.rightAxis.drawGridLinesEnabled = false
BGChart.rightAxis.valueFormatter = ChartYMMOLValueFormatter()
BGChart.rightAxis.granularityEnabled = true
BGChart.rightAxis.granularity = 50
BGChart.maxHighlightDistance = 15.0
BGChart.legend.enabled = false
BGChart.scaleYEnabled = false
BGChart.drawGridBackgroundEnabled = true
BGChart.gridBackgroundColor = NSUIColor.secondarySystemBackground
BGChart.highlightValue(nil, callDelegate: false)
BGChart.data = data
BGChart.setExtraOffsets(left: 5, top: 10, right: 5, bottom: 10)
}
func createVerticalLines() {
BGChart.xAxis.removeAllLimitLines()
BGChartFull.xAxis.removeAllLimitLines()
createNowAndDIALines()
createMidnightLines()
}
func createNowAndDIALines() {
let ul = ChartLimitLine()
ul.limit = Double(dateTimeUtils.getNowTimeIntervalUTC())
ul.lineColor = NSUIColor.systemGray.withAlphaComponent(0.5)
ul.lineWidth = 1
BGChart.xAxis.addLimitLine(ul)
if Storage.shared.show30MinLine.value {
let ul2 = ChartLimitLine()
ul2.limit = Double(dateTimeUtils.getNowTimeIntervalUTC().advanced(by: -30 * 60))
ul2.lineColor = NSUIColor.systemBlue.withAlphaComponent(0.5)
ul2.lineWidth = 1
BGChart.xAxis.addLimitLine(ul2)
}
if Storage.shared.showDIALines.value {
for i in 1 ..< 7 {
let ul = ChartLimitLine()
ul.limit = Double(dateTimeUtils.getNowTimeIntervalUTC() - Double(i * 60 * 60))
ul.lineColor = NSUIColor.systemGray.withAlphaComponent(0.3)
let dash = 10.0 - Double(i)
let space = 5.0 + Double(i)
ul.lineDashLengths = [CGFloat(dash), CGFloat(space)]
ul.lineWidth = 1
BGChart.xAxis.addLimitLine(ul)
}
}
if Storage.shared.show90MinLine.value {
let ul3 = ChartLimitLine()
ul3.limit = Double(dateTimeUtils.getNowTimeIntervalUTC().advanced(by: -90 * 60))
ul3.lineColor = NSUIColor.systemOrange.withAlphaComponent(0.5)
ul3.lineWidth = 1
BGChart.xAxis.addLimitLine(ul3)
}
}
func createMidnightLines() {
// Draw a line at midnight: useful when showing multiple days of data
if Storage.shared.showMidnightLines.value {
var midnightTimeInterval: TimeInterval
if Storage.shared.graphTimeZoneEnabled.value,
let tz = TimeZone(identifier: Storage.shared.graphTimeZoneIdentifier.value)
{
var cal = Calendar.current
cal.timeZone = tz
midnightTimeInterval = cal.startOfDay(for: Date()).timeIntervalSince1970
} else {
midnightTimeInterval = dateTimeUtils.getTimeIntervalMidnightToday()
}
let graphHours = 24 * Storage.shared.downloadDays.value
let graphStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
while midnightTimeInterval > graphStart {
// Large chart
let ul = ChartLimitLine()
ul.limit = Double(midnightTimeInterval)
ul.lineColor = NSUIColor.systemTeal.withAlphaComponent(0.5)
ul.lineDashLengths = [CGFloat(2), CGFloat(5)]
ul.lineWidth = 1
BGChart.xAxis.addLimitLine(ul)
// Small chart
let sl = ChartLimitLine()
sl.limit = Double(midnightTimeInterval)
sl.lineColor = NSUIColor.systemTeal
sl.lineDashLengths = [CGFloat(2), CGFloat(2)]
sl.lineWidth = 1
BGChartFull.xAxis.addLimitLine(sl)
midnightTimeInterval = midnightTimeInterval.advanced(by: -24 * 60 * 60)
}
}
}
func updateBGGraphSettings() {
let dataIndex = 0
let dataIndexPrediction = 1
let lineBG = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
let linePrediction = BGChart.lineData!.dataSets[dataIndexPrediction] as! LineChartDataSet
if Storage.shared.showLines.value {
lineBG.lineWidth = 2
linePrediction.lineWidth = 2
} else {
lineBG.lineWidth = 0
linePrediction.lineWidth = 0
}
if Storage.shared.showDots.value {
lineBG.drawCirclesEnabled = true
linePrediction.drawCirclesEnabled = true
} else {
lineBG.drawCirclesEnabled = false
linePrediction.drawCirclesEnabled = false
}
BGChart.rightAxis.axisMinimum = 0
// Clear limit lines so they don't add multiples when changing the settings
BGChart.rightAxis.removeAllLimitLines()
let thresholds = graphRangeThresholds()
// Add lower red line based on low alert value
let ll = ChartLimitLine()
ll.limit = thresholds.low
ll.lineColor = NSUIColor.systemRed.withAlphaComponent(0.5)
BGChart.rightAxis.addLimitLine(ll)
// Add upper yellow line based on low alert value
let ul = ChartLimitLine()
ul.limit = thresholds.high
ul.lineColor = NSUIColor.systemYellow.withAlphaComponent(0.5)
BGChart.rightAxis.addLimitLine(ul)
// Re-create vertical markers in case their settings changed
createVerticalLines()
BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
}
func updateBGGraph() {
let dataIndex = 0
let entries = bgData
guard !entries.isEmpty else {
return
}
let mainChart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
let smallChart = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
mainChart.removeAll(keepingCapacity: false)
smallChart.removeAll(keepingCapacity: false)
let maxBGOffset: Double = 50
var colors = [NSUIColor]()
topBG = Storage.shared.minBGScale.value
let thresholds = graphRangeThresholds()
for i in 0 ..< entries.count {
if Double(entries[i].sgv) > topBG - maxBGOffset {
topBG = Double(entries[i].sgv) + maxBGOffset
}
let value = ChartDataEntry(x: Double(entries[i].date), y: Double(entries[i].sgv), data: formatPillText(line1: Localizer.toDisplayUnits(String(entries[i].sgv)), time: entries[i].date))
mainChart.append(value)
smallChart.append(value)
if Double(entries[i].sgv) >= thresholds.high {
colors.append(NSUIColor.systemYellow)
} else if Double(entries[i].sgv) <= thresholds.low {
colors.append(NSUIColor.systemRed)
} else {
colors.append(NSUIColor.systemGreen)
}
}
// Set Colors
let lineBG = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
let lineBGSmall = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
lineBG.colors.removeAll()
lineBG.circleColors.removeAll()
lineBGSmall.colors.removeAll()
lineBGSmall.circleColors.removeAll()
if colors.count > 0 {
for i in 0 ..< colors.count {
mainChart.addColor(colors[i])
mainChart.circleColors.append(colors[i])
smallChart.addColor(colors[i])
smallChart.circleColors.append(colors[i])
}
}
BGChart.rightAxis.axisMaximum = Double(calculateMaxBgGraphValue())
BGChart.setVisibleXRangeMinimum(600)
BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
BGChartFull.rightAxis.axisMaximum = Double(calculateMaxBgGraphValue())
BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChartFull.data?.notifyDataChanged()
BGChartFull.notifyDataSetChanged()
if firstGraphLoad {
var scaleX = CGFloat(Storage.shared.chartScaleX.value)
if scaleX > CGFloat(ScaleXMax) {
scaleX = CGFloat(ScaleXMax)
Storage.shared.chartScaleX.value = ScaleXMax
}
BGChart.zoom(scaleX: scaleX, scaleY: 1, x: 1, y: 1)
firstGraphLoad = false
}
// Move to current reading everytime new readings load
// Check if auto-scrolling should be performed
if autoScrollPauseUntil == nil || Date() > autoScrollPauseUntil! {
BGChart.moveViewToAnimated(xValue: dateTimeUtils.getNowTimeIntervalUTC() - (BGChart.visibleXRange * 0.7), yValue: 0.0, axis: .right, duration: 1, easingOption: .easeInBack)
}
}
func updatePredictionGraph(color: UIColor? = nil) {
let dataIndex = 1
var mainChart = BGChart.lineData!.dataSets[dataIndex] as! LineChartDataSet
var smallChart = BGChartFull.lineData!.dataSets[dataIndex] as! LineChartDataSet
mainChart.clear()
smallChart.clear()
var colors = [NSUIColor]()
let maxBGOffset: Double = 20
topPredictionBG = Storage.shared.minBGScale.value
for i in 0 ..< predictionData.count {
var predictionVal = Double(predictionData[i].sgv)
if Double(predictionVal) > topPredictionBG - maxBGOffset {
topPredictionBG = predictionVal + maxBGOffset
}
if i == 0 {
if Storage.shared.showDots.value {
colors.append((color ?? NSUIColor.systemPurple).withAlphaComponent(0.0))
} else {
colors.append((color ?? NSUIColor.systemPurple).withAlphaComponent(1.0))
}
} else if predictionVal > 400 {
colors.append(color ?? NSUIColor.systemYellow)
} else if predictionVal < 0 {
colors.append(color ?? NSUIColor.systemRed)
} else {
colors.append(color ?? NSUIColor.systemPurple)
}
let value = ChartDataEntry(x: predictionData[i].date, y: predictionVal, data: formatPillText(line1: Localizer.toDisplayUnits(String(predictionData[i].sgv)), time: predictionData[i].date))
mainChart.addEntry(value)
smallChart.addEntry(value)
}
smallChart.circleColors.removeAll()
smallChart.colors.removeAll()
mainChart.colors.removeAll()
mainChart.circleColors.removeAll()
if colors.count > 0 {
for i in 0 ..< colors.count {
mainChart.addColor(colors[i])
mainChart.circleColors.append(colors[i])
smallChart.addColor(colors[i])
smallChart.circleColors.append(colors[i])
}
}
BGChart.rightAxis.axisMaximum = Double(calculateMaxBgGraphValue())
BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChartFull.data?.notifyDataChanged()
BGChartFull.notifyDataSetChanged()
}
func updateBasalGraph() {
var dataIndex = 2
BGChart.lineData?.dataSets[dataIndex].clear()
BGChartFull.lineData?.dataSets[dataIndex].clear()
var maxBasal = Storage.shared.minBasalScale.value
var maxBasalSmall = 0.0
for i in 0 ..< basalData.count {
let value = ChartDataEntry(x: Double(basalData[i].date), y: Double(basalData[i].basalRate), data: formatPillText(line1: String(basalData[i].basalRate), time: basalData[i].date))
BGChart.data?.dataSets[dataIndex].addEntry(value)
if Storage.shared.smallGraphTreatments.value {
BGChartFull.data?.dataSets[dataIndex].addEntry(value)
}
if basalData[i].basalRate > maxBasal {
maxBasal = basalData[i].basalRate
}
if basalData[i].basalRate > maxBasalSmall {
maxBasalSmall = basalData[i].basalRate
}
}
BGChart.leftAxis.axisMaximum = maxBasal
BGChartFull.leftAxis.axisMaximum = maxBasalSmall
BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
if Storage.shared.smallGraphTreatments.value {
BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChartFull.data?.notifyDataChanged()
BGChartFull.notifyDataSetChanged()
}
}
func updateBasalScheduledGraph() {
var dataIndex = 5
BGChart.lineData?.dataSets[dataIndex].clear()
BGChartFull.lineData?.dataSets[dataIndex].clear()
for i in 0 ..< basalScheduleData.count {
let value = ChartDataEntry(x: Double(basalScheduleData[i].date), y: Double(basalScheduleData[i].basalRate))
BGChart.data?.dataSets[dataIndex].addEntry(value)
if Storage.shared.smallGraphTreatments.value {
BGChartFull.data?.dataSets[dataIndex].addEntry(value)
}
}
BGChart.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChart.data?.notifyDataChanged()
BGChart.notifyDataSetChanged()
if Storage.shared.smallGraphTreatments.value {
BGChartFull.data?.dataSets[dataIndex].notifyDataSetChanged()
BGChartFull.data?.notifyDataChanged()
BGChartFull.notifyDataSetChanged()