MissedReadingCondition.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // LoopFollow
  2. // MissedReadingCondition.swift
  3. import Foundation
  4. /// Fires when the newest CGM reading is older than `threshold` minutes.
  5. struct MissedReadingCondition: AlarmCondition {
  6. static let type: AlarmType = .missedReading
  7. init() {}
  8. func evaluate(alarm: Alarm, data: AlarmData, now: Date) -> Bool {
  9. // ────────────────────────────────
  10. // 0. sanity checks
  11. // ────────────────────────────────
  12. guard let thresholdMinutes = alarm.threshold, thresholdMinutes > 0 else { return false }
  13. // Skip if we have *no* readings
  14. guard let last = data.bgReadings.last else { return false }
  15. guard let lastChecked = Storage.shared.lastBGChecked.value else {
  16. // Never checked, so don't alarm.
  17. return false
  18. }
  19. let checkedAgeSeconds = now.timeIntervalSince(lastChecked)
  20. if checkedAgeSeconds > 360 { // 6 minutes
  21. // The check itself is stale, so the data is unreliable. Don't alarm.
  22. return false
  23. }
  24. let secondsSinceLast = now.timeIntervalSince(last.date)
  25. return secondsSinceLast >= thresholdMinutes * 60
  26. }
  27. }