OpenAPS.swift 37 KB

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