APSManager.swift 60 KB

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