AlarmManager.swift 7.6 KB

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