AlarmManager.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. FastRiseCondition.self,
  29. // TODO: add other condition types here
  30. ]
  31. ) {
  32. var dict = [AlarmType: AlarmCondition]()
  33. conditionTypes.forEach { dict[$0.type] = $0.init() }
  34. evaluators = dict
  35. }
  36. func checkAlarms(data: AlarmData) {
  37. let now = Date()
  38. let alarms = Storage.shared.alarms.value
  39. let sorted = alarms.sorted { lhs, rhs in
  40. // 1) by type priority
  41. if lhs.type.priority != rhs.type.priority {
  42. return lhs.type.priority < rhs.type.priority
  43. }
  44. // 2) by “main” value for that type
  45. if let asc = lhs.type.thresholdSortAscending {
  46. // pick the right field:
  47. let leftVal: Double
  48. let rightVal: Double
  49. switch lhs.type {
  50. // TODO: Make a alarm type setting of this, sortedBy or something like that
  51. case .fastDrop, .fastRise:
  52. // sort on the per-reading delta
  53. leftVal = lhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  54. rightVal = rhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  55. default:
  56. // sort on the BG limit threshold
  57. leftVal = lhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  58. rightVal = rhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  59. }
  60. return asc ? (leftVal < rightVal) : (leftVal > rightVal)
  61. }
  62. // 3) fallback
  63. return false
  64. }
  65. var skipType: AlarmType?
  66. let isLatestReadingRecent: Bool = {
  67. guard let last = data.bgReadings.last else { return false }
  68. return now.timeIntervalSince(last.date) <= 5 * 60
  69. }()
  70. for alarm in sorted {
  71. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  72. if alarm.type == skipType {
  73. continue
  74. }
  75. // If the alarm is based on bg values, and the value isnt recent, skip to next
  76. if alarm.type.isBGBased, !isLatestReadingRecent {
  77. continue
  78. }
  79. // If this is a bg-based alarm and we've already handled that same BG reading,
  80. // skip until we see a newer one.
  81. if alarm.type.isBGBased,
  82. let lastHandled = lastBGAlarmTime,
  83. let latestDate = data.bgReadings.last?.date,
  84. !(latestDate > lastHandled)
  85. {
  86. continue
  87. }
  88. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  89. // We still want other types af alarm to go off, so we continue here without breaking
  90. if let until = alarm.snoozedUntil, until > now {
  91. skipType = alarm.type
  92. continue
  93. }
  94. // Evaluate the alarm condition.
  95. guard let checker = evaluators[alarm.type],
  96. checker
  97. .shouldFire(
  98. alarm: alarm,
  99. data: data,
  100. now: now,
  101. config: Storage.shared.alarmConfiguration.value
  102. )
  103. else {
  104. // If this alarm is active, but no longer fulfill the requirements, stop it.
  105. // Continue evaluating other alarams
  106. if Observable.shared.currentAlarm.value == alarm.id {
  107. stopAlarm()
  108. }
  109. continue
  110. }
  111. // If this alarm is active, and still fulfill the requirements, let it be active
  112. // Break the loop, nothing else to do
  113. if Observable.shared.currentAlarm.value == alarm.id {
  114. break
  115. }
  116. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  117. Observable.shared.currentAlarm.value = alarm.id
  118. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  119. // Store the latest bg time so we don't use it again
  120. if alarm.type.isBGBased,
  121. let latestDate = data.bgReadings.last?.date
  122. {
  123. lastBGAlarmTime = latestDate
  124. }
  125. break
  126. }
  127. }
  128. func performSnooze(_ snoozeUnits: Int? = nil) {
  129. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  130. var alarms = Storage.shared.alarms.value
  131. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  132. let alarm = alarms[idx]
  133. let units = snoozeUnits ?? alarm.snoozeDuration
  134. let snoozeSeconds = Double(units) * alarm.type.timeUnit.seconds
  135. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  136. Storage.shared.alarms.value = alarms
  137. stopAlarm()
  138. }
  139. }
  140. func stopAlarm() {
  141. AlarmSound.stop()
  142. Observable.shared.currentAlarm.value = nil
  143. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  144. }
  145. }