OpenAPS.swift 37 KB

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