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. await context.perform {
  92. guard let previousDeterminations = results as? [OrefDetermination] else {
  93. return
  94. }
  95. // We need to get the second last Determination for this comparison because we have saved the current Determination already to Core Data
  96. if let previousDetermination = previousDeterminations.dropFirst().first {
  97. let iobChanged = previousDetermination.iob != self.decimalToNSDecimalNumber(determination.iob)
  98. let cobChanged = previousDetermination.cob != Int16(Int(determination.cob ?? 0))
  99. if iobChanged || cobChanged {
  100. Foundation.NotificationCenter.default.post(name: .didUpdateCobIob, object: nil)
  101. }
  102. }
  103. }
  104. }
  105. func attemptToSaveContext() async {
  106. await context.perform {
  107. do {
  108. guard self.context.hasChanges else { return }
  109. try self.context.save()
  110. } catch {
  111. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  112. }
  113. }
  114. }
  115. // fetch glucose to pass it to the meal function and to determine basal
  116. private func fetchAndProcessGlucose() async -> String {
  117. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  118. ofType: GlucoseStored.self,
  119. onContext: context,
  120. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  121. key: "date",
  122. ascending: false,
  123. fetchLimit: 72,
  124. batchSize: 24
  125. )
  126. return await context.perform {
  127. guard let glucoseResults = results as? [GlucoseStored] else {
  128. return ""
  129. }
  130. // convert to JSON
  131. return self.jsonConverter.convertToJSON(glucoseResults)
  132. }
  133. }
  134. private func fetchAndProcessCarbs(additionalCarbs: Decimal? = nil) async -> String {
  135. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  136. ofType: CarbEntryStored.self,
  137. onContext: context,
  138. predicate: NSPredicate.predicateForOneDayAgo,
  139. key: "date",
  140. ascending: false
  141. )
  142. let json = await context.perform {
  143. guard let carbResults = results as? [CarbEntryStored] else {
  144. return ""
  145. }
  146. var jsonArray = self.jsonConverter.convertToJSON(carbResults)
  147. if let additionalCarbs = additionalCarbs {
  148. let additionalEntry = [
  149. "carbs": Double(additionalCarbs),
  150. "actualDate": ISO8601DateFormatter().string(from: Date()),
  151. "id": UUID().uuidString,
  152. "note": NSNull(),
  153. "protein": 0,
  154. "created_at": ISO8601DateFormatter().string(from: Date()),
  155. "isFPU": false,
  156. "fat": 0,
  157. "enteredBy": "Trio"
  158. ] as [String: Any]
  159. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  160. if let jsonData = jsonArray.data(using: .utf8) {
  161. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  162. jsonList?.append(additionalEntry)
  163. // Convert back to JSON string
  164. if let updatedJsonData = try? JSONSerialization
  165. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  166. {
  167. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  168. }
  169. }
  170. }
  171. return jsonArray
  172. }
  173. return json
  174. }
  175. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  176. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  177. ofType: PumpEventStored.self,
  178. onContext: context,
  179. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  180. key: "timestamp",
  181. ascending: false,
  182. batchSize: 50
  183. )
  184. return await context.perform {
  185. guard let pumpEventResults = results as? [PumpEventStored] else {
  186. return nil
  187. }
  188. return pumpEventResults.map(\.objectID)
  189. }
  190. }
  191. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID], iob: Decimal? = nil) async -> String {
  192. // Return an empty JSON object if the list of object IDs is empty
  193. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  194. // Execute all operations on the background context
  195. return await context.perform {
  196. // Load and map pump events to DTOs
  197. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  198. // Optionally add the IOB as a DTO
  199. if let iob = iob {
  200. let iobDTO = self.createIOBDTO(iob: iob)
  201. dtos.insert(iobDTO, at: 0)
  202. }
  203. // Convert the DTOs to JSON
  204. return self.jsonConverter.convertToJSON(dtos)
  205. }
  206. }
  207. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  208. // Load the pump events from the object IDs
  209. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  210. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  211. // Create the DTOs
  212. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  213. var eventDTOs: [PumpEventDTO] = []
  214. if let bolusDTO = event.toBolusDTOEnum() {
  215. eventDTOs.append(bolusDTO)
  216. }
  217. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  218. eventDTOs.append(tempBasalDurationDTO)
  219. }
  220. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  221. eventDTOs.append(tempBasalDTO)
  222. }
  223. return eventDTOs
  224. }
  225. return dtos
  226. }
  227. private func createIOBDTO(iob: Decimal) -> PumpEventDTO {
  228. let oneSecondAgo = Calendar.current
  229. .date(
  230. byAdding: .second,
  231. value: -1,
  232. to: Date()
  233. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  234. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  235. let bolusDTO = BolusDTO(
  236. id: UUID().uuidString,
  237. timestamp: dateFormatted,
  238. amount: Double(iob),
  239. isExternal: false,
  240. isSMB: true,
  241. duration: 0,
  242. _type: "Bolus"
  243. )
  244. return .bolus(bolusDTO)
  245. }
  246. func determineBasal(
  247. currentTemp: TempBasal,
  248. clock: Date = Date(),
  249. carbs: Decimal? = nil,
  250. iob: Decimal? = nil,
  251. simulation: Bool = false
  252. ) async throws -> Determination? {
  253. debug(.openAPS, "Start determineBasal")
  254. // temp_basal
  255. let tempBasal = currentTemp.rawJSON
  256. // Perform asynchronous calls in parallel
  257. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  258. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs ?? 0)
  259. async let glucose = fetchAndProcessGlucose()
  260. async let oref2 = oref2()
  261. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  262. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  263. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  264. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  265. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  266. // Await the results of asynchronous tasks
  267. let (
  268. pumpHistoryJSON,
  269. carbsAsJSON,
  270. glucoseAsJSON,
  271. oref2_variables,
  272. profile,
  273. basalProfile,
  274. autosens,
  275. reservoir,
  276. preferences
  277. ) = await (
  278. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  279. carbs,
  280. glucose,
  281. oref2,
  282. profileAsync,
  283. basalAsync,
  284. autosenseAsync,
  285. reservoirAsync,
  286. preferencesAsync
  287. )
  288. // Meal calculation
  289. let meal = try await self.meal(
  290. pumphistory: pumpHistoryJSON,
  291. profile: profile,
  292. basalProfile: basalProfile,
  293. clock: clock,
  294. carbs: carbsAsJSON,
  295. glucose: glucoseAsJSON
  296. )
  297. // IOB calculation
  298. let iob = try await self.iob(
  299. pumphistory: pumpHistoryJSON,
  300. profile: profile,
  301. clock: clock,
  302. autosens: autosens.isEmpty ? .null : autosens
  303. )
  304. // TODO: refactor this to core data
  305. if !simulation {
  306. storage.save(iob, as: Monitor.iob)
  307. }
  308. // Determine basal
  309. let orefDetermination = try await determineBasal(
  310. glucose: glucoseAsJSON,
  311. currentTemp: tempBasal,
  312. iob: iob,
  313. profile: profile,
  314. autosens: autosens.isEmpty ? .null : autosens,
  315. meal: meal,
  316. microBolusAllowed: true,
  317. reservoir: reservoir,
  318. pumpHistory: pumpHistoryJSON,
  319. preferences: preferences,
  320. basalProfile: basalProfile,
  321. oref2_variables: oref2_variables
  322. )
  323. debug(.openAPS, "Determinated: \(orefDetermination)")
  324. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  325. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  326. // AAPS does it the same way! we'll follow their example!
  327. determination.timestamp = deliverAt
  328. if !simulation {
  329. // save to core data asynchronously
  330. await processDetermination(determination)
  331. }
  332. return determination
  333. } else {
  334. return nil
  335. }
  336. }
  337. func oref2() async -> RawJSON {
  338. await context.perform {
  339. // Retrieve preferences
  340. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  341. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  342. let wp = preferences?.weightPercentage ?? 1.0
  343. let smbMinutes = preferences?.maxSMBBasalMinutes ?? 30
  344. let uamMinutes = preferences?.maxUAMSMBBasalMinutes ?? 30
  345. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  346. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  347. // Fetch unique events for TDD calculation
  348. var uniqueEvents = [[String: Any]]()
  349. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  350. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  351. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  352. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  353. requestTDD.sortDescriptors = [sortTDD]
  354. requestTDD.resultType = .dictionaryResultType
  355. do {
  356. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  357. uniqueEvents = fetchedResults
  358. }
  359. } catch {
  360. debugPrint("Failed to fetch TDD Data")
  361. }
  362. // Get the last active Override
  363. var overrideArray = [OverrideStored]()
  364. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  365. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  366. requestOverrides.sortDescriptors = [sortOverride]
  367. requestOverrides.predicate = NSPredicate.lastActiveOverride
  368. requestOverrides.fetchLimit = 1
  369. try? overrideArray = self.context.fetch(requestOverrides)
  370. // Get the last active Temp Target
  371. var tempTargetsArray = [TempTargetStored]()
  372. let requestTempTargets = TempTargetStored.fetchRequest() as NSFetchRequest<TempTargetStored>
  373. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  374. requestTempTargets.sortDescriptors = [sortTT]
  375. requestTempTargets.predicate = NSPredicate.lastActiveTempTarget
  376. requestTempTargets.fetchLimit = 1
  377. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  378. var isTemptargetActive = tempTargetsArray.first?.enabled ?? false
  379. // Calculate averages for TDD
  380. let total = uniqueEvents.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  381. var indices = uniqueEvents.count
  382. // Fetch data for the past two hours
  383. let twoHoursArray = uniqueEvents.filter { ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo }
  384. var nrOfIndices = twoHoursArray.count
  385. let totalAmount = twoHoursArray.compactMap { ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue }.reduce(0, +)
  386. var useOverride = overrideArray.first?.enabled ?? false
  387. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  388. var unlimited = overrideArray.first?.indefinite ?? true
  389. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  390. let currentTDD = uniqueEvents.last?["totalDailyDose"] as? Decimal ?? 0
  391. if indices == 0 { indices = 1 }
  392. if nrOfIndices == 0 { nrOfIndices = 1 }
  393. let average2hours = totalAmount / Decimal(nrOfIndices)
  394. let average14 = total / Decimal(indices)
  395. let weightedAverage = wp * average2hours + (1 - wp) * average14
  396. var duration: Decimal = 0
  397. var overrideTarget: Decimal = 0
  398. // Handle Overrides
  399. if useOverride {
  400. duration = overrideArray.first?.duration?.decimalValue ?? 0
  401. overrideTarget = overrideArray.first?.target?.decimalValue ?? 0
  402. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  403. let addedMinutes = Int(truncating: overrideArray.first?.duration ?? 0)
  404. let date = overrideArray.first?.date ?? Date()
  405. let overrideEndTime = date.addingTimeInterval(Double(addedMinutes) * 60)
  406. if overrideEndTime < Date(), !unlimited {
  407. // Override has expired
  408. useOverride = false
  409. let saveToCoreData = OverrideStored(context: self.context)
  410. saveToCoreData.enabled = false
  411. saveToCoreData.date = Date()
  412. saveToCoreData.duration = 0
  413. saveToCoreData.indefinite = false
  414. saveToCoreData.percentage = 100
  415. do {
  416. guard self.context.hasChanges else { return "{}" }
  417. try self.context.save()
  418. } catch {
  419. print(error.localizedDescription)
  420. }
  421. }
  422. }
  423. if !useOverride {
  424. // Reset to default values if no override is active
  425. unlimited = true
  426. overridePercentage = 100
  427. duration = 0
  428. overrideTarget = 0
  429. disableSMBs = false
  430. }
  431. // Temp Target Handling
  432. if isTemptargetActive {
  433. if let tempTarget = tempTargetsArray.first {
  434. let tempDuration = tempTarget.duration?.doubleValue ?? 0
  435. let halfBasalTarget = tempTarget.halfBasalTarget ?? NSDecimalNumber(decimal: hbt_)
  436. let startDate = tempTarget.date ?? Date()
  437. let tempTargetEndTime = startDate.addingTimeInterval(tempDuration * 60)
  438. let timeRemaining = tempTargetEndTime.timeIntervalSinceNow / 60 // Time remaining in minutes
  439. if timeRemaining > 0 {
  440. hbt_ = halfBasalTarget.decimalValue
  441. isTemptargetActive = true
  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. }