OpenAPS.swift 37 KB

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