APSManager.swift 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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, callback: ((Bool, String) -> Void)?) 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(_ callback: ((Bool, String) -> Void)?) 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: TrioSettings {
  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, callback: ((Bool, String) -> Void)?) 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. callback?(false, "Error! Failed to enact bolus.")
  382. return
  383. }
  384. guard let pump = pumpManager else { return }
  385. let roundedAmount = pump.roundToSupportedBolusVolume(units: amount)
  386. debug(.apsManager, "Enact bolus \(roundedAmount), manual \(!isSMB)")
  387. do {
  388. try await pump.enactBolus(units: roundedAmount, automatic: isSMB)
  389. debug(.apsManager, "Bolus succeeded")
  390. if !isSMB {
  391. await determineBasalSync()
  392. }
  393. bolusProgress.send(0)
  394. callback?(true, "Bolus enacted successfully.")
  395. } catch {
  396. warning(.apsManager, "Bolus failed with error: \(error.localizedDescription)")
  397. processError(APSError.pumpError(error))
  398. if !isSMB {
  399. processQueue.async {
  400. self.broadcaster.notify(BolusFailureObserver.self, on: self.processQueue) {
  401. $0.bolusDidFail()
  402. }
  403. }
  404. }
  405. callback?(false, "Error! Failed to enact bolus.")
  406. }
  407. }
  408. func cancelBolus(_ callback: ((Bool, String) -> Void)?) 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. callback?(true, "Bolus cancelled successfully.")
  415. } catch {
  416. debug(.apsManager, "Bolus cancellation failed with error: \(error.localizedDescription)")
  417. processError(APSError.pumpError(error))
  418. callback?(false, "Error! Bolus cancellation failed.")
  419. }
  420. bolusReporter?.removeObserver(self)
  421. bolusReporter = nil
  422. bolusProgress.send(nil)
  423. }
  424. func enactTempBasal(rate: Double, duration: TimeInterval) async {
  425. if let error = verifyStatus() {
  426. processError(error)
  427. return
  428. }
  429. guard let pump = pumpManager else { return }
  430. // unable to do temp basal during manual temp basal 😁
  431. if isManualTempBasal {
  432. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  433. return
  434. }
  435. debug(.apsManager, "Enact temp basal \(rate) - \(duration)")
  436. let roundedAmout = pump.roundToSupportedBasalRate(unitsPerHour: rate)
  437. do {
  438. try await pump.enactTempBasal(unitsPerHour: roundedAmout, for: duration)
  439. debug(.apsManager, "Temp Basal succeeded")
  440. } catch {
  441. debug(.apsManager, "Temp Basal failed with error: \(error.localizedDescription)")
  442. processError(APSError.pumpError(error))
  443. }
  444. }
  445. private func fetchCurrentTempBasal(date: Date) async -> TempBasal {
  446. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  447. ofType: PumpEventStored.self,
  448. onContext: privateContext,
  449. predicate: NSPredicate.recentPumpHistory,
  450. key: "timestamp",
  451. ascending: false,
  452. fetchLimit: 1
  453. )
  454. let fetchedTempBasal = await privateContext.perform {
  455. guard let fetchedResults = results as? [PumpEventStored],
  456. let tempBasalEvent = fetchedResults.first,
  457. let tempBasal = tempBasalEvent.tempBasal,
  458. let eventTimestamp = tempBasalEvent.timestamp
  459. else {
  460. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  461. }
  462. let delta = Int((date.timeIntervalSince1970 - eventTimestamp.timeIntervalSince1970) / 60)
  463. let duration = max(0, Int(tempBasal.duration) - delta)
  464. let rate = tempBasal.rate as? Decimal ?? 0
  465. return TempBasal(duration: duration, rate: rate, temp: .absolute, timestamp: date)
  466. }
  467. guard let state = pumpManager?.status.basalDeliveryState else { return fetchedTempBasal }
  468. switch state {
  469. case .active:
  470. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  471. case let .tempBasal(dose):
  472. let rate = Decimal(dose.unitsPerHour)
  473. let durationMin = max(0, Int((dose.endDate.timeIntervalSince1970 - date.timeIntervalSince1970) / 60))
  474. return TempBasal(duration: durationMin, rate: rate, temp: .absolute, timestamp: date)
  475. default:
  476. return fetchedTempBasal
  477. }
  478. }
  479. private func enactDetermination() async throws {
  480. guard let determinationID = await determinationStorage
  481. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  482. else {
  483. throw APSError.apsError(message: "Determination not found")
  484. }
  485. guard let pump = pumpManager else {
  486. throw APSError.apsError(message: "Pump not set")
  487. }
  488. // Unable to do temp basal during manual temp basal 😁
  489. if isManualTempBasal {
  490. throw APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp")
  491. }
  492. let (rateDecimal, durationInSeconds, smbToDeliver) = try await setValues(determinationID: determinationID)
  493. if let rate = rateDecimal, let duration = durationInSeconds {
  494. try await performBasal(pump: pump, rate: rate, duration: duration)
  495. }
  496. // only perform a bolus if smbToDeliver is > 0
  497. if let smb = smbToDeliver, smb.compare(NSDecimalNumber(value: 0)) == .orderedDescending {
  498. try await performBolus(pump: pump, smbToDeliver: smb)
  499. }
  500. }
  501. private func setValues(determinationID: NSManagedObjectID) async throws
  502. -> (NSDecimalNumber?, TimeInterval?, NSDecimalNumber?)
  503. {
  504. return try await privateContext.perform {
  505. do {
  506. let determination = try self.privateContext.existingObject(with: determinationID) as? OrefDetermination
  507. let rate = determination?.rate
  508. let duration = determination?.duration.flatMap { TimeInterval(truncating: $0) * 60 }
  509. let smbToDeliver = determination?.smbToDeliver ?? 0
  510. return (rate, duration, smbToDeliver)
  511. } catch {
  512. throw error
  513. }
  514. }
  515. }
  516. private func performBasal(pump: PumpManager, rate: NSDecimalNumber, duration: TimeInterval) async throws {
  517. try await pump.enactTempBasal(unitsPerHour: Double(truncating: rate), for: duration)
  518. }
  519. private func performBolus(pump: PumpManager, smbToDeliver: NSDecimalNumber) async throws {
  520. try await pump.enactBolus(units: Double(truncating: smbToDeliver), automatic: true)
  521. bolusProgress.send(0)
  522. }
  523. private func reportEnacted(wasEnacted: Bool) async {
  524. guard let determinationID = await determinationStorage
  525. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  526. else {
  527. return
  528. }
  529. await privateContext.perform {
  530. if let determinationUpdated = self.privateContext.object(with: determinationID) as? OrefDetermination {
  531. determinationUpdated.timestamp = Date()
  532. determinationUpdated.enacted = wasEnacted
  533. determinationUpdated.isUploadedToNS = false
  534. do {
  535. guard self.privateContext.hasChanges else { return }
  536. try self.privateContext.save()
  537. debugPrint("Update successful in reportEnacted() \(DebuggingIdentifiers.succeeded)")
  538. } catch {
  539. debugPrint(
  540. "Failed \(DebuggingIdentifiers.succeeded) to save context in reportEnacted(): \(error.localizedDescription)"
  541. )
  542. }
  543. debug(.apsManager, "Determination enacted. Enacted: \(wasEnacted)")
  544. Task.detached(priority: .low) {
  545. await self.statistics()
  546. }
  547. } else {
  548. debugPrint("Failed to update OrefDetermination in reportEnacted()")
  549. }
  550. }
  551. }
  552. private func roundDecimal(_ decimal: Decimal, _ digits: Double) -> Decimal {
  553. let rounded = round(Double(decimal) * pow(10, digits)) / pow(10, digits)
  554. return Decimal(rounded)
  555. }
  556. private func roundDouble(_ double: Double, _ digits: Double) -> Double {
  557. let rounded = round(Double(double) * pow(10, digits)) / pow(10, digits)
  558. return rounded
  559. }
  560. private func medianCalculationDouble(array: [Double]) -> Double {
  561. guard !array.isEmpty else {
  562. return 0
  563. }
  564. let sorted = array.sorted()
  565. let length = array.count
  566. if length % 2 == 0 {
  567. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  568. }
  569. return sorted[length / 2]
  570. }
  571. private func medianCalculation(array: [Int]) -> Double {
  572. guard !array.isEmpty else {
  573. return 0
  574. }
  575. let sorted = array.sorted()
  576. let length = array.count
  577. if length % 2 == 0 {
  578. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  579. }
  580. return Double(sorted[length / 2])
  581. }
  582. private func tir(_ glucose: [GlucoseStored]) -> (TIR: Double, hypos: Double, hypers: Double, normal_: Double) {
  583. privateContext.perform {
  584. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  585. let totalReadings = justGlucoseArray.count
  586. let highLimit = settingsManager.settings.high
  587. let lowLimit = settingsManager.settings.low
  588. let hyperArray = glucose.filter({ $0.glucose >= Int(highLimit) })
  589. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  590. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  591. let hypoArray = glucose.filter({ $0.glucose <= Int(lowLimit) })
  592. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  593. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  594. // Euglyccemic range
  595. let normalArray = glucose.filter({ $0.glucose >= 70 && $0.glucose <= 140 })
  596. let normalReadings = normalArray.compactMap({ each in each.glucose as Int16 }).count
  597. let normalPercentage = Double(normalReadings) / Double(totalReadings) * 100
  598. // TIR
  599. let tir = 100 - (hypoPercentage + hyperPercentage)
  600. return (
  601. roundDouble(tir, 1),
  602. roundDouble(hypoPercentage, 1),
  603. roundDouble(hyperPercentage, 1),
  604. roundDouble(normalPercentage, 1)
  605. )
  606. }
  607. }
  608. private func glucoseStats(_ fetchedGlucose: [GlucoseStored])
  609. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  610. {
  611. let glucose = fetchedGlucose
  612. // First date
  613. let last = glucose.last?.date ?? Date()
  614. // Last date (recent)
  615. let first = glucose.first?.date ?? Date()
  616. // Total time in days
  617. let numberOfDays = (first - last).timeInterval / 8.64E4
  618. let denominator = numberOfDays < 1 ? 1 : numberOfDays
  619. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  620. let sumReadings = justGlucoseArray.reduce(0, +)
  621. let countReadings = justGlucoseArray.count
  622. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  623. let medianGlucose = medianCalculation(array: justGlucoseArray)
  624. var NGSPa1CStatisticValue = 0.0
  625. var IFCCa1CStatisticValue = 0.0
  626. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  627. IFCCa1CStatisticValue = 10.929 *
  628. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  629. var sumOfSquares = 0.0
  630. for array in justGlucoseArray {
  631. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  632. }
  633. var sd = 0.0
  634. var cv = 0.0
  635. // Avoid division by zero
  636. if glucoseAverage > 0 {
  637. sd = sqrt(sumOfSquares / Double(countReadings))
  638. cv = sd / Double(glucoseAverage) * 100
  639. }
  640. let conversionFactor = 0.0555
  641. let units = settingsManager.settings.units
  642. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  643. output = (
  644. ifcc: IFCCa1CStatisticValue,
  645. ngsp: NGSPa1CStatisticValue,
  646. average: glucoseAverage * (units == .mmolL ? conversionFactor : 1),
  647. median: medianGlucose * (units == .mmolL ? conversionFactor : 1),
  648. sd: sd * (units == .mmolL ? conversionFactor : 1), cv: cv,
  649. readings: Double(countReadings) / denominator
  650. )
  651. return output
  652. }
  653. private func loops(_ fetchedLoops: [LoopStatRecord]) -> Loops {
  654. let loops = fetchedLoops
  655. // First date
  656. let previous = loops.last?.end ?? Date()
  657. // Last date (recent)
  658. let current = loops.first?.start ?? Date()
  659. // Total time in days
  660. let totalTime = (current - previous).timeInterval / 8.64E4
  661. //
  662. let durationArray = loops.compactMap({ each in each.duration })
  663. let durationArrayCount = durationArray.count
  664. let durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount) * 60
  665. let medianDuration = medianCalculationDouble(array: durationArray) * 60
  666. let max_duration = (durationArray.max() ?? 0) * 60
  667. let min_duration = (durationArray.min() ?? 0) * 60
  668. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  669. let errorNR = durationArrayCount - successsNR
  670. let total = Double(successsNR + errorNR) == 0 ? 1 : Double(successsNR + errorNR)
  671. let successRate: Double? = (Double(successsNR) / total) * 100
  672. let loopNr = totalTime <= 1 ? total : round(total / (totalTime != 0 ? totalTime : 1))
  673. let intervalArray = loops.compactMap({ each in each.interval as Double })
  674. let count = intervalArray.count != 0 ? intervalArray.count : 1
  675. let median_interval = medianCalculationDouble(array: intervalArray)
  676. let intervalAverage = intervalArray.reduce(0, +) / Double(count)
  677. let maximumInterval = intervalArray.max()
  678. let minimumInterval = intervalArray.min()
  679. //
  680. let output = Loops(
  681. loops: Int(loopNr),
  682. errors: errorNR,
  683. success_rate: roundDecimal(Decimal(successRate ?? 0), 1),
  684. avg_interval: roundDecimal(Decimal(intervalAverage), 1),
  685. median_interval: roundDecimal(Decimal(median_interval), 1),
  686. min_interval: roundDecimal(Decimal(minimumInterval ?? 0), 1),
  687. max_interval: roundDecimal(Decimal(maximumInterval ?? 0), 1),
  688. avg_duration: roundDecimal(Decimal(durationAverage), 1),
  689. median_duration: roundDecimal(Decimal(medianDuration), 1),
  690. min_duration: roundDecimal(Decimal(min_duration), 1),
  691. max_duration: roundDecimal(Decimal(max_duration), 1)
  692. )
  693. return output
  694. }
  695. // fetch glucose for time interval
  696. func fetchGlucose(predicate: NSPredicate, fetchLimit: Int? = nil, batchSize: Int? = nil) async -> [GlucoseStored] {
  697. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  698. ofType: GlucoseStored.self,
  699. onContext: privateContext,
  700. predicate: predicate,
  701. key: "date",
  702. ascending: false,
  703. fetchLimit: fetchLimit,
  704. batchSize: batchSize
  705. )
  706. return await privateContext.perform {
  707. guard let glucoseResults = results as? [GlucoseStored] else {
  708. return []
  709. }
  710. return glucoseResults
  711. }
  712. }
  713. // TODO: - Refactor this whole shit here...
  714. // Add to statistics.JSON for upload to NS.
  715. private func statistics() async {
  716. let now = Date()
  717. if settingsManager.settings.uploadStats != nil {
  718. let hour = Calendar.current.component(.hour, from: now)
  719. guard hour > 20 else {
  720. return
  721. }
  722. // MARK: - Core Data related
  723. async let glucoseStats = glucoseForStats()
  724. async let lastLoopForStats = lastLoopForStats()
  725. async let carbTotal = carbsForStats()
  726. async let preferences = settingsManager.preferences
  727. let loopStats = await loopStats(oneDayGlucose: await glucoseStats.oneDayGlucose.readings)
  728. // Only save and upload once per day
  729. guard (-1 * (await lastLoopForStats ?? .distantPast).timeIntervalSinceNow.hours) > 22 else { return }
  730. let units = settingsManager.settings.units
  731. // MARK: - Not Core Data related stuff
  732. let pref = await preferences
  733. var algo_ = "Oref0"
  734. if pref.sigmoid, pref.enableDynamicCR {
  735. algo_ = "Dynamic ISF + CR: Sigmoid"
  736. } else if pref.sigmoid, !pref.enableDynamicCR {
  737. algo_ = "Dynamic ISF: Sigmoid"
  738. } else if pref.useNewFormula, pref.enableDynamicCR {
  739. algo_ = "Dynamic ISF + CR: Logarithmic"
  740. } else if pref.useNewFormula, !pref.sigmoid,!pref.enableDynamicCR {
  741. algo_ = "Dynamic ISF: Logarithmic"
  742. }
  743. let af = pref.adjustmentFactor
  744. let insulin_type = pref.curve
  745. // let buildDate = Bundle.main.buildDate // TODO: fix this
  746. let version = Bundle.main.releaseVersionNumber
  747. let build = Bundle.main.buildVersionNumber
  748. // Read branch information from branch.txt instead of infoDictionary
  749. var branch = "Unknown"
  750. if let branchFileURL = Bundle.main.url(forResource: "branch", withExtension: "txt"),
  751. let branchFileContent = try? String(contentsOf: branchFileURL)
  752. {
  753. let lines = branchFileContent.components(separatedBy: .newlines)
  754. for line in lines {
  755. let components = line.components(separatedBy: "=")
  756. if components.count == 2 {
  757. let key = components[0].trimmingCharacters(in: .whitespaces)
  758. let value = components[1].trimmingCharacters(in: .whitespaces)
  759. if key == "BRANCH" {
  760. branch = value
  761. break
  762. }
  763. }
  764. }
  765. } else {
  766. branch = "Unknown"
  767. }
  768. let copyrightNotice_ = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? ""
  769. let pump_ = pumpManager?.localizedTitle ?? ""
  770. let cgm = settingsManager.settings.cgm
  771. let file = OpenAPS.Monitor.statistics
  772. var iPa: Decimal = 75
  773. if pref.useCustomPeakTime {
  774. iPa = pref.insulinPeakTime
  775. } else if pref.curve.rawValue == "rapid-acting" {
  776. iPa = 65
  777. } else if pref.curve.rawValue == "ultra-rapid" {
  778. iPa = 50
  779. }
  780. // Insulin placeholder
  781. let insulin = Ins(
  782. TDD: 0,
  783. bolus: 0,
  784. temp_basal: 0,
  785. scheduled_basal: 0,
  786. total_average: 0
  787. )
  788. let processedGlucoseStats = await glucoseStats
  789. let hbA1cDisplayUnit = processedGlucoseStats.hbA1cDisplayUnit
  790. let dailystat = await Statistics(
  791. created_at: Date(),
  792. iPhone: UIDevice.current.getDeviceId,
  793. iOS: UIDevice.current.getOSInfo,
  794. Build_Version: version ?? "",
  795. Build_Number: build ?? "1",
  796. Branch: branch,
  797. CopyRightNotice: String(copyrightNotice_.prefix(32)),
  798. Build_Date: Date(), // TODO: fix this
  799. Algorithm: algo_,
  800. AdjustmentFactor: af,
  801. Pump: pump_,
  802. CGM: cgm.rawValue,
  803. insulinType: insulin_type.rawValue,
  804. peakActivityTime: iPa,
  805. Carbs_24h: await carbTotal,
  806. GlucoseStorage_Days: Decimal(roundDouble(processedGlucoseStats.numberofDays, 1)),
  807. Statistics: Stats(
  808. Distribution: processedGlucoseStats.TimeInRange,
  809. Glucose: processedGlucoseStats.avg,
  810. HbA1c: processedGlucoseStats.hbs,
  811. Units: Units(Glucose: units.rawValue, HbA1c: hbA1cDisplayUnit.rawValue),
  812. LoopCycles: loopStats,
  813. Insulin: insulin,
  814. Variance: processedGlucoseStats.variance
  815. )
  816. )
  817. storage.save(dailystat, as: file)
  818. await saveStatsToCoreData()
  819. }
  820. }
  821. private func saveStatsToCoreData() async {
  822. await privateContext.perform {
  823. let saveStatsCoreData = StatsData(context: self.privateContext)
  824. saveStatsCoreData.lastrun = Date()
  825. do {
  826. guard self.privateContext.hasChanges else { return }
  827. try self.privateContext.save()
  828. } catch {
  829. print(error.localizedDescription)
  830. }
  831. }
  832. }
  833. private func lastLoopForStats() async -> Date? {
  834. let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
  835. let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
  836. requestStats.sortDescriptors = [sortStats]
  837. requestStats.fetchLimit = 1
  838. return await privateContext.perform {
  839. do {
  840. return try self.privateContext.fetch(requestStats).first?.lastrun
  841. } catch {
  842. print(error.localizedDescription)
  843. return .distantPast
  844. }
  845. }
  846. }
  847. private func carbsForStats() async -> Decimal {
  848. let requestCarbs = CarbEntryStored.fetchRequest() as NSFetchRequest<CarbEntryStored>
  849. let daysAgo = Date().addingTimeInterval(-1.days.timeInterval)
  850. requestCarbs.predicate = NSPredicate(format: "carbs > 0 AND date > %@", daysAgo as NSDate)
  851. requestCarbs.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
  852. return await privateContext.perform {
  853. do {
  854. let carbs = try self.privateContext.fetch(requestCarbs)
  855. debugPrint(
  856. "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched carbs"
  857. )
  858. return carbs.reduce(0) { sum, meal in
  859. let mealCarbs = Decimal(string: "\(meal.carbs)") ?? Decimal.zero
  860. return sum + mealCarbs
  861. }
  862. } catch {
  863. debugPrint(
  864. "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while fetching carbs"
  865. )
  866. return 0
  867. }
  868. }
  869. }
  870. private func loopStats(oneDayGlucose: Double) async -> LoopCycles {
  871. let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  872. requestLSR.predicate = NSPredicate(
  873. format: "interval > 0 AND start > %@",
  874. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  875. )
  876. let sortLSR = NSSortDescriptor(key: "start", ascending: false)
  877. requestLSR.sortDescriptors = [sortLSR]
  878. return await privateContext.perform {
  879. do {
  880. let lsr = try self.privateContext.fetch(requestLSR)
  881. // Compute LoopStats for 24 hours
  882. let oneDayLoops = self.loops(lsr)
  883. return LoopCycles(
  884. loops: oneDayLoops.loops,
  885. errors: oneDayLoops.errors,
  886. readings: Int(oneDayGlucose),
  887. success_rate: oneDayLoops.success_rate,
  888. avg_interval: oneDayLoops.avg_interval,
  889. median_interval: oneDayLoops.median_interval,
  890. min_interval: oneDayLoops.min_interval,
  891. max_interval: oneDayLoops.max_interval,
  892. avg_duration: oneDayLoops.avg_duration,
  893. median_duration: oneDayLoops.median_duration,
  894. min_duration: oneDayLoops.max_duration,
  895. max_duration: oneDayLoops.max_duration
  896. )
  897. } catch {
  898. debugPrint(
  899. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to get Loop statistics for Statistics Upload"
  900. )
  901. return LoopCycles(
  902. loops: 0,
  903. errors: 0,
  904. readings: 0,
  905. success_rate: 0,
  906. avg_interval: 0,
  907. median_interval: 0,
  908. min_interval: 0,
  909. max_interval: 0,
  910. avg_duration: 0,
  911. median_duration: 0,
  912. min_duration: 0,
  913. max_duration: 0
  914. )
  915. }
  916. }
  917. }
  918. private func tddForStats() async -> (currentTDD: Decimal, tddTotalAverage: Decimal) {
  919. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  920. let sort = NSSortDescriptor(key: "timestamp", ascending: false)
  921. let daysOf14Ago = Date().addingTimeInterval(-14.days.timeInterval)
  922. requestTDD.predicate = NSPredicate(format: "timestamp > %@", daysOf14Ago as NSDate)
  923. requestTDD.sortDescriptors = [sort]
  924. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  925. requestTDD.resultType = .dictionaryResultType
  926. var currentTDD: Decimal = 0
  927. var tddTotalAverage: Decimal = 0
  928. let results = await privateContext.perform {
  929. do {
  930. let fetchedResults = try self.privateContext.fetch(requestTDD) as? [[String: Any]]
  931. return fetchedResults ?? []
  932. } catch {
  933. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to get TDD Data for Statistics Upload")
  934. return []
  935. }
  936. }
  937. if !results.isEmpty {
  938. if let latestTDD = results.first?["totalDailyDose"] as? NSDecimalNumber {
  939. currentTDD = latestTDD.decimalValue
  940. }
  941. let tddArray = results.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }
  942. if !tddArray.isEmpty {
  943. tddTotalAverage = tddArray.reduce(0, +) / Decimal(tddArray.count)
  944. }
  945. }
  946. return (currentTDD, tddTotalAverage)
  947. }
  948. private func glucoseForStats() async
  949. -> (
  950. oneDayGlucose: (
  951. ifcc: Double,
  952. ngsp: Double,
  953. average: Double,
  954. median: Double,
  955. sd: Double,
  956. cv: Double,
  957. readings: Double
  958. ),
  959. hbA1cDisplayUnit: HbA1cDisplayUnit,
  960. numberofDays: Double,
  961. TimeInRange: TIRs,
  962. avg: Averages,
  963. hbs: Durations,
  964. variance: Variance
  965. )
  966. {
  967. // Get the Glucose Values
  968. let glucose24h = await fetchGlucose(predicate: NSPredicate.predicateForOneDayAgo, fetchLimit: 288, batchSize: 50)
  969. let glucoseOneWeek = await fetchGlucose(
  970. predicate: NSPredicate.predicateForOneWeek,
  971. fetchLimit: 288 * 7,
  972. batchSize: 250
  973. )
  974. let glucoseOneMonth = await fetchGlucose(
  975. predicate: NSPredicate.predicateForOneMonth,
  976. fetchLimit: 288 * 7 * 30,
  977. batchSize: 500
  978. )
  979. let glucoseThreeMonths = await fetchGlucose(
  980. predicate: NSPredicate.predicateForThreeMonths,
  981. fetchLimit: 288 * 7 * 30 * 3,
  982. batchSize: 1000
  983. )
  984. var result: (
  985. oneDayGlucose: (
  986. ifcc: Double,
  987. ngsp: Double,
  988. average: Double,
  989. median: Double,
  990. sd: Double,
  991. cv: Double,
  992. readings: Double
  993. ),
  994. hbA1cDisplayUnit: HbA1cDisplayUnit,
  995. numberofDays: Double,
  996. TimeInRange: TIRs,
  997. avg: Averages,
  998. hbs: Durations,
  999. variance: Variance
  1000. )?
  1001. await privateContext.perform {
  1002. let units = self.settingsManager.settings.units
  1003. // First date
  1004. let previous = glucoseThreeMonths.last?.date ?? Date()
  1005. // Last date (recent)
  1006. let current = glucoseThreeMonths.first?.date ?? Date()
  1007. // Total time in days
  1008. let numberOfDays = (current - previous).timeInterval / 8.64E4
  1009. // Get glucose computations for every case
  1010. let oneDayGlucose = self.glucoseStats(glucose24h)
  1011. let sevenDaysGlucose = self.glucoseStats(glucoseOneWeek)
  1012. let thirtyDaysGlucose = self.glucoseStats(glucoseOneMonth)
  1013. let totalDaysGlucose = self.glucoseStats(glucoseThreeMonths)
  1014. let median = Durations(
  1015. day: self.roundDecimal(Decimal(oneDayGlucose.median), 1),
  1016. week: self.roundDecimal(Decimal(sevenDaysGlucose.median), 1),
  1017. month: self.roundDecimal(Decimal(thirtyDaysGlucose.median), 1),
  1018. total: self.roundDecimal(Decimal(totalDaysGlucose.median), 1)
  1019. )
  1020. let hbA1cDisplayUnit = self.settingsManager.settings.hbA1cDisplayUnit
  1021. let hbs = Durations(
  1022. day: hbA1cDisplayUnit == .mmolMol ?
  1023. self.roundDecimal(Decimal(oneDayGlucose.ifcc), 1) :
  1024. self.roundDecimal(Decimal(oneDayGlucose.ngsp), 1),
  1025. week: hbA1cDisplayUnit == .mmolMol ?
  1026. self.roundDecimal(Decimal(sevenDaysGlucose.ifcc), 1) :
  1027. self.roundDecimal(Decimal(sevenDaysGlucose.ngsp), 1),
  1028. month: hbA1cDisplayUnit == .mmolMol ?
  1029. self.roundDecimal(Decimal(thirtyDaysGlucose.ifcc), 1) :
  1030. self.roundDecimal(Decimal(thirtyDaysGlucose.ngsp), 1),
  1031. total: hbA1cDisplayUnit == .mmolMol ?
  1032. self.roundDecimal(Decimal(totalDaysGlucose.ifcc), 1) :
  1033. self.roundDecimal(Decimal(totalDaysGlucose.ngsp), 1)
  1034. )
  1035. var oneDay_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1036. var sevenDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1037. var thirtyDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1038. var totalDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  1039. // Get TIR computations for every case
  1040. oneDay_ = self.tir(glucose24h)
  1041. sevenDays_ = self.tir(glucoseOneWeek)
  1042. thirtyDays_ = self.tir(glucoseOneMonth)
  1043. totalDays_ = self.tir(glucoseThreeMonths)
  1044. let tir = Durations(
  1045. day: self.roundDecimal(Decimal(oneDay_.TIR), 1),
  1046. week: self.roundDecimal(Decimal(sevenDays_.TIR), 1),
  1047. month: self.roundDecimal(Decimal(thirtyDays_.TIR), 1),
  1048. total: self.roundDecimal(Decimal(totalDays_.TIR), 1)
  1049. )
  1050. let hypo = Durations(
  1051. day: Decimal(oneDay_.hypos),
  1052. week: Decimal(sevenDays_.hypos),
  1053. month: Decimal(thirtyDays_.hypos),
  1054. total: Decimal(totalDays_.hypos)
  1055. )
  1056. let hyper = Durations(
  1057. day: Decimal(oneDay_.hypers),
  1058. week: Decimal(sevenDays_.hypers),
  1059. month: Decimal(thirtyDays_.hypers),
  1060. total: Decimal(totalDays_.hypers)
  1061. )
  1062. let normal = Durations(
  1063. day: Decimal(oneDay_.normal_),
  1064. week: Decimal(sevenDays_.normal_),
  1065. month: Decimal(thirtyDays_.normal_),
  1066. total: Decimal(totalDays_.normal_)
  1067. )
  1068. let range = Threshold(
  1069. low: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.low.asMmolL, 1) :
  1070. self.roundDecimal(self.settingsManager.settings.low, 0),
  1071. high: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.high.asMmolL, 1) :
  1072. self.roundDecimal(self.settingsManager.settings.high, 0)
  1073. )
  1074. let TimeInRange = TIRs(
  1075. TIR: tir,
  1076. Hypos: hypo,
  1077. Hypers: hyper,
  1078. Threshold: range,
  1079. Euglycemic: normal
  1080. )
  1081. let avgs = Durations(
  1082. day: self.roundDecimal(Decimal(oneDayGlucose.average), 1),
  1083. week: self.roundDecimal(Decimal(sevenDaysGlucose.average), 1),
  1084. month: self.roundDecimal(Decimal(thirtyDaysGlucose.average), 1),
  1085. total: self.roundDecimal(Decimal(totalDaysGlucose.average), 1)
  1086. )
  1087. let avg = Averages(Average: avgs, Median: median)
  1088. // Standard Deviations
  1089. let standardDeviations = Durations(
  1090. day: self.roundDecimal(Decimal(oneDayGlucose.sd), 1),
  1091. week: self.roundDecimal(Decimal(sevenDaysGlucose.sd), 1),
  1092. month: self.roundDecimal(Decimal(thirtyDaysGlucose.sd), 1),
  1093. total: self.roundDecimal(Decimal(totalDaysGlucose.sd), 1)
  1094. )
  1095. // CV = standard deviation / sample mean x 100
  1096. let cvs = Durations(
  1097. day: self.roundDecimal(Decimal(oneDayGlucose.cv), 1),
  1098. week: self.roundDecimal(Decimal(sevenDaysGlucose.cv), 1),
  1099. month: self.roundDecimal(Decimal(thirtyDaysGlucose.cv), 1),
  1100. total: self.roundDecimal(Decimal(totalDaysGlucose.cv), 1)
  1101. )
  1102. let variance = Variance(SD: standardDeviations, CV: cvs)
  1103. result = (oneDayGlucose, hbA1cDisplayUnit, numberOfDays, TimeInRange, avg, hbs, variance)
  1104. }
  1105. return result!
  1106. }
  1107. private func loopStats(loopStatRecord: LoopStats) {
  1108. privateContext.perform {
  1109. let nLS = LoopStatRecord(context: self.privateContext)
  1110. nLS.start = loopStatRecord.start
  1111. nLS.end = loopStatRecord.end ?? Date()
  1112. nLS.loopStatus = loopStatRecord.loopStatus
  1113. nLS.duration = loopStatRecord.duration ?? 0.0
  1114. nLS.interval = loopStatRecord.interval ?? 0.0
  1115. do {
  1116. guard self.privateContext.hasChanges else { return }
  1117. try self.privateContext.save()
  1118. } catch {
  1119. print(error.localizedDescription)
  1120. }
  1121. }
  1122. }
  1123. private func processError(_ error: Error) {
  1124. warning(.apsManager, "\(error.localizedDescription)")
  1125. lastError.send(error)
  1126. }
  1127. private func createBolusReporter() {
  1128. bolusReporter = pumpManager?.createBolusProgressReporter(reportingOn: processQueue)
  1129. bolusReporter?.addObserver(self)
  1130. }
  1131. private func clearBolusReporter() {
  1132. bolusReporter?.removeObserver(self)
  1133. bolusReporter = nil
  1134. processQueue.asyncAfter(deadline: .now() + 0.5) {
  1135. self.bolusProgress.send(nil)
  1136. }
  1137. }
  1138. }
  1139. private extension PumpManager {
  1140. func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval) async throws {
  1141. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1142. self.enactTempBasal(unitsPerHour: unitsPerHour, for: duration) { error in
  1143. if let error = error {
  1144. debug(.apsManager, "Temp basal failed: \(unitsPerHour) for: \(duration)")
  1145. continuation.resume(throwing: error)
  1146. } else {
  1147. debug(.apsManager, "Temp basal succeeded: \(unitsPerHour) for: \(duration)")
  1148. continuation.resume(returning: ())
  1149. }
  1150. }
  1151. }
  1152. }
  1153. func enactBolus(units: Double, automatic: Bool) async throws {
  1154. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1155. let automaticValue = automatic ? BolusActivationType.automatic : BolusActivationType.manualRecommendationAccepted
  1156. self.enactBolus(units: units, activationType: automaticValue) { error in
  1157. if let error = error {
  1158. debug(.apsManager, "Bolus failed: \(units)")
  1159. continuation.resume(throwing: error)
  1160. } else {
  1161. debug(.apsManager, "Bolus succeeded: \(units)")
  1162. continuation.resume(returning: ())
  1163. }
  1164. }
  1165. }
  1166. }
  1167. func cancelBolus() async throws -> DoseEntry? {
  1168. try await withCheckedThrowingContinuation { continuation in
  1169. self.cancelBolus { result in
  1170. switch result {
  1171. case let .success(dose):
  1172. debug(.apsManager, "Cancel Bolus succeeded")
  1173. continuation.resume(returning: dose)
  1174. case let .failure(error):
  1175. debug(.apsManager, "Cancel Bolus failed")
  1176. continuation.resume(throwing: APSError.pumpError(error))
  1177. }
  1178. }
  1179. }
  1180. }
  1181. func suspendDelivery() async throws {
  1182. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1183. self.suspendDelivery { error in
  1184. if let error = error {
  1185. continuation.resume(throwing: error)
  1186. } else {
  1187. continuation.resume()
  1188. }
  1189. }
  1190. }
  1191. }
  1192. func resumeDelivery() async throws {
  1193. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1194. self.resumeDelivery { error in
  1195. if let error = error {
  1196. continuation.resume(throwing: error)
  1197. } else {
  1198. continuation.resume()
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. extension BaseAPSManager: PumpManagerStatusObserver {
  1205. func pumpManager(_: PumpManager, didUpdate status: PumpManagerStatus, oldStatus _: PumpManagerStatus) {
  1206. let percent = Int((status.pumpBatteryChargeRemaining ?? 1) * 100)
  1207. privateContext.perform {
  1208. /// only update the last item with the current battery infos instead of saving a new one each time
  1209. let fetchRequest: NSFetchRequest<OpenAPS_Battery> = OpenAPS_Battery.fetchRequest()
  1210. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
  1211. fetchRequest.predicate = NSPredicate.predicateFor30MinAgo
  1212. fetchRequest.fetchLimit = 1
  1213. do {
  1214. let results = try self.privateContext.fetch(fetchRequest)
  1215. let batteryToStore: OpenAPS_Battery
  1216. if let existingBattery = results.first {
  1217. batteryToStore = existingBattery
  1218. } else {
  1219. batteryToStore = OpenAPS_Battery(context: self.privateContext)
  1220. batteryToStore.id = UUID()
  1221. }
  1222. batteryToStore.date = Date()
  1223. batteryToStore.percent = Double(percent)
  1224. batteryToStore.voltage = nil
  1225. batteryToStore.status = percent > 10 ? "normal" : "low"
  1226. batteryToStore.display = status.pumpBatteryChargeRemaining != nil
  1227. guard self.privateContext.hasChanges else { return }
  1228. try self.privateContext.save()
  1229. } catch {
  1230. print("Failed to fetch or save battery: \(error.localizedDescription)")
  1231. }
  1232. }
  1233. // TODO: - remove this after ensuring that NS still gets the same infos from Core Data
  1234. storage.save(status.pumpStatus, as: OpenAPS.Monitor.status)
  1235. }
  1236. }
  1237. extension BaseAPSManager: DoseProgressObserver {
  1238. func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) {
  1239. bolusProgress.send(Decimal(doseProgressReporter.progress.percentComplete))
  1240. if doseProgressReporter.progress.isComplete {
  1241. clearBolusReporter()
  1242. }
  1243. }
  1244. }
  1245. extension PumpManagerStatus {
  1246. var pumpStatus: PumpStatus {
  1247. let bolusing = bolusState != .noBolus
  1248. let suspended = basalDeliveryState?.isSuspended ?? true
  1249. let type = suspended ? StatusType.suspended : (bolusing ? .bolusing : .normal)
  1250. return PumpStatus(status: type, bolusing: bolusing, suspended: suspended, timestamp: Date())
  1251. }
  1252. }