OpenAPS.swift 33 KB

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