HighBGCondition.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // LoopFollow
  2. // HighBGCondition.swift
  3. // Created by Jonas Björkert.
  4. import Foundation
  5. /// Fires when the latest BG – and, if requested, every BG in a persistent-window – is **≥ aboveBG**.
  6. struct HighBGCondition: AlarmCondition {
  7. static let type: AlarmType = .high
  8. init() {}
  9. func evaluate(alarm: Alarm, data: AlarmData, now _: Date) -> Bool {
  10. // ────────────────────────────────
  11. // 0. get the limit
  12. // ────────────────────────────────
  13. guard let high = alarm.aboveBG else { return false }
  14. func isHigh(_ g: GlucoseValue) -> Bool {
  15. g.sgv > 0 && Double(g.sgv) >= high
  16. }
  17. // we already know from `passesBGLimits` that the **latest** reading is ≥ high,
  18. // but we still need to honour the “persistent for N minutes” option.
  19. var persistentOK = true
  20. if let persistentMinutes = alarm.persistentMinutes,
  21. persistentMinutes > 0
  22. {
  23. let window = Int(ceil(Double(persistentMinutes) / 5.0))
  24. if data.bgReadings.count >= window {
  25. let recent = data.bgReadings.suffix(window)
  26. persistentOK = recent.allSatisfy(isHigh)
  27. } else {
  28. // not enough samples yet ⇒ don’t alarm
  29. persistentOK = false
  30. }
  31. }
  32. return persistentOK
  33. }
  34. }