AlarmManager.swift 7.7 KB

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