OpenAPS.swift 40 KB

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