OpenAPS.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  372. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  373. )
  374. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  375. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  376. } else {
  377. let averages = Oref2_variables(
  378. average_total_data: 0,
  379. weightedAverage: 1,
  380. past2hoursAverage: 0,
  381. date: Date(),
  382. isEnabled: temptargetActive,
  383. presetActive: isPercentageEnabled,
  384. overridePercentage: overridePercentage,
  385. useOverride: useOverride,
  386. duration: duration,
  387. unlimited: unlimited,
  388. hbt: hbt_,
  389. overrideTarget: overrideTarget,
  390. smbIsOff: disableSMBs,
  391. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  392. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  393. isf: overrideArray.first?.isf ?? false,
  394. cr: overrideArray.first?.cr ?? false,
  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. }