AlarmManager.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. // LoopFollow
  2. // AlarmManager.swift
  3. // Created by Jonas Björkert on 2025-04-26.
  4. import Foundation
  5. import UserNotifications
  6. class AlarmManager {
  7. static let shared = AlarmManager()
  8. private let evaluators: [AlarmType: AlarmCondition]
  9. private var lastBGAlarmTime: Date?
  10. private init(
  11. conditionTypes: [AlarmCondition.Type] = [
  12. BuildExpireCondition.self,
  13. LowBGCondition.self,
  14. HighBGCondition.self,
  15. FastDropCondition.self,
  16. NotLoopingCondition.self,
  17. OverrideStartCondition.self,
  18. OverrideEndCondition.self,
  19. TempTargetStartCondition.self,
  20. TempTargetEndCondition.self,
  21. RecBolusCondition.self,
  22. COBCondition.self,
  23. MissedReadingCondition.self,
  24. FastRiseCondition.self,
  25. TemporaryCondition.self,
  26. SensorAgeCondition.self,
  27. PumpChangeCondition.self,
  28. PumpVolumeCondition.self,
  29. IOBCondition.self,
  30. BatteryCondition.self,
  31. BatteryDropCondition.self,
  32. ]
  33. ) {
  34. var dict = [AlarmType: AlarmCondition]()
  35. conditionTypes.forEach { dict[$0.type] = $0.init() }
  36. evaluators = dict
  37. }
  38. func checkAlarms(data: AlarmData) {
  39. let now = Date()
  40. let alarms = Storage.shared.alarms.value
  41. let sorted = alarms.sorted { lhs, rhs in
  42. // 1) type-level priority (hard-coded table in AlarmType)
  43. if lhs.type.priority != rhs.type.priority {
  44. return lhs.type.priority < rhs.type.priority
  45. }
  46. // 2) per-type “main value” ordering
  47. if lhs.type == rhs.type, // only makes sense within the same type
  48. let spec = lhs.type.sortSpec
  49. { // (direction, key extractor)
  50. let lv = spec.key(lhs)
  51. let rv = spec.key(rhs)
  52. switch spec.direction {
  53. case .ascending: // smaller ⇒ more urgent
  54. return (lv ?? Double.infinity) < (rv ?? Double.infinity)
  55. case .descending: // bigger ⇒ more urgent
  56. return (lv ?? -Double.infinity) > (rv ?? -Double.infinity)
  57. }
  58. }
  59. // 3) fallback – keep original insertion order
  60. return false
  61. }
  62. var skipType: AlarmType?
  63. let isLatestReadingRecent: Bool = {
  64. guard let last = data.bgReadings.last else { return false }
  65. return now.timeIntervalSince(last.date) <= 5 * 60
  66. }()
  67. for alarm in sorted {
  68. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  69. if alarm.type == skipType {
  70. continue
  71. }
  72. // If the alarm is based on bg values, and the value isnt recent, skip to next
  73. if alarm.type.isBGBased, !isLatestReadingRecent {
  74. continue
  75. }
  76. // If this is a bg-based alarm and we've already handled that same BG reading,
  77. // skip until we see a newer one.
  78. if alarm.type.isBGBased,
  79. let lastHandled = lastBGAlarmTime,
  80. let latestDate = data.bgReadings.last?.date,
  81. !(latestDate > lastHandled)
  82. {
  83. continue
  84. }
  85. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  86. // We still want other types af alarm to go off, so we continue here without breaking
  87. if let until = alarm.snoozedUntil, until > now {
  88. skipType = alarm.type
  89. continue
  90. }
  91. // Evaluate the alarm condition.
  92. guard let checker = evaluators[alarm.type],
  93. checker
  94. .shouldFire(
  95. alarm: alarm,
  96. data: data,
  97. now: now,
  98. config: Storage.shared.alarmConfiguration.value
  99. )
  100. else {
  101. // If this alarm is active, but no longer fulfill the requirements, stop it.
  102. // Continue evaluating other alarams
  103. if Observable.shared.currentAlarm.value == alarm.id {
  104. stopAlarm()
  105. }
  106. continue
  107. }
  108. // If this alarm is active, and still fulfill the requirements, let it be active
  109. // Break the loop, nothing else to do
  110. if Observable.shared.currentAlarm.value == alarm.id {
  111. break
  112. }
  113. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  114. Observable.shared.currentAlarm.value = alarm.id
  115. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  116. // Store the latest bg time so we don't use it again
  117. if alarm.type.isBGBased,
  118. let latestDate = data.bgReadings.last?.date
  119. {
  120. lastBGAlarmTime = latestDate
  121. }
  122. if alarm.type == .temporary {
  123. // turn it off and persist
  124. var list = Storage.shared.alarms.value
  125. if let idx = list.firstIndex(where: { $0.id == alarm.id }) {
  126. list[idx].isEnabled = false
  127. list[idx].snoozedUntil = nil
  128. Storage.shared.alarms.value = list
  129. }
  130. }
  131. break
  132. }
  133. }
  134. func performSnooze(_ snoozeUnits: Int? = nil) {
  135. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  136. var alarms = Storage.shared.alarms.value
  137. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  138. let alarm = alarms[idx]
  139. let units = snoozeUnits ?? alarm.snoozeDuration
  140. if units > 0 {
  141. let snoozeSeconds = Double(units) * alarm.type.snoozeTimeUnit.seconds
  142. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  143. Storage.shared.alarms.value = alarms
  144. }
  145. stopAlarm()
  146. }
  147. }
  148. func stopAlarm() {
  149. AlarmSound.stop()
  150. Observable.shared.currentAlarm.value = nil
  151. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  152. }
  153. }