OpenAPS.swift 40 KB

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