APSManager.swift 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import LoopKitUI
  6. import OmniBLE
  7. import OmniKit
  8. import RileyLinkKit
  9. import SwiftDate
  10. import Swinject
  11. protocol APSManager {
  12. func heartbeat(date: Date)
  13. func autotune() -> AnyPublisher<Autotune?, Never>
  14. func enactBolus(amount: Double, isSMB: Bool)
  15. var pumpManager: PumpManagerUI? { get set }
  16. var bluetoothManager: BluetoothStateManager? { get }
  17. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> { get }
  18. var pumpName: CurrentValueSubject<String, Never> { get }
  19. var isLooping: CurrentValueSubject<Bool, Never> { get }
  20. var lastLoopDate: Date { get }
  21. var lastLoopDateSubject: PassthroughSubject<Date, Never> { get }
  22. var bolusProgress: CurrentValueSubject<Decimal?, Never> { get }
  23. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> { get }
  24. var isManualTempBasal: Bool { get }
  25. func enactTempBasal(rate: Double, duration: TimeInterval)
  26. func makeProfiles() -> AnyPublisher<Bool, Never>
  27. func determineBasal() -> AnyPublisher<Bool, Never>
  28. func determineBasalSync()
  29. func roundBolus(amount: Decimal) -> Decimal
  30. var lastError: CurrentValueSubject<Error?, Never> { get }
  31. func cancelBolus()
  32. func enactAnnouncement(_ announcement: Announcement)
  33. }
  34. enum APSError: LocalizedError {
  35. case pumpError(Error)
  36. case invalidPumpState(message: String)
  37. case glucoseError(message: String)
  38. case apsError(message: String)
  39. case deviceSyncError(message: String)
  40. case manualBasalTemp(message: String)
  41. var errorDescription: String? {
  42. switch self {
  43. case let .pumpError(error):
  44. return "Pump error: \(error.localizedDescription)"
  45. case let .invalidPumpState(message):
  46. return "Error: Invalid Pump State: \(message)"
  47. case let .glucoseError(message):
  48. return "Error: Invalid glucose: \(message)"
  49. case let .apsError(message):
  50. return "APS error: \(message)"
  51. case let .deviceSyncError(message):
  52. return "Sync error: \(message)"
  53. case let .manualBasalTemp(message):
  54. return "Manual Basal Temp : \(message)"
  55. }
  56. }
  57. }
  58. final class BaseAPSManager: APSManager, Injectable {
  59. private let processQueue = DispatchQueue(label: "BaseAPSManager.processQueue")
  60. @Injected() private var storage: FileStorage!
  61. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  62. @Injected() private var alertHistoryStorage: AlertHistoryStorage!
  63. @Injected() private var glucoseStorage: GlucoseStorage!
  64. @Injected() private var tempTargetsStorage: TempTargetsStorage!
  65. @Injected() private var carbsStorage: CarbsStorage!
  66. @Injected() private var announcementsStorage: AnnouncementsStorage!
  67. @Injected() private var deviceDataManager: DeviceDataManager!
  68. @Injected() private var nightscout: NightscoutManager!
  69. @Injected() private var settingsManager: SettingsManager!
  70. @Injected() private var broadcaster: Broadcaster!
  71. @Injected() private var healthKitManager: HealthKitManager!
  72. @Persisted(key: "lastAutotuneDate") private var lastAutotuneDate = Date()
  73. @Persisted(key: "lastStartLoopDate") private var lastStartLoopDate: Date = .distantPast
  74. @Persisted(key: "lastLoopDate") var lastLoopDate: Date = .distantPast {
  75. didSet {
  76. lastLoopDateSubject.send(lastLoopDate)
  77. }
  78. }
  79. let coredataContext = CoreDataStack.shared.persistentContainer.newBackgroundContext()
  80. // let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
  81. private var openAPS: OpenAPS!
  82. private var lifetime = Lifetime()
  83. private var backGroundTaskID: UIBackgroundTaskIdentifier?
  84. var pumpManager: PumpManagerUI? {
  85. get { deviceDataManager.pumpManager }
  86. set { deviceDataManager.pumpManager = newValue }
  87. }
  88. var bluetoothManager: BluetoothStateManager? { deviceDataManager.bluetoothManager }
  89. @Persisted(key: "isManualTempBasal") var isManualTempBasal: Bool = false
  90. let isLooping = CurrentValueSubject<Bool, Never>(false)
  91. let lastLoopDateSubject = PassthroughSubject<Date, Never>()
  92. let lastError = CurrentValueSubject<Error?, Never>(nil)
  93. let bolusProgress = CurrentValueSubject<Decimal?, Never>(nil)
  94. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> {
  95. deviceDataManager.pumpDisplayState
  96. }
  97. var pumpName: CurrentValueSubject<String, Never> {
  98. deviceDataManager.pumpName
  99. }
  100. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> {
  101. deviceDataManager.pumpExpiresAtDate
  102. }
  103. var settings: FreeAPSSettings {
  104. get { settingsManager.settings }
  105. set { settingsManager.settings = newValue }
  106. }
  107. init(resolver: Resolver) {
  108. injectServices(resolver)
  109. openAPS = OpenAPS(storage: storage)
  110. subscribe()
  111. lastLoopDateSubject.send(lastLoopDate)
  112. isLooping
  113. .weakAssign(to: \.deviceDataManager.loopInProgress, on: self)
  114. .store(in: &lifetime)
  115. }
  116. private func subscribe() {
  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. // check the last start of looping is more the loopInterval but the previous loop was completed
  162. if lastLoopDate > lastStartLoopDate {
  163. guard lastStartLoopDate.addingTimeInterval(Config.loopInterval) < Date() else {
  164. debug(.apsManager, "too close to do a loop : \(lastStartLoopDate)")
  165. return
  166. }
  167. }
  168. guard !isLooping.value else {
  169. warning(.apsManager, "Loop already in progress. Skip recommendation.")
  170. return
  171. }
  172. // start background time extension
  173. backGroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Loop starting") {
  174. guard let backgroundTask = self.backGroundTaskID else { return }
  175. UIApplication.shared.endBackgroundTask(backgroundTask)
  176. self.backGroundTaskID = .invalid
  177. }
  178. debug(.apsManager, "Starting loop with a delay of \(UIApplication.shared.backgroundTimeRemaining.rounded())")
  179. lastStartLoopDate = Date()
  180. var loopStatRecord = LoopStats(
  181. start: lastStartLoopDate,
  182. loopStatus: "Starting"
  183. )
  184. isLooping.send(true)
  185. determineBasal()
  186. .replaceEmpty(with: false)
  187. .flatMap { [weak self] success -> AnyPublisher<Void, Error> in
  188. guard let self = self, success else {
  189. return Fail(error: APSError.apsError(message: "Determine basal failed")).eraseToAnyPublisher()
  190. }
  191. // Open loop completed
  192. guard self.settings.closedLoop else {
  193. self.nightscout.uploadStatus()
  194. return Just(()).setFailureType(to: Error.self).eraseToAnyPublisher()
  195. }
  196. self.nightscout.uploadStatus()
  197. // Closed loop - enact suggested
  198. return self.enactSuggested()
  199. }
  200. .sink { [weak self] completion in
  201. guard let self = self else { return }
  202. loopStatRecord.end = Date()
  203. loopStatRecord.duration = self.roundDouble(
  204. (loopStatRecord.end! - loopStatRecord.start).timeInterval / 60,
  205. 2
  206. )
  207. if case let .failure(error) = completion {
  208. loopStatRecord.loopStatus = error.localizedDescription
  209. self.loopCompleted(error: error, loopStatRecord: loopStatRecord)
  210. } else {
  211. loopStatRecord.loopStatus = "Success"
  212. self.loopCompleted(loopStatRecord: loopStatRecord)
  213. }
  214. } receiveValue: {}
  215. .store(in: &lifetime)
  216. }
  217. // Loop exit point
  218. private func loopCompleted(error: Error? = nil, loopStatRecord: LoopStats) {
  219. isLooping.send(false)
  220. // save AH events
  221. let events = pumpHistoryStorage.recent()
  222. healthKitManager.saveIfNeeded(pumpEvents: events)
  223. if let error = error {
  224. warning(.apsManager, "Loop failed with error: \(error.localizedDescription)")
  225. if let backgroundTask = backGroundTaskID {
  226. UIApplication.shared.endBackgroundTask(backgroundTask)
  227. backGroundTaskID = .invalid
  228. }
  229. processError(error)
  230. } else {
  231. debug(.apsManager, "Loop succeeded")
  232. lastLoopDate = Date()
  233. lastError.send(nil)
  234. }
  235. loopStats(loopStatRecord: loopStatRecord)
  236. if settings.closedLoop {
  237. reportEnacted(received: error == nil)
  238. }
  239. // end of the BG tasks
  240. if let backgroundTask = backGroundTaskID {
  241. UIApplication.shared.endBackgroundTask(backgroundTask)
  242. backGroundTaskID = .invalid
  243. }
  244. }
  245. private func verifyStatus() -> Error? {
  246. guard let pump = pumpManager else {
  247. return APSError.invalidPumpState(message: "Pump not set")
  248. }
  249. let status = pump.status.pumpStatus
  250. guard !status.bolusing else {
  251. return APSError.invalidPumpState(message: "Pump is bolusing")
  252. }
  253. guard !status.suspended else {
  254. return APSError.invalidPumpState(message: "Pump suspended")
  255. }
  256. let reservoir = storage.retrieve(OpenAPS.Monitor.reservoir, as: Decimal.self) ?? 100
  257. guard reservoir >= 0 else {
  258. return APSError.invalidPumpState(message: "Reservoir is empty")
  259. }
  260. return nil
  261. }
  262. private func autosens() -> AnyPublisher<Bool, Never> {
  263. guard let autosens = storage.retrieve(OpenAPS.Settings.autosense, as: Autosens.self),
  264. (autosens.timestamp ?? .distantPast).addingTimeInterval(30.minutes.timeInterval) > Date()
  265. else {
  266. return openAPS.autosense()
  267. .map { $0 != nil }
  268. .eraseToAnyPublisher()
  269. }
  270. return Just(false).eraseToAnyPublisher()
  271. }
  272. func determineBasal() -> AnyPublisher<Bool, Never> {
  273. debug(.apsManager, "Start determine basal")
  274. guard let glucose = storage.retrieve(OpenAPS.Monitor.glucose, as: [BloodGlucose].self), glucose.isNotEmpty else {
  275. debug(.apsManager, "Not enough glucose data")
  276. processError(APSError.glucoseError(message: "Not enough glucose data"))
  277. return Just(false).eraseToAnyPublisher()
  278. }
  279. let lastGlucoseDate = glucoseStorage.lastGlucoseDate()
  280. guard lastGlucoseDate >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  281. debug(.apsManager, "Glucose data is stale")
  282. processError(APSError.glucoseError(message: "Glucose data is stale"))
  283. return Just(false).eraseToAnyPublisher()
  284. }
  285. guard glucoseStorage.isGlucoseNotFlat() else {
  286. debug(.apsManager, "Glucose data is too flat")
  287. processError(APSError.glucoseError(message: "Glucose data is too flat"))
  288. return Just(false).eraseToAnyPublisher()
  289. }
  290. let now = Date()
  291. let temp = currentTemp(date: now)
  292. let mainPublisher = makeProfiles()
  293. .flatMap { _ in self.autosens() }
  294. .flatMap { _ in self.dailyAutotune() }
  295. .flatMap { _ in self.openAPS.determineBasal(currentTemp: temp, clock: now) }
  296. .map { suggestion -> Bool in
  297. if let suggestion = suggestion {
  298. DispatchQueue.main.async {
  299. self.broadcaster.notify(SuggestionObserver.self, on: .main) {
  300. $0.suggestionDidUpdate(suggestion)
  301. }
  302. }
  303. }
  304. return suggestion != nil
  305. }
  306. .eraseToAnyPublisher()
  307. if temp.duration == 0,
  308. settings.closedLoop,
  309. settingsManager.preferences.unsuspendIfNoTemp,
  310. let pump = pumpManager,
  311. pump.status.pumpStatus.suspended
  312. {
  313. return pump.resumeDelivery()
  314. .flatMap { _ in mainPublisher }
  315. .replaceError(with: false)
  316. .eraseToAnyPublisher()
  317. }
  318. return mainPublisher
  319. }
  320. func determineBasalSync() {
  321. determineBasal().cancellable().store(in: &lifetime)
  322. }
  323. func makeProfiles() -> AnyPublisher<Bool, Never> {
  324. openAPS.makeProfiles(useAutotune: settings.useAutotune)
  325. .map { tunedProfile in
  326. if let basalProfile = tunedProfile?.basalProfile {
  327. self.processQueue.async {
  328. self.broadcaster.notify(BasalProfileObserver.self, on: self.processQueue) {
  329. $0.basalProfileDidChange(basalProfile)
  330. }
  331. }
  332. }
  333. return tunedProfile != nil
  334. }
  335. .eraseToAnyPublisher()
  336. }
  337. func roundBolus(amount: Decimal) -> Decimal {
  338. guard let pump = pumpManager else { return amount }
  339. let rounded = Decimal(pump.roundToSupportedBolusVolume(units: Double(amount)))
  340. let maxBolus = Decimal(pump.roundToSupportedBolusVolume(units: Double(settingsManager.pumpSettings.maxBolus)))
  341. return min(rounded, maxBolus)
  342. }
  343. private var bolusReporter: DoseProgressReporter?
  344. func enactBolus(amount: Double, isSMB: Bool) {
  345. if let error = verifyStatus() {
  346. processError(error)
  347. processQueue.async {
  348. self.broadcaster.notify(BolusFailureObserver.self, on: self.processQueue) {
  349. $0.bolusDidFail()
  350. }
  351. }
  352. return
  353. }
  354. guard let pump = pumpManager else { return }
  355. let roundedAmout = pump.roundToSupportedBolusVolume(units: amount)
  356. debug(.apsManager, "Enact bolus \(roundedAmout), manual \(!isSMB)")
  357. pump.enactBolus(units: roundedAmout, automatic: isSMB).sink { completion in
  358. if case let .failure(error) = completion {
  359. warning(.apsManager, "Bolus failed with error: \(error.localizedDescription)")
  360. self.processError(APSError.pumpError(error))
  361. if !isSMB {
  362. self.processQueue.async {
  363. self.broadcaster.notify(BolusFailureObserver.self, on: self.processQueue) {
  364. $0.bolusDidFail()
  365. }
  366. }
  367. }
  368. } else {
  369. debug(.apsManager, "Bolus succeeded")
  370. if !isSMB {
  371. self.determineBasal().sink { _ in }.store(in: &self.lifetime)
  372. }
  373. self.bolusProgress.send(0)
  374. }
  375. } receiveValue: { _ in }
  376. .store(in: &lifetime)
  377. }
  378. func cancelBolus() {
  379. guard let pump = pumpManager, pump.status.pumpStatus.bolusing else { return }
  380. debug(.apsManager, "Cancel bolus")
  381. pump.cancelBolus().sink { completion in
  382. if case let .failure(error) = completion {
  383. debug(.apsManager, "Bolus cancellation failed with error: \(error.localizedDescription)")
  384. self.processError(APSError.pumpError(error))
  385. } else {
  386. debug(.apsManager, "Bolus cancelled")
  387. }
  388. self.bolusReporter?.removeObserver(self)
  389. self.bolusReporter = nil
  390. self.bolusProgress.send(nil)
  391. } receiveValue: { _ in }
  392. .store(in: &lifetime)
  393. }
  394. func enactTempBasal(rate: Double, duration: TimeInterval) {
  395. if let error = verifyStatus() {
  396. processError(error)
  397. return
  398. }
  399. guard let pump = pumpManager else { return }
  400. // unable to do temp basal during manual temp basal 😁
  401. if isManualTempBasal {
  402. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  403. return
  404. }
  405. debug(.apsManager, "Enact temp basal \(rate) - \(duration)")
  406. let roundedAmout = pump.roundToSupportedBasalRate(unitsPerHour: rate)
  407. pump.enactTempBasal(unitsPerHour: roundedAmout, for: duration) { error in
  408. if let error = error {
  409. debug(.apsManager, "Temp Basal failed with error: \(error.localizedDescription)")
  410. self.processError(APSError.pumpError(error))
  411. } else {
  412. debug(.apsManager, "Temp Basal succeeded")
  413. let temp = TempBasal(duration: Int(duration / 60), rate: Decimal(rate), temp: .absolute, timestamp: Date())
  414. self.storage.save(temp, as: OpenAPS.Monitor.tempBasal)
  415. if rate == 0, duration == 0 {
  416. self.pumpHistoryStorage.saveCancelTempEvents()
  417. }
  418. }
  419. }
  420. }
  421. func dailyAutotune() -> AnyPublisher<Bool, Never> {
  422. guard settings.useAutotune else {
  423. return Just(false).eraseToAnyPublisher()
  424. }
  425. let now = Date()
  426. guard lastAutotuneDate.isBeforeDate(now, granularity: .day) else {
  427. return Just(false).eraseToAnyPublisher()
  428. }
  429. lastAutotuneDate = now
  430. return autotune().map { $0 != nil }.eraseToAnyPublisher()
  431. }
  432. func autotune() -> AnyPublisher<Autotune?, Never> {
  433. openAPS.autotune().eraseToAnyPublisher()
  434. }
  435. func enactAnnouncement(_ announcement: Announcement) {
  436. guard let action = announcement.action else {
  437. warning(.apsManager, "Invalid Announcement action")
  438. return
  439. }
  440. guard let pump = pumpManager else {
  441. warning(.apsManager, "Pump is not set")
  442. return
  443. }
  444. debug(.apsManager, "Start enact announcement: \(action)")
  445. switch action {
  446. case let .bolus(amount):
  447. if let error = verifyStatus() {
  448. processError(error)
  449. return
  450. }
  451. let roundedAmount = pump.roundToSupportedBolusVolume(units: Double(amount))
  452. pump.enactBolus(units: roundedAmount, activationType: .manualRecommendationAccepted) { error in
  453. if let error = error {
  454. // warning(.apsManager, "Announcement Bolus failed with error: \(error.localizedDescription)")
  455. switch error {
  456. case .uncertainDelivery:
  457. // Do not generate notification on uncertain delivery error
  458. break
  459. default:
  460. // Do not generate notifications for automatic boluses that fail.
  461. warning(.apsManager, "Announcement Bolus failed with error: \(error.localizedDescription)")
  462. }
  463. } else {
  464. debug(.apsManager, "Announcement Bolus succeeded")
  465. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  466. self.bolusProgress.send(0)
  467. }
  468. }
  469. case let .pump(pumpAction):
  470. switch pumpAction {
  471. case .suspend:
  472. if let error = verifyStatus() {
  473. processError(error)
  474. return
  475. }
  476. pump.suspendDelivery { error in
  477. if let error = error {
  478. debug(.apsManager, "Pump not suspended by Announcement: \(error.localizedDescription)")
  479. } else {
  480. debug(.apsManager, "Pump suspended by Announcement")
  481. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  482. self.nightscout.uploadStatus()
  483. }
  484. }
  485. case .resume:
  486. guard pump.status.pumpStatus.suspended else {
  487. return
  488. }
  489. pump.resumeDelivery { error in
  490. if let error = error {
  491. warning(.apsManager, "Pump not resumed by Announcement: \(error.localizedDescription)")
  492. } else {
  493. debug(.apsManager, "Pump resumed by Announcement")
  494. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  495. self.nightscout.uploadStatus()
  496. }
  497. }
  498. }
  499. case let .looping(closedLoop):
  500. settings.closedLoop = closedLoop
  501. debug(.apsManager, "Closed loop \(closedLoop) by Announcement")
  502. announcementsStorage.storeAnnouncements([announcement], enacted: true)
  503. case let .tempbasal(rate, duration):
  504. if let error = verifyStatus() {
  505. processError(error)
  506. return
  507. }
  508. // unable to do temp basal during manual temp basal 😁
  509. if isManualTempBasal {
  510. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  511. return
  512. }
  513. guard !settings.closedLoop else {
  514. return
  515. }
  516. let roundedRate = pump.roundToSupportedBasalRate(unitsPerHour: Double(rate))
  517. pump.enactTempBasal(unitsPerHour: roundedRate, for: TimeInterval(duration) * 60) { error in
  518. if let error = error {
  519. warning(.apsManager, "Announcement TempBasal failed with error: \(error.localizedDescription)")
  520. } else {
  521. debug(.apsManager, "Announcement TempBasal succeeded")
  522. self.announcementsStorage.storeAnnouncements([announcement], enacted: true)
  523. }
  524. }
  525. }
  526. }
  527. private func currentTemp(date: Date) -> TempBasal {
  528. let defaultTemp = { () -> TempBasal in
  529. guard let temp = storage.retrieve(OpenAPS.Monitor.tempBasal, as: TempBasal.self) else {
  530. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: Date())
  531. }
  532. let delta = Int((date.timeIntervalSince1970 - temp.timestamp.timeIntervalSince1970) / 60)
  533. let duration = max(0, temp.duration - delta)
  534. return TempBasal(duration: duration, rate: temp.rate, temp: .absolute, timestamp: date)
  535. }()
  536. guard let state = pumpManager?.status.basalDeliveryState else { return defaultTemp }
  537. switch state {
  538. case .active:
  539. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  540. case let .tempBasal(dose):
  541. let rate = Decimal(dose.unitsPerHour)
  542. let durationMin = max(0, Int((dose.endDate.timeIntervalSince1970 - date.timeIntervalSince1970) / 60))
  543. return TempBasal(duration: durationMin, rate: rate, temp: .absolute, timestamp: date)
  544. default:
  545. return defaultTemp
  546. }
  547. }
  548. private func enactSuggested() -> AnyPublisher<Void, Error> {
  549. guard let suggested = storage.retrieve(OpenAPS.Enact.suggested, as: Suggestion.self) else {
  550. return Fail(error: APSError.apsError(message: "Suggestion not found")).eraseToAnyPublisher()
  551. }
  552. guard Date().timeIntervalSince(suggested.deliverAt ?? .distantPast) < Config.eхpirationInterval else {
  553. return Fail(error: APSError.apsError(message: "Suggestion expired")).eraseToAnyPublisher()
  554. }
  555. guard let pump = pumpManager else {
  556. return Fail(error: APSError.apsError(message: "Pump not set")).eraseToAnyPublisher()
  557. }
  558. // unable to do temp basal during manual temp basal 😁
  559. if isManualTempBasal {
  560. return Fail(error: APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  561. .eraseToAnyPublisher()
  562. }
  563. let basalPublisher: AnyPublisher<Void, Error> = Deferred { () -> AnyPublisher<Void, Error> in
  564. if let error = self.verifyStatus() {
  565. return Fail(error: error).eraseToAnyPublisher()
  566. }
  567. guard let rate = suggested.rate, let duration = suggested.duration else {
  568. // It is OK, no temp required
  569. debug(.apsManager, "No temp required")
  570. return Just(()).setFailureType(to: Error.self)
  571. .eraseToAnyPublisher()
  572. }
  573. return pump.enactTempBasal(unitsPerHour: Double(rate), for: TimeInterval(duration * 60)).map { _ in
  574. let temp = TempBasal(duration: duration, rate: rate, temp: .absolute, timestamp: Date())
  575. self.storage.save(temp, as: OpenAPS.Monitor.tempBasal)
  576. return ()
  577. }
  578. .eraseToAnyPublisher()
  579. }.eraseToAnyPublisher()
  580. let bolusPublisher: AnyPublisher<Void, Error> = Deferred { () -> AnyPublisher<Void, Error> in
  581. if let error = self.verifyStatus() {
  582. return Fail(error: error).eraseToAnyPublisher()
  583. }
  584. guard let units = suggested.units else {
  585. // It is OK, no bolus required
  586. debug(.apsManager, "No bolus required")
  587. return Just(()).setFailureType(to: Error.self)
  588. .eraseToAnyPublisher()
  589. }
  590. return pump.enactBolus(units: Double(units), automatic: true).map { _ in
  591. self.bolusProgress.send(0)
  592. return ()
  593. }
  594. .eraseToAnyPublisher()
  595. }.eraseToAnyPublisher()
  596. return basalPublisher.flatMap { bolusPublisher }.eraseToAnyPublisher()
  597. }
  598. private func reportEnacted(received: Bool) {
  599. if let suggestion = storage.retrieve(OpenAPS.Enact.suggested, as: Suggestion.self), suggestion.deliverAt != nil {
  600. var enacted = suggestion
  601. enacted.timestamp = Date()
  602. enacted.recieved = received
  603. storage.save(enacted, as: OpenAPS.Enact.enacted)
  604. debug(.apsManager, "Suggestion enacted. Received: \(received)")
  605. DispatchQueue.main.async {
  606. self.broadcaster.notify(EnactedSuggestionObserver.self, on: .main) {
  607. $0.enactedSuggestionDidUpdate(enacted)
  608. }
  609. }
  610. nightscout.uploadStatus()
  611. statistics()
  612. }
  613. }
  614. private func roundDecimal(_ decimal: Decimal, _ digits: Double) -> Decimal {
  615. let rounded = round(Double(decimal) * pow(10, digits)) / pow(10, digits)
  616. return Decimal(rounded)
  617. }
  618. private func roundDouble(_ double: Double, _ digits: Double) -> Double {
  619. let rounded = round(Double(double) * pow(10, digits)) / pow(10, digits)
  620. return rounded
  621. }
  622. private func medianCalculation(array: [Double]) -> Double {
  623. guard !array.isEmpty else {
  624. return 0
  625. }
  626. let sorted = array.sorted()
  627. let length = array.count
  628. if length % 2 == 0 {
  629. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  630. }
  631. return sorted[length / 2]
  632. }
  633. // Add to statistics.JSON
  634. private func statistics() {
  635. let now = Date()
  636. if settingsManager.settings.uploadStats {
  637. let hour = Calendar.current.component(.hour, from: now)
  638. guard hour > 0 else {
  639. return
  640. }
  641. coredataContext.performAndWait { [self] in
  642. var stats = [StatsData]()
  643. let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
  644. let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
  645. requestStats.sortDescriptors = [sortStats]
  646. requestStats.fetchLimit = 1
  647. try? stats = coredataContext.fetch(requestStats)
  648. // Only save and upload once per day
  649. // guard (-1 * (stats.first?.lastrun ?? now).timeIntervalSinceNow.hours) > 22 else { return }
  650. let units = self.settingsManager.settings.units
  651. let preferences = settingsManager.preferences
  652. // MARK: Fetch Carbs from CoreData
  653. var carbs = [Carbohydrates]()
  654. var carbTotal: Decimal = 0
  655. let requestCarbs = Carbohydrates.fetchRequest() as NSFetchRequest<Carbohydrates>
  656. let daysAgo = Date().addingTimeInterval(-1.days.timeInterval)
  657. requestCarbs.predicate = NSPredicate(format: "carbs > 0 AND date > %@", daysAgo as NSDate)
  658. let sortCarbs = NSSortDescriptor(key: "date", ascending: true)
  659. requestCarbs.sortDescriptors = [sortCarbs]
  660. try? carbs = coredataContext.fetch(requestCarbs)
  661. carbTotal = carbs.map({ carbs in carbs.carbs as? Decimal ?? 0 }).reduce(0, +)
  662. // MARK: Fetch TDD from CoreData
  663. var tdds = [TDD]()
  664. var currentTDD: Decimal = 0
  665. let requestTDD = TDD.fetchRequest() as NSFetchRequest<TDD>
  666. let sort = NSSortDescriptor(key: "timestamp", ascending: false)
  667. requestTDD.sortDescriptors = [sort]
  668. requestTDD.fetchLimit = 1
  669. try? tdds = coredataContext.fetch(requestTDD)
  670. if !tdds.isEmpty {
  671. currentTDD = tdds[0].tdd?.decimalValue ?? 0
  672. }
  673. var algo_ = "Oref0"
  674. if preferences.sigmoid, preferences.enableDynamicCR {
  675. algo_ = "Dynamic ISF + CR: Sigmoid"
  676. } else if preferences.sigmoid, !preferences.enableDynamicCR {
  677. algo_ = "Dynamic ISF: Sigmoid"
  678. } else if preferences.useNewFormula, preferences.enableDynamicCR {
  679. algo_ = "Dynamic ISF + CR: Logarithmic"
  680. } else if preferences.useNewFormula, !preferences.sigmoid,!preferences.enableDynamicCR {
  681. algo_ = "Dynamic ISF: Logarithmic"
  682. }
  683. let af = preferences.adjustmentFactor
  684. let insulin_type = preferences.curve
  685. let buildDate = Bundle.main.buildDate
  686. let version = Bundle.main.releaseVersionNumber
  687. let build = Bundle.main.buildVersionNumber
  688. let branch = Bundle.main.infoDictionary?["BuildBranch"] as? String ?? ""
  689. let copyrightNotice_ = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? ""
  690. let pump_ = pumpManager?.localizedTitle ?? ""
  691. let cgm = settingsManager.settings.cgm
  692. let file = OpenAPS.Monitor.statistics
  693. var iPa: Decimal = 75
  694. if preferences.useCustomPeakTime {
  695. iPa = preferences.insulinPeakTime
  696. } else if preferences.curve.rawValue == "rapid-acting" {
  697. iPa = 65
  698. } else if preferences.curve.rawValue == "ultra-rapid" {
  699. iPa = 50
  700. }
  701. // MARK: Fetch LoopStatRecords from CoreData
  702. var lsr = [LoopStatRecord]()
  703. var successRate: Double?
  704. var successNR = 0
  705. var errorNR = 0
  706. var minimumInt = 999.0
  707. var maximumInt = 0.0
  708. var minimumLoopTime = 9999.0
  709. var maximumLoopTime = 0.0
  710. var timeIntervalLoops = 0.0
  711. var previousTimeLoop = Date()
  712. var timeForOneLoop = 0.0
  713. var averageLoopTime = 0.0
  714. var timeForOneLoopArray: [Double] = []
  715. var medianLoopTime = 0.0
  716. var timeIntervalLoopArray: [Double] = []
  717. var medianInterval = 0.0
  718. var averageIntervalLoops = 0.0
  719. var averageLoopDuration = 0.0
  720. let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  721. requestLSR.predicate = NSPredicate(
  722. format: "start > %@",
  723. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  724. )
  725. let sortLSR = NSSortDescriptor(key: "start", ascending: false)
  726. requestLSR.sortDescriptors = [sortLSR]
  727. try? lsr = coredataContext.fetch(requestLSR)
  728. if lsr.isNotEmpty {
  729. var i = 0.0
  730. if let loopEnd = lsr[0].end {
  731. previousTimeLoop = loopEnd
  732. }
  733. for each in lsr {
  734. if let loopEnd = each.end {
  735. let loopDuration = each.duration
  736. if each.loopStatus!.contains("Success") {
  737. successNR += 1
  738. } else {
  739. errorNR += 1
  740. }
  741. i += 1
  742. timeIntervalLoops = (previousTimeLoop - (each.start ?? previousTimeLoop)).timeInterval / 60
  743. if timeIntervalLoops > 0.0, i != 1 {
  744. timeIntervalLoopArray.append(timeIntervalLoops)
  745. }
  746. if timeIntervalLoops > maximumInt {
  747. maximumInt = timeIntervalLoops
  748. }
  749. if timeIntervalLoops < minimumInt, i != 1 {
  750. minimumInt = timeIntervalLoops
  751. }
  752. timeForOneLoop = loopDuration
  753. timeForOneLoopArray.append(timeForOneLoop)
  754. if timeForOneLoop >= maximumLoopTime, timeForOneLoop != 0.0 {
  755. maximumLoopTime = timeForOneLoop
  756. }
  757. if timeForOneLoop <= minimumLoopTime, timeForOneLoop != 0.0 {
  758. minimumLoopTime = timeForOneLoop
  759. }
  760. previousTimeLoop = loopEnd
  761. }
  762. }
  763. successRate = (Double(successNR) / Double(i)) * 100
  764. // Average Loop Interval in minutes
  765. let timeOfFirstIndex = lsr[0].start ?? Date()
  766. let lastIndexWithTimestamp = lsr.count - 1
  767. let timeOfLastIndex = lsr[lastIndexWithTimestamp].end ?? Date()
  768. averageLoopTime = (timeOfFirstIndex - timeOfLastIndex).timeInterval / 60 / Double(errorNR + successNR)
  769. // Median values
  770. medianLoopTime = medianCalculation(array: timeForOneLoopArray)
  771. medianInterval = medianCalculation(array: timeIntervalLoopArray)
  772. // Average time interval between loops
  773. averageIntervalLoops = timeIntervalLoopArray.reduce(0, +) / Double(timeIntervalLoopArray.count)
  774. // Average loop duration
  775. averageLoopDuration = timeForOneLoopArray.reduce(0, +) / Double(timeForOneLoopArray.count)
  776. }
  777. if minimumInt == 999.0 {
  778. minimumInt = 0.0
  779. }
  780. if minimumLoopTime == 9999.0 {
  781. minimumLoopTime = 0.0
  782. }
  783. var glucose = [Readings]()
  784. var firstElementTime = Date()
  785. var lastElementTime = Date()
  786. var currentIndexTime = Date()
  787. var bg: Decimal = 0
  788. var bgArray: [Double] = []
  789. var bgArray_1_: [Double] = []
  790. var bgArray_7_: [Double] = []
  791. var bgArray_30_: [Double] = []
  792. var bgArray_90_: [Double] = []
  793. var bgArrayForTIR: [(bg_: Double, date_: Date)] = []
  794. var bgArray_1: [(bg_: Double, date_: Date)] = []
  795. var bgArray_7: [(bg_: Double, date_: Date)] = []
  796. var bgArray_30: [(bg_: Double, date_: Date)] = []
  797. var bgArray_90: [(bg_: Double, date_: Date)] = []
  798. var medianBG = 0.0
  799. var nr_bgs: Decimal = 0
  800. var bg_1: Decimal = 0
  801. var bg_7: Decimal = 0
  802. var bg_30: Decimal = 0
  803. var bg_90: Decimal = 0
  804. var bg_total: Decimal = 0
  805. var j = -1
  806. var conversionFactor: Decimal = 1
  807. if units == .mmolL {
  808. conversionFactor = 0.0555
  809. }
  810. var numberOfDays: Double = 0
  811. var nr1: Decimal = 0
  812. let requestGFS = Readings.fetchRequest() as NSFetchRequest<Readings>
  813. let sortGlucose = NSSortDescriptor(key: "date", ascending: false)
  814. requestGFS.sortDescriptors = [sortGlucose]
  815. try? glucose = coredataContext.fetch(requestGFS)
  816. // Time In Range (%) and Average Glucose. This will be refactored later after some testing.
  817. let endIndex = glucose.count - 1
  818. firstElementTime = glucose[0].date ?? Date()
  819. lastElementTime = glucose[endIndex].date ?? Date()
  820. currentIndexTime = firstElementTime
  821. numberOfDays = (firstElementTime - lastElementTime).timeInterval / 8.64E4
  822. // Make arrays for median calculations and calculate averages
  823. if endIndex >= 0 {
  824. repeat {
  825. j += 1
  826. if glucose[j].glucose > 0 {
  827. currentIndexTime = glucose[j].date ?? firstElementTime
  828. bg += Decimal(glucose[j].glucose) * conversionFactor
  829. bgArray.append(Double(glucose[j].glucose) * Double(conversionFactor))
  830. bgArrayForTIR.append((Double(glucose[j].glucose), glucose[j].date!))
  831. nr_bgs += 1
  832. if (firstElementTime - currentIndexTime).timeInterval <= 8.64E4 { // 1 day
  833. bg_1 = bg / nr_bgs
  834. bgArray_1 = bgArrayForTIR
  835. bgArray_1_ = bgArray
  836. nr1 = nr_bgs
  837. }
  838. if (firstElementTime - currentIndexTime).timeInterval <= 6.048E5 { // 7 days
  839. bg_7 = bg / nr_bgs
  840. bgArray_7 = bgArrayForTIR
  841. bgArray_7_ = bgArray
  842. }
  843. if (firstElementTime - currentIndexTime).timeInterval <= 2.592E6 { // 30 days
  844. bg_30 = bg / nr_bgs
  845. bgArray_30 = bgArrayForTIR
  846. bgArray_30_ = bgArray
  847. }
  848. if (firstElementTime - currentIndexTime).timeInterval <= 7.776E7 { // 90 days
  849. bg_90 = bg / nr_bgs
  850. bgArray_90 = bgArrayForTIR
  851. bgArray_90_ = bgArray
  852. }
  853. }
  854. } while j != glucose.count - 1
  855. }
  856. if nr_bgs > 0 {
  857. // Up to 91 days
  858. bg_total = bg / nr_bgs
  859. }
  860. // Total median
  861. medianBG = medianCalculation(array: bgArray)
  862. func tir(_ array: [(bg_: Double, date_: Date)]) -> (TIR: Double, hypos: Double, hypers: Double) {
  863. var timeInHypo = 0.0
  864. var timeInHyper = 0.0
  865. var hypos = 0.0
  866. var hypers = 0.0
  867. var i = -1
  868. var lastIndex = false
  869. let endIndex = array.count - 1
  870. var hypoLimit = settingsManager.settings.low
  871. var hyperLimit = settingsManager.settings.high
  872. var full_time = 0.0
  873. if endIndex > 0 {
  874. full_time = (array[0].date_ - array[endIndex].date_).timeInterval
  875. }
  876. while i < endIndex {
  877. i += 1
  878. let currentTime = array[i].date_
  879. var previousTime = currentTime
  880. if i + 1 <= endIndex {
  881. previousTime = array[i + 1].date_
  882. } else {
  883. lastIndex = true
  884. }
  885. if array[i].bg_ < Double(hypoLimit), !lastIndex {
  886. // Exclude duration between CGM readings which are more than 30 minutes
  887. timeInHypo += min((currentTime - previousTime).timeInterval, 30.minutes.timeInterval)
  888. } else if array[i].bg_ >= Double(hyperLimit), !lastIndex {
  889. timeInHyper += min((currentTime - previousTime).timeInterval, 30.minutes.timeInterval)
  890. }
  891. }
  892. if timeInHypo == 0.0 {
  893. hypos = 0
  894. } else if full_time != 0.0 { hypos = (timeInHypo / full_time) * 100
  895. }
  896. if timeInHyper == 0.0 {
  897. hypers = 0
  898. } else if full_time != 0.0 { hypers = (timeInHyper / full_time) * 100
  899. }
  900. let TIR = 100 - (hypos + hypers)
  901. return (roundDouble(TIR, 1), roundDouble(hypos, 1), roundDouble(hypers, 1))
  902. }
  903. // HbA1c estimation (%, mmol/mol) 1 day
  904. var NGSPa1CStatisticValue: Decimal = 0.0
  905. var IFCCa1CStatisticValue: Decimal = 0.0
  906. if nr_bgs > 0 {
  907. NGSPa1CStatisticValue = ((bg_1 / conversionFactor) + 46.7) / 28.7 // NGSP (%)
  908. IFCCa1CStatisticValue = 10.929 *
  909. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  910. }
  911. // 7 days
  912. var NGSPa1CStatisticValue_7: Decimal = 0.0
  913. var IFCCa1CStatisticValue_7: Decimal = 0.0
  914. if nr_bgs > 0 {
  915. NGSPa1CStatisticValue_7 = ((bg_7 / conversionFactor) + 46.7) / 28.7
  916. IFCCa1CStatisticValue_7 = 10.929 * (NGSPa1CStatisticValue_7 - 2.152)
  917. }
  918. // 30 days
  919. var NGSPa1CStatisticValue_30: Decimal = 0.0
  920. var IFCCa1CStatisticValue_30: Decimal = 0.0
  921. if nr_bgs > 0 {
  922. NGSPa1CStatisticValue_30 = ((bg_30 / conversionFactor) + 46.7) / 28.7
  923. IFCCa1CStatisticValue_30 = 10.929 * (NGSPa1CStatisticValue_30 - 2.152)
  924. }
  925. // 90 days
  926. var NGSPa1CStatisticValue_90: Decimal = 0.0
  927. var IFCCa1CStatisticValue_90: Decimal = 0.0
  928. if nr_bgs > 0 {
  929. NGSPa1CStatisticValue_90 = ((bg_90 / conversionFactor) + 46.7) / 28.7
  930. IFCCa1CStatisticValue_90 = 10.929 * (NGSPa1CStatisticValue_90 - 2.152)
  931. }
  932. // Total days
  933. var NGSPa1CStatisticValue_total: Decimal = 0.0
  934. var IFCCa1CStatisticValue_total: Decimal = 0.0
  935. if nr_bgs > 0 {
  936. NGSPa1CStatisticValue_total = ((bg_total / conversionFactor) + 46.7) / 28.7
  937. IFCCa1CStatisticValue_total = 10.929 *
  938. (NGSPa1CStatisticValue_total - 2.152)
  939. }
  940. let median = Durations(
  941. day: roundDecimal(Decimal(medianCalculation(array: bgArray_1_)), 1),
  942. week: roundDecimal(Decimal(medianCalculation(array: bgArray_7_)), 1),
  943. month: roundDecimal(Decimal(medianCalculation(array: bgArray_30_)), 1),
  944. total: roundDecimal(Decimal(medianBG), 1)
  945. )
  946. // MARK: Save to Median to CoreData
  947. let saveMedianToCoreData = BGmedian(context: self.coredataContext)
  948. saveMedianToCoreData.date = Date()
  949. saveMedianToCoreData.median = median.total as NSDecimalNumber
  950. saveMedianToCoreData.median_1 = median.day as NSDecimalNumber
  951. saveMedianToCoreData.median_7 = median.week as NSDecimalNumber
  952. saveMedianToCoreData.median_30 = median.month as NSDecimalNumber
  953. saveMedianToCoreData.median_90 = self.roundDecimal(
  954. Decimal(self.medianCalculation(array: bgArray_90_)),
  955. 1
  956. ) as NSDecimalNumber
  957. try? self.coredataContext.save()
  958. var hbs = Durations(
  959. day: roundDecimal(NGSPa1CStatisticValue, 1),
  960. week: roundDecimal(NGSPa1CStatisticValue_7, 1),
  961. month: roundDecimal(NGSPa1CStatisticValue_30, 1),
  962. total: roundDecimal(NGSPa1CStatisticValue_total, 1)
  963. )
  964. let saveHbA1c = HbA1c(context: self.coredataContext)
  965. saveHbA1c.date = Date()
  966. saveHbA1c.hba1c = NGSPa1CStatisticValue_total as NSDecimalNumber
  967. saveHbA1c.hba1c_1 = NGSPa1CStatisticValue as NSDecimalNumber
  968. saveHbA1c.hba1c_7 = NGSPa1CStatisticValue_7 as NSDecimalNumber
  969. saveHbA1c.hba1c_30 = NGSPa1CStatisticValue_30 as NSDecimalNumber
  970. saveHbA1c.hba1c_90 = NGSPa1CStatisticValue_90 as NSDecimalNumber
  971. try? self.coredataContext.save()
  972. // Convert to user-preferred unit
  973. let overrideHbA1cUnit = settingsManager.settings.overrideHbA1cUnit
  974. if units == .mmolL {
  975. // Override if users sets overrideHbA1cUnit: true
  976. if !overrideHbA1cUnit {
  977. hbs = Durations(
  978. day: roundDecimal(IFCCa1CStatisticValue, 1),
  979. week: roundDecimal(IFCCa1CStatisticValue_7, 1),
  980. month: roundDecimal(IFCCa1CStatisticValue_30, 1),
  981. total: roundDecimal(IFCCa1CStatisticValue_total, 1)
  982. )
  983. }
  984. } else if units != .mmolL, overrideHbA1cUnit {
  985. hbs = Durations(
  986. day: roundDecimal(IFCCa1CStatisticValue, 1),
  987. week: roundDecimal(IFCCa1CStatisticValue_7, 1),
  988. month: roundDecimal(IFCCa1CStatisticValue_30, 1),
  989. total: roundDecimal(IFCCa1CStatisticValue_total, 1)
  990. )
  991. }
  992. let nrOfCGMReadings = nr1
  993. let loopstat = LoopCycles(
  994. loops: successNR + errorNR,
  995. errors: errorNR,
  996. readings: Int(nrOfCGMReadings),
  997. success_rate: Decimal(round(successRate ?? 0)),
  998. avg_interval: roundDecimal(Decimal(averageLoopTime), 1),
  999. median_interval: roundDecimal(Decimal(medianInterval), 1),
  1000. min_interval: roundDecimal(Decimal(minimumInt), 1),
  1001. max_interval: roundDecimal(Decimal(maximumInt), 1),
  1002. avg_duration: Decimal(roundDouble(averageLoopDuration, 2)),
  1003. median_duration: Decimal(roundDouble(medianLoopTime, 2)),
  1004. min_duration: roundDecimal(Decimal(minimumLoopTime), 2),
  1005. max_duration: Decimal(roundDouble(maximumLoopTime, 1))
  1006. )
  1007. // TIR calcs for every case
  1008. var oneDay_: (TIR: Double, hypos: Double, hypers: Double) = (0.0, 0.0, 0.0)
  1009. var sevenDays_: (TIR: Double, hypos: Double, hypers: Double) = (0.0, 0.0, 0.0)
  1010. var thirtyDays_: (TIR: Double, hypos: Double, hypers: Double) = (0.0, 0.0, 0.0)
  1011. var totalDays_: (TIR: Double, hypos: Double, hypers: Double) = (0.0, 0.0, 0.0)
  1012. // Get all TIR calcs for every case
  1013. if nr_bgs > 0 {
  1014. oneDay_ = tir(bgArray_1)
  1015. sevenDays_ = tir(bgArray_7)
  1016. thirtyDays_ = tir(bgArray_30)
  1017. totalDays_ = tir(bgArrayForTIR)
  1018. }
  1019. let tir = Durations(
  1020. day: roundDecimal(Decimal(oneDay_.TIR), 1),
  1021. week: roundDecimal(Decimal(sevenDays_.TIR), 1),
  1022. month: roundDecimal(Decimal(thirtyDays_.TIR), 1),
  1023. total: roundDecimal(Decimal(totalDays_.TIR), 1)
  1024. )
  1025. let hypo = Durations(
  1026. day: Decimal(oneDay_.hypos),
  1027. week: Decimal(sevenDays_.hypos),
  1028. month: Decimal(thirtyDays_.hypos),
  1029. total: Decimal(totalDays_.hypos)
  1030. )
  1031. let hyper = Durations(
  1032. day: Decimal(oneDay_.hypers),
  1033. week: Decimal(sevenDays_.hypers),
  1034. month: Decimal(thirtyDays_.hypers),
  1035. total: Decimal(totalDays_.hypers)
  1036. )
  1037. let TimeInRange = TIRs(TIR: tir, Hypos: hypo, Hypers: hyper)
  1038. let avgs = Durations(
  1039. day: roundDecimal(bg_1, 1),
  1040. week: roundDecimal(bg_7, 1),
  1041. month: roundDecimal(bg_30, 1),
  1042. total: roundDecimal(bg_total, 1)
  1043. )
  1044. let saveAverages = BGaverages(context: self.coredataContext)
  1045. saveAverages.date = Date()
  1046. saveAverages.average = bg_total as NSDecimalNumber
  1047. saveAverages.average_1 = bg_1 as NSDecimalNumber
  1048. saveAverages.average_7 = bg_7 as NSDecimalNumber
  1049. saveAverages.average_30 = bg_30 as NSDecimalNumber
  1050. saveAverages.average_90 = bg_90 as NSDecimalNumber
  1051. try? self.coredataContext.save()
  1052. let avg = Averages(Average: avgs, Median: median)
  1053. var insulinDistribution = [InsulinDistribution]()
  1054. var insulin = Ins(
  1055. TDD: 0,
  1056. bolus: 0,
  1057. temp_basal: 0,
  1058. scheduled_basal: 0
  1059. )
  1060. let requestInsulinDistribution = InsulinDistribution.fetchRequest() as NSFetchRequest<InsulinDistribution>
  1061. let sortInsulin = NSSortDescriptor(key: "date", ascending: false)
  1062. requestInsulinDistribution.sortDescriptors = [sortInsulin]
  1063. requestInsulinDistribution.fetchLimit = 1
  1064. try? insulinDistribution = coredataContext.fetch(requestInsulinDistribution)
  1065. insulin = Ins(
  1066. TDD: roundDecimal(currentTDD, 2),
  1067. bolus: insulinDistribution.first != nil ? ((insulinDistribution[0].bolus ?? 0) as Decimal) : 0,
  1068. temp_basal: insulinDistribution.first != nil ? ((insulinDistribution[0].tempBasal ?? 0) as Decimal) : 0,
  1069. scheduled_basal: insulinDistribution
  1070. .first != nil ? ((insulinDistribution[0].scheduledBasal ?? 0) as Decimal) : 0
  1071. )
  1072. var sumOfSquares = 0.0
  1073. var sumOfSquares_1 = 0.0
  1074. var sumOfSquares_7 = 0.0
  1075. var sumOfSquares_30 = 0.0
  1076. // Total
  1077. for array in bgArray {
  1078. sumOfSquares += pow(array - Double(bg_total), 2)
  1079. }
  1080. // One day
  1081. for array_1 in bgArray_1_ {
  1082. sumOfSquares_1 += pow(array_1 - Double(bg_1), 2)
  1083. }
  1084. // week
  1085. for array_7 in bgArray_7_ {
  1086. sumOfSquares_7 += pow(array_7 - Double(bg_7), 2)
  1087. }
  1088. // month
  1089. for array_30 in bgArray_30_ {
  1090. sumOfSquares_30 += pow(array_30 - Double(bg_30), 2)
  1091. }
  1092. // Standard deviation and Coefficient of variation
  1093. var sd_total = 0.0
  1094. var cv_total = 0.0
  1095. var sd_1 = 0.0
  1096. var cv_1 = 0.0
  1097. var sd_7 = 0.0
  1098. var cv_7 = 0.0
  1099. var sd_30 = 0.0
  1100. var cv_30 = 0.0
  1101. // Avoid division by zero
  1102. if bg_total > 0 {
  1103. sd_total = sqrt(sumOfSquares / Double(nr_bgs))
  1104. cv_total = sd_total / Double(bg_total) * 100
  1105. }
  1106. if bg_1 > 0 {
  1107. sd_1 = sqrt(sumOfSquares_1 / Double(bgArray_1_.count))
  1108. cv_1 = sd_1 / Double(bg_1) * 100
  1109. }
  1110. if bg_7 > 0 {
  1111. sd_7 = sqrt(sumOfSquares_7 / Double(bgArray_7_.count))
  1112. cv_7 = sd_7 / Double(bg_7) * 100
  1113. }
  1114. if bg_30 > 0 {
  1115. sd_30 = sqrt(sumOfSquares_30 / Double(bgArray_30_.count))
  1116. cv_30 = sd_30 / Double(bg_30) * 100
  1117. }
  1118. // Standard Deviations
  1119. let standardDeviations = Durations(
  1120. day: roundDecimal(Decimal(sd_1), 1),
  1121. week: roundDecimal(Decimal(sd_7), 1),
  1122. month: roundDecimal(Decimal(sd_30), 1),
  1123. total: roundDecimal(Decimal(sd_total), 1)
  1124. )
  1125. // CV = standard deviation / sample mean x 100
  1126. let cvs = Durations(
  1127. day: roundDecimal(Decimal(cv_1), 1),
  1128. week: roundDecimal(Decimal(cv_7), 1),
  1129. month: roundDecimal(Decimal(cv_30), 1),
  1130. total: roundDecimal(Decimal(cv_total), 1)
  1131. )
  1132. let variance = Variance(SD: standardDeviations, CV: cvs)
  1133. let dailystat = Statistics(
  1134. created_at: Date(),
  1135. iPhone: UIDevice.current.getDeviceId,
  1136. iOS: UIDevice.current.getOSInfo,
  1137. Build_Version: version ?? "",
  1138. Build_Number: build ?? "1",
  1139. Branch: branch,
  1140. CopyRightNotice: String(copyrightNotice_.prefix(32)),
  1141. Build_Date: buildDate,
  1142. Algorithm: algo_,
  1143. AdjustmentFactor: af,
  1144. Pump: pump_,
  1145. CGM: cgm.rawValue,
  1146. insulinType: insulin_type.rawValue,
  1147. peakActivityTime: iPa,
  1148. Carbs_24h: carbTotal,
  1149. GlucoseStorage_Days: Decimal(roundDouble(numberOfDays, 1)),
  1150. Statistics: Stats(
  1151. Distribution: TimeInRange,
  1152. Glucose: avg,
  1153. HbA1c: hbs,
  1154. LoopCycles: loopstat,
  1155. Insulin: insulin,
  1156. Variance: variance
  1157. )
  1158. )
  1159. storage.transaction { storage in
  1160. storage.append(dailystat, to: file, uniqBy: \.created_at)
  1161. let uniqeEvents: [Statistics] = storage.retrieve(file, as: [Statistics].self)?
  1162. .filter { $0.created_at.addingTimeInterval(24.hours.timeInterval) > Date() }
  1163. .sorted { $0.created_at > $1.created_at } ?? []
  1164. storage.save(Array(uniqeEvents), as: file)
  1165. }
  1166. nightscout.uploadStatistics(dailystat: dailystat)
  1167. nightscout.uploadPreferences()
  1168. let saveStatsCoreData = StatsData(context: self.coredataContext)
  1169. saveStatsCoreData.lastrun = Date()
  1170. try? self.coredataContext.save()
  1171. print("Test time of statistics computation: \(-1 * now.timeIntervalSinceNow) s")
  1172. }
  1173. }
  1174. }
  1175. private func loopStats(loopStatRecord: LoopStats) {
  1176. let LoopStatsStartedAt = Date()
  1177. coredataContext.perform {
  1178. let nLS = LoopStatRecord(context: self.coredataContext)
  1179. nLS.start = loopStatRecord.start
  1180. nLS.end = loopStatRecord.end ?? Date()
  1181. nLS.loopStatus = loopStatRecord.loopStatus
  1182. nLS.duration = loopStatRecord.duration ?? 0.0
  1183. try? self.coredataContext.save()
  1184. }
  1185. print("Test time of LoopStats computation: \(-1 * LoopStatsStartedAt.timeIntervalSinceNow) s")
  1186. }
  1187. private func processError(_ error: Error) {
  1188. warning(.apsManager, "\(error.localizedDescription)")
  1189. lastError.send(error)
  1190. }
  1191. private func createBolusReporter() {
  1192. bolusReporter = pumpManager?.createBolusProgressReporter(reportingOn: processQueue)
  1193. bolusReporter?.addObserver(self)
  1194. }
  1195. private func updateStatus() {
  1196. debug(.apsManager, "force update status")
  1197. guard let pump = pumpManager else {
  1198. return
  1199. }
  1200. if let omnipod = pump as? OmnipodPumpManager {
  1201. omnipod.getPodStatus { _ in }
  1202. }
  1203. if let omnipodBLE = pump as? OmniBLEPumpManager {
  1204. omnipodBLE.getPodStatus { _ in }
  1205. }
  1206. }
  1207. private func clearBolusReporter() {
  1208. bolusReporter?.removeObserver(self)
  1209. bolusReporter = nil
  1210. processQueue.asyncAfter(deadline: .now() + 0.5) {
  1211. self.bolusProgress.send(nil)
  1212. self.updateStatus()
  1213. }
  1214. }
  1215. }
  1216. private extension PumpManager {
  1217. func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval) -> AnyPublisher<DoseEntry?, Error> {
  1218. Future { promise in
  1219. self.enactTempBasal(unitsPerHour: unitsPerHour, for: duration) { error in
  1220. if let error = error {
  1221. debug(.apsManager, "Temp basal failed: \(unitsPerHour) for: \(duration)")
  1222. promise(.failure(error))
  1223. } else {
  1224. debug(.apsManager, "Temp basal succeded: \(unitsPerHour) for: \(duration)")
  1225. promise(.success(nil))
  1226. }
  1227. }
  1228. }
  1229. .mapError { APSError.pumpError($0) }
  1230. .eraseToAnyPublisher()
  1231. }
  1232. func enactBolus(units: Double, automatic: Bool) -> AnyPublisher<DoseEntry?, Error> {
  1233. Future { promise in
  1234. // convert automatic
  1235. let automaticValue = automatic ? BolusActivationType.automatic : BolusActivationType.manualRecommendationAccepted
  1236. self.enactBolus(units: units, activationType: automaticValue) { error in
  1237. if let error = error {
  1238. debug(.apsManager, "Bolus failed: \(units)")
  1239. promise(.failure(error))
  1240. } else {
  1241. debug(.apsManager, "Bolus succeded: \(units)")
  1242. promise(.success(nil))
  1243. }
  1244. }
  1245. }
  1246. .mapError { APSError.pumpError($0) }
  1247. .eraseToAnyPublisher()
  1248. }
  1249. func cancelBolus() -> AnyPublisher<DoseEntry?, Error> {
  1250. Future { promise in
  1251. self.cancelBolus { result in
  1252. switch result {
  1253. case let .success(dose):
  1254. debug(.apsManager, "Cancel Bolus succeded")
  1255. promise(.success(dose))
  1256. case let .failure(error):
  1257. debug(.apsManager, "Cancel Bolus failed")
  1258. promise(.failure(error))
  1259. }
  1260. }
  1261. }
  1262. .mapError { APSError.pumpError($0) }
  1263. .eraseToAnyPublisher()
  1264. }
  1265. func suspendDelivery() -> AnyPublisher<Void, Error> {
  1266. Future { promise in
  1267. self.suspendDelivery { error in
  1268. if let error = error {
  1269. promise(.failure(error))
  1270. } else {
  1271. promise(.success(()))
  1272. }
  1273. }
  1274. }
  1275. .mapError { APSError.pumpError($0) }
  1276. .eraseToAnyPublisher()
  1277. }
  1278. func resumeDelivery() -> AnyPublisher<Void, Error> {
  1279. Future { promise in
  1280. self.resumeDelivery { error in
  1281. if let error = error {
  1282. promise(.failure(error))
  1283. } else {
  1284. promise(.success(()))
  1285. }
  1286. }
  1287. }
  1288. .mapError { APSError.pumpError($0) }
  1289. .eraseToAnyPublisher()
  1290. }
  1291. }
  1292. extension BaseAPSManager: PumpManagerStatusObserver {
  1293. func pumpManager(_: PumpManager, didUpdate status: PumpManagerStatus, oldStatus _: PumpManagerStatus) {
  1294. let percent = Int((status.pumpBatteryChargeRemaining ?? 1) * 100)
  1295. let battery = Battery(
  1296. percent: percent,
  1297. voltage: nil,
  1298. string: percent > 10 ? .normal : .low,
  1299. display: status.pumpBatteryChargeRemaining != nil
  1300. )
  1301. storage.save(battery, as: OpenAPS.Monitor.battery)
  1302. storage.save(status.pumpStatus, as: OpenAPS.Monitor.status)
  1303. }
  1304. }
  1305. extension BaseAPSManager: DoseProgressObserver {
  1306. func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) {
  1307. bolusProgress.send(Decimal(doseProgressReporter.progress.percentComplete))
  1308. if doseProgressReporter.progress.isComplete {
  1309. clearBolusReporter()
  1310. }
  1311. }
  1312. }
  1313. extension PumpManagerStatus {
  1314. var pumpStatus: PumpStatus {
  1315. let bolusing = bolusState != .noBolus
  1316. let suspended = basalDeliveryState?.isSuspended ?? true
  1317. let type = suspended ? StatusType.suspended : (bolusing ? .bolusing : .normal)
  1318. return PumpStatus(status: type, bolusing: bolusing, suspended: suspended, timestamp: Date())
  1319. }
  1320. }