OpenAPS.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 createInitialProfiles() 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. )
  455. let profile = try await makeProfile(
  456. preferences: adjustedPreferences,
  457. pumpSettings: pumpSettings,
  458. bgTargets: bgTargets,
  459. basalProfile: basalProfile,
  460. isf: isf,
  461. carbRatio: cr,
  462. tempTargets: tempTargets,
  463. model: model,
  464. autotune: RawJSON.null,
  465. freeaps: freeaps
  466. )
  467. // Save the profiles
  468. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  469. await storage.saveAsync(profile, as: Settings.profile)
  470. } catch {
  471. debug(
  472. .apsManager,
  473. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to create pump profile and normal profile: \(error)"
  474. )
  475. }
  476. }
  477. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  478. await withCheckedContinuation { continuation in
  479. jsWorker.inCommonContext { worker in
  480. worker.evaluateBatch(scripts: [
  481. Script(name: Prepare.log),
  482. Script(name: Bundle.iob),
  483. Script(name: Prepare.iob)
  484. ])
  485. let result = worker.call(function: Function.generate, with: [
  486. pumphistory,
  487. profile,
  488. clock,
  489. autosens
  490. ])
  491. continuation.resume(returning: result)
  492. }
  493. }
  494. }
  495. private func meal(
  496. pumphistory: JSON,
  497. profile: JSON,
  498. basalProfile: JSON,
  499. clock: JSON,
  500. carbs: JSON,
  501. glucose: JSON
  502. ) async throws -> RawJSON {
  503. try await withCheckedThrowingContinuation { continuation in
  504. jsWorker.inCommonContext { worker in
  505. worker.evaluateBatch(scripts: [
  506. Script(name: Prepare.log),
  507. Script(name: Bundle.meal),
  508. Script(name: Prepare.meal)
  509. ])
  510. let result = worker.call(function: Function.generate, with: [
  511. pumphistory,
  512. profile,
  513. clock,
  514. glucose,
  515. basalProfile,
  516. carbs
  517. ])
  518. continuation.resume(returning: result)
  519. }
  520. }
  521. }
  522. private func autosense(
  523. glucose: JSON,
  524. pumpHistory: JSON,
  525. basalprofile: JSON,
  526. profile: JSON,
  527. carbs: JSON,
  528. temptargets: JSON
  529. ) async throws -> RawJSON {
  530. try await withCheckedThrowingContinuation { continuation in
  531. jsWorker.inCommonContext { worker in
  532. worker.evaluateBatch(scripts: [
  533. Script(name: Prepare.log),
  534. Script(name: Bundle.autosens),
  535. Script(name: Prepare.autosens)
  536. ])
  537. let result = worker.call(function: Function.generate, with: [
  538. glucose,
  539. pumpHistory,
  540. basalprofile,
  541. profile,
  542. carbs,
  543. temptargets
  544. ])
  545. continuation.resume(returning: result)
  546. }
  547. }
  548. }
  549. private func determineBasal(
  550. glucose: JSON,
  551. currentTemp: JSON,
  552. iob: JSON,
  553. profile: JSON,
  554. autosens: JSON,
  555. meal: JSON,
  556. microBolusAllowed: Bool,
  557. reservoir: JSON,
  558. pumpHistory: JSON,
  559. preferences: JSON,
  560. basalProfile: JSON,
  561. oref2_variables: JSON
  562. ) async throws -> RawJSON {
  563. try await withCheckedThrowingContinuation { continuation in
  564. jsWorker.inCommonContext { worker in
  565. worker.evaluateBatch(scripts: [
  566. Script(name: Prepare.log),
  567. Script(name: Prepare.determineBasal),
  568. Script(name: Bundle.basalSetTemp),
  569. Script(name: Bundle.getLastGlucose),
  570. Script(name: Bundle.determineBasal)
  571. ])
  572. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  573. worker.evaluate(script: middleware)
  574. }
  575. let result = worker.call(function: Function.generate, with: [
  576. iob,
  577. currentTemp,
  578. glucose,
  579. profile,
  580. autosens,
  581. meal,
  582. microBolusAllowed,
  583. reservoir,
  584. Date(),
  585. pumpHistory,
  586. preferences,
  587. basalProfile,
  588. oref2_variables
  589. ])
  590. continuation.resume(returning: result)
  591. }
  592. }
  593. }
  594. private func exportDefaultPreferences() -> RawJSON {
  595. dispatchPrecondition(condition: .onQueue(processQueue))
  596. return jsWorker.inCommonContext { worker in
  597. worker.evaluateBatch(scripts: [
  598. Script(name: Prepare.log),
  599. Script(name: Bundle.profile),
  600. Script(name: Prepare.profile)
  601. ])
  602. return worker.call(function: Function.exportDefaults, with: [])
  603. }
  604. }
  605. private func makeProfile(
  606. preferences: JSON,
  607. pumpSettings: JSON,
  608. bgTargets: JSON,
  609. basalProfile: JSON,
  610. isf: JSON,
  611. carbRatio: JSON,
  612. tempTargets: JSON,
  613. model: JSON,
  614. autotune: JSON,
  615. freeaps: JSON
  616. ) async throws -> RawJSON {
  617. try await withCheckedThrowingContinuation { continuation in
  618. jsWorker.inCommonContext { worker in
  619. worker.evaluateBatch(scripts: [
  620. Script(name: Prepare.log),
  621. Script(name: Bundle.profile),
  622. Script(name: Prepare.profile)
  623. ])
  624. let result = worker.call(function: Function.generate, with: [
  625. pumpSettings,
  626. bgTargets,
  627. isf,
  628. basalProfile,
  629. preferences,
  630. carbRatio,
  631. tempTargets,
  632. model,
  633. autotune,
  634. freeaps
  635. ])
  636. continuation.resume(returning: result)
  637. }
  638. }
  639. }
  640. private func loadJSON(name: String) -> String {
  641. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  642. }
  643. private func loadFileFromStorage(name: String) -> RawJSON {
  644. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  645. }
  646. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  647. await withCheckedContinuation { continuation in
  648. DispatchQueue.global(qos: .userInitiated).async {
  649. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  650. continuation.resume(returning: result)
  651. }
  652. }
  653. }
  654. private func middlewareScript(name: String) -> Script? {
  655. if let body = storage.retrieveRaw(name) {
  656. return Script(name: name, body: body)
  657. }
  658. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  659. return Script(name: name, body: try! String(contentsOf: url))
  660. }
  661. return nil
  662. }
  663. static func defaults(for file: String) -> RawJSON {
  664. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  665. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  666. return ""
  667. }
  668. return (try? String(contentsOf: url)) ?? ""
  669. }
  670. func processAndSave(forecastData: [String: [Int]]) {
  671. let currentDate = Date()
  672. context.perform {
  673. for (type, values) in forecastData {
  674. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  675. }
  676. do {
  677. guard self.context.hasChanges else { return }
  678. try self.context.save()
  679. } catch {
  680. print(error.localizedDescription)
  681. }
  682. }
  683. }
  684. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  685. let forecast = Forecast(context: context)
  686. forecast.id = UUID()
  687. forecast.date = date
  688. forecast.type = type
  689. for (index, value) in values.enumerated() {
  690. let forecastValue = ForecastValue(context: context)
  691. forecastValue.value = Int32(value)
  692. forecastValue.index = Int32(index)
  693. forecastValue.forecast = forecast
  694. }
  695. }
  696. }
  697. // Non-Async fetch methods for oref2
  698. extension OpenAPS {
  699. func fetchActiveTempTargets() -> [TempTargetStored] {
  700. CoreDataStack.shared.fetchEntities(
  701. ofType: TempTargetStored.self,
  702. onContext: context,
  703. predicate: NSPredicate.lastActiveTempTarget,
  704. key: "date",
  705. ascending: false,
  706. fetchLimit: 1
  707. ) as? [TempTargetStored] ?? []
  708. }
  709. func fetchActiveOverrides() -> [OverrideStored] {
  710. CoreDataStack.shared.fetchEntities(
  711. ofType: OverrideStored.self,
  712. onContext: context,
  713. predicate: NSPredicate.lastActiveOverride,
  714. key: "date",
  715. ascending: false,
  716. fetchLimit: 1
  717. ) as? [OverrideStored] ?? []
  718. }
  719. func fetchHistoricalTDDData(from date: Date) -> [[String: Any]] {
  720. CoreDataStack.shared.fetchEntities(
  721. ofType: OrefDetermination.self,
  722. onContext: context,
  723. predicate: NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", date as NSDate),
  724. key: "timestamp",
  725. ascending: true,
  726. propertiesToFetch: ["timestamp", "totalDailyDose"]
  727. ) as? [[String: Any]] ?? []
  728. }
  729. }