OpenAPS.swift 37 KB

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