OpenAPS.swift 36 KB

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