APSManager.swift 56 KB

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