OpenAPS.swift 40 KB

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