APSManager.swift 62 KB

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