APSManager.swift 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import LoopKitUI
  6. import SwiftDate
  7. import Swinject
  8. protocol APSManager {
  9. func heartbeat(date: Date)
  10. func enactBolus(amount: Double, isSMB: Bool) async
  11. var pumpManager: PumpManagerUI? { get set }
  12. var bluetoothManager: BluetoothStateManager? { get }
  13. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> { get }
  14. var pumpName: CurrentValueSubject<String, Never> { get }
  15. var isLooping: CurrentValueSubject<Bool, Never> { get }
  16. var lastLoopDate: Date { get }
  17. var lastLoopDateSubject: PassthroughSubject<Date, Never> { get }
  18. var bolusProgress: CurrentValueSubject<Decimal?, Never> { get }
  19. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> { get }
  20. var isManualTempBasal: Bool { get }
  21. func enactTempBasal(rate: Double, duration: TimeInterval) async
  22. func determineBasal() async -> Bool
  23. func determineBasalSync() async
  24. func simulateDetermineBasal(carbs: Decimal, iob: Decimal) async -> Determination?
  25. func roundBolus(amount: Decimal) -> Decimal
  26. var lastError: CurrentValueSubject<Error?, Never> { get }
  27. func cancelBolus() async
  28. func enactAnnouncement(_ announcement: Announcement)
  29. }
  30. enum APSError: LocalizedError {
  31. case pumpError(Error)
  32. case invalidPumpState(message: String)
  33. case glucoseError(message: String)
  34. case apsError(message: String)
  35. case deviceSyncError(message: String)
  36. case manualBasalTemp(message: String)
  37. var errorDescription: String? {
  38. switch self {
  39. case let .pumpError(error):
  40. return "Pump error: \(error.localizedDescription)"
  41. case let .invalidPumpState(message):
  42. return "Error: Invalid Pump State: \(message)"
  43. case let .glucoseError(message):
  44. return "Error: Invalid glucose: \(message)"
  45. case let .apsError(message):
  46. return "APS error: \(message)"
  47. case let .deviceSyncError(message):
  48. return "Sync error: \(message)"
  49. case let .manualBasalTemp(message):
  50. return "Manual Basal Temp : \(message)"
  51. }
  52. }
  53. }
  54. final class BaseAPSManager: APSManager, Injectable {
  55. private let processQueue = DispatchQueue(label: "BaseAPSManager.processQueue")
  56. @Injected() private var storage: FileStorage!
  57. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  58. @Injected() private var alertHistoryStorage: AlertHistoryStorage!
  59. @Injected() private var tempTargetsStorage: TempTargetsStorage!
  60. @Injected() private var carbsStorage: CarbsStorage!
  61. @Injected() private var announcementsStorage: AnnouncementsStorage!
  62. @Injected() private var determinationStorage: DeterminationStorage!
  63. @Injected() private var deviceDataManager: DeviceDataManager!
  64. @Injected() private var nightscout: NightscoutManager!
  65. @Injected() private var settingsManager: SettingsManager!
  66. @Injected() private var broadcaster: Broadcaster!
  67. @Persisted(key: "lastLoopStartDate") private var lastLoopStartDate: Date = .distantPast
  68. @Persisted(key: "lastLoopDate") var lastLoopDate: Date = .distantPast {
  69. didSet {
  70. lastLoopDateSubject.send(lastLoopDate)
  71. }
  72. }
  73. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  74. let privateContext = CoreDataStack.shared.newTaskContext()
  75. private var openAPS: OpenAPS!
  76. private var lifetime = Lifetime()
  77. private var backGroundTaskID: UIBackgroundTaskIdentifier?
  78. var pumpManager: PumpManagerUI? {
  79. get { deviceDataManager.pumpManager }
  80. set { deviceDataManager.pumpManager = newValue }
  81. }
  82. var bluetoothManager: BluetoothStateManager? { deviceDataManager.bluetoothManager }
  83. @Persisted(key: "isManualTempBasal") var isManualTempBasal: Bool = false
  84. let isLooping = CurrentValueSubject<Bool, Never>(false)
  85. let lastLoopDateSubject = PassthroughSubject<Date, Never>()
  86. let lastError = CurrentValueSubject<Error?, Never>(nil)
  87. let bolusProgress = CurrentValueSubject<Decimal?, Never>(nil)
  88. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> {
  89. deviceDataManager.pumpDisplayState
  90. }
  91. var pumpName: CurrentValueSubject<String, Never> {
  92. deviceDataManager.pumpName
  93. }
  94. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> {
  95. deviceDataManager.pumpExpiresAtDate
  96. }
  97. var settings: FreeAPSSettings {
  98. get { settingsManager.settings }
  99. set { settingsManager.settings = newValue }
  100. }
  101. init(resolver: Resolver) {
  102. injectServices(resolver)
  103. openAPS = OpenAPS(storage: storage)
  104. subscribe()
  105. lastLoopDateSubject.send(lastLoopDate)
  106. isLooping
  107. .weakAssign(to: \.deviceDataManager.loopInProgress, on: self)
  108. .store(in: &lifetime)
  109. }
  110. private func subscribe() {
  111. if settingsManager.settings.units == .mmolL {
  112. let wasParsed = storage.parseOnFileSettingsToMgdL()
  113. if wasParsed {
  114. Task {
  115. await openAPS.createInitialProfiles()
  116. }
  117. }
  118. }
  119. deviceDataManager.recommendsLoop
  120. .receive(on: processQueue)
  121. .sink { [weak self] in
  122. self?.loop()
  123. }
  124. .store(in: &lifetime)
  125. pumpManager?.addStatusObserver(self, queue: processQueue)
  126. deviceDataManager.errorSubject
  127. .receive(on: processQueue)
  128. .map { APSError.pumpError($0) }
  129. .sink {
  130. self.processError($0)
  131. }
  132. .store(in: &lifetime)
  133. deviceDataManager.bolusTrigger
  134. .receive(on: processQueue)
  135. .sink { bolusing in
  136. if bolusing {
  137. self.createBolusReporter()
  138. } else {
  139. self.clearBolusReporter()
  140. }
  141. }
  142. .store(in: &lifetime)
  143. // manage a manual Temp Basal from OmniPod - Force loop() after stop a temp basal or finished
  144. deviceDataManager.manualTempBasal
  145. .receive(on: processQueue)
  146. .sink { manualBasal in
  147. if manualBasal {
  148. self.isManualTempBasal = true
  149. } else {
  150. if self.isManualTempBasal {
  151. self.isManualTempBasal = false
  152. self.loop()
  153. }
  154. }
  155. }
  156. .store(in: &lifetime)
  157. }
  158. func heartbeat(date: Date) {
  159. deviceDataManager.heartbeat(date: date)
  160. }
  161. // Loop entry point
  162. private func loop() {
  163. Task {
  164. // check the last start of looping is more the loopInterval but the previous loop was completed
  165. if lastLoopDate > lastLoopStartDate {
  166. guard lastLoopStartDate.addingTimeInterval(Config.loopInterval) < Date() else {
  167. debug(.apsManager, "too close to do a loop : \(lastLoopStartDate)")
  168. return
  169. }
  170. }
  171. guard !isLooping.value else {
  172. warning(.apsManager, "Loop already in progress. Skip recommendation.")
  173. return
  174. }
  175. // start background time extension
  176. backGroundTaskID = await UIApplication.shared.beginBackgroundTask(withName: "Loop starting") {
  177. guard let backgroundTask = self.backGroundTaskID else { return }
  178. Task {
  179. UIApplication.shared.endBackgroundTask(backgroundTask)
  180. }
  181. self.backGroundTaskID = .invalid
  182. }
  183. lastLoopStartDate = Date()
  184. var previousLoop = [LoopStatRecord]()
  185. var interval: Double?
  186. do {
  187. try await privateContext.perform {
  188. let requestStats = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  189. let sortStats = NSSortDescriptor(key: "end", ascending: false)
  190. requestStats.sortDescriptors = [sortStats]
  191. requestStats.fetchLimit = 1
  192. previousLoop = try self.privateContext.fetch(requestStats)
  193. if (previousLoop.first?.end ?? .distantFuture) < self.lastLoopStartDate {
  194. interval = self.roundDouble(
  195. (self.lastLoopStartDate - (previousLoop.first?.end ?? Date())).timeInterval / 60,
  196. 1
  197. )
  198. }
  199. }
  200. } catch let error as NSError {
  201. debugPrint(
  202. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch the last loop with error: \(error.userInfo)"
  203. )
  204. }
  205. var loopStatRecord = LoopStats(
  206. start: lastLoopStartDate,
  207. loopStatus: "Starting",
  208. interval: interval
  209. )
  210. isLooping.send(true)
  211. do {
  212. if await !determineBasal() {
  213. throw APSError.apsError(message: "Determine basal failed")
  214. }
  215. // Open loop completed
  216. guard settings.closedLoop else {
  217. loopStatRecord.end = Date()
  218. loopStatRecord.duration = roundDouble((loopStatRecord.end! - loopStatRecord.start).timeInterval / 60, 2)
  219. loopStatRecord.loopStatus = "Success"
  220. await loopCompleted(loopStatRecord: loopStatRecord)
  221. return
  222. }
  223. // Closed loop - enact Determination
  224. try await enactDetermination()
  225. loopStatRecord.end = Date()
  226. loopStatRecord.duration = roundDouble((loopStatRecord.end! - loopStatRecord.start).timeInterval / 60, 2)
  227. loopStatRecord.loopStatus = "Success"
  228. await loopCompleted(loopStatRecord: loopStatRecord)
  229. } catch {
  230. loopStatRecord.end = Date()
  231. loopStatRecord.duration = roundDouble((loopStatRecord.end! - loopStatRecord.start).timeInterval / 60, 2)
  232. loopStatRecord.loopStatus = error.localizedDescription
  233. await loopCompleted(error: error, loopStatRecord: loopStatRecord)
  234. }
  235. if let nightscoutManager = nightscout {
  236. await nightscoutManager.uploadCarbs()
  237. await nightscoutManager.uploadPumpHistory()
  238. await nightscoutManager.uploadOverrides()
  239. await nightscoutManager.uploadTempTargets()
  240. }
  241. // End background task after all the operations are completed
  242. if let backgroundTask = self.backGroundTaskID {
  243. await UIApplication.shared.endBackgroundTask(backgroundTask)
  244. self.backGroundTaskID = .invalid
  245. }
  246. }
  247. }
  248. // Loop exit point
  249. private func loopCompleted(error: Error? = nil, loopStatRecord: LoopStats) async {
  250. isLooping.send(false)
  251. if let error = error {
  252. warning(.apsManager, "Loop failed with error: \(error.localizedDescription)")
  253. if let backgroundTask = backGroundTaskID {
  254. await UIApplication.shared.endBackgroundTask(backgroundTask)
  255. backGroundTaskID = .invalid
  256. }
  257. processError(error)
  258. } else {
  259. debug(.apsManager, "Loop succeeded")
  260. lastLoopDate = Date()
  261. lastError.send(nil)
  262. }
  263. loopStats(loopStatRecord: loopStatRecord)
  264. if settings.closedLoop {
  265. await reportEnacted(wasEnacted: error == nil)
  266. }
  267. // End of the BG tasks
  268. if let backgroundTask = backGroundTaskID {
  269. await UIApplication.shared.endBackgroundTask(backgroundTask)
  270. backGroundTaskID = .invalid
  271. }
  272. }
  273. private func verifyStatus() -> Error? {
  274. guard let pump = pumpManager else {
  275. return APSError.invalidPumpState(message: "Pump not set")
  276. }
  277. let status = pump.status.pumpStatus
  278. guard !status.bolusing else {
  279. return APSError.invalidPumpState(message: "Pump is bolusing")
  280. }
  281. guard !status.suspended else {
  282. return APSError.invalidPumpState(message: "Pump suspended")
  283. }
  284. let reservoir = storage.retrieve(OpenAPS.Monitor.reservoir, as: Decimal.self) ?? 100
  285. guard reservoir >= 0 else {
  286. return APSError.invalidPumpState(message: "Reservoir is empty")
  287. }
  288. return nil
  289. }
  290. func autosense() async throws -> Bool {
  291. guard let autosense = await storage.retrieveAsync(OpenAPS.Settings.autosense, as: Autosens.self),
  292. (autosense.timestamp ?? .distantPast).addingTimeInterval(30.minutes.timeInterval) > Date()
  293. else {
  294. let result = try await openAPS.autosense()
  295. return result != nil
  296. }
  297. return false
  298. }
  299. func determineBasal() async -> Bool {
  300. debug(.apsManager, "Start determine basal")
  301. // Fetch glucose asynchronously
  302. let glucose = await fetchGlucose(predicate: NSPredicate.predicateForOneHourAgo, fetchLimit: 6)
  303. // Perform the context-related checks and actions
  304. let isValidGlucoseData = await privateContext.perform {
  305. guard glucose.count > 2 else {
  306. debug(.apsManager, "Not enough glucose data")
  307. self.processError(APSError.glucoseError(message: "Not enough glucose data"))
  308. return false
  309. }
  310. let dateOfLastGlucose = glucose.first?.date
  311. guard dateOfLastGlucose ?? Date() >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  312. debug(.apsManager, "Glucose data is stale")
  313. self.processError(APSError.glucoseError(message: "Glucose data is stale"))
  314. return false
  315. }
  316. guard !GlucoseStored.glucoseIsFlat(glucose) else {
  317. debug(.apsManager, "Glucose data is too flat")
  318. self.processError(APSError.glucoseError(message: "Glucose data is too flat"))
  319. return false
  320. }
  321. return true
  322. }
  323. guard isValidGlucoseData else {
  324. debug(.apsManager, "Glucose validation failed")
  325. processError(APSError.glucoseError(message: "Glucose validation failed"))
  326. return false
  327. }
  328. do {
  329. let now = Date()
  330. // Start fetching asynchronously
  331. let (currentTemp, _) = try await (
  332. fetchCurrentTempBasal(date: now),
  333. autosense()
  334. )
  335. // Determine basal using the fetched temp and current time
  336. let determination = try await openAPS.determineBasal(currentTemp: currentTemp, clock: now)
  337. if let determination = determination {
  338. DispatchQueue.main.async {
  339. self.broadcaster.notify(DeterminationObserver.self, on: .main) {
  340. $0.determinationDidUpdate(determination)
  341. }
  342. }
  343. return true
  344. } else {
  345. return false
  346. }
  347. } catch {
  348. debug(.apsManager, "Error determining basal: \(error)")
  349. return false
  350. }
  351. }
  352. func determineBasalSync() async {
  353. _ = await determineBasal()
  354. }
  355. func simulateDetermineBasal(carbs: Decimal, iob: Decimal) async -> Determination? {
  356. do {
  357. let temp = await fetchCurrentTempBasal(date: Date.now)
  358. return try await openAPS.determineBasal(currentTemp: temp, clock: Date(), carbs: carbs, iob: iob, simulation: true)
  359. } catch {
  360. debugPrint(
  361. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Error occurred in invokeDummyDetermineBasalSync: \(error)"
  362. )
  363. return nil
  364. }
  365. }
  366. func roundBolus(amount: Decimal) -> Decimal {
  367. guard let pump = pumpManager else { return amount }
  368. let rounded = Decimal(pump.roundToSupportedBolusVolume(units: Double(amount)))
  369. let maxBolus = Decimal(pump.roundToSupportedBolusVolume(units: Double(settingsManager.pumpSettings.maxBolus)))
  370. return min(rounded, maxBolus)
  371. }
  372. private var bolusReporter: DoseProgressReporter?
  373. func enactBolus(amount: Double, isSMB: Bool) async {
  374. if amount <= 0 {
  375. return
  376. }
  377. if let error = verifyStatus() {
  378. processError(error)
  379. processQueue.async {
  380. self.broadcaster.notify(BolusFailureObserver.self, on: self.processQueue) {
  381. $0.bolusDidFail()
  382. }
  383. }
  384. return
  385. }
  386. guard let pump = pumpManager else { return }
  387. let roundedAmount = pump.roundToSupportedBolusVolume(units: amount)
  388. debug(.apsManager, "Enact bolus \(roundedAmount), manual \(!isSMB)")
  389. do {
  390. try await pump.enactBolus(units: roundedAmount, automatic: isSMB)
  391. debug(.apsManager, "Bolus succeeded")
  392. if !isSMB {
  393. await determineBasalSync()
  394. }
  395. bolusProgress.send(0)
  396. } catch {
  397. warning(.apsManager, "Bolus failed with error: \(error.localizedDescription)")
  398. processError(APSError.pumpError(error))
  399. if !isSMB {
  400. processQueue.async {
  401. self.broadcaster.notify(BolusFailureObserver.self, on: self.processQueue) {
  402. $0.bolusDidFail()
  403. }
  404. }
  405. }
  406. }
  407. }
  408. func cancelBolus() async {
  409. guard let pump = pumpManager, pump.status.pumpStatus.bolusing else { return }
  410. debug(.apsManager, "Cancel bolus")
  411. do {
  412. _ = try await pump.cancelBolus()
  413. debug(.apsManager, "Bolus cancelled")
  414. } catch {
  415. debug(.apsManager, "Bolus cancellation failed with error: \(error.localizedDescription)")
  416. processError(APSError.pumpError(error))
  417. }
  418. bolusReporter?.removeObserver(self)
  419. bolusReporter = nil
  420. bolusProgress.send(nil)
  421. }
  422. func enactTempBasal(rate: Double, duration: TimeInterval) async {
  423. if let error = verifyStatus() {
  424. processError(error)
  425. return
  426. }
  427. guard let pump = pumpManager else { return }
  428. // unable to do temp basal during manual temp basal 😁
  429. if isManualTempBasal {
  430. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  431. return
  432. }
  433. debug(.apsManager, "Enact temp basal \(rate) - \(duration)")
  434. let roundedAmout = pump.roundToSupportedBasalRate(unitsPerHour: rate)
  435. do {
  436. try await pump.enactTempBasal(unitsPerHour: roundedAmout, for: duration)
  437. debug(.apsManager, "Temp Basal succeeded")
  438. } catch {
  439. debug(.apsManager, "Temp Basal failed with error: \(error.localizedDescription)")
  440. processError(APSError.pumpError(error))
  441. }
  442. }
  443. func enactAnnouncement(_ announcement: Announcement) {
  444. guard let action = announcement.action else {
  445. warning(.apsManager, "Invalid Announcement action")
  446. return
  447. }
  448. guard let pump = pumpManager else {
  449. warning(.apsManager, "Pump is not set")
  450. return
  451. }
  452. debug(.apsManager, "Start enact announcement: \(action)")
  453. switch action {
  454. case let .bolus(amount):
  455. if let error = verifyStatus() {
  456. processError(error)
  457. return
  458. }
  459. let roundedAmount = pump.roundToSupportedBolusVolume(units: Double(amount))
  460. pump.enactBolus(units: roundedAmount, activationType: .manualRecommendationAccepted) { error in
  461. if let error = error {
  462. // warning(.apsManager, "Announcement Bolus failed with error: \(error.localizedDescription)")
  463. switch error {
  464. case .uncertainDelivery:
  465. // Do not generate notification on uncertain delivery error
  466. break
  467. default:
  468. // Do not generate notifications for automatic boluses that fail.
  469. warning(.apsManager, "Announcement Bolus failed with error: \(error.localizedDescription)")
  470. }
  471. } else {
  472. debug(.apsManager, "Announcement Bolus succeeded")
  473. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  474. self.bolusProgress.send(0)
  475. }
  476. }
  477. case let .pump(pumpAction):
  478. switch pumpAction {
  479. case .suspend:
  480. if let error = verifyStatus() {
  481. processError(error)
  482. return
  483. }
  484. pump.suspendDelivery { error in
  485. if let error = error {
  486. debug(.apsManager, "Pump not suspended by Announcement: \(error.localizedDescription)")
  487. } else {
  488. debug(.apsManager, "Pump suspended by Announcement")
  489. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  490. }
  491. }
  492. case .resume:
  493. guard pump.status.pumpStatus.suspended else {
  494. return
  495. }
  496. pump.resumeDelivery { error in
  497. if let error = error {
  498. warning(.apsManager, "Pump not resumed by Announcement: \(error.localizedDescription)")
  499. } else {
  500. debug(.apsManager, "Pump resumed by Announcement")
  501. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  502. }
  503. }
  504. }
  505. case let .looping(closedLoop):
  506. settings.closedLoop = closedLoop
  507. debug(.apsManager, "Closed loop \(closedLoop) by Announcement")
  508. announcementsStorage.storeAnnouncements([announcement], enacted: true)
  509. case let .tempbasal(rate, duration):
  510. if let error = verifyStatus() {
  511. processError(error)
  512. return
  513. }
  514. // unable to do temp basal during manual temp basal 😁
  515. if isManualTempBasal {
  516. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  517. return
  518. }
  519. guard !settings.closedLoop else {
  520. return
  521. }
  522. let roundedRate = pump.roundToSupportedBasalRate(unitsPerHour: Double(rate))
  523. pump.enactTempBasal(unitsPerHour: roundedRate, for: TimeInterval(duration) * 60) { error in
  524. if let error = error {
  525. warning(.apsManager, "Announcement TempBasal failed with error: \(error.localizedDescription)")
  526. } else {
  527. debug(.apsManager, "Announcement TempBasal succeeded")
  528. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  529. }
  530. }
  531. }
  532. }
  533. private func fetchCurrentTempBasal(date: Date) async -> TempBasal {
  534. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  535. ofType: PumpEventStored.self,
  536. onContext: privateContext,
  537. predicate: NSPredicate.recentPumpHistory,
  538. key: "timestamp",
  539. ascending: false,
  540. fetchLimit: 1
  541. )
  542. let fetchedTempBasal = await privateContext.perform {
  543. guard let fetchedResults = results as? [PumpEventStored],
  544. let tempBasalEvent = fetchedResults.first,
  545. let tempBasal = tempBasalEvent.tempBasal,
  546. let eventTimestamp = tempBasalEvent.timestamp
  547. else {
  548. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  549. }
  550. let delta = Int((date.timeIntervalSince1970 - eventTimestamp.timeIntervalSince1970) / 60)
  551. let duration = max(0, Int(tempBasal.duration) - delta)
  552. let rate = tempBasal.rate as? Decimal ?? 0
  553. return TempBasal(duration: duration, rate: rate, temp: .absolute, timestamp: date)
  554. }
  555. guard let state = pumpManager?.status.basalDeliveryState else { return fetchedTempBasal }
  556. switch state {
  557. case .active:
  558. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  559. case let .tempBasal(dose):
  560. let rate = Decimal(dose.unitsPerHour)
  561. let durationMin = max(0, Int((dose.endDate.timeIntervalSince1970 - date.timeIntervalSince1970) / 60))
  562. return TempBasal(duration: durationMin, rate: rate, temp: .absolute, timestamp: date)
  563. default:
  564. return fetchedTempBasal
  565. }
  566. }
  567. private func enactDetermination() async throws {
  568. guard let determinationID = await determinationStorage
  569. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  570. else {
  571. throw APSError.apsError(message: "Determination not found")
  572. }
  573. guard let pump = pumpManager else {
  574. throw APSError.apsError(message: "Pump not set")
  575. }
  576. // Unable to do temp basal during manual temp basal 😁
  577. if isManualTempBasal {
  578. throw APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp")
  579. }
  580. let (rateDecimal, durationInSeconds, smbToDeliver) = try await setValues(determinationID: determinationID)
  581. if let rate = rateDecimal, let duration = durationInSeconds {
  582. try await performBasal(pump: pump, rate: rate, duration: duration)
  583. }
  584. // only perform a bolus if smbToDeliver is > 0
  585. if let smb = smbToDeliver, smb.compare(NSDecimalNumber(value: 0)) == .orderedDescending {
  586. try await performBolus(pump: pump, smbToDeliver: smb)
  587. }
  588. }
  589. private func setValues(determinationID: NSManagedObjectID) async throws
  590. -> (NSDecimalNumber?, TimeInterval?, NSDecimalNumber?)
  591. {
  592. return try await privateContext.perform {
  593. do {
  594. let determination = try self.privateContext.existingObject(with: determinationID) as? OrefDetermination
  595. let rate = determination?.rate
  596. let duration = determination?.duration.flatMap { TimeInterval(truncating: $0) * 60 }
  597. let smbToDeliver = determination?.smbToDeliver ?? 0
  598. return (rate, duration, smbToDeliver)
  599. } catch {
  600. throw error
  601. }
  602. }
  603. }
  604. private func performBasal(pump: PumpManager, rate: NSDecimalNumber, duration: TimeInterval) async throws {
  605. try await pump.enactTempBasal(unitsPerHour: Double(truncating: rate), for: duration)
  606. }
  607. private func performBolus(pump: PumpManager, smbToDeliver: NSDecimalNumber) async throws {
  608. try await pump.enactBolus(units: Double(truncating: smbToDeliver), automatic: true)
  609. bolusProgress.send(0)
  610. }
  611. private func reportEnacted(wasEnacted: Bool) async {
  612. guard let determinationID = await determinationStorage
  613. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  614. else {
  615. return
  616. }
  617. await privateContext.perform {
  618. if let determinationUpdated = self.privateContext.object(with: determinationID) as? OrefDetermination {
  619. determinationUpdated.timestamp = Date()
  620. determinationUpdated.enacted = wasEnacted
  621. determinationUpdated.isUploadedToNS = false
  622. do {
  623. guard self.privateContext.hasChanges else { return }
  624. try self.privateContext.save()
  625. debugPrint("Update successful in reportEnacted() \(DebuggingIdentifiers.succeeded)")
  626. } catch {
  627. debugPrint(
  628. "Failed \(DebuggingIdentifiers.succeeded) to save context in reportEnacted(): \(error.localizedDescription)"
  629. )
  630. }
  631. debug(.apsManager, "Determination enacted. Enacted: \(wasEnacted)")
  632. Task.detached(priority: .low) {
  633. await self.statistics()
  634. }
  635. } else {
  636. debugPrint("Failed to update OrefDetermination in reportEnacted()")
  637. }
  638. }
  639. }
  640. private func roundDecimal(_ decimal: Decimal, _ digits: Double) -> Decimal {
  641. let rounded = round(Double(decimal) * pow(10, digits)) / pow(10, digits)
  642. return Decimal(rounded)
  643. }
  644. private func roundDouble(_ double: Double, _ digits: Double) -> Double {
  645. let rounded = round(Double(double) * pow(10, digits)) / pow(10, digits)
  646. return rounded
  647. }
  648. private func medianCalculationDouble(array: [Double]) -> Double {
  649. guard !array.isEmpty else {
  650. return 0
  651. }
  652. let sorted = array.sorted()
  653. let length = array.count
  654. if length % 2 == 0 {
  655. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  656. }
  657. return sorted[length / 2]
  658. }
  659. private func medianCalculation(array: [Int]) -> Double {
  660. guard !array.isEmpty else {
  661. return 0
  662. }
  663. let sorted = array.sorted()
  664. let length = array.count
  665. if length % 2 == 0 {
  666. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  667. }
  668. return Double(sorted[length / 2])
  669. }
  670. private func tir(_ glucose: [GlucoseStored]) -> (TIR: Double, hypos: Double, hypers: Double, normal_: Double) {
  671. privateContext.perform {
  672. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  673. let totalReadings = justGlucoseArray.count
  674. let highLimit = settingsManager.settings.high
  675. let lowLimit = settingsManager.settings.low
  676. let hyperArray = glucose.filter({ $0.glucose >= Int(highLimit) })
  677. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  678. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  679. let hypoArray = glucose.filter({ $0.glucose <= Int(lowLimit) })
  680. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  681. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  682. // Euglyccemic range
  683. let normalArray = glucose.filter({ $0.glucose >= 70 && $0.glucose <= 140 })
  684. let normalReadings = normalArray.compactMap({ each in each.glucose as Int16 }).count
  685. let normalPercentage = Double(normalReadings) / Double(totalReadings) * 100
  686. // TIR
  687. let tir = 100 - (hypoPercentage + hyperPercentage)
  688. return (
  689. roundDouble(tir, 1),
  690. roundDouble(hypoPercentage, 1),
  691. roundDouble(hyperPercentage, 1),
  692. roundDouble(normalPercentage, 1)
  693. )
  694. }
  695. }
  696. private func glucoseStats(_ fetchedGlucose: [GlucoseStored])
  697. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  698. {
  699. let glucose = fetchedGlucose
  700. // First date
  701. let last = glucose.last?.date ?? Date()
  702. // Last date (recent)
  703. let first = glucose.first?.date ?? Date()
  704. // Total time in days
  705. let numberOfDays = (first - last).timeInterval / 8.64E4
  706. let denominator = numberOfDays < 1 ? 1 : numberOfDays
  707. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  708. let sumReadings = justGlucoseArray.reduce(0, +)
  709. let countReadings = justGlucoseArray.count
  710. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  711. let medianGlucose = medianCalculation(array: justGlucoseArray)
  712. var NGSPa1CStatisticValue = 0.0
  713. var IFCCa1CStatisticValue = 0.0
  714. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  715. IFCCa1CStatisticValue = 10.929 *
  716. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  717. var sumOfSquares = 0.0
  718. for array in justGlucoseArray {
  719. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  720. }
  721. var sd = 0.0
  722. var cv = 0.0
  723. // Avoid division by zero
  724. if glucoseAverage > 0 {
  725. sd = sqrt(sumOfSquares / Double(countReadings))
  726. cv = sd / Double(glucoseAverage) * 100
  727. }
  728. let conversionFactor = 0.0555
  729. let units = settingsManager.settings.units
  730. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  731. output = (
  732. ifcc: IFCCa1CStatisticValue,
  733. ngsp: NGSPa1CStatisticValue,
  734. average: glucoseAverage * (units == .mmolL ? conversionFactor : 1),
  735. median: medianGlucose * (units == .mmolL ? conversionFactor : 1),
  736. sd: sd * (units == .mmolL ? conversionFactor : 1), cv: cv,
  737. readings: Double(countReadings) / denominator
  738. )
  739. return output
  740. }
  741. private func loops(_ fetchedLoops: [LoopStatRecord]) -> Loops {
  742. let loops = fetchedLoops
  743. // First date
  744. let previous = loops.last?.end ?? Date()
  745. // Last date (recent)
  746. let current = loops.first?.start ?? Date()
  747. // Total time in days
  748. let totalTime = (current - previous).timeInterval / 8.64E4
  749. //
  750. let durationArray = loops.compactMap({ each in each.duration })
  751. let durationArrayCount = durationArray.count
  752. let durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount) * 60
  753. let medianDuration = medianCalculationDouble(array: durationArray) * 60
  754. let max_duration = (durationArray.max() ?? 0) * 60
  755. let min_duration = (durationArray.min() ?? 0) * 60
  756. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  757. let errorNR = durationArrayCount - successsNR
  758. let total = Double(successsNR + errorNR) == 0 ? 1 : Double(successsNR + errorNR)
  759. let successRate: Double? = (Double(successsNR) / total) * 100
  760. let loopNr = totalTime <= 1 ? total : round(total / (totalTime != 0 ? totalTime : 1))
  761. let intervalArray = loops.compactMap({ each in each.interval as Double })
  762. let count = intervalArray.count != 0 ? intervalArray.count : 1
  763. let median_interval = medianCalculationDouble(array: intervalArray)
  764. let intervalAverage = intervalArray.reduce(0, +) / Double(count)
  765. let maximumInterval = intervalArray.max()
  766. let minimumInterval = intervalArray.min()
  767. //
  768. let output = Loops(
  769. loops: Int(loopNr),
  770. errors: errorNR,
  771. success_rate: roundDecimal(Decimal(successRate ?? 0), 1),
  772. avg_interval: roundDecimal(Decimal(intervalAverage), 1),
  773. median_interval: roundDecimal(Decimal(median_interval), 1),
  774. min_interval: roundDecimal(Decimal(minimumInterval ?? 0), 1),
  775. max_interval: roundDecimal(Decimal(maximumInterval ?? 0), 1),
  776. avg_duration: roundDecimal(Decimal(durationAverage), 1),
  777. median_duration: roundDecimal(Decimal(medianDuration), 1),
  778. min_duration: roundDecimal(Decimal(min_duration), 1),
  779. max_duration: roundDecimal(Decimal(max_duration), 1)
  780. )
  781. return output
  782. }
  783. // fetch glucose for time interval
  784. func fetchGlucose(predicate: NSPredicate, fetchLimit: Int? = nil, batchSize: Int? = nil) async -> [GlucoseStored] {
  785. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  786. ofType: GlucoseStored.self,
  787. onContext: privateContext,
  788. predicate: predicate,
  789. key: "date",
  790. ascending: false,
  791. fetchLimit: fetchLimit,
  792. batchSize: batchSize
  793. )
  794. return await privateContext.perform {
  795. guard let glucoseResults = results as? [GlucoseStored] else {
  796. return []
  797. }
  798. return glucoseResults
  799. }
  800. }
  801. // TODO: - Refactor this whole shit here...
  802. // Add to statistics.JSON for upload to NS.
  803. private func statistics() async {
  804. let now = Date()
  805. if settingsManager.settings.uploadStats != nil {
  806. let hour = Calendar.current.component(.hour, from: now)
  807. guard hour > 20 else {
  808. return
  809. }
  810. // MARK: - Core Data related
  811. async let glucoseStats = glucoseForStats()
  812. async let lastLoopForStats = lastLoopForStats()
  813. async let carbTotal = carbsForStats()
  814. async let preferences = settingsManager.preferences
  815. let loopStats = await loopStats(oneDayGlucose: await glucoseStats.oneDayGlucose.readings)
  816. // Only save and upload once per day
  817. guard (-1 * (await lastLoopForStats ?? .distantPast).timeIntervalSinceNow.hours) > 22 else { return }
  818. let units = settingsManager.settings.units
  819. // MARK: - Not Core Data related stuff
  820. let pref = await preferences
  821. var algo_ = "Oref0"
  822. if pref.sigmoid, pref.enableDynamicCR {
  823. algo_ = "Dynamic ISF + CR: Sigmoid"
  824. } else if pref.sigmoid, !pref.enableDynamicCR {
  825. algo_ = "Dynamic ISF: Sigmoid"
  826. } else if pref.useNewFormula, pref.enableDynamicCR {
  827. algo_ = "Dynamic ISF + CR: Logarithmic"
  828. } else if pref.useNewFormula, !pref.sigmoid,!pref.enableDynamicCR {
  829. algo_ = "Dynamic ISF: Logarithmic"
  830. }
  831. let af = pref.adjustmentFactor
  832. let insulin_type = pref.curve
  833. // let buildDate = Bundle.main.buildDate // TODO: fix this
  834. let version = Bundle.main.releaseVersionNumber
  835. let build = Bundle.main.buildVersionNumber
  836. // Read branch information from branch.txt instead of infoDictionary
  837. var branch = "Unknown"
  838. if let branchFileURL = Bundle.main.url(forResource: "branch", withExtension: "txt"),
  839. let branchFileContent = try? String(contentsOf: branchFileURL)
  840. {
  841. let lines = branchFileContent.components(separatedBy: .newlines)
  842. for line in lines {
  843. let components = line.components(separatedBy: "=")
  844. if components.count == 2 {
  845. let key = components[0].trimmingCharacters(in: .whitespaces)
  846. let value = components[1].trimmingCharacters(in: .whitespaces)
  847. if key == "BRANCH" {
  848. branch = value
  849. break
  850. }
  851. }
  852. }
  853. } else {
  854. branch = "Unknown"
  855. }
  856. let copyrightNotice_ = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? ""
  857. let pump_ = pumpManager?.localizedTitle ?? ""
  858. let cgm = settingsManager.settings.cgm
  859. let file = OpenAPS.Monitor.statistics
  860. var iPa: Decimal = 75
  861. if pref.useCustomPeakTime {
  862. iPa = pref.insulinPeakTime
  863. } else if pref.curve.rawValue == "rapid-acting" {
  864. iPa = 65
  865. } else if pref.curve.rawValue == "ultra-rapid" {
  866. iPa = 50
  867. }
  868. // Insulin placeholder
  869. let insulin = Ins(
  870. TDD: 0,
  871. bolus: 0,
  872. temp_basal: 0,
  873. scheduled_basal: 0,
  874. total_average: 0
  875. )
  876. let processedGlucoseStats = await glucoseStats
  877. let hbA1cDisplayUnit = processedGlucoseStats.hbA1cDisplayUnit
  878. let dailystat = await Statistics(
  879. created_at: Date(),
  880. iPhone: UIDevice.current.getDeviceId,
  881. iOS: UIDevice.current.getOSInfo,
  882. Build_Version: version ?? "",
  883. Build_Number: build ?? "1",
  884. Branch: branch,
  885. CopyRightNotice: String(copyrightNotice_.prefix(32)),
  886. Build_Date: Date(), // TODO: fix this
  887. Algorithm: algo_,
  888. AdjustmentFactor: af,
  889. Pump: pump_,
  890. CGM: cgm.rawValue,
  891. insulinType: insulin_type.rawValue,
  892. peakActivityTime: iPa,
  893. Carbs_24h: await carbTotal,
  894. GlucoseStorage_Days: Decimal(roundDouble(processedGlucoseStats.numberofDays, 1)),
  895. Statistics: Stats(
  896. Distribution: processedGlucoseStats.TimeInRange,
  897. Glucose: processedGlucoseStats.avg,
  898. HbA1c: processedGlucoseStats.hbs,
  899. Units: Units(Glucose: units.rawValue, HbA1c: hbA1cDisplayUnit.rawValue),
  900. LoopCycles: loopStats,
  901. Insulin: insulin,
  902. Variance: processedGlucoseStats.variance
  903. )
  904. )
  905. storage.save(dailystat, as: file)
  906. await saveStatsToCoreData()
  907. }
  908. }
  909. private func saveStatsToCoreData() async {
  910. await privateContext.perform {
  911. let saveStatsCoreData = StatsData(context: self.privateContext)
  912. saveStatsCoreData.lastrun = Date()
  913. do {
  914. guard self.privateContext.hasChanges else { return }
  915. try self.privateContext.save()
  916. } catch {
  917. print(error.localizedDescription)
  918. }
  919. }
  920. }
  921. private func lastLoopForStats() async -> Date? {
  922. let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
  923. let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
  924. requestStats.sortDescriptors = [sortStats]
  925. requestStats.fetchLimit = 1
  926. return await privateContext.perform {
  927. do {
  928. return try self.privateContext.fetch(requestStats).first?.lastrun
  929. } catch {
  930. print(error.localizedDescription)
  931. return .distantPast
  932. }
  933. }
  934. }
  935. private func carbsForStats() async -> Decimal {
  936. let requestCarbs = CarbEntryStored.fetchRequest() as NSFetchRequest<CarbEntryStored>
  937. let daysAgo = Date().addingTimeInterval(-1.days.timeInterval)
  938. requestCarbs.predicate = NSPredicate(format: "carbs > 0 AND date > %@", daysAgo as NSDate)
  939. requestCarbs.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
  940. return await privateContext.perform {
  941. do {
  942. let carbs = try self.privateContext.fetch(requestCarbs)
  943. debugPrint(
  944. "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched carbs"
  945. )
  946. return carbs.reduce(0) { sum, meal in
  947. let mealCarbs = Decimal(string: "\(meal.carbs)") ?? Decimal.zero
  948. return sum + mealCarbs
  949. }
  950. } catch {
  951. debugPrint(
  952. "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while fetching carbs"
  953. )
  954. return 0
  955. }
  956. }
  957. }
  958. private func loopStats(oneDayGlucose: Double) async -> LoopCycles {
  959. let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  960. requestLSR.predicate = NSPredicate(
  961. format: "interval > 0 AND start > %@",
  962. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  963. )
  964. let sortLSR = NSSortDescriptor(key: "start", ascending: false)
  965. requestLSR.sortDescriptors = [sortLSR]
  966. return await privateContext.perform {
  967. do {
  968. let lsr = try self.privateContext.fetch(requestLSR)
  969. // Compute LoopStats for 24 hours
  970. let oneDayLoops = self.loops(lsr)
  971. return LoopCycles(
  972. loops: oneDayLoops.loops,
  973. errors: oneDayLoops.errors,
  974. readings: Int(oneDayGlucose),
  975. success_rate: oneDayLoops.success_rate,
  976. avg_interval: oneDayLoops.avg_interval,
  977. median_interval: oneDayLoops.median_interval,
  978. min_interval: oneDayLoops.min_interval,
  979. max_interval: oneDayLoops.max_interval,
  980. avg_duration: oneDayLoops.avg_duration,
  981. median_duration: oneDayLoops.median_duration,
  982. min_duration: oneDayLoops.max_duration,
  983. max_duration: oneDayLoops.max_duration
  984. )
  985. } catch {
  986. debugPrint(
  987. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to get Loop statistics for Statistics Upload"
  988. )
  989. return LoopCycles(
  990. loops: 0,
  991. errors: 0,
  992. readings: 0,
  993. success_rate: 0,
  994. avg_interval: 0,
  995. median_interval: 0,
  996. min_interval: 0,
  997. max_interval: 0,
  998. avg_duration: 0,
  999. median_duration: 0,
  1000. min_duration: 0,
  1001. max_duration: 0
  1002. )
  1003. }
  1004. }
  1005. }
  1006. private func tddForStats() async -> (currentTDD: Decimal, tddTotalAverage: Decimal) {
  1007. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  1008. let sort = NSSortDescriptor(key: "timestamp", ascending: false)
  1009. let daysOf14Ago = Date().addingTimeInterval(-14.days.timeInterval)
  1010. requestTDD.predicate = NSPredicate(format: "timestamp > %@", daysOf14Ago as NSDate)
  1011. requestTDD.sortDescriptors = [sort]
  1012. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  1013. requestTDD.resultType = .dictionaryResultType
  1014. var currentTDD: Decimal = 0
  1015. var tddTotalAverage: Decimal = 0
  1016. let results = await privateContext.perform {
  1017. do {
  1018. let fetchedResults = try self.privateContext.fetch(requestTDD) as? [[String: Any]]
  1019. return fetchedResults ?? []
  1020. } catch {
  1021. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to get TDD Data for Statistics Upload")
  1022. return []
  1023. }
  1024. }
  1025. if !results.isEmpty {
  1026. if let latestTDD = results.first?["totalDailyDose"] as? NSDecimalNumber {
  1027. currentTDD = latestTDD.decimalValue
  1028. }
  1029. let tddArray = results.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }
  1030. if !tddArray.isEmpty {
  1031. tddTotalAverage = tddArray.reduce(0, +) / Decimal(tddArray.count)
  1032. }
  1033. }
  1034. return (currentTDD, tddTotalAverage)
  1035. }
  1036. private func glucoseForStats() async
  1037. -> (
  1038. oneDayGlucose: (
  1039. ifcc: Double,
  1040. ngsp: Double,
  1041. average: Double,
  1042. median: Double,
  1043. sd: Double,
  1044. cv: Double,
  1045. readings: Double
  1046. ),
  1047. hbA1cDisplayUnit: HbA1cDisplayUnit,
  1048. numberofDays: Double,
  1049. TimeInRange: TIRs,
  1050. avg: Averages,
  1051. hbs: Durations,
  1052. variance: Variance
  1053. )
  1054. {
  1055. // Get the Glucose Values
  1056. let glucose24h = await fetchGlucose(predicate: NSPredicate.predicateForOneDayAgo, fetchLimit: 288, batchSize: 50)
  1057. let glucoseOneWeek = await fetchGlucose(
  1058. predicate: NSPredicate.predicateForOneWeek,
  1059. fetchLimit: 288 * 7,
  1060. batchSize: 250
  1061. )
  1062. let glucoseOneMonth = await fetchGlucose(
  1063. predicate: NSPredicate.predicateForOneMonth,
  1064. fetchLimit: 288 * 7 * 30,
  1065. batchSize: 500
  1066. )
  1067. let glucoseThreeMonths = await fetchGlucose(
  1068. predicate: NSPredicate.predicateForThreeMonths,
  1069. fetchLimit: 288 * 7 * 30 * 3,
  1070. batchSize: 1000
  1071. )
  1072. var result: (
  1073. oneDayGlucose: (
  1074. ifcc: Double,
  1075. ngsp: Double,
  1076. average: Double,
  1077. median: Double,
  1078. sd: Double,
  1079. cv: Double,
  1080. readings: Double
  1081. ),
  1082. hbA1cDisplayUnit: HbA1cDisplayUnit,
  1083. numberofDays: Double,
  1084. TimeInRange: TIRs,
  1085. avg: Averages,
  1086. hbs: Durations,
  1087. variance: Variance
  1088. )?
  1089. await privateContext.perform {
  1090. let units = self.settingsManager.settings.units
  1091. // First date
  1092. let previous = glucoseThreeMonths.last?.date ?? Date()
  1093. // Last date (recent)
  1094. let current = glucoseThreeMonths.first?.date ?? Date()
  1095. // Total time in days
  1096. let numberOfDays = (current - previous).timeInterval / 8.64E4
  1097. // Get glucose computations for every case
  1098. let oneDayGlucose = self.glucoseStats(glucose24h)
  1099. let sevenDaysGlucose = self.glucoseStats(glucoseOneWeek)
  1100. let thirtyDaysGlucose = self.glucoseStats(glucoseOneMonth)
  1101. let totalDaysGlucose = self.glucoseStats(glucoseThreeMonths)
  1102. let median = Durations(
  1103. day: self.roundDecimal(Decimal(oneDayGlucose.median), 1),
  1104. week: self.roundDecimal(Decimal(sevenDaysGlucose.median), 1),
  1105. month: self.roundDecimal(Decimal(thirtyDaysGlucose.median), 1),
  1106. total: self.roundDecimal(Decimal(totalDaysGlucose.median), 1)
  1107. )
  1108. let hbA1cDisplayUnit = self.settingsManager.settings.hbA1cDisplayUnit
  1109. let hbs = Durations(
  1110. day: ((units == .mmolL && hbA1cDisplayUnit == .mmolMol) || (units == .mgdL && hbA1cDisplayUnit == .percent)) ?
  1111. self.roundDecimal(Decimal(oneDayGlucose.ifcc), 1) : self.roundDecimal(Decimal(oneDayGlucose.ngsp), 1),
  1112. week: ((units == .mmolL && hbA1cDisplayUnit == .mmolMol) || (units == .mgdL && hbA1cDisplayUnit == .percent)) ?
  1113. self.roundDecimal(Decimal(sevenDaysGlucose.ifcc), 1) : self
  1114. .roundDecimal(Decimal(sevenDaysGlucose.ngsp), 1),
  1115. month: ((units == .mmolL && hbA1cDisplayUnit == .mmolMol) || (units == .mgdL && hbA1cDisplayUnit == .percent)) ?
  1116. self.roundDecimal(Decimal(thirtyDaysGlucose.ifcc), 1) : self
  1117. .roundDecimal(Decimal(thirtyDaysGlucose.ngsp), 1),
  1118. total: ((units == .mmolL && hbA1cDisplayUnit == .mmolMol) || (units == .mgdL && hbA1cDisplayUnit == .percent)) ?
  1119. self.roundDecimal(Decimal(totalDaysGlucose.ifcc), 1) : self.roundDecimal(Decimal(totalDaysGlucose.ngsp), 1)
  1120. )
  1121. var oneDay_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1122. var sevenDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1123. var thirtyDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1124. var totalDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1125. // Get TIR computations for every case
  1126. oneDay_ = self.tir(glucose24h)
  1127. sevenDays_ = self.tir(glucoseOneWeek)
  1128. thirtyDays_ = self.tir(glucoseOneMonth)
  1129. totalDays_ = self.tir(glucoseThreeMonths)
  1130. let tir = Durations(
  1131. day: self.roundDecimal(Decimal(oneDay_.TIR), 1),
  1132. week: self.roundDecimal(Decimal(sevenDays_.TIR), 1),
  1133. month: self.roundDecimal(Decimal(thirtyDays_.TIR), 1),
  1134. total: self.roundDecimal(Decimal(totalDays_.TIR), 1)
  1135. )
  1136. let hypo = Durations(
  1137. day: Decimal(oneDay_.hypos),
  1138. week: Decimal(sevenDays_.hypos),
  1139. month: Decimal(thirtyDays_.hypos),
  1140. total: Decimal(totalDays_.hypos)
  1141. )
  1142. let hyper = Durations(
  1143. day: Decimal(oneDay_.hypers),
  1144. week: Decimal(sevenDays_.hypers),
  1145. month: Decimal(thirtyDays_.hypers),
  1146. total: Decimal(totalDays_.hypers)
  1147. )
  1148. let normal = Durations(
  1149. day: Decimal(oneDay_.normal_),
  1150. week: Decimal(sevenDays_.normal_),
  1151. month: Decimal(thirtyDays_.normal_),
  1152. total: Decimal(totalDays_.normal_)
  1153. )
  1154. let range = Threshold(
  1155. low: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.low.asMmolL, 1) :
  1156. self.roundDecimal(self.settingsManager.settings.low, 0),
  1157. high: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.high.asMmolL, 1) :
  1158. self.roundDecimal(self.settingsManager.settings.high, 0)
  1159. )
  1160. let TimeInRange = TIRs(
  1161. TIR: tir,
  1162. Hypos: hypo,
  1163. Hypers: hyper,
  1164. Threshold: range,
  1165. Euglycemic: normal
  1166. )
  1167. let avgs = Durations(
  1168. day: self.roundDecimal(Decimal(oneDayGlucose.average), 1),
  1169. week: self.roundDecimal(Decimal(sevenDaysGlucose.average), 1),
  1170. month: self.roundDecimal(Decimal(thirtyDaysGlucose.average), 1),
  1171. total: self.roundDecimal(Decimal(totalDaysGlucose.average), 1)
  1172. )
  1173. let avg = Averages(Average: avgs, Median: median)
  1174. // Standard Deviations
  1175. let standardDeviations = Durations(
  1176. day: self.roundDecimal(Decimal(oneDayGlucose.sd), 1),
  1177. week: self.roundDecimal(Decimal(sevenDaysGlucose.sd), 1),
  1178. month: self.roundDecimal(Decimal(thirtyDaysGlucose.sd), 1),
  1179. total: self.roundDecimal(Decimal(totalDaysGlucose.sd), 1)
  1180. )
  1181. // CV = standard deviation / sample mean x 100
  1182. let cvs = Durations(
  1183. day: self.roundDecimal(Decimal(oneDayGlucose.cv), 1),
  1184. week: self.roundDecimal(Decimal(sevenDaysGlucose.cv), 1),
  1185. month: self.roundDecimal(Decimal(thirtyDaysGlucose.cv), 1),
  1186. total: self.roundDecimal(Decimal(totalDaysGlucose.cv), 1)
  1187. )
  1188. let variance = Variance(SD: standardDeviations, CV: cvs)
  1189. result = (oneDayGlucose, hbA1cDisplayUnit, numberOfDays, TimeInRange, avg, hbs, variance)
  1190. }
  1191. return result!
  1192. }
  1193. private func loopStats(loopStatRecord: LoopStats) {
  1194. privateContext.perform {
  1195. let nLS = LoopStatRecord(context: self.privateContext)
  1196. nLS.start = loopStatRecord.start
  1197. nLS.end = loopStatRecord.end ?? Date()
  1198. nLS.loopStatus = loopStatRecord.loopStatus
  1199. nLS.duration = loopStatRecord.duration ?? 0.0
  1200. nLS.interval = loopStatRecord.interval ?? 0.0
  1201. do {
  1202. guard self.privateContext.hasChanges else { return }
  1203. try self.privateContext.save()
  1204. } catch {
  1205. print(error.localizedDescription)
  1206. }
  1207. }
  1208. }
  1209. private func processError(_ error: Error) {
  1210. warning(.apsManager, "\(error.localizedDescription)")
  1211. lastError.send(error)
  1212. }
  1213. private func createBolusReporter() {
  1214. bolusReporter = pumpManager?.createBolusProgressReporter(reportingOn: processQueue)
  1215. bolusReporter?.addObserver(self)
  1216. }
  1217. private func clearBolusReporter() {
  1218. bolusReporter?.removeObserver(self)
  1219. bolusReporter = nil
  1220. processQueue.asyncAfter(deadline: .now() + 0.5) {
  1221. self.bolusProgress.send(nil)
  1222. }
  1223. }
  1224. }
  1225. private extension PumpManager {
  1226. func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval) async throws {
  1227. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1228. self.enactTempBasal(unitsPerHour: unitsPerHour, for: duration) { error in
  1229. if let error = error {
  1230. debug(.apsManager, "Temp basal failed: \(unitsPerHour) for: \(duration)")
  1231. continuation.resume(throwing: error)
  1232. } else {
  1233. debug(.apsManager, "Temp basal succeeded: \(unitsPerHour) for: \(duration)")
  1234. continuation.resume(returning: ())
  1235. }
  1236. }
  1237. }
  1238. }
  1239. func enactBolus(units: Double, automatic: Bool) async throws {
  1240. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1241. let automaticValue = automatic ? BolusActivationType.automatic : BolusActivationType.manualRecommendationAccepted
  1242. self.enactBolus(units: units, activationType: automaticValue) { error in
  1243. if let error = error {
  1244. debug(.apsManager, "Bolus failed: \(units)")
  1245. continuation.resume(throwing: error)
  1246. } else {
  1247. debug(.apsManager, "Bolus succeeded: \(units)")
  1248. continuation.resume(returning: ())
  1249. }
  1250. }
  1251. }
  1252. }
  1253. func cancelBolus() async throws -> DoseEntry? {
  1254. try await withCheckedThrowingContinuation { continuation in
  1255. self.cancelBolus { result in
  1256. switch result {
  1257. case let .success(dose):
  1258. debug(.apsManager, "Cancel Bolus succeeded")
  1259. continuation.resume(returning: dose)
  1260. case let .failure(error):
  1261. debug(.apsManager, "Cancel Bolus failed")
  1262. continuation.resume(throwing: APSError.pumpError(error))
  1263. }
  1264. }
  1265. }
  1266. }
  1267. func suspendDelivery() async throws {
  1268. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1269. self.suspendDelivery { error in
  1270. if let error = error {
  1271. continuation.resume(throwing: error)
  1272. } else {
  1273. continuation.resume()
  1274. }
  1275. }
  1276. }
  1277. }
  1278. func resumeDelivery() async throws {
  1279. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1280. self.resumeDelivery { error in
  1281. if let error = error {
  1282. continuation.resume(throwing: error)
  1283. } else {
  1284. continuation.resume()
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. extension BaseAPSManager: PumpManagerStatusObserver {
  1291. func pumpManager(_: PumpManager, didUpdate status: PumpManagerStatus, oldStatus _: PumpManagerStatus) {
  1292. let percent = Int((status.pumpBatteryChargeRemaining ?? 1) * 100)
  1293. privateContext.perform {
  1294. /// only update the last item with the current battery infos instead of saving a new one each time
  1295. let fetchRequest: NSFetchRequest<OpenAPS_Battery> = OpenAPS_Battery.fetchRequest()
  1296. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
  1297. fetchRequest.predicate = NSPredicate.predicateFor30MinAgo
  1298. fetchRequest.fetchLimit = 1
  1299. do {
  1300. let results = try self.privateContext.fetch(fetchRequest)
  1301. let batteryToStore: OpenAPS_Battery
  1302. if let existingBattery = results.first {
  1303. batteryToStore = existingBattery
  1304. } else {
  1305. batteryToStore = OpenAPS_Battery(context: self.privateContext)
  1306. batteryToStore.id = UUID()
  1307. }
  1308. batteryToStore.date = Date()
  1309. batteryToStore.percent = Int16(percent)
  1310. batteryToStore.voltage = nil
  1311. batteryToStore.status = percent > 10 ? "normal" : "low"
  1312. batteryToStore.display = status.pumpBatteryChargeRemaining != nil
  1313. guard self.privateContext.hasChanges else { return }
  1314. try self.privateContext.save()
  1315. } catch {
  1316. print("Failed to fetch or save battery: \(error.localizedDescription)")
  1317. }
  1318. }
  1319. // TODO: - remove this after ensuring that NS still gets the same infos from Core Data
  1320. storage.save(status.pumpStatus, as: OpenAPS.Monitor.status)
  1321. }
  1322. }
  1323. extension BaseAPSManager: DoseProgressObserver {
  1324. func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) {
  1325. bolusProgress.send(Decimal(doseProgressReporter.progress.percentComplete))
  1326. if doseProgressReporter.progress.isComplete {
  1327. clearBolusReporter()
  1328. }
  1329. }
  1330. }
  1331. extension PumpManagerStatus {
  1332. var pumpStatus: PumpStatus {
  1333. let bolusing = bolusState != .noBolus
  1334. let suspended = basalDeliveryState?.isSuspended ?? true
  1335. let type = suspended ? StatusType.suspended : (bolusing ? .bolusing : .normal)
  1336. return PumpStatus(status: type, bolusing: bolusing, suspended: suspended, timestamp: Date())
  1337. }
  1338. }