OpenAPS.swift 36 KB

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