OpenAPS.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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) {
  26. 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 = Int16(determination.duration ?? 0)
  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. if let predictions = determination.predictions {
  56. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  57. .forEach { type, values in
  58. if let values = values {
  59. let forecast = Forecast(context: self.context)
  60. forecast.id = UUID()
  61. forecast.type = type
  62. forecast.date = Date()
  63. forecast.orefDetermination = newOrefDetermination
  64. for (index, value) in values.enumerated() {
  65. let forecastValue = ForecastValue(context: self.context)
  66. forecastValue.index = Int32(index)
  67. forecastValue.value = Int32(value)
  68. forecast.addToForecastValues(forecastValue)
  69. }
  70. newOrefDetermination.addToForecasts(forecast)
  71. }
  72. }
  73. }
  74. self.attemptToSaveContext()
  75. }
  76. }
  77. func attemptToSaveContext() {
  78. do {
  79. guard context.hasChanges else { return }
  80. try context.save()
  81. } catch {
  82. print(error.localizedDescription)
  83. }
  84. }
  85. // fetch glucose to pass it to the meal function and to determine basal
  86. private func fetchAndProcessGlucose() -> String {
  87. var glucoseAsJSON: String?
  88. context.performAndWait {
  89. let results = CoreDataStack.shared.fetchEntities(
  90. ofType: GlucoseStored.self,
  91. onContext: context,
  92. predicate: NSPredicate.predicateForSixHoursAgo,
  93. key: "date",
  94. ascending: false,
  95. fetchLimit: 72,
  96. batchSize: 24
  97. )
  98. // convert to json
  99. glucoseAsJSON = self.jsonConverter.convertToJSON(results)
  100. }
  101. return glucoseAsJSON ?? "{}"
  102. }
  103. private func fetchAndProcessCarbs() -> String {
  104. // perform fetch AND conversion on the same thread
  105. // if we do it like this we do not change the thread and do not have to pass the objectIDs
  106. var carbsAsJSON: String?
  107. context.performAndWait {
  108. let results = CoreDataStack.shared.fetchEntities(
  109. ofType: CarbEntryStored.self,
  110. onContext: context,
  111. predicate: NSPredicate.predicateForOneDayAgo,
  112. key: "date",
  113. ascending: false
  114. )
  115. // convert to json
  116. carbsAsJSON = self.jsonConverter.convertToJSON(results)
  117. }
  118. return carbsAsJSON ?? "{}"
  119. }
  120. private func fetchPumpHistoryObjectIDs() -> [NSManagedObjectID]? {
  121. context.performAndWait {
  122. let results = CoreDataStack.shared.fetchEntities(
  123. ofType: PumpEventStored.self,
  124. onContext: context,
  125. predicate: NSPredicate.pumpHistoryLast24h,
  126. key: "timestamp",
  127. ascending: false,
  128. batchSize: 50
  129. )
  130. return results.map(\.objectID)
  131. }
  132. }
  133. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> String {
  134. // Return an empty JSON object if the list of object IDs is empty
  135. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  136. // Execute all operations on the background context
  137. let jsonResult = context.performAndWait {
  138. // Load the pump events from the object IDs
  139. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  140. .compactMap { context.object(with: $0) as? PumpEventStored }
  141. // Create the DTOs
  142. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  143. var eventDTOs: [PumpEventDTO] = []
  144. if let bolusDTO = event.toBolusDTOEnum() {
  145. eventDTOs.append(bolusDTO)
  146. }
  147. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  148. eventDTOs.append(tempBasalDTO)
  149. }
  150. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  151. eventDTOs.append(tempBasalDurationDTO)
  152. }
  153. return eventDTOs
  154. }
  155. // Convert the DTOs to JSON
  156. return jsonConverter.convertToJSON(dtos)
  157. }
  158. // Return the JSON result
  159. return jsonResult
  160. }
  161. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) -> Future<Determination?, Never> {
  162. Future { promise in
  163. self.processQueue.async {
  164. debug(.openAPS, "Start determineBasal")
  165. // clock
  166. let dateFormatted = OpenAPS.dateFormatter.string(from: clock)
  167. let dateFormattedAsString = "\"\(dateFormatted)\""
  168. // temp_basal
  169. let tempBasal = currentTemp.rawJSON
  170. self.storage.save(tempBasal, as: Monitor.tempBasal)
  171. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  172. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  173. // carbs
  174. let carbsAsJSON = self.fetchAndProcessCarbs()
  175. /// glucose
  176. let glucoseAsJSON = self.fetchAndProcessGlucose()
  177. /// profile
  178. let profile = self.loadFileFromStorage(name: Settings.profile)
  179. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  180. /// meal
  181. let meal = self.meal(
  182. pumphistory: pumpHistoryJSON,
  183. profile: profile,
  184. basalProfile: basalProfile,
  185. clock: dateFormattedAsString,
  186. carbs: carbsAsJSON,
  187. glucose: glucoseAsJSON
  188. )
  189. self.storage.save(meal, as: Monitor.meal)
  190. // iob
  191. let autosens = self.loadFileFromStorage(name: Settings.autosense)
  192. let iob = self.iob(
  193. pumphistory: pumpHistoryJSON,
  194. profile: profile,
  195. clock: dateFormattedAsString,
  196. autosens: autosens.isEmpty ? .null : autosens
  197. )
  198. self.storage.save(iob, as: Monitor.iob)
  199. // determine-basal
  200. let reservoir = self.loadFileFromStorage(name: Monitor.reservoir)
  201. let preferences = self.loadFileFromStorage(name: Settings.preferences)
  202. // oref2
  203. let oref2_variables = self.oref2()
  204. let orefDetermination = self.determineBasal(
  205. glucose: glucoseAsJSON,
  206. currentTemp: tempBasal,
  207. iob: iob,
  208. profile: profile,
  209. autosens: autosens.isEmpty ? .null : autosens,
  210. meal: meal,
  211. microBolusAllowed: true,
  212. reservoir: reservoir,
  213. pumpHistory: pumpHistoryJSON,
  214. preferences: preferences,
  215. basalProfile: basalProfile,
  216. oref2_variables: oref2_variables
  217. )
  218. debug(.openAPS, "Determinated: \(orefDetermination)")
  219. if var determination = Determination(from: orefDetermination) {
  220. determination.timestamp = determination.deliverAt ?? clock
  221. self.storage.save(determination, as: Enact.suggested)
  222. // save to core data asynchronously
  223. self.processDetermination(determination)
  224. promise(.success(determination))
  225. } else {
  226. promise(.success(nil))
  227. }
  228. }
  229. }
  230. }
  231. func oref2() -> RawJSON {
  232. context.performAndWait {
  233. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  234. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  235. let wp = preferences?.weightPercentage ?? 1
  236. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  237. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  238. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  239. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  240. var uniqueEvents = [OrefDetermination]()
  241. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<OrefDetermination>
  242. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  243. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  244. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  245. requestTDD.sortDescriptors = [sortTDD]
  246. try? uniqueEvents = context.fetch(requestTDD)
  247. var sliderArray = [TempTargetsSlider]()
  248. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  249. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  250. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  251. // requestIsEnbled.fetchLimit = 1
  252. try? sliderArray = context.fetch(requestIsEnbled)
  253. var overrideArray = [Override]()
  254. let requestOverrides = Override.fetchRequest() as NSFetchRequest<Override>
  255. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  256. requestOverrides.sortDescriptors = [sortOverride]
  257. // requestOverrides.fetchLimit = 1
  258. try? overrideArray = context.fetch(requestOverrides)
  259. var tempTargetsArray = [TempTargets]()
  260. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  261. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  262. requestTempTargets.sortDescriptors = [sortTT]
  263. requestTempTargets.fetchLimit = 1
  264. try? tempTargetsArray = context.fetch(requestTempTargets)
  265. let total = uniqueEvents.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  266. var indeces = uniqueEvents.count
  267. // Only fetch once. Use same (previous) fetch
  268. let twoHoursArray = uniqueEvents.filter({ ($0.timestamp ?? Date()) >= twoHoursAgo })
  269. var nrOfIndeces = twoHoursArray.count
  270. let totalAmount = twoHoursArray.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  271. var temptargetActive = tempTargetsArray.first?.active ?? false
  272. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  273. var useOverride = overrideArray.first?.enabled ?? false
  274. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  275. var unlimited = overrideArray.first?.indefinite ?? true
  276. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  277. let currentTDD = (uniqueEvents.last?.totalDailyDose ?? 0) as Decimal
  278. if indeces == 0 {
  279. indeces = 1
  280. }
  281. if nrOfIndeces == 0 {
  282. nrOfIndeces = 1
  283. }
  284. let average2hours = totalAmount / Decimal(nrOfIndeces)
  285. let average14 = total / Decimal(indeces)
  286. let weight = wp
  287. let weighted_average = weight * average2hours + (1 - weight) * average14
  288. var duration: Decimal = 0
  289. var newDuration: Decimal = 0
  290. var overrideTarget: Decimal = 0
  291. if useOverride {
  292. duration = (overrideArray.first?.duration ?? 0) as Decimal
  293. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  294. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  295. let addedMinutes = Int(duration)
  296. let date = overrideArray.first?.date ?? Date()
  297. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  298. !unlimited
  299. {
  300. useOverride = false
  301. let saveToCoreData = Override(context: self.context)
  302. saveToCoreData.enabled = false
  303. saveToCoreData.date = Date()
  304. saveToCoreData.duration = 0
  305. saveToCoreData.indefinite = false
  306. saveToCoreData.percentage = 100
  307. do {
  308. guard self.context.hasChanges else { return "{}" }
  309. try self.context.save()
  310. } catch {
  311. print(error.localizedDescription)
  312. }
  313. }
  314. }
  315. if !useOverride {
  316. unlimited = true
  317. overridePercentage = 100
  318. duration = 0
  319. overrideTarget = 0
  320. disableSMBs = false
  321. }
  322. if temptargetActive {
  323. var duration_ = 0
  324. var hbt = Double(hbt_)
  325. var dd = 0.0
  326. if temptargetActive {
  327. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  328. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  329. let startDate = tempTargetsArray.first?.startDate ?? Date()
  330. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  331. dd = durationPlusStart.timeIntervalSinceNow.minutes
  332. if dd > 0.1 {
  333. hbt_ = Decimal(hbt)
  334. temptargetActive = true
  335. } else {
  336. temptargetActive = false
  337. }
  338. }
  339. }
  340. if currentTDD > 0 {
  341. let averages = Oref2_variables(
  342. average_total_data: average14,
  343. weightedAverage: weighted_average,
  344. past2hoursAverage: average2hours,
  345. date: Date(),
  346. isEnabled: temptargetActive,
  347. presetActive: isPercentageEnabled,
  348. overridePercentage: overridePercentage,
  349. useOverride: useOverride,
  350. duration: duration,
  351. unlimited: unlimited,
  352. hbt: hbt_,
  353. overrideTarget: overrideTarget,
  354. smbIsOff: disableSMBs,
  355. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  356. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  357. isf: overrideArray.first?.isf ?? false,
  358. cr: overrideArray.first?.cr ?? false,
  359. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  360. start: (overrideArray.first?.start ?? 0) as Decimal,
  361. end: (overrideArray.first?.end ?? 0) as Decimal,
  362. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  363. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  364. )
  365. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  366. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  367. } else {
  368. let averages = Oref2_variables(
  369. average_total_data: 0,
  370. weightedAverage: 1,
  371. past2hoursAverage: 0,
  372. date: Date(),
  373. isEnabled: temptargetActive,
  374. presetActive: isPercentageEnabled,
  375. overridePercentage: overridePercentage,
  376. useOverride: useOverride,
  377. duration: duration,
  378. unlimited: unlimited,
  379. hbt: hbt_,
  380. overrideTarget: overrideTarget,
  381. smbIsOff: disableSMBs,
  382. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  383. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  384. isf: overrideArray.first?.isf ?? false,
  385. cr: overrideArray.first?.cr ?? false,
  386. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  387. start: (overrideArray.first?.start ?? 0) as Decimal,
  388. end: (overrideArray.first?.end ?? 0) as Decimal,
  389. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  390. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  391. )
  392. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  393. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  394. }
  395. }
  396. }
  397. func autosense() -> Future<Autosens?, Never> {
  398. Future { promise in
  399. self.processQueue.async {
  400. debug(.openAPS, "Start autosens")
  401. // pump history
  402. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  403. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  404. // carbs
  405. let carbsAsJSON = self.fetchAndProcessCarbs()
  406. /// glucose
  407. let glucoseAsJSON = self.fetchAndProcessGlucose()
  408. let profile = self.loadFileFromStorage(name: Settings.profile)
  409. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  410. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  411. let autosensResult = self.autosense(
  412. glucose: glucoseAsJSON,
  413. pumpHistory: pumpHistoryJSON,
  414. basalprofile: basalProfile,
  415. profile: profile,
  416. carbs: carbsAsJSON,
  417. temptargets: tempTargets
  418. )
  419. debug(.openAPS, "AUTOSENS: \(autosensResult)")
  420. if var autosens = Autosens(from: autosensResult) {
  421. autosens.timestamp = Date()
  422. self.storage.save(autosens, as: Settings.autosense)
  423. promise(.success(autosens))
  424. } else {
  425. promise(.success(nil))
  426. }
  427. }
  428. }
  429. }
  430. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) -> Future<Autotune?, Never> {
  431. Future { promise in
  432. self.processQueue.async {
  433. debug(.openAPS, "Start autotune")
  434. // pump history
  435. let pumpHistoryObjectIDs = self.fetchPumpHistoryObjectIDs() ?? []
  436. let pumpHistoryJSON = self.parsePumpHistory(pumpHistoryObjectIDs)
  437. /// glucose
  438. let glucoseAsJSON = self.fetchAndProcessGlucose()
  439. let profile = self.loadFileFromStorage(name: Settings.profile)
  440. let pumpProfile = self.loadFileFromStorage(name: Settings.pumpProfile)
  441. // carbs
  442. let carbsAsJSON = self.fetchAndProcessCarbs()
  443. let autotunePreppedGlucose = self.autotunePrepare(
  444. pumphistory: pumpHistoryJSON,
  445. profile: profile,
  446. glucose: glucoseAsJSON,
  447. pumpprofile: pumpProfile,
  448. carbs: carbsAsJSON,
  449. categorizeUamAsBasal: categorizeUamAsBasal,
  450. tuneInsulinCurve: tuneInsulinCurve
  451. )
  452. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  453. let previousAutotune = self.storage.retrieve(Settings.autotune, as: RawJSON.self)
  454. let autotuneResult = self.autotuneRun(
  455. autotunePreparedData: autotunePreppedGlucose,
  456. previousAutotuneResult: previousAutotune ?? profile,
  457. pumpProfile: pumpProfile
  458. )
  459. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  460. if let autotune = Autotune(from: autotuneResult) {
  461. self.storage.save(autotuneResult, as: Settings.autotune)
  462. promise(.success(autotune))
  463. } else {
  464. promise(.success(nil))
  465. }
  466. }
  467. }
  468. }
  469. func makeProfiles(useAutotune: Bool) -> Future<Autotune?, Never> {
  470. Future { promise in
  471. debug(.openAPS, "Start makeProfiles")
  472. self.processQueue.async {
  473. var preferences = self.loadFileFromStorage(name: Settings.preferences)
  474. if preferences.isEmpty {
  475. preferences = Preferences().rawJSON
  476. }
  477. let pumpSettings = self.loadFileFromStorage(name: Settings.settings)
  478. let bgTargets = self.loadFileFromStorage(name: Settings.bgTargets)
  479. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  480. let isf = self.loadFileFromStorage(name: Settings.insulinSensitivities)
  481. let cr = self.loadFileFromStorage(name: Settings.carbRatios)
  482. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  483. let model = self.loadFileFromStorage(name: Settings.model)
  484. let autotune = useAutotune ? self.loadFileFromStorage(name: Settings.autotune) : .empty
  485. let freeaps = self.loadFileFromStorage(name: FreeAPS.settings)
  486. let pumpProfile = self.makeProfile(
  487. preferences: preferences,
  488. pumpSettings: pumpSettings,
  489. bgTargets: bgTargets,
  490. basalProfile: basalProfile,
  491. isf: isf,
  492. carbRatio: cr,
  493. tempTargets: tempTargets,
  494. model: model,
  495. autotune: RawJSON.null,
  496. freeaps: freeaps
  497. )
  498. let profile = self.makeProfile(
  499. preferences: preferences,
  500. pumpSettings: pumpSettings,
  501. bgTargets: bgTargets,
  502. basalProfile: basalProfile,
  503. isf: isf,
  504. carbRatio: cr,
  505. tempTargets: tempTargets,
  506. model: model,
  507. autotune: autotune.isEmpty ? .null : autotune,
  508. freeaps: freeaps
  509. )
  510. self.storage.save(pumpProfile, as: Settings.pumpProfile)
  511. self.storage.save(profile, as: Settings.profile)
  512. if let tunedProfile = Autotune(from: profile) {
  513. promise(.success(tunedProfile))
  514. return
  515. }
  516. promise(.success(nil))
  517. }
  518. }
  519. }
  520. // MARK: - Private
  521. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) -> RawJSON {
  522. dispatchPrecondition(condition: .onQueue(processQueue))
  523. return jsWorker.inCommonContext { worker in
  524. worker.evaluate(script: Script(name: Prepare.log))
  525. worker.evaluate(script: Script(name: Bundle.iob))
  526. worker.evaluate(script: Script(name: Prepare.iob))
  527. return worker.call(function: Function.generate, with: [
  528. pumphistory,
  529. profile,
  530. clock,
  531. autosens
  532. ])
  533. }
  534. }
  535. private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> RawJSON {
  536. dispatchPrecondition(condition: .onQueue(processQueue))
  537. return jsWorker.inCommonContext { worker in
  538. worker.evaluate(script: Script(name: Prepare.log))
  539. worker.evaluate(script: Script(name: Bundle.meal))
  540. worker.evaluate(script: Script(name: Prepare.meal))
  541. return worker.call(function: Function.generate, with: [
  542. pumphistory,
  543. profile,
  544. clock,
  545. glucose,
  546. basalProfile,
  547. carbs
  548. ])
  549. }
  550. }
  551. private func autotunePrepare(
  552. pumphistory: JSON,
  553. profile: JSON,
  554. glucose: JSON,
  555. pumpprofile: JSON,
  556. carbs: JSON,
  557. categorizeUamAsBasal: Bool,
  558. tuneInsulinCurve: Bool
  559. ) -> RawJSON {
  560. dispatchPrecondition(condition: .onQueue(processQueue))
  561. return jsWorker.inCommonContext { worker in
  562. worker.evaluate(script: Script(name: Prepare.log))
  563. worker.evaluate(script: Script(name: Bundle.autotunePrep))
  564. worker.evaluate(script: Script(name: Prepare.autotunePrep))
  565. return worker.call(function: Function.generate, with: [
  566. pumphistory,
  567. profile,
  568. glucose,
  569. pumpprofile,
  570. carbs,
  571. categorizeUamAsBasal,
  572. tuneInsulinCurve
  573. ])
  574. }
  575. }
  576. private func autotuneRun(
  577. autotunePreparedData: JSON,
  578. previousAutotuneResult: JSON,
  579. pumpProfile: JSON
  580. ) -> RawJSON {
  581. dispatchPrecondition(condition: .onQueue(processQueue))
  582. return jsWorker.inCommonContext { worker in
  583. worker.evaluate(script: Script(name: Prepare.log))
  584. worker.evaluate(script: Script(name: Bundle.autotuneCore))
  585. worker.evaluate(script: Script(name: Prepare.autotuneCore))
  586. return worker.call(function: Function.generate, with: [
  587. autotunePreparedData,
  588. previousAutotuneResult,
  589. pumpProfile
  590. ])
  591. }
  592. }
  593. private func determineBasal(
  594. glucose: JSON,
  595. currentTemp: JSON,
  596. iob: JSON,
  597. profile: JSON,
  598. autosens: JSON,
  599. meal: JSON,
  600. microBolusAllowed: Bool,
  601. reservoir: JSON,
  602. pumpHistory: JSON,
  603. preferences: JSON,
  604. basalProfile: JSON,
  605. oref2_variables: JSON
  606. ) -> RawJSON {
  607. dispatchPrecondition(condition: .onQueue(processQueue))
  608. return jsWorker.inCommonContext { worker in
  609. worker.evaluate(script: Script(name: Prepare.log))
  610. worker.evaluate(script: Script(name: Prepare.determineBasal))
  611. worker.evaluate(script: Script(name: Bundle.basalSetTemp))
  612. worker.evaluate(script: Script(name: Bundle.getLastGlucose))
  613. worker.evaluate(script: Script(name: Bundle.determineBasal))
  614. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  615. worker.evaluate(script: middleware)
  616. }
  617. return worker.call(
  618. function: Function.generate,
  619. with: [
  620. iob,
  621. currentTemp,
  622. glucose,
  623. profile,
  624. autosens,
  625. meal,
  626. microBolusAllowed,
  627. reservoir,
  628. Date(),
  629. pumpHistory,
  630. preferences,
  631. basalProfile,
  632. oref2_variables
  633. ]
  634. )
  635. }
  636. }
  637. private func autosense(
  638. glucose: JSON,
  639. pumpHistory: JSON,
  640. basalprofile: JSON,
  641. profile: JSON,
  642. carbs: JSON,
  643. temptargets: JSON
  644. ) -> RawJSON {
  645. dispatchPrecondition(condition: .onQueue(processQueue))
  646. return jsWorker.inCommonContext { worker in
  647. worker.evaluate(script: Script(name: Prepare.log))
  648. worker.evaluate(script: Script(name: Bundle.autosens))
  649. worker.evaluate(script: Script(name: Prepare.autosens))
  650. return worker.call(
  651. function: Function.generate,
  652. with: [
  653. glucose,
  654. pumpHistory,
  655. basalprofile,
  656. profile,
  657. carbs,
  658. temptargets
  659. ]
  660. )
  661. }
  662. }
  663. private func exportDefaultPreferences() -> RawJSON {
  664. dispatchPrecondition(condition: .onQueue(processQueue))
  665. return jsWorker.inCommonContext { worker in
  666. worker.evaluate(script: Script(name: Prepare.log))
  667. worker.evaluate(script: Script(name: Bundle.profile))
  668. worker.evaluate(script: Script(name: Prepare.profile))
  669. return worker.call(function: Function.exportDefaults, with: [])
  670. }
  671. }
  672. private func makeProfile(
  673. preferences: JSON,
  674. pumpSettings: JSON,
  675. bgTargets: JSON,
  676. basalProfile: JSON,
  677. isf: JSON,
  678. carbRatio: JSON,
  679. tempTargets: JSON,
  680. model: JSON,
  681. autotune: JSON,
  682. freeaps: JSON
  683. ) -> RawJSON {
  684. dispatchPrecondition(condition: .onQueue(processQueue))
  685. return jsWorker.inCommonContext { worker in
  686. worker.evaluate(script: Script(name: Prepare.log))
  687. worker.evaluate(script: Script(name: Bundle.profile))
  688. worker.evaluate(script: Script(name: Prepare.profile))
  689. return worker.call(
  690. function: Function.generate,
  691. with: [
  692. pumpSettings,
  693. bgTargets,
  694. isf,
  695. basalProfile,
  696. preferences,
  697. carbRatio,
  698. tempTargets,
  699. model,
  700. autotune,
  701. freeaps
  702. ]
  703. )
  704. }
  705. }
  706. private func loadJSON(name: String) -> String {
  707. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  708. }
  709. private func loadFileFromStorage(name: String) -> RawJSON {
  710. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  711. }
  712. private func middlewareScript(name: String) -> Script? {
  713. if let body = storage.retrieveRaw(name) {
  714. return Script(name: "Middleware", body: body)
  715. }
  716. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  717. return Script(name: "Middleware", body: try! String(contentsOf: url))
  718. }
  719. return nil
  720. }
  721. static func defaults(for file: String) -> RawJSON {
  722. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  723. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  724. return ""
  725. }
  726. return (try? String(contentsOf: url)) ?? ""
  727. }
  728. func processAndSave(forecastData: [String: [Int]]) {
  729. let currentDate = Date()
  730. context.perform {
  731. for (type, values) in forecastData {
  732. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  733. }
  734. do {
  735. guard self.context.hasChanges else { return }
  736. try self.context.save()
  737. } catch {
  738. print(error.localizedDescription)
  739. }
  740. }
  741. }
  742. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  743. let forecast = Forecast(context: context)
  744. forecast.id = UUID()
  745. forecast.date = date
  746. forecast.type = type
  747. for (index, value) in values.enumerated() {
  748. let forecastValue = ForecastValue(context: context)
  749. forecastValue.value = Int32(value)
  750. forecastValue.index = Int32(index)
  751. forecastValue.forecast = forecast
  752. }
  753. }
  754. }