AlarmManager.swift 7.6 KB

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