OpenAPS.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import JavaScriptCore
  5. final class OpenAPS {
  6. private let jsWorker = JavaScriptWorker()
  7. private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
  8. private let storage: FileStorage
  9. let context = CoreDataStack.shared.newTaskContext()
  10. let jsonConverter = JSONConverter()
  11. init(storage: FileStorage) {
  12. self.storage = storage
  13. }
  14. static let dateFormatter: ISO8601DateFormatter = {
  15. let formatter = ISO8601DateFormatter()
  16. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  17. return formatter
  18. }()
  19. // Helper function to convert a Decimal? to NSDecimalNumber?
  20. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  21. guard let value = value else { return nil }
  22. return NSDecimalNumber(decimal: value)
  23. }
  24. // Use the helper function for cleaner code
  25. func processDetermination(_ determination: Determination) async {
  26. await context.perform {
  27. let newOrefDetermination = OrefDetermination(context: self.context)
  28. newOrefDetermination.id = UUID()
  29. newOrefDetermination.totalDailyDose = self.decimalToNSDecimalNumber(determination.tdd)
  30. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  31. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  32. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  33. newOrefDetermination.deliverAt = determination.deliverAt
  34. newOrefDetermination.insulinForManualBolus = self.decimalToNSDecimalNumber(determination.insulinForManualBolus)
  35. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  36. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  37. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  38. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  39. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  40. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  41. newOrefDetermination.reason = determination.reason
  42. newOrefDetermination.duration = self.decimalToNSDecimalNumber(determination.duration)
  43. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  44. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  45. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  46. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  47. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  48. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  49. newOrefDetermination.manualBolusErrorString = self.decimalToNSDecimalNumber(determination.manualBolusErrorString)
  50. newOrefDetermination.tempBasal = determination.insulin?.temp_basal.map { NSDecimalNumber(decimal: $0) }
  51. newOrefDetermination.scheduledBasal = determination.insulin?.scheduled_basal.map { NSDecimalNumber(decimal: $0) }
  52. newOrefDetermination.bolus = determination.insulin?.bolus.map { NSDecimalNumber(decimal: $0) }
  53. newOrefDetermination.smbToDeliver = determination.units.map { NSDecimalNumber(decimal: $0) }
  54. newOrefDetermination.carbsRequired = Int16(Int(determination.carbsReq ?? 0))
  55. newOrefDetermination.isUploadedToNS = false
  56. if let predictions = determination.predictions {
  57. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  58. .forEach { type, values in
  59. if let values = values {
  60. let forecast = Forecast(context: self.context)
  61. forecast.id = UUID()
  62. forecast.type = type
  63. forecast.date = Date()
  64. forecast.orefDetermination = newOrefDetermination
  65. for (index, value) in values.enumerated() {
  66. let forecastValue = ForecastValue(context: self.context)
  67. forecastValue.index = Int32(index)
  68. forecastValue.value = Int32(value)
  69. forecast.addToForecastValues(forecastValue)
  70. }
  71. newOrefDetermination.addToForecasts(forecast)
  72. }
  73. }
  74. }
  75. }
  76. // First save the current Determination to Core Data
  77. await attemptToSaveContext()
  78. // After that check for changes in iob and cob and if there are any post a custom Notification
  79. /// this is currently used to update Live Activity so that it stays up to date and not one loop cycle behind
  80. await checkForCobIobUpdate(determination)
  81. }
  82. func checkForCobIobUpdate(_ determination: Determination) async {
  83. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  84. ofType: OrefDetermination.self,
  85. onContext: context,
  86. predicate: NSPredicate.predicateFor30MinAgoForDetermination,
  87. key: "deliverAt",
  88. ascending: false,
  89. fetchLimit: 2
  90. )
  91. guard let previousDeterminations = results as? [OrefDetermination] else {
  92. return
  93. }
  94. // We need to get the second last Determination for this comparison because we have saved the current Determination already to Core Data
  95. if let previousDetermination = previousDeterminations.dropFirst().first {
  96. let iobChanged = previousDetermination.iob != decimalToNSDecimalNumber(determination.iob)
  97. let cobChanged = previousDetermination.cob != Int16(Int(determination.cob ?? 0))
  98. if iobChanged || cobChanged {
  99. Foundation.NotificationCenter.default.post(name: .didUpdateCobIob, object: nil)
  100. }
  101. }
  102. }
  103. func attemptToSaveContext() async {
  104. await context.perform {
  105. do {
  106. guard self.context.hasChanges else { return }
  107. try self.context.save()
  108. } catch {
  109. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  110. }
  111. }
  112. }
  113. // fetch glucose to pass it to the meal function and to determine basal
  114. private func fetchAndProcessGlucose() async -> String {
  115. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  116. ofType: GlucoseStored.self,
  117. onContext: context,
  118. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  119. key: "date",
  120. ascending: false,
  121. fetchLimit: 72,
  122. batchSize: 24
  123. )
  124. guard let glucoseResults = results as? [GlucoseStored] else {
  125. return ""
  126. }
  127. return await context.perform {
  128. // convert to JSON
  129. return self.jsonConverter.convertToJSON(glucoseResults)
  130. }
  131. }
  132. private func fetchAndProcessCarbs() async -> String {
  133. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  134. ofType: CarbEntryStored.self,
  135. onContext: context,
  136. predicate: NSPredicate.predicateForOneDayAgo,
  137. key: "date",
  138. ascending: false
  139. )
  140. guard let carbResults = results as? [CarbEntryStored] else {
  141. return ""
  142. }
  143. // convert to JSON
  144. return await context.perform {
  145. return self.jsonConverter.convertToJSON(carbResults)
  146. }
  147. }
  148. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  149. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  150. ofType: PumpEventStored.self,
  151. onContext: context,
  152. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  153. key: "timestamp",
  154. ascending: false,
  155. batchSize: 50
  156. )
  157. guard let pumpEventResults = results as? [PumpEventStored] else {
  158. return nil
  159. }
  160. return await context.perform {
  161. return pumpEventResults.map(\.objectID)
  162. }
  163. }
  164. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID]) async -> String {
  165. // Return an empty JSON object if the list of object IDs is empty
  166. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  167. // Execute all operations on the background context
  168. return await context.perform {
  169. // Load the pump events from the object IDs
  170. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  171. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  172. // Create the DTOs
  173. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  174. var eventDTOs: [PumpEventDTO] = []
  175. if let bolusDTO = event.toBolusDTOEnum() {
  176. eventDTOs.append(bolusDTO)
  177. }
  178. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  179. eventDTOs.append(tempBasalDurationDTO)
  180. }
  181. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  182. eventDTOs.append(tempBasalDTO)
  183. }
  184. return eventDTOs
  185. }
  186. // Convert the DTOs to JSON
  187. return self.jsonConverter.convertToJSON(dtos)
  188. }
  189. }
  190. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) async throws -> Determination? {
  191. debug(.openAPS, "Start determineBasal")
  192. // clock
  193. self.storage.save(clock, as: Monitor.clock)
  194. // temp_basal
  195. let tempBasal = currentTemp.rawJSON
  196. // Perform asynchronous calls in parallel
  197. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  198. async let carbs = fetchAndProcessCarbs()
  199. async let glucose = fetchAndProcessGlucose()
  200. async let oref2 = oref2()
  201. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  202. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  203. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  204. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  205. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  206. // Await the results of asynchronous tasks
  207. let (
  208. pumpHistoryJSON,
  209. carbsAsJSON,
  210. glucoseAsJSON,
  211. oref2_variables,
  212. profile,
  213. basalProfile,
  214. autosens,
  215. reservoir,
  216. preferences
  217. ) = await (
  218. parsePumpHistory(await pumpHistoryObjectIDs),
  219. carbs,
  220. glucose,
  221. oref2,
  222. profileAsync,
  223. basalAsync,
  224. autosenseAsync,
  225. reservoirAsync,
  226. preferencesAsync
  227. )
  228. // TODO: - Save and fetch profile/basalProfile in/from UserDefaults!
  229. // Meal
  230. let meal = try await self.meal(
  231. pumphistory: pumpHistoryJSON,
  232. profile: profile,
  233. basalProfile: basalProfile,
  234. clock: clock,
  235. carbs: carbsAsJSON,
  236. glucose: glucoseAsJSON
  237. )
  238. // IOB
  239. let iob = try await self.iob(
  240. pumphistory: pumpHistoryJSON,
  241. profile: profile,
  242. clock: clock,
  243. autosens: autosens.isEmpty ? .null : autosens
  244. )
  245. // TODO: refactor this to core data
  246. storage.save(iob, as: Monitor.iob)
  247. // Determine basal
  248. let orefDetermination = try await determineBasal(
  249. glucose: glucoseAsJSON,
  250. currentTemp: tempBasal,
  251. iob: iob,
  252. profile: profile,
  253. autosens: autosens.isEmpty ? .null : autosens,
  254. meal: meal,
  255. microBolusAllowed: true,
  256. reservoir: reservoir,
  257. pumpHistory: pumpHistoryJSON,
  258. preferences: preferences,
  259. basalProfile: basalProfile,
  260. oref2_variables: oref2_variables
  261. )
  262. debug(.openAPS, "Determinated: \(orefDetermination)")
  263. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  264. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  265. // AAPS does it the same way! we'll follow their example!
  266. determination.timestamp = deliverAt
  267. // save to core data asynchronously
  268. await processDetermination(determination)
  269. return determination
  270. } else {
  271. return nil
  272. }
  273. }
  274. func oref2() async -> RawJSON {
  275. await context.perform {
  276. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  277. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  278. let wp = preferences?.weightPercentage ?? 1
  279. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  280. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  281. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  282. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  283. var uniqueEvents = [[String: Any]]()
  284. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  285. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  286. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  287. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  288. requestTDD.sortDescriptors = [sortTDD]
  289. requestTDD.resultType = .dictionaryResultType
  290. do {
  291. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  292. uniqueEvents = fetchedResults
  293. }
  294. } catch {
  295. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch TDD Data")
  296. }
  297. var sliderArray = [TempTargetsSlider]()
  298. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  299. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  300. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  301. // requestIsEnbled.fetchLimit = 1
  302. try? sliderArray = self.context.fetch(requestIsEnbled)
  303. /// Get the last active Override as only this information is apparently used in oref2
  304. var overrideArray = [OverrideStored]()
  305. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  306. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  307. requestOverrides.sortDescriptors = [sortOverride]
  308. requestOverrides.predicate = NSPredicate.lastActiveOverride
  309. requestOverrides.fetchLimit = 1
  310. try? overrideArray = self.context.fetch(requestOverrides)
  311. var tempTargetsArray = [TempTargets]()
  312. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  313. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  314. requestTempTargets.sortDescriptors = [sortTT]
  315. requestTempTargets.fetchLimit = 1
  316. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  317. let total = uniqueEvents.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 }).reduce(0, +)
  318. var indeces = uniqueEvents.count
  319. // Only fetch once. Use same (previous) fetch
  320. let twoHoursArray = uniqueEvents.filter({ ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo })
  321. var nrOfIndeces = twoHoursArray.count
  322. let totalAmount = twoHoursArray.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 })
  323. .reduce(0, +)
  324. var temptargetActive = tempTargetsArray.first?.active ?? false
  325. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  326. var useOverride = overrideArray.first?.enabled ?? false
  327. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  328. var unlimited = overrideArray.first?.indefinite ?? true
  329. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  330. let currentTDD = (uniqueEvents.last?["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0
  331. if indeces == 0 {
  332. indeces = 1
  333. }
  334. if nrOfIndeces == 0 {
  335. nrOfIndeces = 1
  336. }
  337. let average2hours = totalAmount / Decimal(nrOfIndeces)
  338. let average14 = total / Decimal(indeces)
  339. let weight = wp
  340. let weighted_average = weight * average2hours + (1 - weight) * average14
  341. var duration: Decimal = 0
  342. var newDuration: Decimal = 0
  343. var overrideTarget: Decimal = 0
  344. if useOverride {
  345. duration = (overrideArray.first?.duration ?? 0) as Decimal
  346. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  347. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  348. let addedMinutes = Int(duration)
  349. let date = overrideArray.first?.date ?? Date()
  350. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  351. !unlimited
  352. {
  353. useOverride = false
  354. let saveToCoreData = OverrideStored(context: self.context)
  355. saveToCoreData.enabled = false
  356. saveToCoreData.date = Date()
  357. saveToCoreData.duration = 0
  358. saveToCoreData.indefinite = false
  359. saveToCoreData.percentage = 100
  360. do {
  361. guard self.context.hasChanges else { return "{}" }
  362. try self.context.save()
  363. } catch {
  364. print(error.localizedDescription)
  365. }
  366. }
  367. }
  368. if !useOverride {
  369. unlimited = true
  370. overridePercentage = 100
  371. duration = 0
  372. overrideTarget = 0
  373. disableSMBs = false
  374. }
  375. if temptargetActive {
  376. var duration_ = 0
  377. var hbt = Double(hbt_)
  378. var dd = 0.0
  379. if temptargetActive {
  380. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  381. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  382. let startDate = tempTargetsArray.first?.startDate ?? Date()
  383. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  384. dd = durationPlusStart.timeIntervalSinceNow.minutes
  385. if dd > 0.1 {
  386. hbt_ = Decimal(hbt)
  387. temptargetActive = true
  388. } else {
  389. temptargetActive = false
  390. }
  391. }
  392. }
  393. if currentTDD > 0 {
  394. let averages = Oref2_variables(
  395. average_total_data: average14,
  396. weightedAverage: weighted_average,
  397. past2hoursAverage: average2hours,
  398. date: Date(),
  399. isEnabled: temptargetActive,
  400. presetActive: isPercentageEnabled,
  401. overridePercentage: overridePercentage,
  402. useOverride: useOverride,
  403. duration: duration,
  404. unlimited: unlimited,
  405. hbt: hbt_,
  406. overrideTarget: overrideTarget,
  407. smbIsOff: disableSMBs,
  408. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  409. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  410. isf: overrideArray.first?.isf ?? false,
  411. cr: overrideArray.first?.cr ?? false,
  412. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  413. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  414. )
  415. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  416. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  417. } else {
  418. let averages = Oref2_variables(
  419. average_total_data: 0,
  420. weightedAverage: 1,
  421. past2hoursAverage: 0,
  422. date: Date(),
  423. isEnabled: temptargetActive,
  424. presetActive: isPercentageEnabled,
  425. overridePercentage: overridePercentage,
  426. useOverride: useOverride,
  427. duration: duration,
  428. unlimited: unlimited,
  429. hbt: hbt_,
  430. overrideTarget: overrideTarget,
  431. smbIsOff: disableSMBs,
  432. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  433. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  434. isf: overrideArray.first?.isf ?? false,
  435. cr: overrideArray.first?.cr ?? false,
  436. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  437. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  438. )
  439. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  440. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  441. }
  442. }
  443. }
  444. func autosense() async throws -> Autosens? {
  445. debug(.openAPS, "Start autosens")
  446. // Perform asynchronous calls in parallel
  447. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  448. async let carbs = fetchAndProcessCarbs()
  449. async let glucose = fetchAndProcessGlucose()
  450. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  451. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  452. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  453. // Await the results of asynchronous tasks
  454. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  455. parsePumpHistory(await pumpHistoryObjectIDs),
  456. carbs,
  457. glucose,
  458. getProfile,
  459. getBasalProfile,
  460. getTempTargets
  461. )
  462. // Autosense
  463. let autosenseResult = try await autosense(
  464. glucose: glucoseAsJSON,
  465. pumpHistory: pumpHistoryJSON,
  466. basalprofile: basalProfile,
  467. profile: profile,
  468. carbs: carbsAsJSON,
  469. temptargets: tempTargets
  470. )
  471. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  472. if var autosens = Autosens(from: autosenseResult) {
  473. autosens.timestamp = Date()
  474. storage.save(autosens, as: Settings.autosense)
  475. return autosens
  476. } else {
  477. return nil
  478. }
  479. }
  480. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  481. debug(.openAPS, "Start autotune")
  482. // Perform asynchronous calls in parallel
  483. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  484. async let carbs = fetchAndProcessCarbs()
  485. async let glucose = fetchAndProcessGlucose()
  486. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  487. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  488. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  489. // Await the results of asynchronous tasks
  490. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  491. parsePumpHistory(await pumpHistoryObjectIDs),
  492. carbs,
  493. glucose,
  494. getProfile,
  495. getPumpProfile,
  496. getPreviousAutotune
  497. )
  498. // Error need to be handled here because the function is not declared as throws
  499. do {
  500. // Autotune Prepare
  501. let autotunePreppedGlucose = try await autotunePrepare(
  502. pumphistory: pumpHistoryJSON,
  503. profile: profile,
  504. glucose: glucoseAsJSON,
  505. pumpprofile: pumpProfile,
  506. carbs: carbsAsJSON,
  507. categorizeUamAsBasal: categorizeUamAsBasal,
  508. tuneInsulinCurve: tuneInsulinCurve
  509. )
  510. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  511. // Autotune Run
  512. let autotuneResult = try await autotuneRun(
  513. autotunePreparedData: autotunePreppedGlucose,
  514. previousAutotuneResult: previousAutotune ?? profile,
  515. pumpProfile: pumpProfile
  516. )
  517. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  518. if let autotune = Autotune(from: autotuneResult) {
  519. storage.save(autotuneResult, as: Settings.autotune)
  520. return autotune
  521. } else {
  522. return nil
  523. }
  524. } catch {
  525. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  526. return nil
  527. }
  528. }
  529. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  530. debug(.openAPS, "Start makeProfiles")
  531. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  532. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  533. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  534. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  535. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  536. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  537. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  538. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  539. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  540. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  541. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  542. getPreferences,
  543. getPumpSettings,
  544. getBGTargets,
  545. getBasalProfile,
  546. getISF,
  547. getCR,
  548. getTempTargets,
  549. getModel,
  550. getAutotune,
  551. getFreeAPS
  552. )
  553. var adjustedPreferences = preferences
  554. if adjustedPreferences.isEmpty {
  555. adjustedPreferences = Preferences().rawJSON
  556. }
  557. do {
  558. // Pump Profile
  559. let pumpProfile = try await makeProfile(
  560. preferences: adjustedPreferences,
  561. pumpSettings: pumpSettings,
  562. bgTargets: bgTargets,
  563. basalProfile: basalProfile,
  564. isf: isf,
  565. carbRatio: cr,
  566. tempTargets: tempTargets,
  567. model: model,
  568. autotune: RawJSON.null,
  569. freeaps: freeaps
  570. )
  571. // Profile
  572. let profile = try await makeProfile(
  573. preferences: adjustedPreferences,
  574. pumpSettings: pumpSettings,
  575. bgTargets: bgTargets,
  576. basalProfile: basalProfile,
  577. isf: isf,
  578. carbRatio: cr,
  579. tempTargets: tempTargets,
  580. model: model,
  581. autotune: autotune.isEmpty ? .null : autotune,
  582. freeaps: freeaps
  583. )
  584. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  585. await storage.saveAsync(profile, as: Settings.profile)
  586. if let tunedProfile = Autotune(from: profile) {
  587. return tunedProfile
  588. } else {
  589. return nil
  590. }
  591. } catch {
  592. debug(
  593. .apsManager,
  594. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  595. )
  596. return nil
  597. }
  598. }
  599. // MARK: - Private
  600. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  601. await withCheckedContinuation { continuation in
  602. jsWorker.inCommonContext { worker in
  603. worker.evaluateBatch(scripts: [
  604. Script(name: Prepare.log),
  605. Script(name: Bundle.iob),
  606. Script(name: Prepare.iob)
  607. ])
  608. let result = worker.call(function: Function.generate, with: [
  609. pumphistory,
  610. profile,
  611. clock,
  612. autosens
  613. ])
  614. continuation.resume(returning: result)
  615. }
  616. }
  617. }
  618. private func meal(
  619. pumphistory: JSON,
  620. profile: JSON,
  621. basalProfile: JSON,
  622. clock: JSON,
  623. carbs: JSON,
  624. glucose: JSON
  625. ) async throws -> RawJSON {
  626. try await withCheckedThrowingContinuation { continuation in
  627. jsWorker.inCommonContext { worker in
  628. worker.evaluateBatch(scripts: [
  629. Script(name: Prepare.log),
  630. Script(name: Bundle.meal),
  631. Script(name: Prepare.meal)
  632. ])
  633. let result = worker.call(function: Function.generate, with: [
  634. pumphistory,
  635. profile,
  636. clock,
  637. glucose,
  638. basalProfile,
  639. carbs
  640. ])
  641. continuation.resume(returning: result)
  642. }
  643. }
  644. }
  645. private func autosense(
  646. glucose: JSON,
  647. pumpHistory: JSON,
  648. basalprofile: JSON,
  649. profile: JSON,
  650. carbs: JSON,
  651. temptargets: JSON
  652. ) async throws -> RawJSON {
  653. try await withCheckedThrowingContinuation { continuation in
  654. jsWorker.inCommonContext { worker in
  655. worker.evaluateBatch(scripts: [
  656. Script(name: Prepare.log),
  657. Script(name: Bundle.autosens),
  658. Script(name: Prepare.autosens)
  659. ])
  660. let result = worker.call(function: Function.generate, with: [
  661. glucose,
  662. pumpHistory,
  663. basalprofile,
  664. profile,
  665. carbs,
  666. temptargets
  667. ])
  668. continuation.resume(returning: result)
  669. }
  670. }
  671. }
  672. private func autotunePrepare(
  673. pumphistory: JSON,
  674. profile: JSON,
  675. glucose: JSON,
  676. pumpprofile: JSON,
  677. carbs: JSON,
  678. categorizeUamAsBasal: Bool,
  679. tuneInsulinCurve: Bool
  680. ) async throws -> RawJSON {
  681. try await withCheckedThrowingContinuation { continuation in
  682. jsWorker.inCommonContext { worker in
  683. worker.evaluateBatch(scripts: [
  684. Script(name: Prepare.log),
  685. Script(name: Bundle.autotunePrep),
  686. Script(name: Prepare.autotunePrep)
  687. ])
  688. let result = worker.call(function: Function.generate, with: [
  689. pumphistory,
  690. profile,
  691. glucose,
  692. pumpprofile,
  693. carbs,
  694. categorizeUamAsBasal,
  695. tuneInsulinCurve
  696. ])
  697. continuation.resume(returning: result)
  698. }
  699. }
  700. }
  701. private func autotuneRun(
  702. autotunePreparedData: JSON,
  703. previousAutotuneResult: JSON,
  704. pumpProfile: JSON
  705. ) async throws -> RawJSON {
  706. try await withCheckedThrowingContinuation { continuation in
  707. jsWorker.inCommonContext { worker in
  708. worker.evaluateBatch(scripts: [
  709. Script(name: Prepare.log),
  710. Script(name: Bundle.autotuneCore),
  711. Script(name: Prepare.autotuneCore)
  712. ])
  713. let result = worker.call(function: Function.generate, with: [
  714. autotunePreparedData,
  715. previousAutotuneResult,
  716. pumpProfile
  717. ])
  718. continuation.resume(returning: result)
  719. }
  720. }
  721. }
  722. private func determineBasal(
  723. glucose: JSON,
  724. currentTemp: JSON,
  725. iob: JSON,
  726. profile: JSON,
  727. autosens: JSON,
  728. meal: JSON,
  729. microBolusAllowed: Bool,
  730. reservoir: JSON,
  731. pumpHistory: JSON,
  732. preferences: JSON,
  733. basalProfile: JSON,
  734. oref2_variables: JSON
  735. ) async throws -> RawJSON {
  736. try await withCheckedThrowingContinuation { continuation in
  737. jsWorker.inCommonContext { worker in
  738. worker.evaluateBatch(scripts: [
  739. Script(name: Prepare.log),
  740. Script(name: Prepare.determineBasal),
  741. Script(name: Bundle.basalSetTemp),
  742. Script(name: Bundle.getLastGlucose),
  743. Script(name: Bundle.determineBasal)
  744. ])
  745. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  746. worker.evaluate(script: middleware)
  747. }
  748. let result = worker.call(function: Function.generate, with: [
  749. iob,
  750. currentTemp,
  751. glucose,
  752. profile,
  753. autosens,
  754. meal,
  755. microBolusAllowed,
  756. reservoir,
  757. Date(),
  758. pumpHistory,
  759. preferences,
  760. basalProfile,
  761. oref2_variables
  762. ])
  763. continuation.resume(returning: result)
  764. }
  765. }
  766. }
  767. private func exportDefaultPreferences() -> RawJSON {
  768. dispatchPrecondition(condition: .onQueue(processQueue))
  769. return jsWorker.inCommonContext { worker in
  770. worker.evaluateBatch(scripts: [
  771. Script(name: Prepare.log),
  772. Script(name: Bundle.profile),
  773. Script(name: Prepare.profile)
  774. ])
  775. return worker.call(function: Function.exportDefaults, with: [])
  776. }
  777. }
  778. private func makeProfile(
  779. preferences: JSON,
  780. pumpSettings: JSON,
  781. bgTargets: JSON,
  782. basalProfile: JSON,
  783. isf: JSON,
  784. carbRatio: JSON,
  785. tempTargets: JSON,
  786. model: JSON,
  787. autotune: JSON,
  788. freeaps: JSON
  789. ) async throws -> RawJSON {
  790. try await withCheckedThrowingContinuation { continuation in
  791. jsWorker.inCommonContext { worker in
  792. worker.evaluateBatch(scripts: [
  793. Script(name: Prepare.log),
  794. Script(name: Bundle.profile),
  795. Script(name: Prepare.profile)
  796. ])
  797. let result = worker.call(function: Function.generate, with: [
  798. pumpSettings,
  799. bgTargets,
  800. isf,
  801. basalProfile,
  802. preferences,
  803. carbRatio,
  804. tempTargets,
  805. model,
  806. autotune,
  807. freeaps
  808. ])
  809. continuation.resume(returning: result)
  810. }
  811. }
  812. }
  813. private func loadJSON(name: String) -> String {
  814. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  815. }
  816. private func loadFileFromStorage(name: String) -> RawJSON {
  817. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  818. }
  819. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  820. await withCheckedContinuation { continuation in
  821. DispatchQueue.global(qos: .userInitiated).async {
  822. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  823. continuation.resume(returning: result)
  824. }
  825. }
  826. }
  827. private func middlewareScript(name: String) -> Script? {
  828. if let body = storage.retrieveRaw(name) {
  829. return Script(name: "Middleware", body: body)
  830. }
  831. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  832. return Script(name: "Middleware", body: try! String(contentsOf: url))
  833. }
  834. return nil
  835. }
  836. static func defaults(for file: String) -> RawJSON {
  837. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  838. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  839. return ""
  840. }
  841. return (try? String(contentsOf: url)) ?? ""
  842. }
  843. func processAndSave(forecastData: [String: [Int]]) {
  844. let currentDate = Date()
  845. context.perform {
  846. for (type, values) in forecastData {
  847. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  848. }
  849. do {
  850. guard self.context.hasChanges else { return }
  851. try self.context.save()
  852. } catch {
  853. print(error.localizedDescription)
  854. }
  855. }
  856. }
  857. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  858. let forecast = Forecast(context: context)
  859. forecast.id = UUID()
  860. forecast.date = date
  861. forecast.type = type
  862. for (index, value) in values.enumerated() {
  863. let forecastValue = ForecastValue(context: context)
  864. forecastValue.value = Int32(value)
  865. forecastValue.index = Int32(index)
  866. forecastValue.forecast = forecast
  867. }
  868. }
  869. }