AlarmManager.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. FutureCarbsCondition.self,
  33. DBSizeCondition.self,
  34. ]
  35. ) {
  36. var dict = [AlarmType: AlarmCondition]()
  37. conditionTypes.forEach { dict[$0.type] = $0.init() }
  38. evaluators = dict
  39. }
  40. func checkAlarms(data: AlarmData) {
  41. let now = Date()
  42. var alarmTriggered = false
  43. // No alarm activity while onboarding is on screen — existing or
  44. // QR-imported alarms shouldn't sound mid-setup.
  45. if Observable.shared.isOnboardingActive.value {
  46. if Observable.shared.currentAlarm.value != nil {
  47. stopAlarm()
  48. }
  49. return
  50. }
  51. let config = Storage.shared.alarmConfiguration.value
  52. // Honor the "Snooze All" setting. If active, stop any current alarm and exit.
  53. if let snoozeUntil = config.snoozeUntil, snoozeUntil > now {
  54. if Observable.shared.currentAlarm.value != nil {
  55. stopAlarm()
  56. }
  57. return
  58. }
  59. let alarms = Storage.shared.alarms.value
  60. let sorted = alarms.sorted(by: Alarm.byPriorityThenSpec)
  61. var skipType: AlarmType?
  62. let isLatestReadingRecent: Bool = {
  63. guard let last = data.bgReadings.last else { return false }
  64. return now.timeIntervalSince(last.date) <= 5 * 60
  65. }()
  66. for alarm in sorted {
  67. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  68. if alarm.type == skipType {
  69. continue
  70. }
  71. // If an alarm is BG-based, it usually requires recent data.
  72. // We make a specific exception for .missedReading, whose entire
  73. // purpose is to fire when recent BG data is NOT recent.
  74. if alarm.type.isBGBased, alarm.type != .missedReading, !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. LogManager.shared.log(category: .alarm, message: "Stopping alarm \(alarm) because it no longer meets its requirements", isDebug: true)
  106. stopAlarm()
  107. }
  108. continue
  109. }
  110. // If this alarm is active, and still fulfill the requirements, let it be active
  111. // Break the loop, nothing else to do
  112. if Observable.shared.currentAlarm.value == alarm.id {
  113. break
  114. }
  115. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  116. Observable.shared.currentAlarm.value = alarm.id
  117. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  118. // Store the latest bg time so we don't use it again
  119. if alarm.type.isBGBased,
  120. let latestDate = data.bgReadings.last?.date
  121. {
  122. lastBGAlarmTime = latestDate
  123. }
  124. if alarm.type == .temporary {
  125. // turn it off and persist
  126. var list = Storage.shared.alarms.value
  127. if let idx = list.firstIndex(where: { $0.id == alarm.id }) {
  128. list[idx].isEnabled = false
  129. list[idx].snoozedUntil = nil
  130. Storage.shared.alarms.value = list
  131. }
  132. }
  133. alarmTriggered = true
  134. break
  135. }
  136. if isLatestReadingRecent, Storage.shared.persistentNotification.value, !alarmTriggered, let latestDate = data.bgReadings.last?.date, latestDate > Storage.shared.persistentNotificationLastBGTime.value {
  137. sendNotification(title: String(localized: "Latest BG"))
  138. Storage.shared.persistentNotificationLastBGTime.value = now
  139. }
  140. }
  141. func performSnooze(_ snoozeUnits: Int? = nil) {
  142. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  143. var alarms = Storage.shared.alarms.value
  144. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  145. let alarm = alarms[idx]
  146. let units = snoozeUnits ?? alarm.snoozeDuration
  147. if units > 0 {
  148. let snoozeSeconds = Double(units) * alarm.type.snoozeTimeUnit.seconds
  149. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  150. Storage.shared.alarms.value = alarms
  151. }
  152. Observable.shared.alarmSoundPlaying.value = false
  153. stopAlarm()
  154. }
  155. }
  156. func stopAlarm() {
  157. AlarmSound.stop()
  158. Observable.shared.currentAlarm.value = nil
  159. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  160. }
  161. func sendNotification(title: String, actionTitle: String? = nil) {
  162. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  163. let content = UNMutableNotificationContent()
  164. content.title = title
  165. content.subtitle += Observable.shared.bgText.value + " "
  166. content.subtitle += Observable.shared.directionText.value + " "
  167. content.subtitle += Observable.shared.deltaText.value
  168. content.categoryIdentifier = "category"
  169. content.sound = .default
  170. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  171. let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
  172. UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  173. if let actionTitle = actionTitle {
  174. let action = UNNotificationAction(identifier: "snooze", title: actionTitle, options: [])
  175. let category = UNNotificationCategory(identifier: "category", actions: [action], intentIdentifiers: [], options: [])
  176. UNUserNotificationCenter.current().setNotificationCategories([category])
  177. }
  178. }
  179. }