APSManager.swift 56 KB

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