OpenAPS.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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(
  166. _ pumpHistoryObjectIDs: [NSManagedObjectID],
  167. simulatedBolusAmount: Decimal? = nil
  168. ) async -> String {
  169. // Return an empty JSON object if the list of object IDs is empty
  170. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  171. // Execute all operations on the background context
  172. return await context.perform {
  173. // Load and map pump events to DTOs
  174. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  175. // Optionally add the IOB as a DTO
  176. if let simulatedBolusAmount = simulatedBolusAmount {
  177. let simulatedBolusDTO = self.createSimulatedBolusDTO(simulatedBolusAmount: simulatedBolusAmount)
  178. dtos.insert(simulatedBolusDTO, at: 0)
  179. }
  180. // Convert the DTOs to JSON
  181. return self.jsonConverter.convertToJSON(dtos)
  182. }
  183. }
  184. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  185. // Load the pump events from the object IDs
  186. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  187. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  188. // Create the DTOs
  189. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  190. var eventDTOs: [PumpEventDTO] = []
  191. if let bolusDTO = event.toBolusDTOEnum() {
  192. eventDTOs.append(bolusDTO)
  193. }
  194. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  195. eventDTOs.append(tempBasalDurationDTO)
  196. }
  197. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  198. eventDTOs.append(tempBasalDTO)
  199. }
  200. if let pumpSuspendDTO = event.toPumpSuspendDTO() {
  201. eventDTOs.append(pumpSuspendDTO)
  202. }
  203. if let pumpResumeDTO = event.toPumpResumeDTO() {
  204. eventDTOs.append(pumpResumeDTO)
  205. }
  206. if let rewindDTO = event.toRewindDTO() {
  207. eventDTOs.append(rewindDTO)
  208. }
  209. if let primeDTO = event.toPrimeDTO() {
  210. eventDTOs.append(primeDTO)
  211. }
  212. return eventDTOs
  213. }
  214. return dtos
  215. }
  216. private func createSimulatedBolusDTO(simulatedBolusAmount: Decimal) -> PumpEventDTO {
  217. let oneSecondAgo = Calendar.current
  218. .date(
  219. byAdding: .second,
  220. value: -1,
  221. to: Date()
  222. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  223. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  224. let bolusDTO = BolusDTO(
  225. id: UUID().uuidString,
  226. timestamp: dateFormatted,
  227. amount: Double(simulatedBolusAmount),
  228. isExternal: false,
  229. isSMB: true,
  230. duration: 0,
  231. _type: "Bolus"
  232. )
  233. return .bolus(bolusDTO)
  234. }
  235. func determineBasal(
  236. currentTemp: TempBasal,
  237. clock: Date = Date(),
  238. simulatedCarbsAmount: Decimal? = nil,
  239. simulatedBolusAmount: Decimal? = nil,
  240. simulation: Bool = false
  241. ) async throws -> Determination? {
  242. debug(.openAPS, "Start determineBasal")
  243. // temp_basal
  244. let tempBasal = currentTemp.rawJSON
  245. // Perform asynchronous calls in parallel
  246. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  247. async let carbs = fetchAndProcessCarbs(additionalCarbs: simulatedCarbsAmount ?? 0)
  248. async let glucose = fetchAndProcessGlucose()
  249. async let oref2 = oref2()
  250. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  251. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  252. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  253. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  254. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  255. // Await the results of asynchronous tasks
  256. let (
  257. pumpHistoryJSON,
  258. carbsAsJSON,
  259. glucoseAsJSON,
  260. oref2_variables,
  261. profile,
  262. basalProfile,
  263. autosens,
  264. reservoir,
  265. preferences
  266. ) = await (
  267. parsePumpHistory(await pumpHistoryObjectIDs, simulatedBolusAmount: simulatedBolusAmount),
  268. carbs,
  269. glucose,
  270. oref2,
  271. profileAsync,
  272. basalAsync,
  273. autosenseAsync,
  274. reservoirAsync,
  275. preferencesAsync
  276. )
  277. // Meal calculation
  278. let meal = try await self.meal(
  279. pumphistory: pumpHistoryJSON,
  280. profile: profile,
  281. basalProfile: basalProfile,
  282. clock: clock,
  283. carbs: carbsAsJSON,
  284. glucose: glucoseAsJSON
  285. )
  286. // IOB calculation
  287. let iob = try await self.iob(
  288. pumphistory: pumpHistoryJSON,
  289. profile: profile,
  290. clock: clock,
  291. autosens: autosens.isEmpty ? .null : autosens
  292. )
  293. // TODO: refactor this to core data
  294. if !simulation {
  295. storage.save(iob, as: Monitor.iob)
  296. }
  297. // Determine basal
  298. let orefDetermination = try await determineBasal(
  299. glucose: glucoseAsJSON,
  300. currentTemp: tempBasal,
  301. iob: iob,
  302. profile: profile,
  303. autosens: autosens.isEmpty ? .null : autosens,
  304. meal: meal,
  305. microBolusAllowed: true,
  306. reservoir: reservoir,
  307. pumpHistory: pumpHistoryJSON,
  308. preferences: preferences,
  309. basalProfile: basalProfile,
  310. oref2_variables: oref2_variables
  311. )
  312. debug(.openAPS, "Determinated: \(orefDetermination)")
  313. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  314. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  315. // AAPS does it the same way! we'll follow their example!
  316. determination.timestamp = deliverAt
  317. if !simulation {
  318. // save to core data asynchronously
  319. await processDetermination(determination)
  320. }
  321. return determination
  322. } else {
  323. return nil
  324. }
  325. }
  326. func oref2() async -> RawJSON {
  327. await context.perform {
  328. // Retrieve user preferences
  329. let userPreferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  330. let weightPercentage = userPreferences?.weightPercentage ?? 1.0
  331. let maxSMBBasalMinutes = userPreferences?.maxSMBBasalMinutes ?? 30
  332. let maxUAMBasalMinutes = userPreferences?.maxUAMSMBBasalMinutes ?? 30
  333. // Fetch historical events for Total Daily Dose (TDD) calculation
  334. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  335. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  336. let historicalTDDData = self.fetchHistoricalTDDData(from: tenDaysAgo)
  337. // Fetch the last active Override
  338. let activeOverrides = self.fetchActiveOverrides()
  339. let isOverrideActive = activeOverrides.first?.enabled ?? false
  340. let overridePercentage = Decimal(activeOverrides.first?.percentage ?? 100)
  341. let isOverrideIndefinite = activeOverrides.first?.indefinite ?? true
  342. let disableSMBs = activeOverrides.first?.smbIsOff ?? false
  343. let overrideTargetBG = activeOverrides.first?.target?.decimalValue ?? 0
  344. // Calculate averages for Total Daily Dose (TDD)
  345. let totalTDD = historicalTDDData.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  346. let totalDaysCount = max(historicalTDDData.count, 1)
  347. // Fetch recent TDD data for the past two hours
  348. let recentTDDData = historicalTDDData.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  349. let recentDataCount = max(recentTDDData.count, 1)
  350. let recentTotalTDD = recentTDDData.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }
  351. .reduce(0, +)
  352. let currentTDD = historicalTDDData.last?["totalDailyDose"] as? Decimal ?? 0
  353. let averageTDDLastTwoHours = recentTotalTDD / Decimal(recentDataCount)
  354. let averageTDDLastTenDays = totalTDD / Decimal(totalDaysCount)
  355. let weightedTDD = weightPercentage * averageTDDLastTwoHours + (1 - weightPercentage) * averageTDDLastTenDays
  356. // Prepare Oref2 variables
  357. let oref2Data = Oref2_variables(
  358. average_total_data: currentTDD > 0 ? averageTDDLastTenDays : 0,
  359. weightedAverage: currentTDD > 0 ? weightedTDD : 1,
  360. past2hoursAverage: currentTDD > 0 ? averageTDDLastTwoHours : 0,
  361. date: Date(),
  362. overridePercentage: overridePercentage,
  363. useOverride: isOverrideActive,
  364. duration: activeOverrides.first?.duration?.decimalValue ?? 0,
  365. unlimited: isOverrideIndefinite,
  366. overrideTarget: overrideTargetBG,
  367. smbIsOff: disableSMBs,
  368. advancedSettings: activeOverrides.first?.advancedSettings ?? false,
  369. isfAndCr: activeOverrides.first?.isfAndCr ?? false,
  370. isf: activeOverrides.first?.isf ?? false,
  371. cr: activeOverrides.first?.cr ?? false,
  372. smbIsScheduledOff: activeOverrides.first?.smbIsScheduledOff ?? false,
  373. start: (activeOverrides.first?.start ?? 0) as Decimal,
  374. end: (activeOverrides.first?.end ?? 0) as Decimal,
  375. smbMinutes: activeOverrides.first?.smbMinutes?.decimalValue ?? maxSMBBasalMinutes,
  376. uamMinutes: activeOverrides.first?.uamMinutes?.decimalValue ?? maxUAMBasalMinutes
  377. )
  378. // Save and return the Oref2 variables
  379. self.storage.save(oref2Data, as: OpenAPS.Monitor.oref2_variables)
  380. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  381. }
  382. }
  383. func autosense() async throws -> Autosens? {
  384. debug(.openAPS, "Start autosens")
  385. // Perform asynchronous calls in parallel
  386. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  387. async let carbs = fetchAndProcessCarbs()
  388. async let glucose = fetchAndProcessGlucose()
  389. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  390. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  391. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  392. // Await the results of asynchronous tasks
  393. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  394. parsePumpHistory(await pumpHistoryObjectIDs),
  395. carbs,
  396. glucose,
  397. getProfile,
  398. getBasalProfile,
  399. getTempTargets
  400. )
  401. // Autosense
  402. let autosenseResult = try await autosense(
  403. glucose: glucoseAsJSON,
  404. pumpHistory: pumpHistoryJSON,
  405. basalprofile: basalProfile,
  406. profile: profile,
  407. carbs: carbsAsJSON,
  408. temptargets: tempTargets
  409. )
  410. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  411. if var autosens = Autosens(from: autosenseResult) {
  412. autosens.timestamp = Date()
  413. await storage.saveAsync(autosens, as: Settings.autosense)
  414. return autosens
  415. } else {
  416. return nil
  417. }
  418. }
  419. func createProfiles() async {
  420. debug(.openAPS, "Start creating pump profile and user profile")
  421. // Load required settings and profiles asynchronously
  422. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  423. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  424. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  425. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  426. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  427. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  428. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  429. async let getTrioSettingDefaults = loadFileFromStorageAsync(name: Trio.settings)
  430. let (pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, trioSettings) = await (
  431. getPumpSettings,
  432. getBGTargets,
  433. getBasalProfile,
  434. getISF,
  435. getCR,
  436. getTempTargets,
  437. getModel,
  438. getTrioSettingDefaults
  439. )
  440. // Retrieve user preferences, or set defaults if not available
  441. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
  442. let defaultHalfBasalTarget = preferences.halfBasalExerciseTarget
  443. var adjustedPreferences = preferences
  444. // Check for active Temp Targets and adjust HBT if necessary
  445. await context.perform {
  446. // Check if a Temp Target is active and if its HBT differs from user preferences
  447. if let activeTempTarget = self.fetchActiveTempTargets().first,
  448. activeTempTarget.enabled,
  449. let activeHBT = activeTempTarget.halfBasalTarget?.decimalValue,
  450. activeHBT != defaultHalfBasalTarget
  451. {
  452. // Overwrite the HBT in preferences
  453. adjustedPreferences.halfBasalExerciseTarget = activeHBT
  454. debug(.openAPS, "Updated halfBasalExerciseTarget to active Temp Target value: \(activeHBT)")
  455. }
  456. }
  457. do {
  458. let pumpProfile = try await makeProfile(
  459. preferences: adjustedPreferences,
  460. pumpSettings: pumpSettings,
  461. bgTargets: bgTargets,
  462. basalProfile: basalProfile,
  463. isf: isf,
  464. carbRatio: cr,
  465. tempTargets: tempTargets,
  466. model: model,
  467. autotune: RawJSON.null,
  468. trioData: trioSettings
  469. )
  470. let profile = try await makeProfile(
  471. preferences: adjustedPreferences,
  472. pumpSettings: pumpSettings,
  473. bgTargets: bgTargets,
  474. basalProfile: basalProfile,
  475. isf: isf,
  476. carbRatio: cr,
  477. tempTargets: tempTargets,
  478. model: model,
  479. autotune: RawJSON.null,
  480. trioData: trioSettings
  481. )
  482. // Save the profiles
  483. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  484. await storage.saveAsync(profile, as: Settings.profile)
  485. } catch {
  486. debug(
  487. .apsManager,
  488. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to create pump profile and normal profile: \(error)"
  489. )
  490. }
  491. }
  492. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  493. await withCheckedContinuation { continuation in
  494. jsWorker.inCommonContext { worker in
  495. worker.evaluateBatch(scripts: [
  496. Script(name: Prepare.log),
  497. Script(name: Bundle.iob),
  498. Script(name: Prepare.iob)
  499. ])
  500. let result = worker.call(function: Function.generate, with: [
  501. pumphistory,
  502. profile,
  503. clock,
  504. autosens
  505. ])
  506. continuation.resume(returning: result)
  507. }
  508. }
  509. }
  510. private func meal(
  511. pumphistory: JSON,
  512. profile: JSON,
  513. basalProfile: JSON,
  514. clock: JSON,
  515. carbs: JSON,
  516. glucose: JSON
  517. ) async throws -> RawJSON {
  518. try await withCheckedThrowingContinuation { continuation in
  519. jsWorker.inCommonContext { worker in
  520. worker.evaluateBatch(scripts: [
  521. Script(name: Prepare.log),
  522. Script(name: Bundle.meal),
  523. Script(name: Prepare.meal)
  524. ])
  525. let result = worker.call(function: Function.generate, with: [
  526. pumphistory,
  527. profile,
  528. clock,
  529. glucose,
  530. basalProfile,
  531. carbs
  532. ])
  533. continuation.resume(returning: result)
  534. }
  535. }
  536. }
  537. private func autosense(
  538. glucose: JSON,
  539. pumpHistory: JSON,
  540. basalprofile: JSON,
  541. profile: JSON,
  542. carbs: JSON,
  543. temptargets: JSON
  544. ) async throws -> RawJSON {
  545. try await withCheckedThrowingContinuation { continuation in
  546. jsWorker.inCommonContext { worker in
  547. worker.evaluateBatch(scripts: [
  548. Script(name: Prepare.log),
  549. Script(name: Bundle.autosens),
  550. Script(name: Prepare.autosens)
  551. ])
  552. let result = worker.call(function: Function.generate, with: [
  553. glucose,
  554. pumpHistory,
  555. basalprofile,
  556. profile,
  557. carbs,
  558. temptargets
  559. ])
  560. continuation.resume(returning: result)
  561. }
  562. }
  563. }
  564. private func determineBasal(
  565. glucose: JSON,
  566. currentTemp: JSON,
  567. iob: JSON,
  568. profile: JSON,
  569. autosens: JSON,
  570. meal: JSON,
  571. microBolusAllowed: Bool,
  572. reservoir: JSON,
  573. pumpHistory: JSON,
  574. preferences: JSON,
  575. basalProfile: JSON,
  576. oref2_variables: JSON
  577. ) async throws -> RawJSON {
  578. try await withCheckedThrowingContinuation { continuation in
  579. jsWorker.inCommonContext { worker in
  580. worker.evaluateBatch(scripts: [
  581. Script(name: Prepare.log),
  582. Script(name: Prepare.determineBasal),
  583. Script(name: Bundle.basalSetTemp),
  584. Script(name: Bundle.getLastGlucose),
  585. Script(name: Bundle.determineBasal)
  586. ])
  587. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  588. worker.evaluate(script: middleware)
  589. }
  590. let result = worker.call(function: Function.generate, with: [
  591. iob,
  592. currentTemp,
  593. glucose,
  594. profile,
  595. autosens,
  596. meal,
  597. microBolusAllowed,
  598. reservoir,
  599. Date(),
  600. pumpHistory,
  601. preferences,
  602. basalProfile,
  603. oref2_variables
  604. ])
  605. continuation.resume(returning: result)
  606. }
  607. }
  608. }
  609. private func exportDefaultPreferences() -> RawJSON {
  610. dispatchPrecondition(condition: .onQueue(processQueue))
  611. return jsWorker.inCommonContext { worker in
  612. worker.evaluateBatch(scripts: [
  613. Script(name: Prepare.log),
  614. Script(name: Bundle.profile),
  615. Script(name: Prepare.profile)
  616. ])
  617. return worker.call(function: Function.exportDefaults, with: [])
  618. }
  619. }
  620. private func makeProfile(
  621. preferences: JSON,
  622. pumpSettings: JSON,
  623. bgTargets: JSON,
  624. basalProfile: JSON,
  625. isf: JSON,
  626. carbRatio: JSON,
  627. tempTargets: JSON,
  628. model: JSON,
  629. autotune: JSON,
  630. trioData: JSON
  631. ) async throws -> RawJSON {
  632. try await withCheckedThrowingContinuation { continuation in
  633. jsWorker.inCommonContext { worker in
  634. worker.evaluateBatch(scripts: [
  635. Script(name: Prepare.log),
  636. Script(name: Bundle.profile),
  637. Script(name: Prepare.profile)
  638. ])
  639. let result = worker.call(function: Function.generate, with: [
  640. pumpSettings,
  641. bgTargets,
  642. isf,
  643. basalProfile,
  644. preferences,
  645. carbRatio,
  646. tempTargets,
  647. model,
  648. autotune,
  649. trioData
  650. ])
  651. continuation.resume(returning: result)
  652. }
  653. }
  654. }
  655. private func loadJSON(name: String) -> String {
  656. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  657. }
  658. private func loadFileFromStorage(name: String) -> RawJSON {
  659. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  660. }
  661. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  662. await withCheckedContinuation { continuation in
  663. DispatchQueue.global(qos: .userInitiated).async {
  664. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  665. continuation.resume(returning: result)
  666. }
  667. }
  668. }
  669. private func middlewareScript(name: String) -> Script? {
  670. if let body = storage.retrieveRaw(name) {
  671. return Script(name: name, body: body)
  672. }
  673. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  674. return Script(name: name, body: try! String(contentsOf: url))
  675. }
  676. return nil
  677. }
  678. static func defaults(for file: String) -> RawJSON {
  679. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  680. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  681. return ""
  682. }
  683. return (try? String(contentsOf: url)) ?? ""
  684. }
  685. func processAndSave(forecastData: [String: [Int]]) {
  686. let currentDate = Date()
  687. context.perform {
  688. for (type, values) in forecastData {
  689. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  690. }
  691. do {
  692. guard self.context.hasChanges else { return }
  693. try self.context.save()
  694. } catch {
  695. print(error.localizedDescription)
  696. }
  697. }
  698. }
  699. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  700. let forecast = Forecast(context: context)
  701. forecast.id = UUID()
  702. forecast.date = date
  703. forecast.type = type
  704. for (index, value) in values.enumerated() {
  705. let forecastValue = ForecastValue(context: context)
  706. forecastValue.value = Int32(value)
  707. forecastValue.index = Int32(index)
  708. forecastValue.forecast = forecast
  709. }
  710. }
  711. }
  712. // Non-Async fetch methods for oref2
  713. extension OpenAPS {
  714. func fetchActiveTempTargets() -> [TempTargetStored] {
  715. CoreDataStack.shared.fetchEntities(
  716. ofType: TempTargetStored.self,
  717. onContext: context,
  718. predicate: NSPredicate.lastActiveTempTarget,
  719. key: "date",
  720. ascending: false,
  721. fetchLimit: 1
  722. ) as? [TempTargetStored] ?? []
  723. }
  724. func fetchActiveOverrides() -> [OverrideStored] {
  725. CoreDataStack.shared.fetchEntities(
  726. ofType: OverrideStored.self,
  727. onContext: context,
  728. predicate: NSPredicate.lastActiveOverride,
  729. key: "date",
  730. ascending: false,
  731. fetchLimit: 1
  732. ) as? [OverrideStored] ?? []
  733. }
  734. func fetchHistoricalTDDData(from date: Date) -> [[String: Any]] {
  735. CoreDataStack.shared.fetchEntities(
  736. ofType: OrefDetermination.self,
  737. onContext: context,
  738. predicate: NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", date as NSDate),
  739. key: "timestamp",
  740. ascending: true,
  741. propertiesToFetch: ["timestamp", "totalDailyDose"]
  742. ) as? [[String: Any]] ?? []
  743. }
  744. }