OpenAPS.swift 35 KB

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