OpenAPS.swift 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. // After that check for changes in iob and cob and if there are any post a custom Notification
  79. /// this is currently used to update Live Activity so that it stays up to date and not one loop cycle behind
  80. await checkForCobIobUpdate(determination)
  81. }
  82. func checkForCobIobUpdate(_ determination: Determination) async {
  83. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  84. ofType: OrefDetermination.self,
  85. onContext: context,
  86. predicate: NSPredicate.predicateFor30MinAgoForDetermination,
  87. key: "deliverAt",
  88. ascending: false,
  89. fetchLimit: 2
  90. )
  91. guard let previousDeterminations = results as? [OrefDetermination] else {
  92. return
  93. }
  94. // We need to get the second last Determination for this comparison because we have saved the current Determination already to Core Data
  95. if let previousDetermination = previousDeterminations.dropFirst().first {
  96. let iobChanged = previousDetermination.iob != decimalToNSDecimalNumber(determination.iob)
  97. let cobChanged = previousDetermination.cob != Int16(Int(determination.cob ?? 0))
  98. if iobChanged || cobChanged {
  99. Foundation.NotificationCenter.default.post(name: .didUpdateCobIob, object: nil)
  100. }
  101. }
  102. }
  103. func attemptToSaveContext() async {
  104. await context.perform {
  105. do {
  106. guard self.context.hasChanges else { return }
  107. try self.context.save()
  108. } catch {
  109. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  110. }
  111. }
  112. }
  113. // fetch glucose to pass it to the meal function and to determine basal
  114. private func fetchAndProcessGlucose() async -> String {
  115. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  116. ofType: GlucoseStored.self,
  117. onContext: context,
  118. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  119. key: "date",
  120. ascending: false,
  121. fetchLimit: 72,
  122. batchSize: 24
  123. )
  124. guard let glucoseResults = results as? [GlucoseStored] else {
  125. return ""
  126. }
  127. return await context.perform {
  128. // convert to JSON
  129. return self.jsonConverter.convertToJSON(glucoseResults)
  130. }
  131. }
  132. private func fetchAndProcessCarbs(additionalCarbs: Decimal? = nil) async -> String {
  133. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  134. ofType: CarbEntryStored.self,
  135. onContext: context,
  136. predicate: NSPredicate.predicateForOneDayAgo,
  137. key: "date",
  138. ascending: false
  139. )
  140. guard let carbResults = results as? [CarbEntryStored] else {
  141. return ""
  142. }
  143. let json = await context.perform {
  144. var jsonArray = self.jsonConverter.convertToJSON(carbResults)
  145. if let additionalCarbs = additionalCarbs {
  146. let additionalEntry = [
  147. "carbs": Double(additionalCarbs),
  148. "actualDate": ISO8601DateFormatter().string(from: Date()),
  149. "id": UUID().uuidString,
  150. "note": NSNull(),
  151. "protein": 0,
  152. "created_at": ISO8601DateFormatter().string(from: Date()),
  153. "isFPU": false,
  154. "fat": 0,
  155. "enteredBy": "Trio"
  156. ] as [String: Any]
  157. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  158. if let jsonData = jsonArray.data(using: .utf8) {
  159. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  160. jsonList?.append(additionalEntry)
  161. // Convert back to JSON string
  162. if let updatedJsonData = try? JSONSerialization
  163. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  164. {
  165. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  166. }
  167. }
  168. }
  169. return jsonArray
  170. }
  171. return json
  172. }
  173. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  174. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  175. ofType: PumpEventStored.self,
  176. onContext: context,
  177. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  178. key: "timestamp",
  179. ascending: false,
  180. batchSize: 50
  181. )
  182. guard let pumpEventResults = results as? [PumpEventStored] else {
  183. return nil
  184. }
  185. return await context.perform {
  186. return pumpEventResults.map(\.objectID)
  187. }
  188. }
  189. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID], iob: Decimal? = nil) async -> String {
  190. // Return an empty JSON object if the list of object IDs is empty
  191. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  192. // Execute all operations on the background context
  193. return await context.perform {
  194. // Load and map pump events to DTOs
  195. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  196. // Optionally add the IOB as a DTO
  197. if let iob = iob {
  198. let iobDTO = self.createIOBDTO(iob: iob)
  199. dtos.insert(iobDTO, at: 0)
  200. }
  201. // Convert the DTOs to JSON
  202. return self.jsonConverter.convertToJSON(dtos)
  203. }
  204. }
  205. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  206. // Load the pump events from the object IDs
  207. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  208. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  209. // Create the DTOs
  210. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  211. var eventDTOs: [PumpEventDTO] = []
  212. if let bolusDTO = event.toBolusDTOEnum() {
  213. eventDTOs.append(bolusDTO)
  214. }
  215. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  216. eventDTOs.append(tempBasalDurationDTO)
  217. }
  218. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  219. eventDTOs.append(tempBasalDTO)
  220. }
  221. return eventDTOs
  222. }
  223. return dtos
  224. }
  225. private func createIOBDTO(iob: Decimal) -> PumpEventDTO {
  226. let oneSecondAgo = Calendar.current
  227. .date(
  228. byAdding: .second,
  229. value: -1,
  230. to: Date()
  231. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  232. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  233. let bolusDTO = BolusDTO(
  234. id: UUID().uuidString,
  235. timestamp: dateFormatted,
  236. amount: Double(iob),
  237. isExternal: false,
  238. isSMB: true,
  239. duration: 0,
  240. _type: "Bolus"
  241. )
  242. return .bolus(bolusDTO)
  243. }
  244. func determineBasal(
  245. currentTemp: TempBasal,
  246. clock: Date = Date(),
  247. carbs: Decimal? = nil,
  248. iob: Decimal? = nil,
  249. simulation: Bool = false
  250. ) async throws -> Determination? {
  251. debug(.openAPS, "Start determineBasal")
  252. // temp_basal
  253. let tempBasal = currentTemp.rawJSON
  254. // Perform asynchronous calls in parallel
  255. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  256. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs ?? 0)
  257. async let glucose = fetchAndProcessGlucose()
  258. async let oref2 = oref2()
  259. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  260. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  261. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  262. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  263. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  264. // Await the results of asynchronous tasks
  265. let (
  266. pumpHistoryJSON,
  267. carbsAsJSON,
  268. glucoseAsJSON,
  269. oref2_variables,
  270. profile,
  271. basalProfile,
  272. autosens,
  273. reservoir,
  274. preferences
  275. ) = await (
  276. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  277. carbs,
  278. glucose,
  279. oref2,
  280. profileAsync,
  281. basalAsync,
  282. autosenseAsync,
  283. reservoirAsync,
  284. preferencesAsync
  285. )
  286. // Meal calculation
  287. let meal = try await self.meal(
  288. pumphistory: pumpHistoryJSON,
  289. profile: profile,
  290. basalProfile: basalProfile,
  291. clock: clock,
  292. carbs: carbsAsJSON,
  293. glucose: glucoseAsJSON
  294. )
  295. // IOB calculation
  296. let iob = try await self.iob(
  297. pumphistory: pumpHistoryJSON,
  298. profile: profile,
  299. clock: clock,
  300. autosens: autosens.isEmpty ? .null : autosens
  301. )
  302. // TODO: refactor this to core data
  303. if !simulation {
  304. storage.save(iob, as: Monitor.iob)
  305. }
  306. // Determine basal
  307. let orefDetermination = try await determineBasal(
  308. glucose: glucoseAsJSON,
  309. currentTemp: tempBasal,
  310. iob: iob,
  311. profile: profile,
  312. autosens: autosens.isEmpty ? .null : autosens,
  313. meal: meal,
  314. microBolusAllowed: true,
  315. reservoir: reservoir,
  316. pumpHistory: pumpHistoryJSON,
  317. preferences: preferences,
  318. basalProfile: basalProfile,
  319. oref2_variables: oref2_variables
  320. )
  321. debug(.openAPS, "Determinated: \(orefDetermination)")
  322. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  323. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  324. // AAPS does it the same way! we'll follow their example!
  325. determination.timestamp = deliverAt
  326. if !simulation {
  327. // save to core data asynchronously
  328. await processDetermination(determination)
  329. }
  330. return determination
  331. } else {
  332. return nil
  333. }
  334. }
  335. func oref2() async -> RawJSON {
  336. await context.perform {
  337. // Retrieve preferences
  338. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  339. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  340. let wp = preferences?.weightPercentage ?? 1.0
  341. let smbMinutes = preferences?.maxSMBBasalMinutes ?? 30
  342. let uamMinutes = preferences?.maxUAMSMBBasalMinutes ?? 30
  343. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  344. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  345. // Fetch unique events for TDD calculation
  346. var uniqueEvents = [[String: Any]]()
  347. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  348. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  349. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  350. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  351. requestTDD.sortDescriptors = [sortTDD]
  352. requestTDD.resultType = .dictionaryResultType
  353. do {
  354. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  355. uniqueEvents = fetchedResults
  356. }
  357. } catch {
  358. debugPrint("Failed to fetch TDD Data")
  359. }
  360. // Get the last active Override
  361. var overrideArray = [OverrideStored]()
  362. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  363. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  364. requestOverrides.sortDescriptors = [sortOverride]
  365. requestOverrides.predicate = NSPredicate.lastActiveOverride
  366. requestOverrides.fetchLimit = 1
  367. try? overrideArray = self.context.fetch(requestOverrides)
  368. // Get the last active Temp Target
  369. var tempTargetsArray = [TempTargetStored]()
  370. let requestTempTargets = TempTargetStored.fetchRequest() as NSFetchRequest<TempTargetStored>
  371. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  372. requestTempTargets.sortDescriptors = [sortTT]
  373. requestTempTargets.predicate = NSPredicate.lastActiveTempTarget
  374. requestTempTargets.fetchLimit = 1
  375. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  376. var isTemptargetActive = tempTargetsArray.first?.enabled ?? false
  377. // Calculate averages for TDD
  378. let total = uniqueEvents.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  379. var indices = uniqueEvents.count
  380. // Fetch data for the past two hours
  381. let twoHoursArray = uniqueEvents.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  382. var nrOfIndices = twoHoursArray.count
  383. let totalAmount = twoHoursArray.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  384. var useOverride = overrideArray.first?.enabled ?? false
  385. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  386. var unlimited = overrideArray.first?.indefinite ?? true
  387. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  388. let currentTDD = uniqueEvents.last?["totalDailyDose"] as? Decimal ?? 0
  389. if indices == 0 { indices = 1 }
  390. if nrOfIndices == 0 { nrOfIndices = 1 }
  391. let average2hours = totalAmount / Decimal(nrOfIndices)
  392. let average14 = total / Decimal(indices)
  393. let weightedAverage = wp * average2hours + (1 - wp) * average14
  394. var duration: Decimal = 0
  395. var overrideTarget: Decimal = 0
  396. // Handle Overrides
  397. if useOverride {
  398. duration = overrideArray.first?.duration?.decimalValue ?? 0
  399. overrideTarget = overrideArray.first?.target?.decimalValue ?? 0
  400. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  401. let addedMinutes = Int(truncating: overrideArray.first?.duration ?? 0)
  402. let date = overrideArray.first?.date ?? Date()
  403. let overrideEndTime = date.addingTimeInterval(Double(addedMinutes) * 60)
  404. if overrideEndTime < Date(), !unlimited {
  405. // Override has expired
  406. useOverride = false
  407. let saveToCoreData = OverrideStored(context: self.context)
  408. saveToCoreData.enabled = false
  409. saveToCoreData.date = Date()
  410. saveToCoreData.duration = 0
  411. saveToCoreData.indefinite = false
  412. saveToCoreData.percentage = 100
  413. do {
  414. guard self.context.hasChanges else { return "{}" }
  415. try self.context.save()
  416. } catch {
  417. print(error.localizedDescription)
  418. }
  419. }
  420. }
  421. if !useOverride {
  422. // Reset to default values if no override is active
  423. unlimited = true
  424. overridePercentage = 100
  425. duration = 0
  426. overrideTarget = 0
  427. disableSMBs = false
  428. }
  429. // Temp Target Handling
  430. if isTemptargetActive {
  431. if let tempTarget = tempTargetsArray.first {
  432. let tempDuration = tempTarget.duration?.doubleValue ?? 0
  433. let targetValue = tempTarget.target?.doubleValue ?? Double(truncating: hbt_ as NSNumber)
  434. let startDate = tempTarget.date ?? Date()
  435. let tempTargetEndTime = startDate.addingTimeInterval(tempDuration * 60)
  436. let timeRemaining = tempTargetEndTime.timeIntervalSinceNow / 60 // Time remaining in minutes
  437. if timeRemaining > 0 {
  438. hbt_ = Decimal(targetValue)
  439. isTemptargetActive = true
  440. } else {
  441. isTemptargetActive = false
  442. }
  443. }
  444. }
  445. // Prepare Oref2 variables
  446. let averages = Oref2_variables(
  447. average_total_data: currentTDD > 0 ? average14 : 0,
  448. weightedAverage: currentTDD > 0 ? weightedAverage : 1,
  449. past2hoursAverage: currentTDD > 0 ? average2hours : 0,
  450. date: Date(),
  451. isEnabled: isTemptargetActive,
  452. presetActive: isTemptargetActive,
  453. overridePercentage: overridePercentage,
  454. useOverride: useOverride,
  455. duration: duration,
  456. unlimited: unlimited,
  457. hbt: hbt_,
  458. overrideTarget: overrideTarget,
  459. smbIsOff: disableSMBs,
  460. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  461. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  462. isf: overrideArray.first?.isf ?? false,
  463. cr: overrideArray.first?.cr ?? false,
  464. smbMinutes: overrideArray.first?.smbMinutes?.decimalValue ?? smbMinutes,
  465. uamMinutes: overrideArray.first?.uamMinutes?.decimalValue ?? uamMinutes
  466. )
  467. // Save and return the Oref2 variables
  468. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  469. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  470. }
  471. }
  472. func autosense() async throws -> Autosens? {
  473. debug(.openAPS, "Start autosens")
  474. // Perform asynchronous calls in parallel
  475. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  476. async let carbs = fetchAndProcessCarbs()
  477. async let glucose = fetchAndProcessGlucose()
  478. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  479. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  480. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  481. // Await the results of asynchronous tasks
  482. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  483. parsePumpHistory(await pumpHistoryObjectIDs),
  484. carbs,
  485. glucose,
  486. getProfile,
  487. getBasalProfile,
  488. getTempTargets
  489. )
  490. // Autosense
  491. let autosenseResult = try await autosense(
  492. glucose: glucoseAsJSON,
  493. pumpHistory: pumpHistoryJSON,
  494. basalprofile: basalProfile,
  495. profile: profile,
  496. carbs: carbsAsJSON,
  497. temptargets: tempTargets
  498. )
  499. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  500. if var autosens = Autosens(from: autosenseResult) {
  501. autosens.timestamp = Date()
  502. await storage.saveAsync(autosens, as: Settings.autosense)
  503. return autosens
  504. } else {
  505. return nil
  506. }
  507. }
  508. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  509. debug(.openAPS, "Start autotune")
  510. // Perform asynchronous calls in parallel
  511. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  512. async let carbs = fetchAndProcessCarbs()
  513. async let glucose = fetchAndProcessGlucose()
  514. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  515. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  516. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  517. // Await the results of asynchronous tasks
  518. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  519. parsePumpHistory(await pumpHistoryObjectIDs),
  520. carbs,
  521. glucose,
  522. getProfile,
  523. getPumpProfile,
  524. getPreviousAutotune
  525. )
  526. // Error need to be handled here because the function is not declared as throws
  527. do {
  528. // Autotune Prepare
  529. let autotunePreppedGlucose = try await autotunePrepare(
  530. pumphistory: pumpHistoryJSON,
  531. profile: profile,
  532. glucose: glucoseAsJSON,
  533. pumpprofile: pumpProfile,
  534. carbs: carbsAsJSON,
  535. categorizeUamAsBasal: categorizeUamAsBasal,
  536. tuneInsulinCurve: tuneInsulinCurve
  537. )
  538. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  539. // Autotune Run
  540. let autotuneResult = try await autotuneRun(
  541. autotunePreparedData: autotunePreppedGlucose,
  542. previousAutotuneResult: previousAutotune ?? profile,
  543. pumpProfile: pumpProfile
  544. )
  545. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  546. if let autotune = Autotune(from: autotuneResult) {
  547. storage.save(autotuneResult, as: Settings.autotune)
  548. return autotune
  549. } else {
  550. return nil
  551. }
  552. } catch {
  553. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  554. return nil
  555. }
  556. }
  557. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  558. debug(.openAPS, "Start makeProfiles")
  559. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  560. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  561. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  562. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  563. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  564. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  565. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  566. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  567. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  568. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  569. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  570. getPreferences,
  571. getPumpSettings,
  572. getBGTargets,
  573. getBasalProfile,
  574. getISF,
  575. getCR,
  576. getTempTargets,
  577. getModel,
  578. getAutotune,
  579. getFreeAPS
  580. )
  581. var adjustedPreferences = preferences
  582. if adjustedPreferences.isEmpty {
  583. adjustedPreferences = Preferences().rawJSON
  584. }
  585. do {
  586. // Pump Profile
  587. let pumpProfile = try await makeProfile(
  588. preferences: adjustedPreferences,
  589. pumpSettings: pumpSettings,
  590. bgTargets: bgTargets,
  591. basalProfile: basalProfile,
  592. isf: isf,
  593. carbRatio: cr,
  594. tempTargets: tempTargets,
  595. model: model,
  596. autotune: RawJSON.null,
  597. freeaps: freeaps
  598. )
  599. // Profile
  600. let profile = try await makeProfile(
  601. preferences: adjustedPreferences,
  602. pumpSettings: pumpSettings,
  603. bgTargets: bgTargets,
  604. basalProfile: basalProfile,
  605. isf: isf,
  606. carbRatio: cr,
  607. tempTargets: tempTargets,
  608. model: model,
  609. autotune: autotune.isEmpty ? .null : autotune,
  610. freeaps: freeaps
  611. )
  612. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  613. await storage.saveAsync(profile, as: Settings.profile)
  614. if let tunedProfile = Autotune(from: profile) {
  615. return tunedProfile
  616. } else {
  617. return nil
  618. }
  619. } catch {
  620. debug(
  621. .apsManager,
  622. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  623. )
  624. return nil
  625. }
  626. }
  627. // MARK: - Private
  628. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  629. await withCheckedContinuation { continuation in
  630. jsWorker.inCommonContext { worker in
  631. worker.evaluateBatch(scripts: [
  632. Script(name: Prepare.log),
  633. Script(name: Bundle.iob),
  634. Script(name: Prepare.iob)
  635. ])
  636. let result = worker.call(function: Function.generate, with: [
  637. pumphistory,
  638. profile,
  639. clock,
  640. autosens
  641. ])
  642. continuation.resume(returning: result)
  643. }
  644. }
  645. }
  646. private func meal(
  647. pumphistory: JSON,
  648. profile: JSON,
  649. basalProfile: JSON,
  650. clock: JSON,
  651. carbs: JSON,
  652. glucose: JSON
  653. ) async throws -> RawJSON {
  654. try await withCheckedThrowingContinuation { continuation in
  655. jsWorker.inCommonContext { worker in
  656. worker.evaluateBatch(scripts: [
  657. Script(name: Prepare.log),
  658. Script(name: Bundle.meal),
  659. Script(name: Prepare.meal)
  660. ])
  661. let result = worker.call(function: Function.generate, with: [
  662. pumphistory,
  663. profile,
  664. clock,
  665. glucose,
  666. basalProfile,
  667. carbs
  668. ])
  669. continuation.resume(returning: result)
  670. }
  671. }
  672. }
  673. private func autosense(
  674. glucose: JSON,
  675. pumpHistory: JSON,
  676. basalprofile: JSON,
  677. profile: JSON,
  678. carbs: JSON,
  679. temptargets: JSON
  680. ) async throws -> RawJSON {
  681. try await withCheckedThrowingContinuation { continuation in
  682. jsWorker.inCommonContext { worker in
  683. worker.evaluateBatch(scripts: [
  684. Script(name: Prepare.log),
  685. Script(name: Bundle.autosens),
  686. Script(name: Prepare.autosens)
  687. ])
  688. let result = worker.call(function: Function.generate, with: [
  689. glucose,
  690. pumpHistory,
  691. basalprofile,
  692. profile,
  693. carbs,
  694. temptargets
  695. ])
  696. continuation.resume(returning: result)
  697. }
  698. }
  699. }
  700. private func autotunePrepare(
  701. pumphistory: JSON,
  702. profile: JSON,
  703. glucose: JSON,
  704. pumpprofile: JSON,
  705. carbs: JSON,
  706. categorizeUamAsBasal: Bool,
  707. tuneInsulinCurve: Bool
  708. ) async throws -> RawJSON {
  709. try await withCheckedThrowingContinuation { continuation in
  710. jsWorker.inCommonContext { worker in
  711. worker.evaluateBatch(scripts: [
  712. Script(name: Prepare.log),
  713. Script(name: Bundle.autotunePrep),
  714. Script(name: Prepare.autotunePrep)
  715. ])
  716. let result = worker.call(function: Function.generate, with: [
  717. pumphistory,
  718. profile,
  719. glucose,
  720. pumpprofile,
  721. carbs,
  722. categorizeUamAsBasal,
  723. tuneInsulinCurve
  724. ])
  725. continuation.resume(returning: result)
  726. }
  727. }
  728. }
  729. private func autotuneRun(
  730. autotunePreparedData: JSON,
  731. previousAutotuneResult: JSON,
  732. pumpProfile: JSON
  733. ) async throws -> RawJSON {
  734. try await withCheckedThrowingContinuation { continuation in
  735. jsWorker.inCommonContext { worker in
  736. worker.evaluateBatch(scripts: [
  737. Script(name: Prepare.log),
  738. Script(name: Bundle.autotuneCore),
  739. Script(name: Prepare.autotuneCore)
  740. ])
  741. let result = worker.call(function: Function.generate, with: [
  742. autotunePreparedData,
  743. previousAutotuneResult,
  744. pumpProfile
  745. ])
  746. continuation.resume(returning: result)
  747. }
  748. }
  749. }
  750. private func determineBasal(
  751. glucose: JSON,
  752. currentTemp: JSON,
  753. iob: JSON,
  754. profile: JSON,
  755. autosens: JSON,
  756. meal: JSON,
  757. microBolusAllowed: Bool,
  758. reservoir: JSON,
  759. pumpHistory: JSON,
  760. preferences: JSON,
  761. basalProfile: JSON,
  762. oref2_variables: JSON
  763. ) async throws -> RawJSON {
  764. try await withCheckedThrowingContinuation { continuation in
  765. jsWorker.inCommonContext { worker in
  766. worker.evaluateBatch(scripts: [
  767. Script(name: Prepare.log),
  768. Script(name: Prepare.determineBasal),
  769. Script(name: Bundle.basalSetTemp),
  770. Script(name: Bundle.getLastGlucose),
  771. Script(name: Bundle.determineBasal)
  772. ])
  773. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  774. worker.evaluate(script: middleware)
  775. }
  776. let result = worker.call(function: Function.generate, with: [
  777. iob,
  778. currentTemp,
  779. glucose,
  780. profile,
  781. autosens,
  782. meal,
  783. microBolusAllowed,
  784. reservoir,
  785. Date(),
  786. pumpHistory,
  787. preferences,
  788. basalProfile,
  789. oref2_variables
  790. ])
  791. continuation.resume(returning: result)
  792. }
  793. }
  794. }
  795. private func exportDefaultPreferences() -> RawJSON {
  796. dispatchPrecondition(condition: .onQueue(processQueue))
  797. return jsWorker.inCommonContext { worker in
  798. worker.evaluateBatch(scripts: [
  799. Script(name: Prepare.log),
  800. Script(name: Bundle.profile),
  801. Script(name: Prepare.profile)
  802. ])
  803. return worker.call(function: Function.exportDefaults, with: [])
  804. }
  805. }
  806. private func makeProfile(
  807. preferences: JSON,
  808. pumpSettings: JSON,
  809. bgTargets: JSON,
  810. basalProfile: JSON,
  811. isf: JSON,
  812. carbRatio: JSON,
  813. tempTargets: JSON,
  814. model: JSON,
  815. autotune: JSON,
  816. freeaps: JSON
  817. ) async throws -> RawJSON {
  818. try await withCheckedThrowingContinuation { continuation in
  819. jsWorker.inCommonContext { worker in
  820. worker.evaluateBatch(scripts: [
  821. Script(name: Prepare.log),
  822. Script(name: Bundle.profile),
  823. Script(name: Prepare.profile)
  824. ])
  825. let result = worker.call(function: Function.generate, with: [
  826. pumpSettings,
  827. bgTargets,
  828. isf,
  829. basalProfile,
  830. preferences,
  831. carbRatio,
  832. tempTargets,
  833. model,
  834. autotune,
  835. freeaps
  836. ])
  837. continuation.resume(returning: result)
  838. }
  839. }
  840. }
  841. private func loadJSON(name: String) -> String {
  842. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  843. }
  844. private func loadFileFromStorage(name: String) -> RawJSON {
  845. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  846. }
  847. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  848. await withCheckedContinuation { continuation in
  849. DispatchQueue.global(qos: .userInitiated).async {
  850. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  851. continuation.resume(returning: result)
  852. }
  853. }
  854. }
  855. private func middlewareScript(name: String) -> Script? {
  856. if let body = storage.retrieveRaw(name) {
  857. return Script(name: "Middleware", body: body)
  858. }
  859. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  860. return Script(name: "Middleware", body: try! String(contentsOf: url))
  861. }
  862. return nil
  863. }
  864. static func defaults(for file: String) -> RawJSON {
  865. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  866. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  867. return ""
  868. }
  869. return (try? String(contentsOf: url)) ?? ""
  870. }
  871. func processAndSave(forecastData: [String: [Int]]) {
  872. let currentDate = Date()
  873. context.perform {
  874. for (type, values) in forecastData {
  875. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  876. }
  877. do {
  878. guard self.context.hasChanges else { return }
  879. try self.context.save()
  880. } catch {
  881. print(error.localizedDescription)
  882. }
  883. }
  884. }
  885. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  886. let forecast = Forecast(context: context)
  887. forecast.id = UUID()
  888. forecast.date = date
  889. forecast.type = type
  890. for (index, value) in values.enumerated() {
  891. let forecastValue = ForecastValue(context: context)
  892. forecastValue.value = Int32(value)
  893. forecastValue.index = Int32(index)
  894. forecastValue.forecast = forecast
  895. }
  896. }
  897. }