OpenAPS.swift 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  340. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  341. let wp = preferences?.weightPercentage ?? 1
  342. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  343. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  344. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  345. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  346. var uniqueEvents = [[String: Any]]()
  347. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<NSFetchRequestResult>
  348. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  349. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  350. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  351. requestTDD.sortDescriptors = [sortTDD]
  352. requestTDD.resultType = .dictionaryResultType
  353. do {
  354. if let fetchedResults = try self.context.fetch(requestTDD) as? [[String: Any]] {
  355. uniqueEvents = fetchedResults
  356. }
  357. } catch {
  358. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch TDD Data")
  359. }
  360. var sliderArray = [TempTargetsSlider]()
  361. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  362. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  363. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  364. // requestIsEnbled.fetchLimit = 1
  365. try? sliderArray = self.context.fetch(requestIsEnbled)
  366. /// Get the last active Override as only this information is apparently used in oref2
  367. var overrideArray = [OverrideStored]()
  368. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  369. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  370. requestOverrides.sortDescriptors = [sortOverride]
  371. requestOverrides.predicate = NSPredicate.lastActiveOverride
  372. requestOverrides.fetchLimit = 1
  373. try? overrideArray = self.context.fetch(requestOverrides)
  374. var tempTargetsArray = [TempTargets]()
  375. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  376. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  377. requestTempTargets.sortDescriptors = [sortTT]
  378. requestTempTargets.fetchLimit = 1
  379. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  380. let total = uniqueEvents.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 }).reduce(0, +)
  381. var indeces = uniqueEvents.count
  382. // Only fetch once. Use same (previous) fetch
  383. let twoHoursArray = uniqueEvents.filter({ ($0["timestamp"] as? Date ?? Date()) >= twoHoursAgo })
  384. var nrOfIndeces = twoHoursArray.count
  385. let totalAmount = twoHoursArray.compactMap({ ($0["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0 })
  386. .reduce(0, +)
  387. var temptargetActive = tempTargetsArray.first?.active ?? false
  388. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  389. var useOverride = overrideArray.first?.enabled ?? false
  390. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  391. var unlimited = overrideArray.first?.indefinite ?? true
  392. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  393. let currentTDD = (uniqueEvents.last?["totalDailyDose"] as? NSDecimalNumber)?.decimalValue ?? 0
  394. if indeces == 0 {
  395. indeces = 1
  396. }
  397. if nrOfIndeces == 0 {
  398. nrOfIndeces = 1
  399. }
  400. let average2hours = totalAmount / Decimal(nrOfIndeces)
  401. let average14 = total / Decimal(indeces)
  402. let weight = wp
  403. let weighted_average = weight * average2hours + (1 - weight) * average14
  404. var duration: Decimal = 0
  405. var overrideTarget: Decimal = 0
  406. if useOverride {
  407. duration = (overrideArray.first?.duration ?? 0) as Decimal
  408. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  409. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  410. let addedMinutes = Int(duration)
  411. let date = overrideArray.first?.date ?? Date()
  412. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  413. !unlimited
  414. {
  415. useOverride = false
  416. let saveToCoreData = OverrideStored(context: self.context)
  417. saveToCoreData.enabled = false
  418. saveToCoreData.date = Date()
  419. saveToCoreData.duration = 0
  420. saveToCoreData.indefinite = false
  421. saveToCoreData.percentage = 100
  422. do {
  423. guard self.context.hasChanges else { return "{}" }
  424. try self.context.save()
  425. } catch {
  426. print(error.localizedDescription)
  427. }
  428. }
  429. }
  430. if !useOverride {
  431. unlimited = true
  432. overridePercentage = 100
  433. duration = 0
  434. overrideTarget = 0
  435. disableSMBs = false
  436. }
  437. if temptargetActive {
  438. var duration_ = 0
  439. var hbt = Double(hbt_)
  440. var dd = 0.0
  441. if temptargetActive {
  442. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  443. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  444. let startDate = tempTargetsArray.first?.startDate ?? Date()
  445. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  446. dd = durationPlusStart.timeIntervalSinceNow.minutes
  447. if dd > 0.1 {
  448. hbt_ = Decimal(hbt)
  449. temptargetActive = true
  450. } else {
  451. temptargetActive = false
  452. }
  453. }
  454. }
  455. if currentTDD > 0 {
  456. let averages = Oref2_variables(
  457. average_total_data: average14,
  458. weightedAverage: weighted_average,
  459. past2hoursAverage: average2hours,
  460. date: Date(),
  461. isEnabled: temptargetActive,
  462. presetActive: isPercentageEnabled,
  463. overridePercentage: overridePercentage,
  464. useOverride: useOverride,
  465. duration: duration,
  466. unlimited: unlimited,
  467. hbt: hbt_,
  468. overrideTarget: overrideTarget,
  469. smbIsOff: disableSMBs,
  470. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  471. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  472. isf: overrideArray.first?.isf ?? false,
  473. cr: overrideArray.first?.cr ?? false,
  474. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  475. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  476. )
  477. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  478. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  479. } else {
  480. let averages = Oref2_variables(
  481. average_total_data: 0,
  482. weightedAverage: 1,
  483. past2hoursAverage: 0,
  484. date: Date(),
  485. isEnabled: temptargetActive,
  486. presetActive: isPercentageEnabled,
  487. overridePercentage: overridePercentage,
  488. useOverride: useOverride,
  489. duration: duration,
  490. unlimited: unlimited,
  491. hbt: hbt_,
  492. overrideTarget: overrideTarget,
  493. smbIsOff: disableSMBs,
  494. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  495. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  496. isf: overrideArray.first?.isf ?? false,
  497. cr: overrideArray.first?.cr ?? false,
  498. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  499. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  500. )
  501. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  502. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  503. }
  504. }
  505. }
  506. func autosense() async throws -> Autosens? {
  507. debug(.openAPS, "Start autosens")
  508. // Perform asynchronous calls in parallel
  509. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  510. async let carbs = fetchAndProcessCarbs()
  511. async let glucose = fetchAndProcessGlucose()
  512. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  513. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  514. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  515. // Await the results of asynchronous tasks
  516. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  517. parsePumpHistory(await pumpHistoryObjectIDs),
  518. carbs,
  519. glucose,
  520. getProfile,
  521. getBasalProfile,
  522. getTempTargets
  523. )
  524. // Autosense
  525. let autosenseResult = try await autosense(
  526. glucose: glucoseAsJSON,
  527. pumpHistory: pumpHistoryJSON,
  528. basalprofile: basalProfile,
  529. profile: profile,
  530. carbs: carbsAsJSON,
  531. temptargets: tempTargets
  532. )
  533. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  534. if var autosens = Autosens(from: autosenseResult) {
  535. autosens.timestamp = Date()
  536. await storage.saveAsync(autosens, as: Settings.autosense)
  537. return autosens
  538. } else {
  539. return nil
  540. }
  541. }
  542. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  543. debug(.openAPS, "Start autotune")
  544. // Perform asynchronous calls in parallel
  545. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  546. async let carbs = fetchAndProcessCarbs()
  547. async let glucose = fetchAndProcessGlucose()
  548. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  549. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  550. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  551. // Await the results of asynchronous tasks
  552. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  553. parsePumpHistory(await pumpHistoryObjectIDs),
  554. carbs,
  555. glucose,
  556. getProfile,
  557. getPumpProfile,
  558. getPreviousAutotune
  559. )
  560. // Error need to be handled here because the function is not declared as throws
  561. do {
  562. // Autotune Prepare
  563. let autotunePreppedGlucose = try await autotunePrepare(
  564. pumphistory: pumpHistoryJSON,
  565. profile: profile,
  566. glucose: glucoseAsJSON,
  567. pumpprofile: pumpProfile,
  568. carbs: carbsAsJSON,
  569. categorizeUamAsBasal: categorizeUamAsBasal,
  570. tuneInsulinCurve: tuneInsulinCurve
  571. )
  572. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  573. // Autotune Run
  574. let autotuneResult = try await autotuneRun(
  575. autotunePreparedData: autotunePreppedGlucose,
  576. previousAutotuneResult: previousAutotune ?? profile,
  577. pumpProfile: pumpProfile
  578. )
  579. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  580. if let autotune = Autotune(from: autotuneResult) {
  581. storage.save(autotuneResult, as: Settings.autotune)
  582. return autotune
  583. } else {
  584. return nil
  585. }
  586. } catch {
  587. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  588. return nil
  589. }
  590. }
  591. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  592. debug(.openAPS, "Start makeProfiles")
  593. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  594. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  595. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  596. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  597. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  598. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  599. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  600. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  601. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  602. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  603. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  604. getPreferences,
  605. getPumpSettings,
  606. getBGTargets,
  607. getBasalProfile,
  608. getISF,
  609. getCR,
  610. getTempTargets,
  611. getModel,
  612. getAutotune,
  613. getFreeAPS
  614. )
  615. var adjustedPreferences = preferences
  616. if adjustedPreferences.isEmpty {
  617. adjustedPreferences = Preferences().rawJSON
  618. }
  619. do {
  620. // Pump Profile
  621. let pumpProfile = try await makeProfile(
  622. preferences: adjustedPreferences,
  623. pumpSettings: pumpSettings,
  624. bgTargets: bgTargets,
  625. basalProfile: basalProfile,
  626. isf: isf,
  627. carbRatio: cr,
  628. tempTargets: tempTargets,
  629. model: model,
  630. autotune: RawJSON.null,
  631. freeaps: freeaps
  632. )
  633. // Profile
  634. let profile = try await makeProfile(
  635. preferences: adjustedPreferences,
  636. pumpSettings: pumpSettings,
  637. bgTargets: bgTargets,
  638. basalProfile: basalProfile,
  639. isf: isf,
  640. carbRatio: cr,
  641. tempTargets: tempTargets,
  642. model: model,
  643. autotune: autotune.isEmpty ? .null : autotune,
  644. freeaps: freeaps
  645. )
  646. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  647. await storage.saveAsync(profile, as: Settings.profile)
  648. if let tunedProfile = Autotune(from: profile) {
  649. return tunedProfile
  650. } else {
  651. return nil
  652. }
  653. } catch {
  654. debug(
  655. .apsManager,
  656. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  657. )
  658. return nil
  659. }
  660. }
  661. // MARK: - Private
  662. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  663. await withCheckedContinuation { continuation in
  664. jsWorker.inCommonContext { worker in
  665. worker.evaluateBatch(scripts: [
  666. Script(name: Prepare.log),
  667. Script(name: Bundle.iob),
  668. Script(name: Prepare.iob)
  669. ])
  670. let result = worker.call(function: Function.generate, with: [
  671. pumphistory,
  672. profile,
  673. clock,
  674. autosens
  675. ])
  676. continuation.resume(returning: result)
  677. }
  678. }
  679. }
  680. private func meal(
  681. pumphistory: JSON,
  682. profile: JSON,
  683. basalProfile: JSON,
  684. clock: JSON,
  685. carbs: JSON,
  686. glucose: JSON
  687. ) async throws -> RawJSON {
  688. try await withCheckedThrowingContinuation { continuation in
  689. jsWorker.inCommonContext { worker in
  690. worker.evaluateBatch(scripts: [
  691. Script(name: Prepare.log),
  692. Script(name: Bundle.meal),
  693. Script(name: Prepare.meal)
  694. ])
  695. let result = worker.call(function: Function.generate, with: [
  696. pumphistory,
  697. profile,
  698. clock,
  699. glucose,
  700. basalProfile,
  701. carbs
  702. ])
  703. continuation.resume(returning: result)
  704. }
  705. }
  706. }
  707. private func autosense(
  708. glucose: JSON,
  709. pumpHistory: JSON,
  710. basalprofile: JSON,
  711. profile: JSON,
  712. carbs: JSON,
  713. temptargets: JSON
  714. ) async throws -> RawJSON {
  715. try await withCheckedThrowingContinuation { continuation in
  716. jsWorker.inCommonContext { worker in
  717. worker.evaluateBatch(scripts: [
  718. Script(name: Prepare.log),
  719. Script(name: Bundle.autosens),
  720. Script(name: Prepare.autosens)
  721. ])
  722. let result = worker.call(function: Function.generate, with: [
  723. glucose,
  724. pumpHistory,
  725. basalprofile,
  726. profile,
  727. carbs,
  728. temptargets
  729. ])
  730. continuation.resume(returning: result)
  731. }
  732. }
  733. }
  734. private func autotunePrepare(
  735. pumphistory: JSON,
  736. profile: JSON,
  737. glucose: JSON,
  738. pumpprofile: JSON,
  739. carbs: JSON,
  740. categorizeUamAsBasal: Bool,
  741. tuneInsulinCurve: Bool
  742. ) async throws -> RawJSON {
  743. try await withCheckedThrowingContinuation { continuation in
  744. jsWorker.inCommonContext { worker in
  745. worker.evaluateBatch(scripts: [
  746. Script(name: Prepare.log),
  747. Script(name: Bundle.autotunePrep),
  748. Script(name: Prepare.autotunePrep)
  749. ])
  750. let result = worker.call(function: Function.generate, with: [
  751. pumphistory,
  752. profile,
  753. glucose,
  754. pumpprofile,
  755. carbs,
  756. categorizeUamAsBasal,
  757. tuneInsulinCurve
  758. ])
  759. continuation.resume(returning: result)
  760. }
  761. }
  762. }
  763. private func autotuneRun(
  764. autotunePreparedData: JSON,
  765. previousAutotuneResult: JSON,
  766. pumpProfile: JSON
  767. ) async throws -> RawJSON {
  768. try await withCheckedThrowingContinuation { continuation in
  769. jsWorker.inCommonContext { worker in
  770. worker.evaluateBatch(scripts: [
  771. Script(name: Prepare.log),
  772. Script(name: Bundle.autotuneCore),
  773. Script(name: Prepare.autotuneCore)
  774. ])
  775. let result = worker.call(function: Function.generate, with: [
  776. autotunePreparedData,
  777. previousAutotuneResult,
  778. pumpProfile
  779. ])
  780. continuation.resume(returning: result)
  781. }
  782. }
  783. }
  784. private func determineBasal(
  785. glucose: JSON,
  786. currentTemp: JSON,
  787. iob: JSON,
  788. profile: JSON,
  789. autosens: JSON,
  790. meal: JSON,
  791. microBolusAllowed: Bool,
  792. reservoir: JSON,
  793. pumpHistory: JSON,
  794. preferences: JSON,
  795. basalProfile: JSON,
  796. oref2_variables: JSON
  797. ) async throws -> RawJSON {
  798. try await withCheckedThrowingContinuation { continuation in
  799. jsWorker.inCommonContext { worker in
  800. worker.evaluateBatch(scripts: [
  801. Script(name: Prepare.log),
  802. Script(name: Prepare.determineBasal),
  803. Script(name: Bundle.basalSetTemp),
  804. Script(name: Bundle.getLastGlucose),
  805. Script(name: Bundle.determineBasal)
  806. ])
  807. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  808. worker.evaluate(script: middleware)
  809. }
  810. let result = worker.call(function: Function.generate, with: [
  811. iob,
  812. currentTemp,
  813. glucose,
  814. profile,
  815. autosens,
  816. meal,
  817. microBolusAllowed,
  818. reservoir,
  819. Date(),
  820. pumpHistory,
  821. preferences,
  822. basalProfile,
  823. oref2_variables
  824. ])
  825. continuation.resume(returning: result)
  826. }
  827. }
  828. }
  829. private func exportDefaultPreferences() -> RawJSON {
  830. dispatchPrecondition(condition: .onQueue(processQueue))
  831. return jsWorker.inCommonContext { worker in
  832. worker.evaluateBatch(scripts: [
  833. Script(name: Prepare.log),
  834. Script(name: Bundle.profile),
  835. Script(name: Prepare.profile)
  836. ])
  837. return worker.call(function: Function.exportDefaults, with: [])
  838. }
  839. }
  840. private func makeProfile(
  841. preferences: JSON,
  842. pumpSettings: JSON,
  843. bgTargets: JSON,
  844. basalProfile: JSON,
  845. isf: JSON,
  846. carbRatio: JSON,
  847. tempTargets: JSON,
  848. model: JSON,
  849. autotune: JSON,
  850. freeaps: JSON
  851. ) async throws -> RawJSON {
  852. try await withCheckedThrowingContinuation { continuation in
  853. jsWorker.inCommonContext { worker in
  854. worker.evaluateBatch(scripts: [
  855. Script(name: Prepare.log),
  856. Script(name: Bundle.profile),
  857. Script(name: Prepare.profile)
  858. ])
  859. let result = worker.call(function: Function.generate, with: [
  860. pumpSettings,
  861. bgTargets,
  862. isf,
  863. basalProfile,
  864. preferences,
  865. carbRatio,
  866. tempTargets,
  867. model,
  868. autotune,
  869. freeaps
  870. ])
  871. continuation.resume(returning: result)
  872. }
  873. }
  874. }
  875. private func loadJSON(name: String) -> String {
  876. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  877. }
  878. private func loadFileFromStorage(name: String) -> RawJSON {
  879. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  880. }
  881. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  882. await withCheckedContinuation { continuation in
  883. DispatchQueue.global(qos: .userInitiated).async {
  884. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  885. continuation.resume(returning: result)
  886. }
  887. }
  888. }
  889. private func middlewareScript(name: String) -> Script? {
  890. if let body = storage.retrieveRaw(name) {
  891. return Script(name: "Middleware", body: body)
  892. }
  893. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  894. return Script(name: "Middleware", body: try! String(contentsOf: url))
  895. }
  896. return nil
  897. }
  898. static func defaults(for file: String) -> RawJSON {
  899. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  900. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  901. return ""
  902. }
  903. return (try? String(contentsOf: url)) ?? ""
  904. }
  905. func processAndSave(forecastData: [String: [Int]]) {
  906. let currentDate = Date()
  907. context.perform {
  908. for (type, values) in forecastData {
  909. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  910. }
  911. do {
  912. guard self.context.hasChanges else { return }
  913. try self.context.save()
  914. } catch {
  915. print(error.localizedDescription)
  916. }
  917. }
  918. }
  919. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  920. let forecast = Forecast(context: context)
  921. forecast.id = UUID()
  922. forecast.date = date
  923. forecast.type = type
  924. for (index, value) in values.enumerated() {
  925. let forecastValue = ForecastValue(context: context)
  926. forecastValue.value = Int32(value)
  927. forecastValue.index = Int32(index)
  928. forecastValue.forecast = forecast
  929. }
  930. }
  931. }