OpenAPS.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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.predicateForSixHoursAgo,
  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.pumpHistoryLast24h,
  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 tempBasalDTO = event.toTempBasalDTOEnum() {
  179. eventDTOs.append(tempBasalDTO)
  180. }
  181. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  182. eventDTOs.append(tempBasalDurationDTO)
  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. let dateFormatted = OpenAPS.dateFormatter.string(from: clock)
  194. let dateFormattedAsString = "\"\(dateFormatted)\""
  195. // temp_basal
  196. let tempBasal = currentTemp.rawJSON
  197. // Perform asynchronous calls in parallel
  198. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  199. async let carbs = fetchAndProcessCarbs()
  200. async let glucose = fetchAndProcessGlucose()
  201. async let oref2 = oref2()
  202. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  203. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  204. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  205. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  206. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  207. // Await the results of asynchronous tasks
  208. let (
  209. pumpHistoryJSON,
  210. carbsAsJSON,
  211. glucoseAsJSON,
  212. oref2_variables,
  213. profile,
  214. basalProfile,
  215. autosens,
  216. reservoir,
  217. preferences
  218. ) = await (
  219. parsePumpHistory(await pumpHistoryObjectIDs),
  220. carbs,
  221. glucose,
  222. oref2,
  223. profileAsync,
  224. basalAsync,
  225. autosenseAsync,
  226. reservoirAsync,
  227. preferencesAsync
  228. )
  229. // TODO: - Save and fetch profile/basalProfile in/from UserDefaults!
  230. // Meal
  231. let meal = try await self.meal(
  232. pumphistory: pumpHistoryJSON,
  233. profile: profile,
  234. basalProfile: basalProfile,
  235. clock: dateFormattedAsString,
  236. carbs: carbsAsJSON,
  237. glucose: glucoseAsJSON
  238. )
  239. // IOB
  240. let iob = try await self.iob(
  241. pumphistory: pumpHistoryJSON,
  242. profile: profile,
  243. clock: dateFormattedAsString,
  244. autosens: autosens.isEmpty ? .null : autosens
  245. )
  246. // TODO: refactor this to core data
  247. storage.save(iob, as: Monitor.iob)
  248. // Determine basal
  249. let orefDetermination = try await determineBasal(
  250. glucose: glucoseAsJSON,
  251. currentTemp: tempBasal,
  252. iob: iob,
  253. profile: profile,
  254. autosens: autosens.isEmpty ? .null : autosens,
  255. meal: meal,
  256. microBolusAllowed: true,
  257. reservoir: reservoir,
  258. pumpHistory: pumpHistoryJSON,
  259. preferences: preferences,
  260. basalProfile: basalProfile,
  261. oref2_variables: oref2_variables
  262. )
  263. debug(.openAPS, "Determinated: \(orefDetermination)")
  264. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  265. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  266. // AAPS does it the same way! we'll follow their example!
  267. determination.timestamp = deliverAt
  268. // save to core data asynchronously
  269. await processDetermination(determination)
  270. return determination
  271. } else {
  272. return nil
  273. }
  274. }
  275. func oref2() async -> RawJSON {
  276. await context.perform {
  277. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  278. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  279. let wp = preferences?.weightPercentage ?? 1
  280. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  281. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  282. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  283. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  284. var uniqueEvents = [[String: Any]]()
  285. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  286. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  287. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  288. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  289. requestTDD.sortDescriptors = [sortTDD]
  290. requestTDD.resultType = .dictionaryResultType
  291. do {
  292. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  293. uniqueEvents = fetchedResults
  294. }
  295. } catch {
  296. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch TDD Data")
  297. }
  298. var sliderArray = [TempTargetsSlider]()
  299. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  300. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  301. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  302. // requestIsEnbled.fetchLimit = 1
  303. try? sliderArray = self.context.fetch(requestIsEnbled)
  304. /// Get the last active Override as only this information is apparently used in oref2
  305. var overrideArray = [OverrideStored]()
  306. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  307. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  308. requestOverrides.sortDescriptors = [sortOverride]
  309. requestOverrides.predicate = NSPredicate.lastActiveOverride
  310. requestOverrides.fetchLimit = 1
  311. try? overrideArray = self.context.fetch(requestOverrides)
  312. var tempTargetsArray = [TempTargets]()
  313. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  314. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  315. requestTempTargets.sortDescriptors = [sortTT]
  316. requestTempTargets.fetchLimit = 1
  317. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  318. let total = uniqueEvents.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 }).reduce(0, +)
  319. var indeces = uniqueEvents.count
  320. // Only fetch once. Use same (previous) fetch
  321. let twoHoursArray = uniqueEvents.filter({ ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo })
  322. var nrOfIndeces = twoHoursArray.count
  323. let totalAmount = twoHoursArray.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 })
  324. .reduce(0, +)
  325. var temptargetActive = tempTargetsArray.first?.active ?? false
  326. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  327. var useOverride = overrideArray.first?.enabled ?? false
  328. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  329. var unlimited = overrideArray.first?.indefinite ?? true
  330. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  331. let currentTDD = (uniqueEvents.last?["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0
  332. if indeces == 0 {
  333. indeces = 1
  334. }
  335. if nrOfIndeces == 0 {
  336. nrOfIndeces = 1
  337. }
  338. let average2hours = totalAmount / Decimal(nrOfIndeces)
  339. let average14 = total / Decimal(indeces)
  340. let weight = wp
  341. let weighted_average = weight * average2hours + (1 - weight) * average14
  342. var duration: Decimal = 0
  343. var newDuration: Decimal = 0
  344. var overrideTarget: Decimal = 0
  345. if useOverride {
  346. duration = (overrideArray.first?.duration ?? 0) as Decimal
  347. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  348. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  349. let addedMinutes = Int(duration)
  350. let date = overrideArray.first?.date ?? Date()
  351. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  352. !unlimited
  353. {
  354. useOverride = false
  355. let saveToCoreData = OverrideStored(context: self.context)
  356. saveToCoreData.enabled = false
  357. saveToCoreData.date = Date()
  358. saveToCoreData.duration = 0
  359. saveToCoreData.indefinite = false
  360. saveToCoreData.percentage = 100
  361. do {
  362. guard self.context.hasChanges else { return "{}" }
  363. try self.context.save()
  364. } catch {
  365. print(error.localizedDescription)
  366. }
  367. }
  368. }
  369. if !useOverride {
  370. unlimited = true
  371. overridePercentage = 100
  372. duration = 0
  373. overrideTarget = 0
  374. disableSMBs = false
  375. }
  376. if temptargetActive {
  377. var duration_ = 0
  378. var hbt = Double(hbt_)
  379. var dd = 0.0
  380. if temptargetActive {
  381. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  382. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  383. let startDate = tempTargetsArray.first?.startDate ?? Date()
  384. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  385. dd = durationPlusStart.timeIntervalSinceNow.minutes
  386. if dd > 0.1 {
  387. hbt_ = Decimal(hbt)
  388. temptargetActive = true
  389. } else {
  390. temptargetActive = false
  391. }
  392. }
  393. }
  394. if currentTDD > 0 {
  395. let averages = Oref2_variables(
  396. average_total_data: average14,
  397. weightedAverage: weighted_average,
  398. past2hoursAverage: average2hours,
  399. date: Date(),
  400. isEnabled: temptargetActive,
  401. presetActive: isPercentageEnabled,
  402. overridePercentage: overridePercentage,
  403. useOverride: useOverride,
  404. duration: duration,
  405. unlimited: unlimited,
  406. hbt: hbt_,
  407. overrideTarget: overrideTarget,
  408. smbIsOff: disableSMBs,
  409. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  410. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  411. isf: overrideArray.first?.isf ?? false,
  412. cr: overrideArray.first?.cr ?? false,
  413. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  414. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  415. )
  416. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  417. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  418. } else {
  419. let averages = Oref2_variables(
  420. average_total_data: 0,
  421. weightedAverage: 1,
  422. past2hoursAverage: 0,
  423. date: Date(),
  424. isEnabled: temptargetActive,
  425. presetActive: isPercentageEnabled,
  426. overridePercentage: overridePercentage,
  427. useOverride: useOverride,
  428. duration: duration,
  429. unlimited: unlimited,
  430. hbt: hbt_,
  431. overrideTarget: overrideTarget,
  432. smbIsOff: disableSMBs,
  433. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  434. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  435. isf: overrideArray.first?.isf ?? false,
  436. cr: overrideArray.first?.cr ?? false,
  437. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  438. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  439. )
  440. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  441. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  442. }
  443. }
  444. }
  445. func autosense() async throws -> Autosens? {
  446. debug(.openAPS, "Start autosens")
  447. // Perform asynchronous calls in parallel
  448. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  449. async let carbs = fetchAndProcessCarbs()
  450. async let glucose = fetchAndProcessGlucose()
  451. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  452. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  453. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  454. // Await the results of asynchronous tasks
  455. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  456. parsePumpHistory(await pumpHistoryObjectIDs),
  457. carbs,
  458. glucose,
  459. getProfile,
  460. getBasalProfile,
  461. getTempTargets
  462. )
  463. // Autosense
  464. let autosenseResult = try await autosense(
  465. glucose: glucoseAsJSON,
  466. pumpHistory: pumpHistoryJSON,
  467. basalprofile: basalProfile,
  468. profile: profile,
  469. carbs: carbsAsJSON,
  470. temptargets: tempTargets
  471. )
  472. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  473. if var autosens = Autosens(from: autosenseResult) {
  474. autosens.timestamp = Date()
  475. storage.save(autosens, as: Settings.autosense)
  476. return autosens
  477. } else {
  478. return nil
  479. }
  480. }
  481. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  482. debug(.openAPS, "Start autotune")
  483. // Perform asynchronous calls in parallel
  484. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  485. async let carbs = fetchAndProcessCarbs()
  486. async let glucose = fetchAndProcessGlucose()
  487. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  488. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  489. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  490. // Await the results of asynchronous tasks
  491. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  492. parsePumpHistory(await pumpHistoryObjectIDs),
  493. carbs,
  494. glucose,
  495. getProfile,
  496. getPumpProfile,
  497. getPreviousAutotune
  498. )
  499. // Error need to be handled here because the function is not declared as throws
  500. do {
  501. // Autotune Prepare
  502. let autotunePreppedGlucose = try await autotunePrepare(
  503. pumphistory: pumpHistoryJSON,
  504. profile: profile,
  505. glucose: glucoseAsJSON,
  506. pumpprofile: pumpProfile,
  507. carbs: carbsAsJSON,
  508. categorizeUamAsBasal: categorizeUamAsBasal,
  509. tuneInsulinCurve: tuneInsulinCurve
  510. )
  511. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  512. // Autotune Run
  513. let autotuneResult = try await autotuneRun(
  514. autotunePreparedData: autotunePreppedGlucose,
  515. previousAutotuneResult: previousAutotune ?? profile,
  516. pumpProfile: pumpProfile
  517. )
  518. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  519. if let autotune = Autotune(from: autotuneResult) {
  520. storage.save(autotuneResult, as: Settings.autotune)
  521. return autotune
  522. } else {
  523. return nil
  524. }
  525. } catch {
  526. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  527. return nil
  528. }
  529. }
  530. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  531. debug(.openAPS, "Start makeProfiles")
  532. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  533. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  534. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  535. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  536. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  537. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  538. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  539. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  540. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  541. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  542. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  543. getPreferences,
  544. getPumpSettings,
  545. getBGTargets,
  546. getBasalProfile,
  547. getISF,
  548. getCR,
  549. getTempTargets,
  550. getModel,
  551. getAutotune,
  552. getFreeAPS
  553. )
  554. var adjustedPreferences = preferences
  555. if adjustedPreferences.isEmpty {
  556. adjustedPreferences = Preferences().rawJSON
  557. }
  558. do {
  559. // Pump Profile
  560. let pumpProfile = try await makeProfile(
  561. preferences: adjustedPreferences,
  562. pumpSettings: pumpSettings,
  563. bgTargets: bgTargets,
  564. basalProfile: basalProfile,
  565. isf: isf,
  566. carbRatio: cr,
  567. tempTargets: tempTargets,
  568. model: model,
  569. autotune: RawJSON.null,
  570. freeaps: freeaps
  571. )
  572. // Profile
  573. let profile = try await makeProfile(
  574. preferences: adjustedPreferences,
  575. pumpSettings: pumpSettings,
  576. bgTargets: bgTargets,
  577. basalProfile: basalProfile,
  578. isf: isf,
  579. carbRatio: cr,
  580. tempTargets: tempTargets,
  581. model: model,
  582. autotune: autotune.isEmpty ? .null : autotune,
  583. freeaps: freeaps
  584. )
  585. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  586. await storage.saveAsync(profile, as: Settings.profile)
  587. if let tunedProfile = Autotune(from: profile) {
  588. return tunedProfile
  589. } else {
  590. return nil
  591. }
  592. } catch {
  593. debug(
  594. .apsManager,
  595. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  596. )
  597. return nil
  598. }
  599. }
  600. // MARK: - Private
  601. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  602. await withCheckedContinuation { continuation in
  603. jsWorker.inCommonContext { worker in
  604. worker.evaluateBatch(scripts: [
  605. Script(name: Prepare.log),
  606. Script(name: Bundle.iob),
  607. Script(name: Prepare.iob)
  608. ])
  609. let result = worker.call(function: Function.generate, with: [
  610. pumphistory,
  611. profile,
  612. clock,
  613. autosens
  614. ])
  615. continuation.resume(returning: result)
  616. }
  617. }
  618. }
  619. private func meal(
  620. pumphistory: JSON,
  621. profile: JSON,
  622. basalProfile: JSON,
  623. clock: JSON,
  624. carbs: JSON,
  625. glucose: JSON
  626. ) async throws -> RawJSON {
  627. try await withCheckedThrowingContinuation { continuation in
  628. jsWorker.inCommonContext { worker in
  629. worker.evaluateBatch(scripts: [
  630. Script(name: Prepare.log),
  631. Script(name: Bundle.meal),
  632. Script(name: Prepare.meal)
  633. ])
  634. let result = worker.call(function: Function.generate, with: [
  635. pumphistory,
  636. profile,
  637. clock,
  638. glucose,
  639. basalProfile,
  640. carbs
  641. ])
  642. continuation.resume(returning: result)
  643. }
  644. }
  645. }
  646. private func autosense(
  647. glucose: JSON,
  648. pumpHistory: JSON,
  649. basalprofile: JSON,
  650. profile: JSON,
  651. carbs: JSON,
  652. temptargets: JSON
  653. ) async throws -> RawJSON {
  654. try await withCheckedThrowingContinuation { continuation in
  655. jsWorker.inCommonContext { worker in
  656. worker.evaluateBatch(scripts: [
  657. Script(name: Prepare.log),
  658. Script(name: Bundle.autosens),
  659. Script(name: Prepare.autosens)
  660. ])
  661. let result = worker.call(function: Function.generate, with: [
  662. glucose,
  663. pumpHistory,
  664. basalprofile,
  665. profile,
  666. carbs,
  667. temptargets
  668. ])
  669. continuation.resume(returning: result)
  670. }
  671. }
  672. }
  673. private func autotunePrepare(
  674. pumphistory: JSON,
  675. profile: JSON,
  676. glucose: JSON,
  677. pumpprofile: JSON,
  678. carbs: JSON,
  679. categorizeUamAsBasal: Bool,
  680. tuneInsulinCurve: Bool
  681. ) async throws -> RawJSON {
  682. try await withCheckedThrowingContinuation { continuation in
  683. jsWorker.inCommonContext { worker in
  684. worker.evaluateBatch(scripts: [
  685. Script(name: Prepare.log),
  686. Script(name: Bundle.autotunePrep),
  687. Script(name: Prepare.autotunePrep)
  688. ])
  689. let result = worker.call(function: Function.generate, with: [
  690. pumphistory,
  691. profile,
  692. glucose,
  693. pumpprofile,
  694. carbs,
  695. categorizeUamAsBasal,
  696. tuneInsulinCurve
  697. ])
  698. continuation.resume(returning: result)
  699. }
  700. }
  701. }
  702. private func autotuneRun(
  703. autotunePreparedData: JSON,
  704. previousAutotuneResult: JSON,
  705. pumpProfile: JSON
  706. ) async throws -> RawJSON {
  707. try await withCheckedThrowingContinuation { continuation in
  708. jsWorker.inCommonContext { worker in
  709. worker.evaluateBatch(scripts: [
  710. Script(name: Prepare.log),
  711. Script(name: Bundle.autotuneCore),
  712. Script(name: Prepare.autotuneCore)
  713. ])
  714. let result = worker.call(function: Function.generate, with: [
  715. autotunePreparedData,
  716. previousAutotuneResult,
  717. pumpProfile
  718. ])
  719. continuation.resume(returning: result)
  720. }
  721. }
  722. }
  723. private func determineBasal(
  724. glucose: JSON,
  725. currentTemp: JSON,
  726. iob: JSON,
  727. profile: JSON,
  728. autosens: JSON,
  729. meal: JSON,
  730. microBolusAllowed: Bool,
  731. reservoir: JSON,
  732. pumpHistory: JSON,
  733. preferences: JSON,
  734. basalProfile: JSON,
  735. oref2_variables: JSON
  736. ) async throws -> RawJSON {
  737. try await withCheckedThrowingContinuation { continuation in
  738. jsWorker.inCommonContext { worker in
  739. worker.evaluateBatch(scripts: [
  740. Script(name: Prepare.log),
  741. Script(name: Prepare.determineBasal),
  742. Script(name: Bundle.basalSetTemp),
  743. Script(name: Bundle.getLastGlucose),
  744. Script(name: Bundle.determineBasal)
  745. ])
  746. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  747. worker.evaluate(script: middleware)
  748. }
  749. let result = worker.call(function: Function.generate, with: [
  750. iob,
  751. currentTemp,
  752. glucose,
  753. profile,
  754. autosens,
  755. meal,
  756. microBolusAllowed,
  757. reservoir,
  758. Date(),
  759. pumpHistory,
  760. preferences,
  761. basalProfile,
  762. oref2_variables
  763. ])
  764. continuation.resume(returning: result)
  765. }
  766. }
  767. }
  768. private func exportDefaultPreferences() -> RawJSON {
  769. dispatchPrecondition(condition: .onQueue(processQueue))
  770. return jsWorker.inCommonContext { worker in
  771. worker.evaluateBatch(scripts: [
  772. Script(name: Prepare.log),
  773. Script(name: Bundle.profile),
  774. Script(name: Prepare.profile)
  775. ])
  776. return worker.call(function: Function.exportDefaults, with: [])
  777. }
  778. }
  779. private func makeProfile(
  780. preferences: JSON,
  781. pumpSettings: JSON,
  782. bgTargets: JSON,
  783. basalProfile: JSON,
  784. isf: JSON,
  785. carbRatio: JSON,
  786. tempTargets: JSON,
  787. model: JSON,
  788. autotune: JSON,
  789. freeaps: JSON
  790. ) async throws -> RawJSON {
  791. try await withCheckedThrowingContinuation { continuation in
  792. jsWorker.inCommonContext { worker in
  793. worker.evaluateBatch(scripts: [
  794. Script(name: Prepare.log),
  795. Script(name: Bundle.profile),
  796. Script(name: Prepare.profile)
  797. ])
  798. let result = worker.call(function: Function.generate, with: [
  799. pumpSettings,
  800. bgTargets,
  801. isf,
  802. basalProfile,
  803. preferences,
  804. carbRatio,
  805. tempTargets,
  806. model,
  807. autotune,
  808. freeaps
  809. ])
  810. continuation.resume(returning: result)
  811. }
  812. }
  813. }
  814. private func loadJSON(name: String) -> String {
  815. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  816. }
  817. private func loadFileFromStorage(name: String) -> RawJSON {
  818. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  819. }
  820. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  821. await withCheckedContinuation { continuation in
  822. DispatchQueue.global(qos: .userInitiated).async {
  823. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  824. continuation.resume(returning: result)
  825. }
  826. }
  827. }
  828. private func middlewareScript(name: String) -> Script? {
  829. if let body = storage.retrieveRaw(name) {
  830. return Script(name: "Middleware", body: body)
  831. }
  832. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  833. return Script(name: "Middleware", body: try! String(contentsOf: url))
  834. }
  835. return nil
  836. }
  837. static func defaults(for file: String) -> RawJSON {
  838. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  839. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  840. return ""
  841. }
  842. return (try? String(contentsOf: url)) ?? ""
  843. }
  844. func processAndSave(forecastData: [String: [Int]]) {
  845. let currentDate = Date()
  846. context.perform {
  847. for (type, values) in forecastData {
  848. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  849. }
  850. do {
  851. guard self.context.hasChanges else { return }
  852. try self.context.save()
  853. } catch {
  854. print(error.localizedDescription)
  855. }
  856. }
  857. }
  858. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  859. let forecast = Forecast(context: context)
  860. forecast.id = UUID()
  861. forecast.date = date
  862. forecast.type = type
  863. for (index, value) in values.enumerated() {
  864. let forecastValue = ForecastValue(context: context)
  865. forecastValue.value = Int32(value)
  866. forecastValue.index = Int32(index)
  867. forecastValue.forecast = forecast
  868. }
  869. }
  870. }