AlarmManager.swift 6.2 KB

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