OpenAPS.swift 35 KB

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