OpenAPS.swift 34 KB

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