OpenAPS.swift 34 KB

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