APSManager.swift 61 KB

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