AlarmManager.swift 7.4 KB

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