HighBGCondition.swift 1.4 KB

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