OpenAPS.swift 33 KB

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