AlarmManager.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. //
  2. // AlarmManager.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2025-03-15.
  6. // Copyright © 2025 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UserNotifications
  10. class AlarmManager {
  11. static let shared = AlarmManager()
  12. private let evaluators: [AlarmType: AlarmCondition]
  13. private var lastBGAlarmTime: Date?
  14. private init(
  15. conditionTypes: [AlarmCondition.Type] = [
  16. BuildExpireCondition.self,
  17. LowBGCondition.self,
  18. HighBGCondition.self,
  19. FastDropCondition.self,
  20. NotLoopingCondition.self,
  21. OverrideStartCondition.self,
  22. OverrideEndCondition.self,
  23. TempTargetStartCondition.self,
  24. TempTargetEndCondition.self,
  25. RecBolusCondition.self,
  26. COBCondition.self,
  27. MissedReadingCondition.self,
  28. // TODO: add other condition types here
  29. ]
  30. ) {
  31. var dict = [AlarmType: AlarmCondition]()
  32. conditionTypes.forEach { dict[$0.type] = $0.init() }
  33. evaluators = dict
  34. }
  35. func checkAlarms(data: AlarmData) {
  36. let now = Date()
  37. let alarms = Storage.shared.alarms.value
  38. let sorted = alarms.sorted { lhs, rhs in
  39. // 1) by type priority
  40. if lhs.type.priority != rhs.type.priority {
  41. return lhs.type.priority < rhs.type.priority
  42. }
  43. // 2) by “main” value for that type
  44. if let asc = lhs.type.thresholdSortAscending {
  45. // pick the right field:
  46. let leftVal: Double
  47. let rightVal: Double
  48. switch lhs.type {
  49. // TODO: Make a alarm type setting of this, sortedBy or something like that
  50. case .fastDrop, .fastRise:
  51. // sort on the per-reading delta
  52. leftVal = lhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  53. rightVal = rhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  54. default:
  55. // sort on the BG limit threshold
  56. leftVal = lhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  57. rightVal = rhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  58. }
  59. return asc ? (leftVal < rightVal) : (leftVal > rightVal)
  60. }
  61. // 3) fallback
  62. return false
  63. }
  64. var skipType: AlarmType?
  65. let isLatestReadingRecent: Bool = {
  66. guard let last = data.bgReadings.last else { return false }
  67. return now.timeIntervalSince(last.date) <= 5 * 60
  68. }()
  69. for alarm in sorted {
  70. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  71. if alarm.type == skipType {
  72. continue
  73. }
  74. // If the alarm is based on bg values, and the value isnt recent, skip to next
  75. if alarm.type.isBGBased, !isLatestReadingRecent {
  76. continue
  77. }
  78. // If this is a bg-based alarm and we've already handled that same BG reading,
  79. // skip until we see a newer one.
  80. if alarm.type.isBGBased,
  81. let lastHandled = lastBGAlarmTime,
  82. let latestDate = data.bgReadings.last?.date,
  83. !(latestDate > lastHandled)
  84. {
  85. continue
  86. }
  87. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  88. // We still want other types af alarm to go off, so we continue here without breaking
  89. if let until = alarm.snoozedUntil, until > now {
  90. skipType = alarm.type
  91. continue
  92. }
  93. // Evaluate the alarm condition.
  94. guard let checker = evaluators[alarm.type],
  95. checker
  96. .shouldFire(
  97. alarm: alarm,
  98. data: data,
  99. now: now,
  100. config: Storage.shared.alarmConfiguration.value
  101. )
  102. else {
  103. // If this alarm is active, but no longer fulfill the requirements, stop it.
  104. // Continue evaluating other alarams
  105. if Observable.shared.currentAlarm.value == alarm.id {
  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. break
  125. }
  126. }
  127. func performSnooze(_ snoozeUnits: Int? = nil) {
  128. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  129. var alarms = Storage.shared.alarms.value
  130. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  131. let alarm = alarms[idx]
  132. let units = snoozeUnits ?? alarm.snoozeDuration
  133. let snoozeSeconds = Double(units) * alarm.type.timeUnit.seconds
  134. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  135. Storage.shared.alarms.value = alarms
  136. stopAlarm()
  137. }
  138. }
  139. func stopAlarm() {
  140. AlarmSound.stop()
  141. Observable.shared.currentAlarm.value = nil
  142. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  143. }
  144. }