OpenAPS.swift 42 KB

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