AlarmManager.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // LoopFollow
  2. // AlarmManager.swift
  3. import Foundation
  4. import UserNotifications
  5. class AlarmManager {
  6. static let shared = AlarmManager()
  7. private let evaluators: [AlarmType: AlarmCondition]
  8. private var lastBGAlarmTime: Date?
  9. private init(
  10. conditionTypes: [AlarmCondition.Type] = [
  11. BuildExpireCondition.self,
  12. LowBGCondition.self,
  13. HighBGCondition.self,
  14. FastDropCondition.self,
  15. NotLoopingCondition.self,
  16. OverrideStartCondition.self,
  17. OverrideEndCondition.self,
  18. TempTargetStartCondition.self,
  19. TempTargetEndCondition.self,
  20. RecBolusCondition.self,
  21. COBCondition.self,
  22. MissedReadingCondition.self,
  23. FastRiseCondition.self,
  24. TemporaryCondition.self,
  25. SensorAgeCondition.self,
  26. PumpChangeCondition.self,
  27. PumpVolumeCondition.self,
  28. PumpBatteryCondition.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. var alarmTriggered = false
  41. let config = Storage.shared.alarmConfiguration.value
  42. // Honor the "Snooze All" setting. If active, stop any current alarm and exit.
  43. if let snoozeUntil = config.snoozeUntil, snoozeUntil > now {
  44. if Observable.shared.currentAlarm.value != nil {
  45. stopAlarm()
  46. }
  47. return
  48. }
  49. let alarms = Storage.shared.alarms.value
  50. let sorted = alarms.sorted(by: Alarm.byPriorityThenSpec)
  51. var skipType: AlarmType?
  52. let isLatestReadingRecent: Bool = {
  53. guard let last = data.bgReadings.last else { return false }
  54. return now.timeIntervalSince(last.date) <= 5 * 60
  55. }()
  56. for alarm in sorted {
  57. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  58. if alarm.type == skipType {
  59. continue
  60. }
  61. // If an alarm is BG-based, it usually requires recent data.
  62. // We make a specific exception for .missedReading, whose entire
  63. // purpose is to fire when recent BG data is NOT recent.
  64. if alarm.type.isBGBased, alarm.type != .missedReading, !isLatestReadingRecent {
  65. continue
  66. }
  67. // If this is a bg-based alarm and we've already handled that same BG reading,
  68. // skip until we see a newer one.
  69. if alarm.type.isBGBased,
  70. let lastHandled = lastBGAlarmTime,
  71. let latestDate = data.bgReadings.last?.date,
  72. !(latestDate > lastHandled)
  73. {
  74. continue
  75. }
  76. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  77. // We still want other types af alarm to go off, so we continue here without breaking
  78. if let until = alarm.snoozedUntil, until > now {
  79. skipType = alarm.type
  80. continue
  81. }
  82. // Evaluate the alarm condition.
  83. guard let checker = evaluators[alarm.type],
  84. checker
  85. .shouldFire(
  86. alarm: alarm,
  87. data: data,
  88. now: now,
  89. config: Storage.shared.alarmConfiguration.value
  90. )
  91. else {
  92. // If this alarm is active, but no longer fulfill the requirements, stop it.
  93. // Continue evaluating other alarams
  94. if Observable.shared.currentAlarm.value == alarm.id {
  95. LogManager.shared.log(category: .alarm, message: "Stopping alarm \(alarm) because it no longer meets its requirements", isDebug: true)
  96. stopAlarm()
  97. }
  98. continue
  99. }
  100. // If this alarm is active, and still fulfill the requirements, let it be active
  101. // Break the loop, nothing else to do
  102. if Observable.shared.currentAlarm.value == alarm.id {
  103. break
  104. }
  105. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  106. Observable.shared.currentAlarm.value = alarm.id
  107. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  108. // Store the latest bg time so we don't use it again
  109. if alarm.type.isBGBased,
  110. let latestDate = data.bgReadings.last?.date
  111. {
  112. lastBGAlarmTime = latestDate
  113. }
  114. if alarm.type == .temporary {
  115. // turn it off and persist
  116. var list = Storage.shared.alarms.value
  117. if let idx = list.firstIndex(where: { $0.id == alarm.id }) {
  118. list[idx].isEnabled = false
  119. list[idx].snoozedUntil = nil
  120. Storage.shared.alarms.value = list
  121. }
  122. }
  123. alarmTriggered = true
  124. break
  125. }
  126. if isLatestReadingRecent, Storage.shared.persistentNotification.value, !alarmTriggered, let latestDate = data.bgReadings.last?.date, latestDate > Storage.shared.persistentNotificationLastBGTime.value {
  127. sendNotification(title: "Latest BG")
  128. Storage.shared.persistentNotificationLastBGTime.value = now
  129. }
  130. }
  131. func performSnooze(_ snoozeUnits: Int? = nil) {
  132. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  133. var alarms = Storage.shared.alarms.value
  134. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  135. let alarm = alarms[idx]
  136. let units = snoozeUnits ?? alarm.snoozeDuration
  137. if units > 0 {
  138. let snoozeSeconds = Double(units) * alarm.type.snoozeTimeUnit.seconds
  139. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  140. Storage.shared.alarms.value = alarms
  141. }
  142. Observable.shared.alarmSoundPlaying.value = false
  143. stopAlarm()
  144. }
  145. }
  146. func stopAlarm() {
  147. AlarmSound.stop()
  148. Observable.shared.currentAlarm.value = nil
  149. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  150. }
  151. func sendNotification(title: String, actionTitle: String? = nil) {
  152. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  153. let content = UNMutableNotificationContent()
  154. content.title = title
  155. content.subtitle += Observable.shared.bgText.value + " "
  156. content.subtitle += Observable.shared.directionText.value + " "
  157. content.subtitle += Observable.shared.deltaText.value
  158. content.categoryIdentifier = "category"
  159. content.sound = .default
  160. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  161. let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
  162. UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  163. if let actionTitle = actionTitle {
  164. let action = UNNotificationAction(identifier: "snooze", title: actionTitle, options: [])
  165. let category = UNNotificationCategory(identifier: "category", actions: [action], intentIdentifiers: [], options: [])
  166. UNUserNotificationCenter.current().setNotificationCategories([category])
  167. }
  168. }
  169. }