OpenAPS.swift 34 KB

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