From b077b1d5b1b213930df8e9c264f5444fcce9f224 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Mar 2021 22:47:45 +0100 Subject: [PATCH 1/5] load Action String Handler --- .../plugins/general/wear/ActionStringHandler.kt | 8 ++++++-- .../androidaps/plugins/general/wear/WearPlugin.kt | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 8216e093fc..1fa4210b9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -59,7 +59,7 @@ class ActionStringHandler @Inject constructor( private val sp: SP, private val rxBus: RxBusWrapper, private val aapsLogger: AAPSLogger, - aapsSchedulers: AapsSchedulers, + private val aapsSchedulers: AapsSchedulers, private val resourceHelper: ResourceHelper, private val injector: HasAndroidInjector, private val context: Context, @@ -92,7 +92,7 @@ class ActionStringHandler @Inject constructor( private val disposable = CompositeDisposable() - init { + fun setup() { disposable += rxBus .toObservable(EventWearInitiateAction::class.java) .observeOn(aapsSchedulers.main) @@ -104,6 +104,10 @@ class ActionStringHandler @Inject constructor( .subscribe({ handleConfirmation(it.action) }, fabricPrivacy::logException) } + fun tearDown(){ + disposable.clear() + } + @Synchronized private fun handleInitiate(actionString: String) { if (!sp.getBoolean(R.string.key_wear_control, false)) return diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index f3cdd7a7f2..74bd00d7f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -35,7 +35,8 @@ class WearPlugin @Inject constructor( private val mainApp: MainApp, private val fabricPrivacy: FabricPrivacy, private val loopPlugin: Lazy, - private val rxBus: RxBusWrapper + private val rxBus: RxBusWrapper, + private val actionStringHandler: Lazy ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) @@ -127,11 +128,13 @@ class WearPlugin @Inject constructor( mainApp.startService(intent) } }, fabricPrivacy::logException)) + actionStringHandler.get().setup() } override fun onStop() { disposable.clear() super.onStop() + actionStringHandler.get().setup() } private fun sendDataToWatch(status: Boolean, basals: Boolean, bgValue: Boolean) { From 57f9fa073055c36ccd85c720934b6df825c6aa98 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Mar 2021 22:49:22 +0100 Subject: [PATCH 2/5] correct call of teardown wear plugin --- .../nightscout/androidaps/plugins/general/wear/WearPlugin.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index 74bd00d7f0..e4a486a89e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -134,7 +134,7 @@ class WearPlugin @Inject constructor( override fun onStop() { disposable.clear() super.onStop() - actionStringHandler.get().setup() + actionStringHandler.get().tearDown() } private fun sendDataToWatch(status: Boolean, basals: Boolean, bgValue: Boolean) { From bd72473253f8e2dfb86ad3f591a8f97995de3f0b Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 28 Mar 2021 20:42:15 +0100 Subject: [PATCH 3/5] - checked all PumpHistoryEntryType entries and removed most of the ones that are not in go code from Eric - fixed problem with BGReceived512 --- .../pump/MedtronicPumpHistoryDecoder.java | 44 ++++----- .../history/pump/PumpHistoryEntryType.java | 97 +++++++------------ .../medtronic/data/MedtronicHistoryData.java | 20 ++-- .../MedtronicPumpHistoryDecoderUTest.java | 48 ++++----- 4 files changed, 92 insertions(+), 117 deletions(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java index 3a6c4851ec..04d715063a 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java @@ -205,7 +205,7 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder getSuspendResumeRecords() { List filteredItems = getFilteredItems(this.newHistory, // - PumpHistoryEntryType.Suspend, // - PumpHistoryEntryType.Resume); + PumpHistoryEntryType.SuspendPump, // + PumpHistoryEntryType.ResumePump); List outList = new ArrayList<>(); @@ -1145,14 +1145,14 @@ public class MedtronicHistoryData { List filtered2Items = new ArrayList<>(); - if ((filteredItems.size() % 2 == 0) && (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.Resume)) { + if ((filteredItems.size() % 2 == 0) && (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.ResumePump)) { // full resume suspends (S R S R) filtered2Items.addAll(filteredItems); - } else if ((filteredItems.size() % 2 == 0) && (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.Suspend)) { + } else if ((filteredItems.size() % 2 == 0) && (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.SuspendPump)) { // not full suspends, need to retrive one more record and discard first one (R S R S) -> ([S] R S R [xS]) filteredItems.remove(0); - PumpHistoryEntry oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.Suspend); + PumpHistoryEntry oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.SuspendPump); if (oneMoreEntryFromHistory != null) { filteredItems.add(oneMoreEntryFromHistory); } else { @@ -1161,10 +1161,10 @@ public class MedtronicHistoryData { filtered2Items.addAll(filteredItems); } else { - if (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.Resume) { + if (filteredItems.get(0).getEntryType() == PumpHistoryEntryType.ResumePump) { // get one more from history (R S R) -> ([S] R S R) - PumpHistoryEntry oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.Suspend); + PumpHistoryEntry oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.SuspendPump); if (oneMoreEntryFromHistory != null) { filteredItems.add(oneMoreEntryFromHistory); } else { diff --git a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java index 999cd7ae23..fe7f001654 100644 --- a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java +++ b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,24 +53,6 @@ public class MedtronicPumpHistoryDecoderUTest { /* - MedtronicPumpHistoryDecoder decoder = new MedtronicPumpHistoryDecoder(); - - - @Before - public void setup() { - - System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace"); - - // final TestAppender appender = new TestAppender(); - // final Logger logger = Logger.getRootLogger(); - // logger.addAppender(appender); - // try { - // Logger.getLogger(MyTest.class).info("Test"); - // } finally { - // logger.removeAppender(appender); - // } - } - // @Test public void decodeRecord() throws Exception { @@ -197,26 +180,43 @@ public class MedtronicPumpHistoryDecoderUTest { @Test public void historyProblem_148_amunhateb() throws Exception { - byte[] historyPageData = ByteUtil.createByteArrayFromString( - "5A 0F 20 F4 0C 03 15 19 11 00 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 11 00 0F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 01 12 12 00 25 DE 2D 43 15 01 50 50 00 26 EA 2D 43 15 01 4B 4B 00 2C C9 34 43 15 62 00 2F CB 17 03 15 01 33 33 00 16 DE 37 43 15 07 00 00 07 FE 23 95 6D 23 95 0A 08 00 2B 00 00 00 00 07 FE 03 8E 2C 04 70 38 00 00 04 70 38 00 00 00 00 00 00 04 70 64 06 00 00 00 06 08 00 2B 00 00 00 2C A0 2F E3 01 04 15 33 00 2F E7 04 44 15 00 16 03 2F E7 04 44 15 33 28 3B C2 06 44 15 00 16 01 3B C2 06 44 15 08 08 17 DB 0B 44 15 00 26 00 06 26 00 0C 26 00 12 28 00 18 26 00 1E 26 00 24 24 00 2A 26 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 18 17 DB 0B 44 15 00 26 00 02 26 00 04 26 00 06 24 00 08 24 00 0A 24 00 0C 26 00 0E 26 00 10 26 00 12 28 00 14 28 00 16 28 00 18 26 00 1A 26 00 1C 26 00 1E 26 00 20 26 00 22 26 00 24 24 00 26 24 00 28 24 00 2A 26 00 2C 26 00 2E 26 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 45 45 00 28 E9 2B 44 15 19 00 00 C1 0D 04 15 1A 00 15 C3 0D 04 15 1A 01 33 C3 0D 04 15 01 28 28 00 07 CC 2E 44 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 2D"); + List pumpHistoryEntries = readAndParseHistoryPage("5A 0F 20 F4 0C 03 15 19 11 00 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1A 11 00 0F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 1E 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 32 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 01 12 12 00 25 DE 2D 43 15 01 50 50 00 26 EA 2D 43 15 01 4B 4B 00 2C C9 34 43 15 62 00 2F CB 17 03 15 01 33 33 00 16 DE 37 43 15 07 00 00 07 FE 23 95 6D 23 95 0A 08 00 2B 00 00 00 00 07 FE 03 8E 2C 04 70 38 00 00 04 70 38 00 00 00 00 00 00 04 70 64 06 00 00 00 06 08 00 2B 00 00 00 2C A0 2F E3 01 04 15 33 00 2F E7 04 44 15 00 16 03 2F E7 04 44 15 33 28 3B C2 06 44 15 00 16 01 3B C2 06 44 15 08 08 17 DB 0B 44 15 00 26 00 06 26 00 0C 26 00 12 28 00 18 26 00 1E 26 00 24 24 00 2A 26 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 09 18 17 DB 0B 44 15 00 26 00 02 26 00 04 26 00 06 24 00 08 24 00 0A 24 00 0C 26 00 0E 26 00 10 26 00 12 28 00 14 28 00 16 28 00 18 26 00 1A 26 00 1C 26 00 1E 26 00 20 26 00 22 26 00 24 24 00 26 24 00 28 24 00 2A 26 00 2C 26 00 2E 26 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 45 45 00 28 E9 2B 44 15 19 00 00 C1 0D 04 15 1A 00 15 C3 0D 04 15 1A 01 33 C3 0D 04 15 01 28 28 00 07 CC 2E 44 15 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 14 2D", + MedtronicDeviceType.Medtronic_522_722); - System.out.println("HDP:" + historyPageData.length); + Assert.assertEquals(20, pumpHistoryEntries.size()); + } - medtronicUtil.setMedtronicPumpModel(MedtronicDeviceType.Medtronic_522_722); + @Test + public void historyProblem_423_duzy78() throws Exception { + List pumpHistoryEntries = readAndParseHistoryPage("16 00 08 D0 0E 51 15 33 60 0A D0 0E 51 15 00 16 01 0A D0 0E 51 15 33 00 07 DF 0E 51 15 00 16 00 07 DF 0E 51 15 33 6C 09 DF 0E 51 15 00 16 01 09 DF 0E 51 15 33 00 25 ED 0E 51 15 00 16 00 25 ED 0E 51 15 33 2C 27 ED 0E 51 15 00 16 01 27 ED 0E 51 15 33 00 07 F4 0E 51 15 00 16 00 07 F4 0E 51 15 33 00 09 F4 0E 51 15 00 16 01 09 F4 0E 51 15 33 2C 25 D5 0F 51 15 00 16 01 25 D5 0F 51 15 01 3C 3C 00 30 D5 4F 51 15 33 2C 25 F7 0F 51 15 00 16 01 25 F7 0F 51 15 33 00 07 C6 10 51 15 00 16 00 07 C6 10 51 15 33 30 09 C6 10 51 15 00 16 01 09 C6 10 51 15 33 30 25 E8 10 51 15 00 16 01 25 E8 10 51 15 33 30 24 CF 11 51 15 00 16 01 24 CF 11 51 15 33 00 23 E4 11 51 15 00 16 00 23 E4 11 51 15 33 3C 25 E4 11 51 15 00 16 01 25 E4 11 51 15 33 00 23 E8 11 51 15 00 16 00 23 E8 11 51 15 33 4A 25 E8 11 51 15 00 16 01 25 E8 11 51 15 33 00 19 EE 11 51 15 00 16 00 19 EE 11 51 15 33 30 1B EE 11 51 15 00 16 01 1B EE 11 51 15 33 00 23 F2 11 51 15 00 16 00 23 F2 11 51 15 33 3E 25 F2 11 51 15 00 16 01 25 F2 11 51 15 33 00 24 C0 12 51 15 00 16 00 24 C0 12 51 15 33 5E 25 C0 12 51 15 00 16 01 25 C0 12 51 15 33 00 23 CF 12 51 15 00 16 00 23 CF 12 51 15 33 64 25 CF 12 51 15 00 16 01 25 CF 12 51 15 33 00 23 D9 12 51 15 00 16 00 23 D9 12 51 15 33 6A 25 D9 12 51 15 00 16 01 25 D9 12 51 15 33 00 23 E9 12 51 15 00 16 00 23 E9 12 51 15 33 30 25 E9 12 51 15 00 16 01 25 E9 12 51 15 01 16 16 00 10 C2 53 51 15 33 30 24 CF 13 51 15 00 16 01 24 CF 13 51 15 33 30 04 EE 13 51 15 00 16 01 04 EE 13 51 15 01 14 14 00 3B F0 53 51 15 33 00 22 C0 14 51 15 00 16 00 22 C0 14 51 15 33 22 24 C0 14 51 15 00 16 01 24 C0 14 51 15 33 22 03 DF 14 51 15 00 16 01 03 DF 14 51 15 1E 00 37 E1 14 11 15 1F 00 01 EE 14 11 15 33 22 03 C6 15 51 15 00 16 01 03 C6 15 51 15 33 00 20 D9 15 51 15 00 16 00 20 D9 15 51 15 33 34 22 D9 15 51 15 00 16 01 22 D9 15 51 15 39 14 0E DF 35 71 15 83 92 40 01 0B 0B 00 37 E0 55 51 15 33 00 21 E3 15 51 15 00 16 00 21 E3 15 51 15 33 22 22 E3 15 51 15 00 16 01 22 E3 15 51 15 33 00 21 E8 15 51 15 00 16 00 21 E8 15 51 15 33 30 23 E8 15 51 15 00 16 01 23 E8 15 51 15 33 00 20 ED 15 51 15 00 16 00 20 ED 15 51 15 33 22 22 ED 15 51 15 00 16 01 22 ED 15 51 15 33 00 03 F8 15 51 15 00 16 00 03 F8 15 51 15 33 32 05 F8 15 51 15 00 16 01 05 F8 15 51 15 33 00 01 CB 16 51 15 00 16 00 01 CB 16 51 15 33 20 03 CB 16 51 15 00 16 01 03 CB 16 51 15 33 2A 20 ED 16 51 15 00 16 01 20 ED 16 51 15 33 00 02 F8 16 51 15 00 16 00 02 F8 16 51 15 33 2C 04 F8 16 51 15 00 16 01 04 F8 16 51 15 33 00 1F CA 17 51 15 00 16 00 1F CA 17 51 15 33 34 21 CA 17 51 15 00 16 01 21 CA 17 51 15 33 00 1F D4 17 51 15 00 16 00 1F D4 17 51 15 33 38 21 D4 17 51 15 00 16 01 21 D4 17 51 15 33 00 15 EE 17 51 15 00 16 00 15 EE 17 51 15 33 42 17 EE 17 51 15 00 16 01 17 EE 17 51 15 07 00 00 08 0A 31 95 6C 31 95 05 00 A1 A1 A1 01 00 00 08 0A 04 8E 39 03 7C 2B 00 00 03 7C 2B 00 00 00 00 00 00 03 7C 64 07 00 00 00 07 33 00 05 C1 00 52 15 00 16 00 05 C1 00 52 15 33 50 07 C1 00 52 15 00 16 01 07 C1 00 52 15 33 00 01 CB 00 52 15 00 16 00 01 CB 00 52 15 33 26 03 CB 00 52 15 00 16 01 03 CB 00 52 15 33 00 1E DE 00 52 15 00 00 00 8F 0E", + MedtronicDeviceType.Medtronic_515_715); + + Assert.assertEquals(131, pumpHistoryEntries.size()); + } + + + private List readAndParseHistoryPage(String historyPageString, MedtronicDeviceType medtronicDeviceType) throws Exception { + byte[] historyPageData = ByteUtil.createByteArrayFromString(historyPageString); + + aapsLogger.debug("History Page Length:" + historyPageData.length); + + medtronicUtil.setMedtronicPumpModel(medtronicDeviceType); RawHistoryPage historyPage = new RawHistoryPage(aapsLogger); historyPage.appendData(historyPageData); List pumpHistoryEntries = decoder.processPageAndCreateRecords(historyPage); - System.out.println("PumpHistoryEntries: " + pumpHistoryEntries.size()); - displayHistoryRecords(pumpHistoryEntries); + + return pumpHistoryEntries; } private void displayHistoryRecords(List pumpHistoryEntries) { + aapsLogger.debug("PumpHistoryEntries: " + pumpHistoryEntries.size()); + for (PumpHistoryEntry pumpHistoryEntry : pumpHistoryEntries) { aapsLogger.debug(pumpHistoryEntry.toString()); } From e9f4f8789422133699c5ff2ef70416a569b52bd0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 30 Mar 2021 19:37:26 +0200 Subject: [PATCH 4/5] Remove Tratment.class where possible --- .../androidaps/db/CompatDBHelper.kt | 4 +- .../androidaps/dialogs/CarbsDialog.kt | 4 +- .../androidaps/dialogs/InsulinDialog.kt | 2 +- .../androidaps/events/EventNsTreatment.kt | 21 -- .../androidaps/events/EventTreatmentChange.kt | 4 +- .../androidaps/plugins/aps/loop/LoopPlugin.kt | 10 +- .../aps/openAPSAMA/DetermineBasalResultAMA.kt | 3 +- .../aps/openAPSSMB/DetermineBasalResultSMB.kt | 2 +- .../maintenance/MaintenanceFragment.kt | 7 +- .../DataSyncSelectorImplementation.kt | 9 +- .../nsclient/NSClientAddUpdateWorker.kt | 57 ++++- .../general/nsclient/NSClientRemoveWorker.kt | 46 +++- .../general/openhumans/OpenHumansUploader.kt | 12 +- .../general/overview/OverviewFragment.kt | 3 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 83 +++---- .../general/tidepool/comm/UploadChunk.kt | 16 +- .../general/tidepool/elements/BolusElement.kt | 19 +- .../tidepool/elements/WizardElement.kt | 37 ++-- .../general/tidepool/utils/RateLimit.kt | 7 +- .../general/wear/ActionStringHandler.kt | 11 +- .../wearintegration/WatchUpdaterService.java | 2 + .../plugins/insulin/ActivityGraph.kt | 14 +- .../IobCobCalculatorPlugin.kt | 30 ++- .../androidaps/plugins/pump/mdi/MDIPlugin.kt | 21 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 18 +- .../sensitivity/SensitivityOref1Plugin.kt | 1 + .../plugins/source/RandomBgPlugin.kt | 3 +- .../plugins/treatments/TreatmentService.java | 203 +----------------- .../plugins/treatments/TreatmentsPlugin.java | 27 ++- .../fragments/TreatmentsBolusCarbsFragment.kt | 9 +- .../androidaps/queue/CommandQueue.kt | 3 +- .../queue/commands/CommandSMBBolus.kt | 2 +- .../androidaps/utils/stats/TddCalculator.kt | 5 +- .../layout/treatments_bolus_carbs_item.xml | 62 +++--- app/src/main/res/values/strings.xml | 1 + .../SmsCommunicatorPluginTest.kt | 30 --- .../androidaps/queue/CommandQueueTest.kt | 13 +- .../androidaps/queue/QueueThreadTest.kt | 2 +- .../general/automation/triggers/Trigger.kt | 5 +- .../automation/triggers/TriggerBolusAgo.kt | 9 +- .../triggers/TriggerRecurringTime.kt | 5 +- .../automation/triggers/TriggerTempTarget.kt | 6 - .../automation/triggers/TriggerTime.kt | 6 +- .../automation/triggers/TriggerTimeRange.kt | 6 +- .../general/automation/TestBaseWithProfile.kt | 4 +- .../automation/actions/ActionsTestBase.kt | 4 +- .../triggers/TriggerBolusAgoTest.kt | 21 +- .../automation/triggers/TriggerTestBase.kt | 9 +- .../plugins/pump/combo/ComboPlugin.java | 7 +- .../androidaps/data/PumpEnactResult.kt | 5 +- .../nightscout/androidaps/db/Treatment.java | 8 - .../androidaps/interfaces/PumpSync.kt | 59 ++++- .../interfaces/TreatmentServiceInterface.kt | 9 - .../interfaces/TreatmentsInterface.java | 4 - .../androidaps/plugins/aps/loop/APSResult.kt | 2 + .../plugins/general/nsclient/NSUpload.java | 7 +- .../events/EventOverviewBolusProgress.kt | 4 +- .../iobCobCalculator/data/AutosensData.java | 1 - .../plugins/pump/PumpSyncImplementation.kt | 88 +++++--- .../treatments/TreatmentUpdateReturn.java | 2 - .../androidaps/queue/commands/Command.kt | 2 + .../utils/extensions/BolusExtension.kt | 48 ++++- .../utils/extensions/CarbsExtension.kt | 43 +++- .../nightscout/androidaps/dana/DanaPump.kt | 4 +- .../danaRKorean/DanaRKoreanPlugin.java | 40 +++- .../services/DanaRKoreanExecutionService.java | 4 +- .../androidaps/danaRv2/DanaRv2Plugin.java | 5 +- .../services/DanaRv2ExecutionService.java | 3 +- .../androidaps/danar/DanaRPlugin.java | 5 +- .../AbstractDanaRExecutionService.java | 4 +- .../danar/services/DanaRExecutionService.java | 3 +- .../pump/danaR/comm/MsgBolusProgressTest.kt | 6 +- .../pump/danaR/comm/MsgBolusStopTest.kt | 6 +- .../pump/danaRKorean/DanaRKoreanPluginTest.kt | 4 +- .../androidaps/danars/DanaRSPlugin.kt | 5 +- .../comm/DanaRS_Packet_APS_History_Events.kt | 41 ++-- .../danars/services/DanaRSService.kt | 3 +- .../DanaRSPacketNotifyDeliveryCompleteTest.kt | 3 +- .../DanaRsPacketBolusSetStepBolusStopTest.kt | 3 +- ...naRsPacketNotifyDeliveryRateDisplayTest.kt | 3 +- .../8.json | 124 +++++++++-- .../androidaps/database/AppDatabase.kt | 2 +- .../androidaps/database/AppRepository.kt | 13 +- .../androidaps/database/daos/BolusDao.kt | 27 ++- .../androidaps/database/daos/CarbsDao.kt | 9 +- .../database/embedments/InterfaceIDs.kt | 10 +- .../androidaps/database/entities/Bolus.kt | 7 +- .../InsertPumpBolusWithTempIdTransaction.kt | 28 +++ ...idateAAPSStartedTherapyEventTransaction.kt | 2 +- .../transactions/SyncNsBolusTransaction.kt | 50 +++++ .../transactions/SyncNsCarbsTransaction.kt | 50 +++++ .../transactions/SyncPumpBolusTransaction.kt | 12 +- .../SyncPumpBolusWithTempIdTransaction.kt | 33 +++ .../pump/insight/LocalInsightPlugin.java | 4 +- .../pump/common/PumpPluginAbstract.java | 4 +- 95 files changed, 1004 insertions(+), 680 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/InsertPumpBolusWithTempIdTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsBolusTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsCarbsTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusWithTempIdTransaction.kt diff --git a/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt b/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt index 42978b9324..dad08a143a 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt @@ -50,11 +50,11 @@ class CompatDBHelper @Inject constructor( } it.filterIsInstance().firstOrNull()?.let { aapsLogger.debug(LTag.DATABASE, "Firing EventFoodDatabaseChanged") - rxBus.send(EventTreatmentChange(null)) + rxBus.send(EventTreatmentChange()) } it.filterIsInstance().firstOrNull()?.let { aapsLogger.debug(LTag.DATABASE, "Firing EventFoodDatabaseChanged") - rxBus.send(EventTreatmentChange(null)) + rxBus.send(EventTreatmentChange()) } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index 87a0c99e55..ded8ac184d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -277,13 +277,13 @@ class CarbsDialog : DialogFragmentWithDate() { detailedBolusInfo.carbs = carbsAfterConstraints.toDouble() detailedBolusInfo.context = context detailedBolusInfo.notes = notes - detailedBolusInfo.carbsDuration = T.mins(duration.toLong()).msecs() + detailedBolusInfo.carbsDuration = T.hours(duration.toLong()).msecs() detailedBolusInfo.carbsTimestamp = time uel.log(Action.CARBS, detailedBolusInfo.notes, ValueWithUnit(detailedBolusInfo.timestamp, Units.Timestamp), ValueWithUnit(detailedBolusInfo.carbs, Units.G), ValueWithUnit(detailedBolusInfo.carbTime, Units.M, detailedBolusInfo.carbTime != 0), - ValueWithUnit(detailedBolusInfo.carbsDuration, Units.H, detailedBolusInfo.carbsDuration != 0L) + ValueWithUnit(T.msecs(detailedBolusInfo.carbsDuration).hours(), Units.H, detailedBolusInfo.carbsDuration != 0L) ) commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index 99a7cf80ec..c117f39e4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -177,7 +177,7 @@ class InsulinDialog : DialogFragmentWithDate() { actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) val timeOffset = binding.time.value.toInt() - val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs() + val time = dateUtil._now() + T.mins(timeOffset.toLong()).msecs() if (timeOffset != 0) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt deleted file mode 100644 index 149894c221..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.nightscout.androidaps.events - -import org.json.JSONObject - - -/** - * Event which is published with data fetched from NightScout specific for the - * Treatment-class. - * - * - * Payload is the from NS retrieved JSON-String which should be handled by all - * subscriber. - */ - -class EventNsTreatment(val mode: Int, val payload: JSONObject) : Event() { - companion object { - val ADD = 0 - val UPDATE = 1 - val REMOVE = 2 - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt index 679b62ee30..2f25231b00 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt @@ -1,5 +1,3 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.db.Treatment - -class EventTreatmentChange(val treatment: Treatment?) : EventLoop() +class EventTreatmentChange : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index 22b780a4fa..8d7a2f783d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -233,7 +233,9 @@ open class LoopPlugin @Inject constructor( private fun treatmentTimeThreshold(durationMinutes: Int): Boolean { val threshold = System.currentTimeMillis() + durationMinutes * 60 * 1000 var bool = false - if (treatmentsPlugin.lastBolusTime > threshold || treatmentsPlugin.lastCarbTime > threshold) bool = true + val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L + val lastCarbsTime = repository.getLastCarbsRecord()?.timestamp ?: 0L + if (lastBolusTime > threshold || lastCarbsTime > threshold) bool = true return bool } @@ -295,7 +297,7 @@ open class LoopPlugin @Inject constructor( resultAfterConstraints.smb = constraintChecker.applyBolusConstraints(resultAfterConstraints.smbConstraint!!).value() // safety check for multiple SMBs - val lastBolusTime = treatmentsPlugin.lastBolusTime + val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > System.currentTimeMillis()) { aapsLogger.debug(LTag.APS, "SMB requested but still in 3 min interval") resultAfterConstraints.smb = 0.0 @@ -573,7 +575,7 @@ open class LoopPlugin @Inject constructor( return } val pump = activePlugin.activePump - val lastBolusTime = treatmentsPlugin.lastBolusTime + val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L if (lastBolusTime != 0L && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { aapsLogger.debug(LTag.APS, "SMB requested but still in 3 min interval") callback?.result(PumpEnactResult(injector) @@ -595,7 +597,7 @@ open class LoopPlugin @Inject constructor( // deliver SMB val detailedBolusInfo = DetailedBolusInfo() - detailedBolusInfo.lastKnownBolusTime = treatmentsPlugin.lastBolusTime + detailedBolusInfo.lastKnownBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L detailedBolusInfo.eventType = DetailedBolusInfo.EventType.CORRECTION_BOLUS detailedBolusInfo.insulin = request.smb detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.SMB diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt index 8f462b2f19..b93afc5984 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSAMA import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.utils.DateUtil import org.json.JSONException import org.json.JSONObject import org.mozilla.javascript.NativeObject @@ -14,7 +13,7 @@ class DetermineBasalResultAMA private constructor(injector: HasAndroidInjector) private var snoozeBG = 0.0 internal constructor(injector: HasAndroidInjector, result: NativeObject, j: JSONObject) : this(injector) { - date = DateUtil.now() + date = dateUtil._now() json = j if (result.containsKey("error")) { reason = result["error"].toString() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt index 46b68bbd0a..589eff449c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt @@ -13,7 +13,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector) private var snoozeBG = 0.0 internal constructor(injector: HasAndroidInjector, result: JSONObject) : this(injector) { - date = DateUtil.now() + date = dateUtil._now() json = result try { if (result.has("error")) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 32b3001911..e2473b5005 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -8,7 +8,7 @@ import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository -import info.nightscout.androidaps.database.entities.UserEntry.* +import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.events.EventNewBG import info.nightscout.androidaps.interfaces.DatabaseHelperInterface @@ -17,7 +17,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -32,7 +31,6 @@ class MaintenanceFragment : DaggerFragment() { @Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var importExportPrefs: ImportExportPrefsInterface @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @@ -66,9 +64,6 @@ class MaintenanceFragment : DaggerFragment() { compositeDisposable.add( fromAction { databaseHelper.resetDatabases() - // should be handled by Plugin-Interface and - // additional service interface and plugin registry - treatmentsPlugin.service.resetTreatments() repository.clearDatabases() } .subscribeOn(aapsSchedulers.io) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index b3e49e8c16..386c6da064 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -40,9 +40,12 @@ class DataSyncSelectorImplementation @Inject constructor( // Prepared for v3 (returns all modified after) override fun changedBoluses(): List { val startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) - return appRepository.getModifiedBolusesDataFromId(startId).blockingGet().also { - aapsLogger.debug(LTag.NSCLIENT, "Loading Bolus data for sync from $startId. Records ${it.size}") - } + return appRepository.getModifiedBolusesDataFromId(startId) + .blockingGet() + .filter { it.type != Bolus.Type.PRIMING } + .also { + aapsLogger.debug(LTag.NSCLIENT, "Loading Bolus data for sync from $startId. Records ${it.size}") + } } override fun processChangedBolusesCompat(): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt index 2be9f8d4b5..8264e8ed63 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt @@ -9,9 +9,10 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit +import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction +import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction -import info.nightscout.androidaps.events.EventNsTreatment import info.nightscout.androidaps.interfaces.ConfigInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -25,6 +26,8 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetLong import info.nightscout.androidaps.utils.buildHelper.BuildHelper +import info.nightscout.androidaps.utils.extensions.bolusFromJson +import info.nightscout.androidaps.utils.extensions.carbsFromJson import info.nightscout.androidaps.utils.extensions.temporaryTargetFromJson import info.nightscout.androidaps.utils.extensions.therapyEventFromJson import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -73,9 +76,56 @@ class NSClientAddUpdateWorker( if (mills != 0L && mills < dateutil._now()) if (mills > latestDateInReceivedData) latestDateInReceivedData = mills + if (insulin > 0) { + bolusFromJson(json)?.let { bolus -> + repository.runTransactionForResult(SyncNsBolusTransaction(bolus)) + .doOnError { + aapsLogger.error(LTag.DATABASE, "Error while saving bolus", it) + ret = Result.failure() + } + .blockingGet() + .also { result -> + result.inserted.forEach { + uel.log(UserEntry.Action.CAREPORTAL_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.U) + ) + } + result.invalidated.forEach { + uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.U) + ) + } + } + } ?: aapsLogger.error("Error parsing bolus json $json") + } + if (carbs > 0) { + carbsFromJson(json)?.let { carb -> + repository.runTransactionForResult(SyncNsCarbsTransaction(carb)) + .doOnError { + aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) + ret = Result.failure() + } + .blockingGet() + .also { result -> + result.inserted.forEach { + uel.log(UserEntry.Action.CAREPORTAL_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.G) + ) + } + result.invalidated.forEach { + uel.log(UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.G) + ) + } + } + } ?: aapsLogger.error("Error parsing bolus json $json") + } when { - insulin > 0 || carbs > 0 -> - rxBus.send(EventNsTreatment(EventNsTreatment.ADD, json)) + insulin > 0 || carbs > 0 -> Any() eventType == TherapyEvent.Type.TEMPORARY_TARGET.text -> temporaryTargetFromJson(json)?.let { temporaryTarget -> repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget)) @@ -115,7 +165,6 @@ class NSClientAddUpdateWorker( eventType == TherapyEvent.Type.INSULIN_CHANGE.text || eventType == TherapyEvent.Type.SENSOR_CHANGE.text || eventType == TherapyEvent.Type.FINGER_STICK_BG_VALUE.text || - eventType == TherapyEvent.Type.NOTE.text || eventType == TherapyEvent.Type.NONE.text || eventType == TherapyEvent.Type.ANNOUNCEMENT.text || eventType == TherapyEvent.Type.QUESTION.text || diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt index 34156d6f3a..2c932dc086 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt @@ -8,10 +8,10 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit +import info.nightscout.androidaps.database.transactions.SyncNsBolusTransaction +import info.nightscout.androidaps.database.transactions.SyncNsCarbsTransaction import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction -import info.nightscout.androidaps.events.EventNsTreatment -import info.nightscout.androidaps.events.EventNsTreatment.Companion.REMOVE import info.nightscout.androidaps.interfaces.ConfigInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -21,6 +21,8 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper +import info.nightscout.androidaps.utils.extensions.bolusFromNsIdForInvalidating +import info.nightscout.androidaps.utils.extensions.carbsFromNsIdForInvalidating import info.nightscout.androidaps.utils.extensions.temporaryTargetFromNsIdForInvalidating import info.nightscout.androidaps.utils.extensions.therapyEventFromNsIdForInvalidating import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -61,7 +63,7 @@ class NSClientRemoveWorker( val temporaryTarget = temporaryTargetFromNsIdForInvalidating(nsId) repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget)) .doOnError { - aapsLogger.error(LTag.DATABASE, "Error while removing temporary target", it) + aapsLogger.error(LTag.DATABASE, "Error while invalidating temporary target", it) ret = Result.failure() } .blockingGet() @@ -81,7 +83,7 @@ class NSClientRemoveWorker( val therapyEvent = therapyEventFromNsIdForInvalidating(nsId) repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEvent)) .doOnError { - aapsLogger.error(LTag.DATABASE, "Error while removing therapy event", it) + aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) ret = Result.failure() } .blockingGet() @@ -94,8 +96,40 @@ class NSClientRemoveWorker( } } - // Insulin, carbs - rxBus.send(EventNsTreatment(REMOVE, json)) + // room Bolus + val bolus = bolusFromNsIdForInvalidating(nsId) + repository.runTransactionForResult(SyncNsBolusTransaction(bolus)) + .doOnError { + aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it) + ret = Result.failure() + } + .blockingGet() + .also { result -> + result.invalidated.forEach { + uel.log( + UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.U)) + } + } + + // room Bolus + val carbs = carbsFromNsIdForInvalidating(nsId) + repository.runTransactionForResult(SyncNsCarbsTransaction(carbs)) + .doOnError { + aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it) + ret = Result.failure() + } + .blockingGet() + .also { result -> + result.invalidated.forEach { + uel.log( + UserEntry.Action.CAREPORTAL_DELETED_FROM_NS, + ValueWithUnit(it.timestamp, UserEntry.Units.Timestamp, true), + ValueWithUnit(it.amount, UserEntry.Units.G)) + } + } + // old DB model databaseHelper.deleteTempBasalById(nsId) databaseHelper.deleteExtendedBolusById(nsId) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt index b1de3bab2e..2d621b1cc5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt @@ -28,7 +28,6 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.extensions.toConstant import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -61,7 +60,6 @@ class OpenHumansUploader @Inject constructor( private val sp: SP, private val rxBus: RxBusWrapper, private val context: Context, - private val treatmentsPlugin: TreatmentsPlugin, private val databaseHelper: DatabaseHelperInterface, val repository: AppRepository ) : PluginBase( @@ -356,11 +354,11 @@ class OpenHumansUploader @Inject constructor( if (currentProgress % 1000L == 0L) showOngoingNotification(maxProgress, currentProgress) } copyDisposable = Completable.fromCallable { databaseHelper.clearOpenHumansQueue() } - .andThen(Single.defer { Single.just(databaseHelper.getCountOfAllRows() + treatmentsPlugin.service.count()) }) - .doOnSuccess { maxProgress = it } - .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } } - .map { enqueueTreatment(it); increaseCounter() } - .ignoreElements() +// .andThen(Single.defer { Single.just(databaseHelper.getCountOfAllRows() + treatmentsPlugin.service.count()) }) +// .doOnSuccess { maxProgress = it } +// .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } } +// .map { enqueueTreatment(it); increaseCounter() } +// .ignoreElements() .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) .map { enqueueBGReading(it); increaseCounter() } .ignoreElements() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index c3a02a250b..b0dcee802b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -778,7 +778,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (config.APS && lastRun?.constraintsProcessed != null) { if (lastRun.constraintsProcessed!!.carbsReq > 0) { //only display carbsreq when carbs have not been entered recently - if (treatmentsPlugin.lastCarbTime < lastRun.lastAPSRun) { + val lastCarbsTime = repository.getLastBolusRecord()?.timestamp ?: 0L + if (lastCarbsTime < lastRun.lastAPSRun) { cobText = cobText + " | " + lastRun.constraintsProcessed!!.carbsReq + " " + resourceHelper.gs(R.string.required) } binding.infoLayout.cob.text = cobText diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 72bdabc0fe..49d7a813bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -98,7 +98,6 @@ class SmsCommunicatorPlugin @Inject constructor( val commands = mapOf( "BG" to "BG", "LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20", - "TREATMENTS" to "TREATMENTS REFRESH", "NSCLIENT" to "NSCLIENT RESTART", "PUMP" to "PUMP\nPUMP CONNECT\nPUMP DISCONNECT 30\n", "BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n", @@ -245,61 +244,58 @@ class SmsCommunicatorPlugin @Inject constructor( if (divided.isNotEmpty() && isCommand(divided[0].toUpperCase(Locale.getDefault()), receivedSms.phoneNumber)) { when (divided[0].toUpperCase(Locale.getDefault())) { - "BG" -> + "BG" -> if (divided.size == 1) processBG(receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "LOOP" -> + "LOOP" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processLOOP(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "TREATMENTS" -> - if (divided.size == 2) processTREATMENTS(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "NSCLIENT" -> + "NSCLIENT" -> if (divided.size == 2) processNSCLIENT(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "PUMP" -> + "PUMP" -> if (!remoteCommandsAllowed && divided.size > 1) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size <= 3) processPUMP(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "PROFILE" -> + "PROFILE" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processPROFILE(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "BASAL" -> + "BASAL" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processBASAL(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "EXTENDED" -> + "EXTENDED" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processEXTENDED(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "BOLUS" -> + "BOLUS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 && DateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed))) else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended))) else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "CARBS" -> + "CARBS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processCARBS(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "CAL" -> + "CAL" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processCAL(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "TARGET" -> + "TARGET" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processTARGET(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "SMS" -> + "SMS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processSMS(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - "HELP" -> + "HELP" -> if (divided.size == 1 || divided.size == 2) processHELP(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - else -> + else -> if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) { messageToConfirm?.action(divided[0]) messageToConfirm = null @@ -453,16 +449,6 @@ class SmsCommunicatorPlugin @Inject constructor( } } - private fun processTREATMENTS(divided: Array, receivedSms: Sms) { - if (divided[1].toUpperCase(Locale.getDefault()) == "REFRESH") { - activePlugin.activeTreatments.service.resetTreatments() - rxBus.send(EventNSClientRestart()) - sendSMS(Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT")) - receivedSms.processed = true - } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - } - private fun processNSCLIENT(divided: Array, receivedSms: Sms) { if (divided[1].toUpperCase(Locale.getDefault()) == "RESTART") { rxBus.send(EventNSClientRestart()) @@ -870,32 +856,23 @@ class SmsCommunicatorPlugin @Inject constructor( val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.carbs = anInteger().toDouble() detailedBolusInfo.timestamp = secondLong() - if (activePlugin.activePump.pumpDescription.storesCarbInfo) { - commandQueue.bolus(detailedBolusInfo, object : Callback() { - override fun run() { - if (result.success) { - var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) - replyText += "\n" + activePlugin.activePump.shortStatus(true) - sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.SMS_CARBS, activePlugin.activePump.shortStatus(true), ValueWithUnit(R.string.smscommunicator_carbsset, 1), ValueWithUnit(anInteger - ?: 0, Units.G)) - } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed, anInteger) - replyText += "\n" + activePlugin.activePump.shortStatus(true) - sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.SMS_CARBS, activePlugin.activePump.shortStatus(true), ValueWithUnit(R.string.smscommunicator_carbsfailed, 1), ValueWithUnit(anInteger - ?: 0, Units.G)) - } + commandQueue.bolus(detailedBolusInfo, object : Callback() { + override fun run() { + if (result.success) { + var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) + replyText += "\n" + activePlugin.activePump.shortStatus(true) + sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) + uel.log(Action.SMS_CARBS, activePlugin.activePump.shortStatus(true), ValueWithUnit(R.string.smscommunicator_carbsset, 1), ValueWithUnit(anInteger + ?: 0, Units.G)) + } else { + var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed, anInteger) + replyText += "\n" + activePlugin.activePump.shortStatus(true) + sendSMS(Sms(receivedSms.phoneNumber, replyText)) + uel.log(Action.SMS_CARBS, activePlugin.activePump.shortStatus(true), ValueWithUnit(R.string.smscommunicator_carbsfailed, 1), ValueWithUnit(anInteger + ?: 0, Units.G)) } - }) - } else { - activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, true) - var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) - replyText += "\n" + activePlugin.activePump.shortStatus(true) - sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.SMS_CARBS, activePlugin.activePump.shortStatus(true), ValueWithUnit(R.string.smscommunicator_carbsset, 1), ValueWithUnit(anInteger - ?: 0, Units.G)) - } + } + }) } }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index 74a7f29a5f..dd4705b4dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -115,14 +115,16 @@ class UploadChunk @Inject constructor( private fun getTreatments(start: Long, end: Long): List { val result = LinkedList() - val treatments = treatmentsPlugin.service.getTreatmentDataFromTime(start, end, true) - for (treatment in treatments) { - if (treatment.carbs > 0) { - result.add(WizardElement(treatment)) - } else if (treatment.insulin > 0) { - result.add(BolusElement(treatment)) + repository.getBolusesDataFromTimeToTime(start, end, true) + .blockingGet() + .forEach { bolus -> + result.add(BolusElement(bolus)) + } + repository.getCarbsDataFromTimeToTime(start, end, true) + .blockingGet() + .forEach { carb -> + result.add(WizardElement(carb)) } - } return result } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt index f437018994..51279c7057 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt @@ -1,22 +1,19 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose -import info.nightscout.androidaps.db.Treatment +import info.nightscout.androidaps.database.entities.Bolus import java.util.* -class BolusElement(treatment: Treatment) - : BaseElement(treatment.date, UUID.nameUUIDFromBytes(("AAPS-bolus" + treatment.date).toByteArray()).toString()) { +class BolusElement(bolus: Bolus) + : BaseElement(bolus.timestamp, UUID.nameUUIDFromBytes(("AAPS-bolus" + bolus.timestamp).toByteArray()).toString()) { - @Expose - var subType = "normal" - @Expose - var normal: Double = 0.0 - @Expose - var expectedNormal: Double = 0.0 + @Expose var subType = "normal" + @Expose var normal: Double = 0.0 + @Expose var expectedNormal: Double = 0.0 init { type = "bolus" - normal = treatment.insulin - expectedNormal = treatment.insulin + normal = bolus.amount + expectedNormal = bolus.amount } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt index 87aba24d1c..dc498d573b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt @@ -1,33 +1,28 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose -import info.nightscout.androidaps.db.Treatment +import info.nightscout.androidaps.database.entities.Bolus +import info.nightscout.androidaps.database.entities.Carbs import java.util.* -class WizardElement(treatment: Treatment) - : BaseElement(treatment.date, UUID.nameUUIDFromBytes(("AAPS-wizard" + treatment.date).toByteArray()).toString()) { +class WizardElement(carbs: Carbs) + : BaseElement(carbs.timestamp, UUID.nameUUIDFromBytes(("AAPS-wizard" + carbs.timestamp).toByteArray()).toString()) { - @Expose - var units = "mg/dL" - @Expose - var carbInput: Double = 0.toDouble() - @Expose - var insulinCarbRatio: Double = 0.toDouble() - @Expose - var bolus: BolusElement? = null + @Expose var units = "mg/dL" + @Expose var carbInput: Double = 0.toDouble() + @Expose var insulinCarbRatio: Double = 0.toDouble() + @Expose var bolus: BolusElement? = null init { type = "wizard" - carbInput = treatment.carbs - insulinCarbRatio = treatment.ic - if (treatment.insulin > 0) { - bolus = BolusElement(treatment) - } else { - val fake = Treatment() - fake.insulin = 0.0001 - fake.date = treatment.date - bolus = BolusElement(fake) // fake insulin record - } + carbInput = carbs.amount + val fake = Bolus( + amount = 0.0001, + timestamp = carbs.timestamp, + type = Bolus.Type.NORMAL, + isBasalInsulin = false + ) + bolus = BolusElement(fake) // fake insulin record } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt index 9e48d0b90f..3169adcd94 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt @@ -10,7 +10,8 @@ import javax.inject.Singleton @Singleton class RateLimit @Inject constructor( - val aapsLogger: AAPSLogger + private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil ) { private val rateLimits = HashMap() @@ -20,13 +21,13 @@ class RateLimit @Inject constructor( fun rateLimit(name: String, seconds: Int): Boolean { // check if over limit rateLimits[name]?.let { - if (DateUtil.now() - it < T.secs(seconds.toLong()).msecs()) { + if (dateUtil._now() - it < T.secs(seconds.toLong()).msecs()) { aapsLogger.debug(LTag.TIDEPOOL, "$name rate limited: $seconds seconds") return false } } // not over limit - rateLimits[name] = DateUtil.now() + rateLimits[name] = dateUtil._now() return true } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 07429c4fcc..329edc9b0a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -26,7 +26,6 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction @@ -78,8 +77,7 @@ class ActionStringHandler @Inject constructor( private val dateUtil: DateUtil, private val config: Config, private val databaseHelper: DatabaseHelperInterface, - private val repository: AppRepository, - private val nsUpload: NSUpload + private val repository: AppRepository ) { private val timeout = 65 * 1000 @@ -613,9 +611,8 @@ class ActionStringHandler @Inject constructor( detailedBolusInfo.carbs = carbs.toDouble() detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.NORMAL detailedBolusInfo.carbsTimestamp = carbsTime - detailedBolusInfo.carbsDuration = carbsDuration.toLong() - val storesCarbs = activePlugin.activePump.pumpDescription.storesCarbInfo - if (detailedBolusInfo.insulin > 0 || (storesCarbs && carbsDuration == 0)) { + detailedBolusInfo.carbsDuration = T.hours(carbsDuration.toLong()).msecs() + if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { @@ -625,8 +622,6 @@ class ActionStringHandler @Inject constructor( } } }) - } else { - activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index b5d53cc808..8cb8318c2b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -527,6 +527,8 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } repository.getBolusesIncludingInvalidFromTime(startTimeWindow, true).blockingGet() + .stream() + .filter(bolus -> bolus.getType() != Bolus.Type.PRIMING) .forEach(bolus -> boluses.add(treatmentMap(bolus.getTimestamp(), bolus.getAmount(), 0, bolus.getType() == Bolus.Type.SMB, bolus.isValid()))); repository.getCarbsIncludingInvalidFromTime(startTimeWindow, true).blockingGet() .forEach(carb -> boluses.add(treatmentMap(carb.getTimestamp(), 0, carb.getAmount(), false, carb.isValid()))); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt index a6575c1886..236269fb69 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.kt @@ -6,7 +6,7 @@ import android.util.AttributeSet import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries -import info.nightscout.androidaps.db.Treatment +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.utils.T import java.util.* @@ -22,15 +22,17 @@ class ActivityGraph : GraphView { removeAllSeries() mSecondScale = null val hours = floor(insulin.dia + 1).toLong() - val t = Treatment().also { - it.date = 0 - it.insulin = 1.0 - } + val bolus = Bolus( + timestamp = 0, + amount = 1.0, + type = Bolus.Type.NORMAL, + isBasalInsulin = false + ) val activityArray: MutableList = ArrayList() val iobArray: MutableList = ArrayList() var time: Long = 0 while (time <= T.hours(hours).msecs()) { - val iob = t.iobCalc(time, insulin.dia) + val iob = insulin.iobCalcForTreatment(bolus, time, insulin.dia) activityArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.activityContrib)) iobArray.add(DataPoint(T.msecs(time).mins().toDouble(), iob.iobContrib)) time += T.mins(5).msecs() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index dc5d33e56e..10713c9da9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -28,6 +28,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.extensions.expandCarbs import info.nightscout.androidaps.utils.extensions.iobCalc import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -531,7 +532,8 @@ open class IobCobCalculatorPlugin @Inject constructor( var displayCob: Double? = null var futureCarbs = 0.0 val now = DateUtil.now() - val carbs = repository.getCarbsDataFromTime(now, true).blockingGet() + val carbs = repository.getCarbsDataFromTime(now, true) + .blockingGet() if (autosensData != null) { displayCob = autosensData.cob carbs.forEach { carb -> @@ -601,12 +603,15 @@ open class IobCobCalculatorPlugin @Inject constructor( sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME) } val absorptionTimeAgo = now - (maxAbsorptionHours * T.hours(1).msecs()).toLong() - repository.getCarbsDataFromTimeToTime(absorptionTimeAgo + 1, now, true).blockingGet().forEach { - if (it.amount > 0) { - result.carbs += it.amount - if (it.timestamp > result.lastCarbTime) result.lastCarbTime = it.timestamp + repository.getCarbsDataFromTimeToTime(absorptionTimeAgo + 1, now, true) + .map { it.map { c -> c.expandCarbs() }.flatten() } + .blockingGet() + .forEach { + if (it.amount > 0) { + result.carbs += it.amount + if (it.timestamp > result.lastCarbTime) result.lastCarbTime = it.timestamp + } } - } val autosensData = getLastAutosensDataSynchronized("getMealData()") if (autosensData != null) { result.mealCOB = autosensData.cob @@ -614,7 +619,7 @@ open class IobCobCalculatorPlugin @Inject constructor( result.slopeFromMaxDeviation = autosensData.slopeFromMaxDeviation result.usedMinCarbsImpact = autosensData.usedMinCarbsImpact } - result.lastBolusTime = treatmentsPlugin.lastBolusTime + result.lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L return result } @@ -778,6 +783,15 @@ open class IobCobCalculatorPlugin @Inject constructor( } } + /** + * Time range to the past for IOB calculation + * @return milliseconds + */ + fun range(): Long { + val dia = profileFunction.getProfile()?.dia ?: Constants.defaultDIA + return (60 * 60 * 1000L * (24 + dia)).toLong() + } + override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now()) override fun calculateIobFromBolusToTime(timestamp: Long): IobTotal { @@ -786,7 +800,7 @@ open class IobCobCalculatorPlugin @Inject constructor( val dia = profile.dia val divisor = sp.getDouble(R.string.key_openapsama_bolussnooze_dia_divisor, 2.0) - val boluses = repository.getBolusesDataFromTime(timestamp, true).blockingGet() + val boluses = repository.getBolusesDataFromTime(timestamp - range(), true).blockingGet() boluses.forEach { t -> if (t.isValid && t.timestamp < timestamp) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt index ea7b47f332..58c2af56f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt @@ -10,9 +10,9 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.InstanceId.instanceId +import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONException import org.json.JSONObject @@ -25,7 +25,8 @@ class MDIPlugin @Inject constructor( aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, commandQueue: CommandQueueProvider, - private val treatmentsPlugin: TreatmentsPlugin + private val dateUtil: DateUtil, + private val pumpSync: PumpSync ) : PumpPluginBase(PluginDescription() .mainType(PluginType.PUMP) .pluginIcon(R.drawable.ic_ict) @@ -73,7 +74,21 @@ class MDIPlugin @Inject constructor( result.bolusDelivered = detailedBolusInfo.insulin result.carbsDelivered = detailedBolusInfo.carbs result.comment = resourceHelper.gs(R.string.virtualpump_resultok) - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) + if (detailedBolusInfo.insulin > 0) + pumpSync.syncBolusWithPumpId( + timestamp = detailedBolusInfo.timestamp, + amount = detailedBolusInfo.insulin, + type = detailedBolusInfo.bolusType, + pumpId = dateUtil._now(), + pumpType = PumpType.MDI, + pumpSerial = serialNumber()) + if (detailedBolusInfo.carbs > 0) + pumpSync.syncCarbsWithTimestamp( + timestamp = detailedBolusInfo.timestamp + T.mins(detailedBolusInfo.carbTime.toLong()).msecs(), + amount = detailedBolusInfo.carbs, + pumpId = null, + pumpType = PumpType.MDI, + pumpSerial = serialNumber()) return result } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 480ea6323f..c515fa97e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -27,6 +27,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.InstanceId.instanceId +import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -205,11 +206,20 @@ open class VirtualPumpPlugin @Inject constructor( rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() if (detailedBolusInfo.insulin > 0) - pumpSync.syncBolusWithPumpId(dateUtil._now(), detailedBolusInfo.insulin, detailedBolusInfo.bolusType, dateUtil._now(), pumpType - ?: PumpType.GENERIC_AAPS, serialNumber()) + pumpSync.syncBolusWithPumpId( + timestamp = detailedBolusInfo.timestamp, + amount = detailedBolusInfo.insulin, + type = detailedBolusInfo.bolusType, + pumpId = dateUtil._now(), + pumpType = pumpType ?: PumpType.GENERIC_AAPS, + pumpSerial = serialNumber()) if (detailedBolusInfo.carbs > 0) - pumpSync.syncCarbsWithTimestamp(dateUtil._now(), detailedBolusInfo.carbs, dateUtil._now(), pumpType - ?: PumpType.GENERIC_AAPS, serialNumber()) + pumpSync.syncCarbsWithTimestamp( + timestamp = detailedBolusInfo.timestamp + T.mins(detailedBolusInfo.carbTime.toLong()).msecs(), + amount = detailedBolusInfo.carbs, + pumpId = null, + pumpType = pumpType ?: PumpType.GENERIC_AAPS, + pumpSerial = serialNumber()) return result } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt index 7ac255b31f..e0d6af60c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -106,6 +106,7 @@ open class SensitivityOref1Plugin @Inject constructor( if (isEvent5minBack(siteChanges, autosensData.time)) { deviationsArray.clear() pastSensitivity += "(SITECHANGE)" + pastSensitivity += "(SITECHANGE)" } // reset deviations after profile switch diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index f09d15d1de..89f8dc7f6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -87,7 +87,8 @@ class RandomBgPlugin @Inject constructor( } override fun specialEnableCondition(): Boolean { - return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && buildHelper.isEngineeringMode() +// return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && buildHelper.isEngineeringMode() + return true } private fun handleNewData() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index a4f85e3882..eb83083b6e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -17,8 +17,6 @@ import com.j256.ormlite.table.TableUtils; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; import java.sql.SQLException; import java.util.ArrayList; @@ -36,7 +34,6 @@ import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; @@ -49,11 +46,8 @@ import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; -import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; -import io.reactivex.disposables.CompositeDisposable; /** @@ -70,8 +64,6 @@ public class TreatmentService extends OrmLiteBaseService impleme @Inject OpenHumansUploader openHumansUploader; @Inject AapsSchedulers aapsSchedulers; - private final CompositeDisposable disposable = new CompositeDisposable(); - private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTreatmentEventPost = null; @@ -79,20 +71,6 @@ public class TreatmentService extends OrmLiteBaseService impleme injector.androidInjector().inject(this); onCreate(); dbInitialize(); - disposable.add(rxBus - .toObservable(EventNsTreatment.class) - .observeOn(aapsSchedulers.getIo()) - .subscribe(event -> { - int mode = event.getMode(); - JSONObject payload = event.getPayload(); - - if (mode == EventNsTreatment.Companion.getADD() || mode == EventNsTreatment.Companion.getUPDATE()) { - this.createTreatmentFromJsonIfNotExists(payload); - } else { // EventNsTreatment.REMOVE - this.deleteNS(payload); - } - }, fabricPrivacy::logException) - ); } /** @@ -215,18 +193,6 @@ public class TreatmentService extends OrmLiteBaseService impleme } } - public void resetTreatments() { - try { - TableUtils.dropTable(this.getConnectionSource(), Treatment.class, true); - TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); - DatabaseHelper.updateEarliestDataChange(0); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - scheduleTreatmentChange(null, true); - } - - /** * A place to centrally register events to be posted, if any data changed. * This should be implemented in an abstract service-class. @@ -272,14 +238,14 @@ public class TreatmentService extends OrmLiteBaseService impleme public void scheduleTreatmentChange(@Nullable final Treatment treatment, boolean runImmediately) { if (runImmediately) { aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventReloadTreatmentData"); - rxBus.send(new EventReloadTreatmentData(new EventTreatmentChange(treatment))); + rxBus.send(new EventReloadTreatmentData(new EventTreatmentChange())); if (DatabaseHelper.earliestDataChange != null) { aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventNewHistoryData"); rxBus.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); } DatabaseHelper.earliestDataChange = null; } else { - this.scheduleEvent(new EventReloadTreatmentData(new EventTreatmentChange(treatment)), treatmentEventWorker, new ICallback() { + this.scheduleEvent(new EventReloadTreatmentData(new EventTreatmentChange()), treatmentEventWorker, new ICallback() { @Override public void setPost(ScheduledFuture post) { scheduledTreatmentEventPost = post; @@ -293,16 +259,6 @@ public class TreatmentService extends OrmLiteBaseService impleme } } - public List getTreatmentData() { - try { - return this.getDao().queryForAll(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - - return new ArrayList<>(); - } - public long count() { try { return this.getDao().countOf(); @@ -326,26 +282,6 @@ public class TreatmentService extends OrmLiteBaseService impleme "unit": "ml" } */ - public void createTreatmentFromJsonIfNotExists(JSONObject json) { - try { - Treatment treatment = Treatment.createFromJson(json); - if (treatment != null) { - - if (MedtronicHistoryData.doubleBolusDebug) - aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", medtronicPumpPlugin.isEnabled()); - - if (!medtronicPumpPlugin.isEnabled()) - createOrUpdate(treatment); - else - createOrUpdateMedtronic(treatment, true); - } else - aapsLogger.error("Date is null: " + treatment.toString()); - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - // return true if new record is created public UpdateReturn createOrUpdate(Treatment treatment) { if (treatment != null && treatment.source == Source.NONE) { @@ -654,107 +590,6 @@ public class TreatmentService extends OrmLiteBaseService impleme } } - /** - * Returns the newest record with insulin > 0 - */ - @Nullable - public Treatment getLastBolus(boolean excludeSMB) { - try { - QueryBuilder queryBuilder = getDao().queryBuilder(); - Where where = queryBuilder.where(); - where.gt("insulin", 0); - where.and().le("date", DateUtil.now()); - where.and().eq("isValid", true); - if (excludeSMB) where.and().eq("isSMB", false); - queryBuilder.orderBy("date", false); - queryBuilder.limit(1L); - - List result = getDao().query(queryBuilder.prepare()); - if (result.isEmpty()) - return null; - return result.get(0); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - /** - * Returns the newest record with carbs > 0 - */ - @Nullable - public Treatment getLastCarb() { - try { - QueryBuilder queryBuilder = getDao().queryBuilder(); - Where where = queryBuilder.where(); - where.gt("carbs", 0); - where.and().le("date", DateUtil.now()); - where.and().eq("isValid", true); - queryBuilder.orderBy("date", false); - queryBuilder.limit(1L); - - List result = getDao().query(queryBuilder.prepare()); - if (result.isEmpty()) - return null; - return result.get(0); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - public void deleteNS(JSONObject json) { - String _id = JsonHelper.safeGetString(json, "_id"); - if (_id != null && !_id.isEmpty()) - this.deleteByNSId(_id); - } - - /** - * deletes an entry by its NS Id. - *

- * Basically a convenience method for findByNSId and delete. - * - * @param _id - */ - private void deleteByNSId(String _id) { - Treatment stored = findByNSId(_id); - if (stored != null) { - aapsLogger.debug(LTag.DATATREATMENTS, "Removing Treatment record from database: " + stored.toString()); - try { - getDao().delete(stored); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - DatabaseHelper.updateEarliestDataChange(stored.date); - this.scheduleTreatmentChange(stored, false); - } - } - - /** - * deletes the treatment and sends the treatmentChange Event - *

- * should be moved ot a Service - * - * @param treatment - */ - public void delete(Treatment treatment) { - try { - getDao().delete(treatment); - DatabaseHelper.updateEarliestDataChange(treatment.date); - this.scheduleTreatmentChange(treatment, true); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public void update(Treatment treatment) { - try { - getDao().update(treatment); - DatabaseHelper.updateEarliestDataChange(treatment.date); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - scheduleTreatmentChange(treatment, true); - } - /** * finds treatment by its NS Id. * @@ -784,40 +619,6 @@ public class TreatmentService extends OrmLiteBaseService impleme return null; } - public List getTreatmentDataFromTime(long mills, boolean ascending) { - try { - TreatmentDaoWrapper daoTreatments = getDao(); - List treatments; - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - queryBuilder.orderBy("date", ascending); - Where where = queryBuilder.where(); - where.ge("date", mills); - PreparedQuery preparedQuery = queryBuilder.prepare(); - treatments = daoTreatments.query(preparedQuery); - return treatments; - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return new ArrayList<>(); - } - - public List getTreatmentDataFromTime(long from, long to, boolean ascending) { - try { - TreatmentDaoWrapper daoTreatments = getDao(); - List treatments; - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - queryBuilder.orderBy("date", ascending); - Where where = queryBuilder.where(); - where.between("date", from, to); - PreparedQuery preparedQuery = queryBuilder.prepare(); - treatments = daoTreatments.query(preparedQuery); - return treatments; - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return new ArrayList<>(); - } - @Nullable @Override public IBinder onBind(Intent intent) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 3d266433ad..402017e384 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -8,7 +8,6 @@ import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -62,6 +61,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryDa import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; +import info.nightscout.androidaps.utils.extensions.BolusExtensionKt; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -240,7 +240,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface /** * Returns all Treatments after specified timestamp. Also returns invalid entries (required to - * map "Fill Canula" entries to history (and not to add double bolus for it) + * map "Fill Cannula" entries to history (and not to add double bolus for it) * * @param fromTimestamp * @return @@ -269,7 +269,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } */ } - +/* @Override public long getLastBolusTime() { Treatment last = getService().getLastBolus(false); @@ -305,6 +305,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } + */ + @Override public boolean isInHistoryRealTempBasalInProgress() { return getRealTempBasalFromHistory(System.currentTimeMillis()) != null; @@ -413,10 +415,21 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (runningTBR != null) { running = runningTBR.tempBasalConvertedToAbsolute(i, profile); } - Treatment treatment = new Treatment(getInjector()); - treatment.date = i; - treatment.insulin = running * 5.0 / 60.0; // 5 min chunk - Iob iob = treatment.iobCalc(time, profile.getDia()); + Bolus bolus = new Bolus( + 0, // id + 0, // version + 0, //dateCreated + true, // isValid + null, + null, + i, + 0, + running * 5.0 / 60.0, + Bolus.Type.NORMAL, + true, + null + ); + Iob iob = BolusExtensionKt.iobCalc(bolus, activePlugin, time, profile.getDia()); total.basaliob += iob.getIobContrib(); total.activity += iob.getActivityContrib(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt index 66256414b7..b5a2cd335e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt @@ -101,7 +101,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { .observeOn(aapsSchedulers.main) .subscribeBy( onError = { aapsLogger.error("Error removing entries", it) }, - onComplete = { rxBus.send(EventTreatmentChange(null)) } + onComplete = { rxBus.send(EventTreatmentChange()) } ) rxBus.send(EventNSClientRestart()) } @@ -190,7 +190,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { .zipWith(bolusMealLinksWithInvalid(now)) { first, second -> first + second } .zipWith(calcResultMealLinksWithInvalid(now)) { first, second -> first + second } .map { ml -> - ml.sortedBy { + ml.sortedByDescending { it.carbs?.timestamp ?: it.bolus?.timestamp ?: it.bolusCalculatorResult?.timestamp } @@ -205,7 +205,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { .zipWith(bolusMealLinks(now)) { first, second -> first + second } .zipWith(calcResultMealLinks(now)) { first, second -> first + second } .map { ml -> - ml.sortedBy { + ml.sortedByDescending { it.carbs?.timestamp ?: it.bolus?.timestamp ?: it.bolusCalculatorResult?.timestamp } @@ -285,7 +285,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { when (ml.bolus.type) { Bolus.Type.SMB -> "SMB" Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus) - else -> "" + Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime) } } // Carbs @@ -293,6 +293,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { ml.carbs?.let { carbs -> holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp) holder.binding.carbs.text = resourceHelper.gs(R.string.format_carbs, carbs.amount.toInt()) + holder.binding.carbsDuration.text = resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) holder.binding.carbsNs.visibility = (NSUpload.isIdValid(carbs.interfaceIDs.nightscoutId)).toVisibility() holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility() holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility() diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index be0c11ba6c..70b56e858d 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -217,7 +217,8 @@ open class CommandQueue @Inject constructor( aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running") return false } - if (detailedBolusInfo.lastKnownBolusTime < activePlugin.get().activeTreatments.lastBolusTime) { + val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L + if (detailedBolusInfo.lastKnownBolusTime < lastBolusTime) { aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time") return false } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index c7e88cfd06..7d937ce0c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -22,7 +22,7 @@ class CommandSMBBolus( override fun execute() { val r: PumpEnactResult - val lastBolusTime = activePlugin.activeTreatments.lastBolusTime + val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > dateUtil._now()) { aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval") r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval") diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 4f8c3b57e0..1ece37cabe 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -6,6 +6,7 @@ import android.util.LongSparseArray import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.DatabaseHelperInterface @@ -56,7 +57,9 @@ class TddCalculator @Inject constructor( initializeData(range) val result = LongSparseArray() - repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet().forEach { t-> + repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet() + .filter { it.type != Bolus.Type.PRIMING } + .forEach { t-> val midnight = MidnightTime.calc(t.timestamp) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) tdd.bolus += t.amount diff --git a/app/src/main/res/layout/treatments_bolus_carbs_item.xml b/app/src/main/res/layout/treatments_bolus_carbs_item.xml index 5c9d3849ce..fba6a1e3e5 100644 --- a/app/src/main/res/layout/treatments_bolus_carbs_item.xml +++ b/app/src/main/res/layout/treatments_bolus_carbs_item.xml @@ -78,28 +78,22 @@ android:text="1.1.2000" tools:ignore="HardcodedText,RtlSymmetry" /> - - + android:layout_marginStart="10dp" + android:text="1.00 U" + android:textStyle="bold" + tools:ignore="HardcodedText" /> + android:text="0.45U" + android:textStyle="bold" + tools:ignore="HardcodedText" /> @@ -121,7 +116,6 @@ android:id="@+id/meal_or_correction" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" android:text="Meal" android:textAlignment="textEnd" tools:ignore="HardcodedText" /> @@ -130,7 +124,7 @@ android:id="@+id/bolus_ns" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="NS" android:textColor="@color/colorSetTempButton" tools:ignore="HardcodedText" /> @@ -139,7 +133,7 @@ android:id="@+id/bolus_pump" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="PH" android:textColor="@color/colorSetTempButton" tools:ignore="HardcodedText" /> @@ -148,7 +142,7 @@ android:id="@+id/bolus_invalid" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="@string/invalid" android:textColor="@android:color/holo_red_light" /> @@ -156,11 +150,16 @@ android:id="@+id/bolus_remove" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="@string/remove_button" android:textAlignment="viewEnd" android:textColor="@android:color/holo_orange_light" /> + + + + @@ -212,7 +217,7 @@ android:id="@+id/carbs_ns" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="NS" android:textColor="@color/colorSetTempButton" tools:ignore="HardcodedText" /> @@ -221,7 +226,7 @@ android:id="@+id/carbs_pump" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="PH" android:textColor="@color/colorSetTempButton" tools:ignore="HardcodedText" /> @@ -230,7 +235,7 @@ android:id="@+id/carbs_invalid" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="@string/invalid" android:textColor="@android:color/holo_red_light" /> @@ -238,20 +243,25 @@ android:id="@+id/carbs_remove" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:layout_marginEnd="10dp" + android:layout_marginStart="5dp" android:text="@string/remove_button" android:textAlignment="viewEnd" android:textColor="@android:color/holo_orange_light" /> + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 80e62d7037..a93c050aa5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1134,5 +1134,6 @@ Current basal value Profile carbs ratio value Full sync + Prime diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index 6776c92c31..94e18a5b48 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -468,36 +468,6 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) - //TREATMENTS REFRESH - PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) - PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) - smsCommunicatorPlugin.messages = ArrayList() - sms = Sms("1234", "TREATMENTS REFRESH") - smsCommunicatorPlugin.processSms(sms) - Assert.assertFalse(sms.ignored) - Assert.assertEquals("TREATMENTS REFRESH", smsCommunicatorPlugin.messages[0].text) - Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("TREATMENTS REFRESH")) - - //TREATMENTS BLA BLA - PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) - PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) - smsCommunicatorPlugin.messages = ArrayList() - sms = Sms("1234", "TREATMENTS BLA BLA") - smsCommunicatorPlugin.processSms(sms) - Assert.assertFalse(sms.ignored) - Assert.assertEquals("TREATMENTS BLA BLA", smsCommunicatorPlugin.messages[0].text) - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) - - //TREATMENTS BLABLA - PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) - PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) - smsCommunicatorPlugin.messages = ArrayList() - sms = Sms("1234", "TREATMENTS BLABLA") - smsCommunicatorPlugin.processSms(sms) - Assert.assertFalse(sms.ignored) - Assert.assertEquals("TREATMENTS BLABLA", smsCommunicatorPlugin.messages[0].text) - Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) - //NSCLIENT RESTART PowerMockito.`when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) PowerMockito.`when`(loopPlugin.isSuspended).thenReturn(false) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt index 7d4bc8a96b..deb93405f0 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.TestPumpPlugin import info.nightscout.androidaps.core.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.ProfileFunction @@ -41,7 +42,8 @@ import java.util.* @RunWith(PowerMockRunner::class) @PrepareForTest( ConstraintChecker::class, VirtualPumpPlugin::class, ToastUtils::class, Context::class, - TreatmentsPlugin::class, FabricPrivacy::class, LoggerUtils::class, PowerManager::class) + TreatmentsPlugin::class, FabricPrivacy::class, LoggerUtils::class, PowerManager::class, + AppRepository::class) class CommandQueueTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @@ -113,7 +115,14 @@ class CommandQueueTest : TestBaseWithProfile() { `when`(lazyActivePlugin.get()).thenReturn(activePlugin) `when`(activePlugin.activePump).thenReturn(testPumpPlugin) `when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface) - `when`(treatmentsInterface.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis) + `when`(repository.getLastBolusRecord()).thenReturn( + Bolus( + timestamp = Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis, + type = Bolus.Type.NORMAL, + amount = 0.0, + isBasalInsulin = false + ) + ) `when`(profileFunction.getProfile()).thenReturn(validProfile) val bolusConstraint = Constraint(0.0) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt index 9a3ba0be4a..ef0c2cd756 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt @@ -75,7 +75,7 @@ class QueueThreadTest : TestBaseWithProfile() { Mockito.`when`(lazyActivePlugin.get()).thenReturn(activePlugin) Mockito.`when`(activePlugin.activePump).thenReturn(pumpPlugin) Mockito.`when`(activePlugin.activeTreatments).thenReturn(treatmentsInterface) - Mockito.`when`(treatmentsInterface.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis) +// Mockito.`when`(treatmentsInterface.lastBolusTime).thenReturn(Calendar.getInstance().also { it.set(2000, 0, 1) }.timeInMillis) Mockito.`when`(profileFunction.getProfile()).thenReturn(validProfile) val bolusConstraint = Constraint(0.0) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index dc9a5a8cb1..ca84090bba 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -10,6 +10,7 @@ import androidx.appcompat.app.AppCompatActivity import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction @@ -22,6 +23,7 @@ import info.nightscout.androidaps.plugins.general.automation.events.EventTrigger import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerRemove import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.services.LastLocationDataContainer +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException @@ -37,10 +39,11 @@ abstract class Trigger(val injector: HasAndroidInjector) { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var sp: SP @Inject lateinit var locationDataContainer: LastLocationDataContainer - @Inject lateinit var treatmentsInterface: TreatmentsInterface + @Inject lateinit var repository: AppRepository @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculator @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider + @Inject lateinit var dateUtil: DateUtil init { injector.androidInjector().inject(this) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt index 723da22bd4..aebda7eb56 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt @@ -4,19 +4,20 @@ import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetString import org.json.JSONObject class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { - var minutesAgo: InputDuration = InputDuration( 30, InputDuration.TimeUnit.MINUTES) + + var minutesAgo: InputDuration = InputDuration(30, InputDuration.TimeUnit.MINUTES) var comparator: Comparator = Comparator(resourceHelper) private constructor(injector: HasAndroidInjector, triggerBolusAgo: TriggerBolusAgo) : this(injector) { @@ -35,7 +36,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val lastBolusTime = treatmentsInterface.getLastBolusTime(true) + val lastBolusTime = repository.getLastBolusRecordOfType(Bolus.Type.NORMAL)?.timestamp ?: 0L if (lastBolusTime == 0L) return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) @@ -44,7 +45,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) false } - val last = (DateUtil.now() - lastBolusTime).toDouble() / (60 * 1000) + val last = (dateUtil._now() - lastBolusTime).toDouble() / (60 * 1000) aapsLogger.debug(LTag.AUTOMATION, "LastBolus min ago: $minutesAgo") val doRun = comparator.value.check(last.toInt(), minutesAgo.getMinutes()) if (doRun) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt index 4d15d779e5..2a51eca64a 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt @@ -10,15 +10,12 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputTime import info.nightscout.androidaps.plugins.general.automation.elements.InputWeekDay import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.MidnightTime import org.json.JSONObject import java.util.* -import javax.inject.Inject class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { - @Inject lateinit var dateUtil: DateUtil val days = InputWeekDay() val time = InputTime(resourceHelper, dateUtil) @@ -34,7 +31,7 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { return this } - override fun shouldRun() : Boolean { + override fun shouldRun(): Boolean { val currentMinSinceMidnight = getMinSinceMidnight(dateUtil._now()) val scheduledDayOfWeek = Calendar.getInstance()[Calendar.DAY_OF_WEEK] if (days.isSet(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(scheduledDayOfWeek)))) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt index 8302608a47..b70f3d888f 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt @@ -4,22 +4,16 @@ import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -import javax.inject.Inject class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { - @Inject lateinit var repository: AppRepository - @Inject lateinit var dateUtil: DateUtil - var comparator = ComparatorExists(resourceHelper) constructor(injector: HasAndroidInjector, compare: ComparatorExists.Compare) : this(injector) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt index 722d50abe2..53eb6312c2 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.general.automation.triggers -import android.content.Context import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector @@ -13,10 +12,8 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import org.json.JSONObject -import javax.inject.Inject class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { - @Inject lateinit var dateUtil: DateUtil var time = InputDateTime(resourceHelper, dateUtil) @@ -24,7 +21,8 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { this.time.value = runAt } - @Suppress("unused") constructor(injector: HasAndroidInjector, triggerTime: TriggerTime) : this(injector) { + @Suppress("unused") + constructor(injector: HasAndroidInjector, triggerTime: TriggerTime) : this(injector) { this.time.value = triggerTime.time.value } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt index ff183bee41..8241eb3f62 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt @@ -13,13 +13,10 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.MidnightTime import org.json.JSONObject -import javax.inject.Inject // Trigger for time range ( from 10:00AM till 13:00PM ) class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { - @Inject lateinit var dateUtil: DateUtil - // in minutes since midnight 60 means 1AM var range = InputTimeRange(resourceHelper, dateUtil) @@ -28,7 +25,8 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { range.end = end } - @Suppress("unused") constructor(injector: HasAndroidInjector, triggerTimeRange: TriggerTimeRange) : this(injector) { + @Suppress("unused") + constructor(injector: HasAndroidInjector, triggerTimeRange: TriggerTimeRange) : this(injector) { range.start = triggerTimeRange.range.start range.end = triggerTimeRange.range.end } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt index e3e5c7391b..50936b666b 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.interfaces.ActivePluginProvider @@ -21,7 +22,7 @@ import org.mockito.Mock import org.powermock.core.classloader.annotations.PrepareForTest @Suppress("SpellCheckingInspection") -@PrepareForTest(FabricPrivacy::class) +@PrepareForTest(FabricPrivacy::class, AppRepository::class) open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePluginProvider @@ -32,6 +33,7 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var defaultValueHelper: DefaultValueHelper @Mock lateinit var dateUtil: DateUtil @Mock lateinit var configInterface: ConfigInterface + @Mock lateinit var repository: AppRepository val rxBus = RxBusWrapper(aapsSchedulers) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt index 173c7d8e9d..e970cefef0 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt @@ -6,7 +6,6 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -18,7 +17,7 @@ import org.mockito.Mock import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest -@PrepareForTest(RxBusWrapper::class, ActionsTestBase.TestLoopPlugin::class, AppRepository::class) +@PrepareForTest(RxBusWrapper::class, ActionsTestBase.TestLoopPlugin::class) open class ActionsTestBase : TestBaseWithProfile() { open class TestLoopPlugin( @@ -45,7 +44,6 @@ open class ActionsTestBase : TestBaseWithProfile() { @Mock lateinit var profilePlugin: ProfileInterface @Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorInterface @Mock lateinit var loopPlugin: TestLoopPlugin - @Mock lateinit var repository: AppRepository private val pluginDescription = PluginDescription() lateinit var testPumpPlugin: TestPumpPlugin diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt index 1394801ce1..1d27750569 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.automation.R +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.utils.DateUtil import org.json.JSONException @@ -29,8 +30,15 @@ class TriggerBolusAgoTest : TriggerTestBase() { @Test fun shouldRunTest() { - `when`(treatmentsInterface.getLastBolusTime(true)).thenReturn(now) // Set last bolus time to now - `when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min + `when`(repository.getLastBolusRecordOfType(Bolus.Type.NORMAL)).thenReturn( + Bolus( + timestamp = now, + amount = 0.0, + type = Bolus.Type.NORMAL, + isBasalInsulin = false + ) + ) // Set last bolus time to now + `when`(dateUtil._now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min var t = TriggerBolusAgo(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL) Assert.assertEquals(110, t.minutesAgo.value) Assert.assertEquals(Comparator.Compare.IS_EQUAL, t.comparator.value) @@ -52,7 +60,14 @@ class TriggerBolusAgoTest : TriggerTestBase() { Assert.assertTrue(t.shouldRun()) t = TriggerBolusAgo(injector).setValue(390).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER) Assert.assertTrue(t.shouldRun()) - PowerMockito.`when`(treatmentsInterface.getLastBolusTime(true)).thenReturn(0L) // Set last bolus time to 0 + `when`(repository.getLastBolusRecordOfType(Bolus.Type.NORMAL)).thenReturn( + Bolus( + timestamp = 0L, + amount = 0.0, + type = Bolus.Type.NORMAL, + isBasalInsulin = false + ) + ) // Set last bolus time to 0 t = TriggerBolusAgo(injector).comparator(Comparator.Compare.IS_NOT_AVAILABLE) Assert.assertTrue(t.shouldRun()) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt index 3b453772ed..f589bfcdea 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt @@ -14,13 +14,14 @@ import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.services.LastLocationDataContainer +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Before import org.mockito.Mock import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest -@PrepareForTest(LastLocationDataContainer::class, AutomationPlugin::class, AppRepository::class) +@PrepareForTest(LastLocationDataContainer::class, AutomationPlugin::class) open class TriggerTestBase : TestBaseWithProfile() { @Mock lateinit var sp: SP @@ -29,11 +30,10 @@ open class TriggerTestBase : TestBaseWithProfile() { @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculator @Mock lateinit var context: Context @Mock lateinit var automationPlugin: AutomationPlugin - @Mock lateinit var repository: AppRepository lateinit var receiverStatusStore: ReceiverStatusStore private val pluginDescription = PluginDescription() - lateinit var testPumpPlugin : TestPumpPlugin + lateinit var testPumpPlugin: TestPumpPlugin @Before fun prepareMock1() { @@ -51,10 +51,11 @@ open class TriggerTestBase : TestBaseWithProfile() { it.profileFunction = profileFunction it.sp = sp it.locationDataContainer = locationDataContainer - it.treatmentsInterface = treatmentsInterface + it.repository = repository it.activePlugin = activePlugin it.iobCobCalculatorPlugin = iobCobCalculatorPlugin it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin) + it.dateUtil = dateUtil } if (it is TriggerBg) { it.profileFunction = profileFunction diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 4b6981457a..82fbbe0340 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -28,7 +28,6 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -488,8 +487,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false); EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; - bolusingEvent.setT(new Treatment()); - bolusingEvent.getT().isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + bolusingEvent.setT(new EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB)); bolusingEvent.setPercent(100); rxBus.send(bolusingEvent); @@ -566,8 +564,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr return new PumpEnactResult(getInjector()).success(true).enacted(false); } - Treatment treatment = new Treatment(); - treatment.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + EventOverviewBolusProgress.Treatment treatment = new EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); EventOverviewBolusProgress.INSTANCE.setT(treatment); // start bolus delivery diff --git a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt index f1e05341be..66c4b51b16 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt @@ -31,11 +31,8 @@ class PumpEnactResult(injector: HasAndroidInjector) { var bolusDelivered = 0.0 // real value of delivered insulin var carbsDelivered = 0.0 // real value of delivered carbs var queued = false - fun success(success: Boolean): PumpEnactResult { - this.success = success - return this - } + fun success(success: Boolean): PumpEnactResult = this.also { this.success = success } fun enacted(enacted: Boolean): PumpEnactResult = this.also { it.enacted = enacted } fun comment(comment: String): PumpEnactResult = this.also { it.comment = comment } fun comment(comment: Int): PumpEnactResult = this.also { it.comment = resourceHelper.gs(comment) } diff --git a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java index a4f636348f..550de2b38a 100644 --- a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -297,14 +297,6 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase { // ----------------- DataPointInterface end -------------------- - public Iob iobCalc(long time, double dia) { - if (!isValid) - return new Iob(); - - InsulinInterface insulinInterface = activePlugin.getActiveInsulin(); - return insulinInterface.iobCalcForTreatment(this, time, dia); - } - @Override public long getDate() { return this.date; diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt index 7e838b62c7..a94d82ac28 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt @@ -4,8 +4,53 @@ import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.plugins.pump.common.defs.PumpType interface PumpSync { - fun addBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpType: PumpType, pumpSerial: String) - fun syncBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpId: Long?, pumpType: PumpType, pumpSerial: String) + /** + * Create bolus with temporary id + * + * Search for combination of temporaryId, PumpType, pumpSerial + * + * If db record doesn't exist, new record is created. + * If exists false is returned and data is ignored + * + * USAGE: + * Generate unique temporaryId + * Call before bolus when no pumpId is known (provide timestamp, amount, temporaryId, type, pumpType, pumpSerial) + * After reading record from history or completed bolus call syncBolusWithTempId with the same temporaryId provided + * If syncBolusWithTempId is not called afterwards record remains valid and is calculated towards iob + * + * @param timestamp timestamp of event from pump history + * @param amount amount of insulin + * @param temporaryId temporary id generated when pump id in not know yet + * @param type type of bolus (NORMAL, SMB, PRIME) + * @param pumpType pump type like PumpType.ACCU_CHEK_COMBO + * @param pumpSerial pump serial number + * @return true if new record is created + **/ + fun addBolusWithTempId(timestamp: Long, amount: Double, temporaryId: Long, type: DetailedBolusInfo.BolusType, pumpType: PumpType, pumpSerial: String) : Boolean + + /** + * Synchronization of boluses with temporary id + * + * Search for combination of temporaryId, PumpType, pumpSerial + * + * If db record doesn't exist data is ignored and false returned. + * If exists, amount and timestamp is updated, type and pumpId only if provided + * isValid field is preserved + * + * USAGE: + * After reading record from history or completed bolus call syncBolusWithTempId and + * provide updated timestamp, amount, pumpId (if known), type (if change needed) with the same temporaryId, pumpType, pumpSerial + * + * @param timestamp timestamp of event from pump history + * @param amount amount of insulin + * @param temporaryId temporary id generated when pump id in not know yet + * @param type type of bolus (NORMAL, SMB, PRIME) + * @param pumpId pump id from history + * @param pumpType pump type like PumpType.ACCU_CHEK_COMBO + * @param pumpSerial pump serial number + * @return true if record is successfully updated + **/ + fun syncBolusWithTempId(timestamp: Long, amount: Double, temporaryId: Long, type: DetailedBolusInfo.BolusType?, pumpId: Long?, pumpType: PumpType, pumpSerial: String) : Boolean /** * Synchronization of boluses @@ -13,17 +58,18 @@ interface PumpSync { * Search for combination of pumpId, PumpType, pumpSerial * * If db record doesn't exist, new record is created. - * If exists, data is updated + * If exists, amount, type (if provided) and timestamp is updated * isValid field is preserved * * @param timestamp timestamp of event from pump history * @param amount amount of insulin - * @param type type of bolus (NORMAL, SMB, PRIME). Default is NORMAL + * @param type type of bolus (NORMAL, SMB, PRIME) * @param pumpId pump id from history * @param pumpType pump type like PumpType.ACCU_CHEK_COMBO * @param pumpSerial pump serial number + * @return true if new record is created **/ - fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType = DetailedBolusInfo.BolusType.NORMAL, pumpId: Long, pumpType: PumpType, pumpSerial: String) + fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType?, pumpId: Long, pumpType: PumpType, pumpSerial: String) : Boolean /** * Synchronization of carbs @@ -39,8 +85,9 @@ interface PumpSync { * @param pumpId pump id from history if coming form pump history * @param pumpType pump type like PumpType.ACCU_CHEK_COMBO * @param pumpSerial pump serial number + * @return true if new record is created **/ - fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String) + fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String) : Boolean /** * Synchronization of events like CANNULA_CHANGE diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt index ff3aaa114f..3c6b9ae8eb 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt @@ -4,15 +4,6 @@ import info.nightscout.androidaps.db.Treatment interface TreatmentServiceInterface { - fun getTreatmentDataFromTime(mills: Long, ascending: Boolean): List - fun getTreatmentDataFromTime(from: Long, to: Long, ascending: Boolean): List - fun getTreatmentData(): List - fun getLastBolus(excludeSMB: Boolean): Treatment? - fun getLastCarb(): Treatment? fun createOrUpdateMedtronic(treatment: Treatment, fromNightScout: Boolean): UpdateReturn fun createOrUpdate(treatment: Treatment): UpdateReturn - fun resetTreatments() - fun delete(data: Treatment) - fun update(data: Treatment) - fun count(): Long } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index d8e5bd1cd1..aedbdce672 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -31,10 +31,6 @@ public interface TreatmentsInterface { @Deprecated List getTreatmentsFromHistoryAfterTimestamp(long timestamp); - long getLastBolusTime(); - - long getLastBolusTime(boolean excludeSMB); - // real basals (not faked by extended bolus) boolean isInHistoryRealTempBasalInProgress(); diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt index 3a7e187dd7..37ceec483b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt @@ -14,6 +14,7 @@ import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HtmlHelper.fromHtml import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -37,6 +38,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { @Inject lateinit var treatmentsPlugin: TreatmentsInterface @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var dateUtil: DateUtil var date: Long = 0 var reason: String? = null diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java index 5ee4414cdf..a15f0340a2 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java @@ -43,18 +43,21 @@ public class NSUpload { private final SP sp; private final UploadQueueInterface uploadQueue; private final RunningConfiguration runningConfiguration; + private final DateUtil dateUtil; @Inject public NSUpload( AAPSLogger aapsLogger, SP sp, UploadQueueInterface uploadQueue, - RunningConfiguration runningConfiguration + RunningConfiguration runningConfiguration, + DateUtil dateUtil ) { this.aapsLogger = aapsLogger; this.sp = sp; this.uploadQueue = uploadQueue; this.runningConfiguration = runningConfiguration; + this.dateUtil = dateUtil; } public void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) { @@ -208,7 +211,7 @@ public class NSUpload { IobTotal[] iob = iobCobCalculatorPlugin.calculateIobArrayInDia(profile); if (iob.length > 0) { deviceStatus.iob = iob[0].json(); - deviceStatus.iob.put("time", DateUtil.toISOString(DateUtil.now())); + deviceStatus.iob.put("time", DateUtil.toISOString(dateUtil._now())); } } deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL; diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt index fe43913333..5230bc979c 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt @@ -1,9 +1,11 @@ package info.nightscout.androidaps.plugins.general.overview.events -import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.events.Event object EventOverviewBolusProgress : Event() { + + data class Treatment constructor(@JvmField var insulin: Double = 0.0, @JvmField var carbs: Int = 0, @JvmField var isSMB: Boolean) + var status = "" var t: Treatment? = null var percent = 0 diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java index 49d26a29f7..73741edd79 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java @@ -13,7 +13,6 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.core.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.database.entities.Carbs; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index df3d5b2a9b..bf8d383274 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -6,10 +6,7 @@ import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.TherapyEvent -import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampCarbsTransaction -import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction -import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction -import info.nightscout.androidaps.database.transactions.SyncPumpBolusTransaction +import info.nightscout.androidaps.database.transactions.* import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -25,19 +22,54 @@ class PumpSyncImplementation @Inject constructor( private val disposable = CompositeDisposable() - override fun addBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpType: PumpType, pumpSerial: String) { - TODO("Not yet implemented") - } - - override fun syncBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpId: Long?, pumpType: PumpType, pumpSerial: String) { - TODO("Not yet implemented") - } - - override fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType, pumpId: Long, pumpType: PumpType, pumpSerial: String) { + override fun addBolusWithTempId(timestamp: Long, amount: Double, temporaryId: Long, type: DetailedBolusInfo.BolusType, pumpType: PumpType, pumpSerial: String) : Boolean { val bolus = Bolus( timestamp = timestamp, amount = amount, type = type.toDBbBolusType(), + interfaceIDs_backing = InterfaceIDs( + temporaryId = temporaryId, + pumpType = pumpType.toDbPumpType(), + pumpSerial = pumpSerial + ), + isBasalInsulin = false + ) + repository.runTransactionForResult(InsertPumpBolusWithTempIdTransaction(bolus)) + .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } + .blockingGet() + .also { result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } + return result.inserted.size > 0 + } + } + + override fun syncBolusWithTempId(timestamp: Long, amount: Double, temporaryId: Long, type: DetailedBolusInfo.BolusType?, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean { + val bolus = Bolus( + timestamp = timestamp, + amount = amount, + type = Bolus.Type.NORMAL, // not used for update + interfaceIDs_backing = InterfaceIDs( + temporaryId = temporaryId, + pumpId = pumpId, + pumpType = pumpType.toDbPumpType(), + pumpSerial = pumpSerial + ), + isBasalInsulin = false + ) + repository.runTransactionForResult(SyncPumpBolusWithTempIdTransaction(bolus, type?.toDBbBolusType())) + .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } + .blockingGet() + .also { result -> + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated carbs $it") } + return result.updated.size > 0 + } + } + + override fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType?, pumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean { + val bolus = Bolus( + timestamp = timestamp, + amount = amount, + type = type?.toDBbBolusType() ?: Bolus.Type.NORMAL, interfaceIDs_backing = InterfaceIDs( pumpId = pumpId, pumpType = pumpType.toDbPumpType(), @@ -45,17 +77,17 @@ class PumpSyncImplementation @Inject constructor( ), isBasalInsulin = false ) - disposable += repository.runTransactionForResult(SyncPumpBolusTransaction(bolus)) - .subscribe( - { result -> - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated carbs $it") } - }, - { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } - ) + repository.runTransactionForResult(SyncPumpBolusTransaction(bolus, type?.toDBbBolusType())) + .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } + .blockingGet() + .also { result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated carbs $it") } + return result.inserted.size > 0 + } } - override fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String) { + override fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean { val carbs = Carbs( timestamp = timestamp, amount = amount, @@ -65,11 +97,13 @@ class PumpSyncImplementation @Inject constructor( pumpType = pumpType.toDbPumpType(), pumpSerial = pumpSerial) ) - disposable += repository.runTransactionForResult(InsertIfNewByTimestampCarbsTransaction(carbs)) - .subscribe( - { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } }, - { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } - ) + repository.runTransactionForResult(InsertIfNewByTimestampCarbsTransaction(carbs)) + .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } + .blockingGet() + .also { result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } + return result.inserted.size > 0 + } } override fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String?, pumpId: Long?, pumpType: PumpType, pumpSerial: String) { diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentUpdateReturn.java b/core/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentUpdateReturn.java index 42b71b0217..c56a1c4441 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentUpdateReturn.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentUpdateReturn.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.treatments; -import info.nightscout.androidaps.db.Treatment; - public class TreatmentUpdateReturn { public TreatmentUpdateReturn(boolean success, boolean newRecord) { diff --git a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt index 1b90b24da4..0692ac68e3 100644 --- a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt +++ b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.core.R import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.queue.Callback @@ -17,6 +18,7 @@ abstract class Command( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var repository: AppRepository enum class CommandType { BOLUS, diff --git a/core/src/main/java/info/nightscout/androidaps/utils/extensions/BolusExtension.kt b/core/src/main/java/info/nightscout/androidaps/utils/extensions/BolusExtension.kt index 000a06efaf..61c122de28 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/extensions/BolusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/extensions/BolusExtension.kt @@ -1,19 +1,17 @@ package info.nightscout.androidaps.utils.extensions -import com.google.gson.Gson -import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Iob +import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.utils.DateUtil -import org.json.JSONException +import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject fun Bolus.iobCalc(activePlugin: ActivePluginProvider, time: Long, dia: Double): Iob { - if (!isValid) return Iob() + if (!isValid || type == Bolus.Type.PRIMING ) return Iob() val insulinInterface: InsulinInterface = activePlugin.activeInsulin return insulinInterface.iobCalcForTreatment(this, time, dia) } @@ -24,8 +22,48 @@ fun Bolus.toJson(): JSONObject = .put("insulin", amount) .put("created_at", DateUtil.toISOString(timestamp)) .put("date", timestamp) + .put("type", type.name) + .put("isValid", isValid) .put("isSMB", type == Bolus.Type.SMB).also { if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) + if (interfaceIDs.pumpType != null) it.put("pumpType", interfaceIDs.pumpType!!.name) + if (interfaceIDs.pumpSerial != null) it.put("pumpSerial", interfaceIDs.pumpSerial) if (interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) } +/* + create fake object with nsID and isValid == false + */ +fun bolusFromNsIdForInvalidating(nsId: String): Bolus = + bolusFromJson( + JSONObject() + .put("mills", 1) + .put("insulin", -1.0) + .put("_id", nsId) + .put("isValid", false) + )!! + +fun bolusFromJson(jsonObject: JSONObject): Bolus? { + val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null + val amount = JsonHelper.safeGetDoubleAllowNull(jsonObject, "insulin") ?: return null + val type = Bolus.Type.fromString(JsonHelper.safeGetString(jsonObject, "type")) + val isValid = JsonHelper.safeGetBoolean(jsonObject, "isValid", true) + val id = JsonHelper.safeGetStringAllowNull(jsonObject, "_id", null) ?: return null + val pumpId = JsonHelper.safeGetLongAllowNull(jsonObject, "pumpId", null) + val pumpType = InterfaceIDs.PumpType.fromString(JsonHelper.safeGetStringAllowNull(jsonObject, "pumpType", null)) + val pumpSerial = JsonHelper.safeGetStringAllowNull(jsonObject, "pumpSerial", null) + + return Bolus( + timestamp = timestamp, + amount = amount, + type = type, + isValid = isValid, + isBasalInsulin = false + ).also { + it.interfaceIDs.nightscoutId = id + it.interfaceIDs.pumpId = pumpId + it.interfaceIDs.pumpType = pumpType + it.interfaceIDs.pumpSerial = pumpSerial + } +} + diff --git a/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt b/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt index bbf7e76b26..87866d9cf3 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt @@ -1,10 +1,13 @@ package info.nightscout.androidaps.utils.extensions +import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import org.json.JSONObject +import java.util.concurrent.TimeUnit import kotlin.math.roundToInt fun Carbs.expandCarbs(): List = @@ -13,7 +16,7 @@ fun Carbs.expandCarbs(): List = carbs.add(this) } else { var remainingCarbs = this.amount - val ticks = T.msecs(this.duration).mins() * 4 //duration guaranteed to be integer greater zero + val ticks = T.msecs(this.duration).hours() * 4 //duration guaranteed to be integer greater zero for (i in 0 until ticks) { val carbTime = this.timestamp + i * 15 * 60 * 1000 val smallCarbAmount = (1.0 * remainingCarbs / (ticks - i)).roundToInt() //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs @@ -36,5 +39,43 @@ fun Carbs.toJson(): JSONObject = .put("date", timestamp).also { if (duration != 0L) it.put("duration", duration) if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) + if (interfaceIDs.pumpType != null) it.put("pumpType", interfaceIDs.pumpType!!.name) + if (interfaceIDs.pumpSerial != null) it.put("pumpSerial", interfaceIDs.pumpSerial) if (interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) } + +/* + create fake object with nsID and isValid == false + */ +fun carbsFromNsIdForInvalidating(nsId: String): Carbs = + carbsFromJson( + JSONObject() + .put("mills", 1) + .put("carbs", -1.0) + .put("_id", nsId) + .put("isValid", false) + )!! + +fun carbsFromJson(jsonObject: JSONObject): Carbs? { + val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null + val duration = JsonHelper.safeGetLong(jsonObject, "duration") + val amount = JsonHelper.safeGetDoubleAllowNull(jsonObject, "carbs") ?: return null + val isValid = JsonHelper.safeGetBoolean(jsonObject, "isValid", true) + val id = JsonHelper.safeGetStringAllowNull(jsonObject, "_id", null) ?: return null + val pumpId = JsonHelper.safeGetLongAllowNull(jsonObject, "pumpId", null) + val pumpType = InterfaceIDs.PumpType.fromString(JsonHelper.safeGetStringAllowNull(jsonObject, "pumpType", null)) + val pumpSerial = JsonHelper.safeGetStringAllowNull(jsonObject, "pumpSerial", null) + + return Carbs( + timestamp = timestamp, + duration = duration, + amount = amount, + isValid = isValid + ).also { + it.interfaceIDs.nightscoutId = id + it.interfaceIDs.pumpId = pumpId + it.interfaceIDs.pumpType = pumpType + it.interfaceIDs.pumpSerial = pumpSerial + } +} + diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt index 430916d0d5..60b68cbcd1 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt @@ -3,10 +3,10 @@ package info.nightscout.androidaps.dana import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -180,7 +180,7 @@ class DanaPump @Inject constructor( var bolusStartErrorCode: Int = 0 // last start bolus erroCode var historyDoneReceived: Boolean = false // true when last history message is received - var bolusingTreatment: Treatment? = null // actually delivered treatment + var bolusingTreatment: EventOverviewBolusProgress.Treatment? = null // actually delivered treatment var bolusAmountToBeDelivered = 0.0 // amount to be delivered var bolusProgressLastTimeStamp: Long = 0 // timestamp of last bolus progress message var bolusStopped = false // bolus finished diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java index 5aa0fcafe0..2dcafe1fa5 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java @@ -21,21 +21,23 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; +import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -50,6 +52,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { private final ResourceHelper resourceHelper; private final ConstraintChecker constraintChecker; private final FabricPrivacy fabricPrivacy; + private final PumpSync pumpSync; @Inject public DanaRKoreanPlugin( @@ -65,6 +68,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { SP sp, CommandQueueProvider commandQueue, DateUtil dateUtil, + PumpSync pumpSync, FabricPrivacy fabricPrivacy ) { super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil); @@ -72,6 +76,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { this.context = context; this.resourceHelper = resourceHelper; this.constraintChecker = constraintChecker; + this.pumpSync = pumpSync; this.fabricPrivacy = fabricPrivacy; getPluginDescription().description(R.string.description_pump_dana_r_korean); @@ -163,23 +168,40 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + EventOverviewBolusProgress.Treatment treatment = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) - connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); + connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, treatment); PumpEnactResult result = new PumpEnactResult(getInjector()); - result.success(connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.getBolusStep()) - .bolusDelivered(t.insulin) + result.success(connectionOK && Math.abs(detailedBolusInfo.insulin - treatment.insulin) < pumpDescription.getBolusStep()) + .bolusDelivered(treatment.insulin) .carbsDelivered(detailedBolusInfo.carbs); if (!result.getSuccess()) - result.comment(resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.getBolusStartErrorCode())); + result.comment(resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, treatment.insulin, danaPump.getBolusStartErrorCode())); else result.comment(R.string.ok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.getBolusDelivered()); - detailedBolusInfo.insulin = t.insulin; + detailedBolusInfo.insulin = treatment.insulin; detailedBolusInfo.timestamp = System.currentTimeMillis(); - activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); + + if (detailedBolusInfo.insulin > 0) + pumpSync.syncBolusWithPumpId( + detailedBolusInfo.timestamp, + detailedBolusInfo.insulin, + detailedBolusInfo.getBolusType(), + dateUtil._now(), + PumpType.DANA_R_KOREAN, + serialNumber() + ); + if (detailedBolusInfo.carbs > 0) + pumpSync.syncCarbsWithTimestamp( + detailedBolusInfo.timestamp + T.mins(detailedBolusInfo.carbTime).msecs(), + detailedBolusInfo.carbs, + null, + PumpType.DANA_R_KOREAN, + serialNumber() + ); + return result; } else { PumpEnactResult result = new PumpEnactResult(getInjector()); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java index e8bfd4fa91..2d7ea60435 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java @@ -38,7 +38,6 @@ import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal; import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; @@ -52,6 +51,7 @@ import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.queue.commands.Command; @@ -254,7 +254,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { return null; } - public boolean bolus(double amount, int carbs, long carbtime, final Treatment t) { + public boolean bolus(double amount, int carbs, long carbtime, final EventOverviewBolusProgress.Treatment t) { if (!isConnected()) return false; if (BolusProgressDialog.stopPressed) return false; diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index f13c4ebbd8..c53d025a78 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -20,7 +20,6 @@ import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -29,6 +28,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; @@ -182,8 +182,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { detailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java index ada2d39a22..17384b1161 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java @@ -52,7 +52,6 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBasic; import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; @@ -338,7 +337,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { return true; } - public boolean bolus(final double amount, int carbs, long carbtime, final Treatment t) { + public boolean bolus(final double amount, int carbs, long carbtime, final EventOverviewBolusProgress.Treatment t) { if (!isConnected()) return false; if (BolusProgressDialog.stopPressed) return false; diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index 54b32791f9..d2ea26c091 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -19,7 +19,6 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; @@ -30,6 +29,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -161,8 +161,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java index 920ffe617c..4ee619fdff 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java @@ -35,7 +35,6 @@ import info.nightscout.androidaps.danar.comm.MsgPCCommStart; import info.nightscout.androidaps.danar.comm.MsgPCCommStop; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventBTChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; @@ -43,6 +42,7 @@ import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.ToastUtils; @@ -95,7 +95,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { public abstract PumpEnactResult loadEvents(); - public abstract boolean bolus(double amount, int carbs, long carbtime, final Treatment t); + public abstract boolean bolus(double amount, int carbs, long carbtime, final EventOverviewBolusProgress.Treatment t); public abstract boolean highTempBasal(int percent, int durationInMinutes); // Rv2 only diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java index c6f523780f..ddbca639e2 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java @@ -45,7 +45,6 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; @@ -263,7 +262,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { return null; } - public boolean bolus(double amount, int carbs, long carbtime, final Treatment t) { + public boolean bolus(double amount, int carbs, long carbtime, final EventOverviewBolusProgress.Treatment t) { if (!isConnected()) return false; if (BolusProgressDialog.stopPressed) return false; diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt index d21a8f7939..a7c470008b 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt @@ -1,10 +1,8 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.danar.comm.MsgBolusProgress -import info.nightscout.androidaps.db.Treatment +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -17,7 +15,7 @@ class MsgBolusProgressTest : DanaRTestBase() { @Test fun runTest() { `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.bolusdelivering), ArgumentMatchers.anyDouble())).thenReturn("Delivering %1\$.2fU") - danaPump.bolusingTreatment = Treatment(HasAndroidInjector { AndroidInjector { } }) + danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) danaPump.bolusAmountToBeDelivered = 3.0 val packet = MsgBolusProgress(injector) diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt index d3bc63f092..46b901ec60 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt @@ -1,10 +1,8 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.danar.comm.MsgBolusStop -import info.nightscout.androidaps.db.Treatment +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -16,7 +14,7 @@ class MsgBolusStopTest : DanaRTestBase() { @Test fun runTest() { `when`(resourceHelper.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered") - danaPump.bolusingTreatment = Treatment(HasAndroidInjector { AndroidInjector { } }) + danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val packet = MsgBolusStop(injector) // test message decoding diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt index f948cf7a10..894a33be7c 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.danar.R import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert @@ -30,6 +31,7 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var sp: SP @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var pumpSync: PumpSync lateinit var danaPump: DanaPump @@ -46,7 +48,7 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, injector) - danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, aapsSchedulers, rxBus, danaPump, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, dateUtil, fabricPrivacy) + danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, aapsSchedulers, rxBus, danaPump, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, dateUtil, pumpSync, fabricPrivacy) } @Test @Throws(Exception::class) diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt index 0add10a2d0..d358e24216 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -15,7 +15,6 @@ import info.nightscout.androidaps.danars.services.DanaRSService import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventConfigBuilderChange import info.nightscout.androidaps.interfaces.* @@ -26,6 +25,7 @@ import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.defs.PumpType @@ -278,8 +278,7 @@ class DanaRSPlugin @Inject constructor( if (carbTime == 0) carbTime-- // better set 1 min back to prevents clash with insulin detailedBolusInfo.carbTime = 0 detailedBolusInfoStorage.add(detailedBolusInfo) // will be picked up on reading history - val t = Treatment() - t.isSMB = detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB + val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB); var connectionOK = false if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = danaRSService?.bolus(detailedBolusInfo.insulin, carbs.toInt(), DateUtil.now() + T.mins(carbTime.toLong()).msecs(), t) ?: false diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt index 5c01008eb3..fb33f44e35 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt @@ -124,26 +124,26 @@ open class DanaRS_Packet_APS_History_Events( DanaPump.BOLUS -> { val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0) - ?: DetailedBolusInfo() - detailedBolusInfo.bolusTimestamp = datetime - detailedBolusInfo.pumpType = PumpType.DANA_RS - detailedBolusInfo.pumpSerial = danaPump.serialNumber - detailedBolusInfo.bolusPumpId = pumpId - detailedBolusInfo.insulin = param1 / 100.0 - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = datetime, + amount = param1 / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = pumpId, + pumpType = PumpType.DANA_RS, + pumpSerial = danaPump.serialNumber) aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") status = "BOLUS " + dateUtil.timeString(datetime) } DanaPump.DUALBOLUS -> { val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0) - ?: DetailedBolusInfo() - detailedBolusInfo.bolusTimestamp = datetime - detailedBolusInfo.pumpType = PumpType.DANA_RS - detailedBolusInfo.pumpSerial = danaPump.serialNumber - detailedBolusInfo.bolusPumpId = pumpId - detailedBolusInfo.insulin = param1 / 100.0 - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = datetime, + amount = param1 / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = pumpId, + pumpType = PumpType.DANA_RS, + pumpSerial = danaPump.serialNumber) aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") status = "DUALBOLUS " + dateUtil.timeString(datetime) } @@ -196,13 +196,12 @@ open class DanaRS_Packet_APS_History_Events( } DanaPump.CARBS -> { - val emptyCarbsInfo = DetailedBolusInfo() - emptyCarbsInfo.carbs = param1.toDouble() - emptyCarbsInfo.carbsTimestamp = datetime - emptyCarbsInfo.pumpType = PumpType.DANA_RS - emptyCarbsInfo.pumpSerial = danaPump.serialNumber - emptyCarbsInfo.carbsPumpId = pumpId - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(emptyCarbsInfo, false) + val newRecord = pumpSync.syncCarbsWithTimestamp( + timestamp = datetime, + amount = param1.toDouble(), + pumpId = pumpId, + pumpType = PumpType.DANA_RS, + pumpSerial = danaPump.serialNumber) aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") status = "CARBS " + dateUtil.timeString(datetime) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index 5ce7fb1407..c729c0e3cd 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.danars.comm.* import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.dialogs.BolusProgressDialog import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventInitializationChanged @@ -247,7 +246,7 @@ class DanaRSService : DaggerService() { return PumpEnactResult(injector).success(message.success()) } - fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: Treatment): Boolean { + fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean { if (!isConnected) return false if (BolusProgressDialog.stopPressed) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt index 3ded5b81cd..1b2ef69411 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.danars.DanaRSTestBase import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -43,7 +44,7 @@ class DanaRSPacketNotifyDeliveryCompleteTest : DanaRSTestBase() { @Test fun runTest() { `when`(resourceHelper.gs(anyInt(), anyDouble())).thenReturn("SomeString") - danaPump.bolusingTreatment = Treatment(packetInjector) + danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val packet = DanaRS_Packet_Notify_Delivery_Complete(packetInjector) // test params Assert.assertEquals(null, packet.requestParams) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt index 2de51051ff..128f02bd0b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.danars.DanaRSTestBase import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -42,7 +43,7 @@ class DanaRsPacketBolusSetStepBolusStopTest : DanaRSTestBase() { @Test fun runTest() { `when`(resourceHelper.gs(Mockito.anyInt())).thenReturn("SomeString") - danaPump.bolusingTreatment = Treatment(packetInjector) + danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val testPacket = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(packetInjector) // test message decoding testPacket.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index 18db110e5b..61413466dd 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import org.junit.Assert import org.junit.Before @@ -69,6 +70,6 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { @Before fun mock() { danaRSPlugin = DanaRSPlugin(packetInjector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) - danaPump.bolusingTreatment = Treatment(packetInjector) + danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) } } \ No newline at end of file diff --git a/database/schemas/info.nightscout.androidaps.database.AppDatabase/8.json b/database/schemas/info.nightscout.androidaps.database.AppDatabase/8.json index 3d0a4f7f7d..b7cc18ae83 100644 --- a/database/schemas/info.nightscout.androidaps.database.AppDatabase/8.json +++ b/database/schemas/info.nightscout.androidaps.database.AppDatabase/8.json @@ -2,11 +2,11 @@ "formatVersion": 1, "database": { "version": 8, - "identityHash": "2e4a472793f7dd21528ddcb540500f1b", + "identityHash": "dab6024e846ee68708e8cfc047c39662", "entities": [ { "tableName": "apsResults", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `algorithm` TEXT NOT NULL, `glucoseStatusJson` TEXT NOT NULL, `currentTempJson` TEXT NOT NULL, `iobDataJson` TEXT NOT NULL, `profileJson` TEXT NOT NULL, `autosensDataJson` TEXT, `mealDataJson` TEXT NOT NULL, `isMicroBolusAllowed` INTEGER, `resultJson` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `algorithm` TEXT NOT NULL, `glucoseStatusJson` TEXT NOT NULL, `currentTempJson` TEXT NOT NULL, `iobDataJson` TEXT NOT NULL, `profileJson` TEXT NOT NULL, `autosensDataJson` TEXT, `mealDataJson` TEXT NOT NULL, `isMicroBolusAllowed` INTEGER, `resultJson` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -128,6 +128,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -187,7 +193,7 @@ }, { "tableName": "boluses", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `amount` REAL NOT NULL, `type` TEXT NOT NULL, `isBasalInsulin` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT, `insulinEndTime` INTEGER, `peak` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `amount` REAL NOT NULL, `type` TEXT NOT NULL, `isBasalInsulin` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT, `insulinEndTime` INTEGER, `peak` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -273,6 +279,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -350,7 +362,7 @@ }, { "tableName": "bolusCalculatorResults", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `targetBGLow` REAL NOT NULL, `targetBGHigh` REAL NOT NULL, `isf` REAL NOT NULL, `ic` REAL NOT NULL, `bolusIOB` REAL NOT NULL, `wasBolusIOBUsed` INTEGER NOT NULL, `basalIOB` REAL NOT NULL, `wasBasalIOBUsed` INTEGER NOT NULL, `glucoseValue` REAL NOT NULL, `wasGlucoseUsed` INTEGER NOT NULL, `glucoseDifference` REAL NOT NULL, `glucoseInsulin` REAL NOT NULL, `glucoseTrend` REAL NOT NULL, `wasTrendUsed` INTEGER NOT NULL, `trendInsulin` REAL NOT NULL, `cob` REAL NOT NULL, `wasCOBUsed` INTEGER NOT NULL, `cobInsulin` REAL NOT NULL, `carbs` REAL NOT NULL, `wereCarbsUsed` INTEGER NOT NULL, `carbsInsulin` REAL NOT NULL, `otherCorrection` REAL NOT NULL, `wasSuperbolusUsed` INTEGER NOT NULL, `superbolusInsulin` REAL NOT NULL, `wasTempTargetUsed` INTEGER NOT NULL, `totalInsulin` REAL NOT NULL, `percentageCorrection` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `note` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `bolusCalculatorResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `targetBGLow` REAL NOT NULL, `targetBGHigh` REAL NOT NULL, `isf` REAL NOT NULL, `ic` REAL NOT NULL, `bolusIOB` REAL NOT NULL, `wasBolusIOBUsed` INTEGER NOT NULL, `basalIOB` REAL NOT NULL, `wasBasalIOBUsed` INTEGER NOT NULL, `glucoseValue` REAL NOT NULL, `wasGlucoseUsed` INTEGER NOT NULL, `glucoseDifference` REAL NOT NULL, `glucoseInsulin` REAL NOT NULL, `glucoseTrend` REAL NOT NULL, `wasTrendUsed` INTEGER NOT NULL, `trendInsulin` REAL NOT NULL, `cob` REAL NOT NULL, `wasCOBUsed` INTEGER NOT NULL, `cobInsulin` REAL NOT NULL, `carbs` REAL NOT NULL, `wereCarbsUsed` INTEGER NOT NULL, `carbsInsulin` REAL NOT NULL, `otherCorrection` REAL NOT NULL, `wasSuperbolusUsed` INTEGER NOT NULL, `superbolusInsulin` REAL NOT NULL, `wasTempTargetUsed` INTEGER NOT NULL, `totalInsulin` REAL NOT NULL, `percentageCorrection` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `note` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `bolusCalculatorResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -592,6 +604,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -651,7 +669,7 @@ }, { "tableName": "carbs", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `carbs`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `carbs`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -731,6 +749,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -790,7 +814,7 @@ }, { "tableName": "effectiveProfileSwitches", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `effectiveProfileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `effectiveProfileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -870,6 +894,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -929,7 +959,7 @@ }, { "tableName": "extendedBoluses", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `isEmulatingTempBasal` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `isEmulatingTempBasal` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1015,6 +1045,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1074,7 +1110,7 @@ }, { "tableName": "glucoseValues", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `raw` REAL, `value` REAL NOT NULL, `trendArrow` TEXT NOT NULL, `noise` REAL, `sourceSensor` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `glucoseValues`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `raw` REAL, `value` REAL NOT NULL, `trendArrow` TEXT NOT NULL, `noise` REAL, `sourceSensor` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `glucoseValues`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1172,6 +1208,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1231,7 +1273,7 @@ }, { "tableName": "profileSwitches", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `timeshift` INTEGER NOT NULL, `percentage` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `profileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `timeshift` INTEGER NOT NULL, `percentage` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `profileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1353,6 +1395,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1430,7 +1478,7 @@ }, { "tableName": "temporaryBasals", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `type` TEXT NOT NULL, `isAbsolute` INTEGER NOT NULL, `rate` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `type` TEXT NOT NULL, `isAbsolute` INTEGER NOT NULL, `rate` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1522,6 +1570,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1581,7 +1635,7 @@ }, { "tableName": "temporaryTargets", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `reason` TEXT NOT NULL, `highTarget` REAL NOT NULL, `lowTarget` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryTargets`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `reason` TEXT NOT NULL, `highTarget` REAL NOT NULL, `lowTarget` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryTargets`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1673,6 +1727,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1732,7 +1792,7 @@ }, { "tableName": "therapyEvents", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `type` TEXT NOT NULL, `note` TEXT, `enteredBy` TEXT, `glucose` REAL, `glucoseType` TEXT, `glucoseUnit` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `therapyEvents`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `type` TEXT NOT NULL, `note` TEXT, `enteredBy` TEXT, `glucose` REAL, `glucoseType` TEXT, `glucoseUnit` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `therapyEvents`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1842,6 +1902,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -1901,7 +1967,7 @@ }, { "tableName": "totalDailyDoses", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalAmount` REAL, `bolusAmount` REAL, `totalAmount` REAL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `totalDailyDoses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalAmount` REAL, `bolusAmount` REAL, `totalAmount` REAL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `totalDailyDoses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -1987,6 +2053,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -2046,7 +2118,7 @@ }, { "tableName": "apsResultLinks", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `apsResultId` INTEGER NOT NULL, `smbId` INTEGER, `tbrId` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`apsResultId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`smbId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`tbrId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `apsResultLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `apsResultId` INTEGER NOT NULL, `smbId` INTEGER, `tbrId` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`apsResultId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`smbId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`tbrId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `apsResultLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -2120,6 +2192,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -2228,7 +2306,7 @@ }, { "tableName": "multiwaveBolusLinks", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `bolusId` INTEGER NOT NULL, `extendedBolusId` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`bolusId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`extendedBolusId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `multiwaveBolusLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `bolusId` INTEGER NOT NULL, `extendedBolusId` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`bolusId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`extendedBolusId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `multiwaveBolusLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -2296,6 +2374,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -2535,7 +2619,7 @@ }, { "tableName": "foods", - "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `name` TEXT NOT NULL, `category` TEXT, `subCategory` TEXT, `portion` REAL NOT NULL, `carbs` INTEGER NOT NULL, `fat` INTEGER, `protein` INTEGER, `energy` INTEGER, `unit` TEXT NOT NULL, `gi` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `foods`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `name` TEXT NOT NULL, `category` TEXT, `subCategory` TEXT, `portion` REAL NOT NULL, `carbs` INTEGER NOT NULL, `fat` INTEGER, `protein` INTEGER, `energy` INTEGER, `unit` TEXT NOT NULL, `gi` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `foods`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", "fields": [ { "fieldPath": "id", @@ -2651,6 +2735,12 @@ "affinity": "TEXT", "notNull": false }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, { "fieldPath": "interfaceIDs_backing.pumpId", "columnName": "pumpId", @@ -2704,7 +2794,7 @@ "views": [], "setupQueries": [ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", - "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2e4a472793f7dd21528ddcb540500f1b')" + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'dab6024e846ee68708e8cfc047c39662')" ] } } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt index aa1bb34071..a4516b6982 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt @@ -6,7 +6,7 @@ import androidx.room.TypeConverters import info.nightscout.androidaps.database.daos.* import info.nightscout.androidaps.database.entities.* -const val DATABASE_VERSION = 8 +const val DATABASE_VERSION = 9 @Database(version = DATABASE_VERSION, entities = [APSResult::class, Bolus::class, BolusCalculatorResult::class, Carbs::class, diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt index 8bda97439b..5c0d0de0d2 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.database -import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.* import info.nightscout.androidaps.database.interfaces.DBEntry import info.nightscout.androidaps.database.transactions.Transaction @@ -263,7 +262,7 @@ open class AppRepository @Inject internal constructor( * It is a Maybe as there might be no next element. * */ fun getNextSyncElementBolus(id: Long): Maybe> = - database.bolusDao.getNextModifiedOrNewAfter(id) + database.bolusDao.getNextModifiedOrNewAfterExclude(id, Bolus.Type.PRIMING) .flatMap { nextIdElement -> val nextIdElemReferenceId = nextIdElement.referenceId if (nextIdElemReferenceId == null) { @@ -278,8 +277,11 @@ open class AppRepository @Inject internal constructor( database.bolusDao.getModifiedFrom(lastId) .subscribeOn(Schedulers.io()) - fun findBolusByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? = - database.bolusDao.findByPumpIds(pumpId, pumpType, pumpSerial) + fun getLastBolusRecord(): Bolus? = + database.bolusDao.getLastBolusRecord() + + fun getLastBolusRecordOfType(type: Bolus.Type): Bolus? = + database.bolusDao.getLastBolusRecordOfType(type) fun getOldestBolusRecord(): Bolus? = database.bolusDao.getOldestBolusRecord() @@ -334,6 +336,9 @@ open class AppRepository @Inject internal constructor( fun getCarbsByTimestamp(timestamp: Long): Carbs? = database.carbsDao.findByTimestamp(timestamp) + fun getLastCarbsRecord(): Carbs? = + database.carbsDao.getLastCarbsRecord() + fun getOldestCarbsRecord(): Carbs? = database.carbsDao.getOldestCarbsRecord() diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt index e0685baa04..e5c7543b17 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt @@ -18,11 +18,26 @@ internal interface BolusDao : TraceableDao { @Query("DELETE FROM $TABLE_BOLUSES") override fun deleteAllEntries() + @Query("SELECT * FROM $TABLE_BOLUSES WHERE timestamp = :timestamp AND referenceId IS NULL") + fun findByTimestamp(timestamp: Long): Bolus? + + @Query("SELECT * FROM $TABLE_BOLUSES WHERE nightscoutId = :nsId AND referenceId IS NULL") + fun findByNSId(nsId: String): Bolus? + @Query("SELECT * FROM $TABLE_BOLUSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? - @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") - fun getOldestBolusRecord(): Bolus? + @Query("SELECT * FROM $TABLE_BOLUSES WHERE temporaryId = :temporaryId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") + fun findByPumpTempIds(temporaryId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? + + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + fun getLastBolusRecord(exclude: Bolus.Type = Bolus.Type.PRIMING): Bolus? + + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type == :only AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + fun getLastBolusRecordOfType(only: Bolus.Type): Bolus? + + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + fun getOldestBolusRecord(exclude: Bolus.Type = Bolus.Type.PRIMING): Bolus? @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getBolusesFromTime(timestamp: Long): Single> @@ -37,12 +52,12 @@ internal interface BolusDao : TraceableDao { fun getBolusesIncludingInvalidFromTimeToTime(from: Long, to: Long): Single> // This query will be used with v3 to get all changed records - @Query("SELECT * FROM $TABLE_BOLUSES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_BOLUSES WHERE id > :id) ORDER BY id ASC") - fun getModifiedFrom(id: Long): Single> + @Query("SELECT * FROM $TABLE_BOLUSES WHERE id > :id AND type <> :exclude AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_BOLUSES WHERE id > :id) ORDER BY id ASC") + fun getModifiedFrom(id: Long, exclude: Bolus.Type = Bolus.Type.PRIMING): Single> // for WS we need 1 record only - @Query("SELECT * FROM $TABLE_BOLUSES WHERE id > :id ORDER BY id ASC limit 1") - fun getNextModifiedOrNewAfter(id: Long): Maybe + @Query("SELECT * FROM $TABLE_BOLUSES WHERE id > :id AND type <> :exclude ORDER BY id ASC limit 1") + fun getNextModifiedOrNewAfterExclude(id: Long, exclude: Bolus.Type = Bolus.Type.PRIMING): Maybe @Query("SELECT * FROM $TABLE_BOLUSES WHERE id = :referenceId") fun getCurrentFromHistoric(referenceId: Long): Maybe diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt index 5d86cc7918..be8bf7e368 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt @@ -3,10 +3,7 @@ package info.nightscout.androidaps.database.daos import androidx.room.Dao import androidx.room.Query import info.nightscout.androidaps.database.TABLE_CARBS -import info.nightscout.androidaps.database.TABLE_THERAPY_EVENTS -import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.Carbs -import info.nightscout.androidaps.database.entities.TherapyEvent import io.reactivex.Maybe import io.reactivex.Single @@ -20,9 +17,15 @@ internal interface CarbsDao : TraceableDao { @Query("DELETE FROM $TABLE_CARBS") override fun deleteAllEntries() + @Query("SELECT * FROM $TABLE_CARBS WHERE nightscoutId = :nsId AND referenceId IS NULL") + fun findByNSId(nsId: String): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(timestamp: Long): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id DESC LIMIT 1") + fun getLastCarbsRecord(): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") fun getOldestCarbsRecord(): Carbs? diff --git a/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt index c9de90aa4b..beb7eb5184 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt @@ -1,10 +1,13 @@ package info.nightscout.androidaps.database.embedments +import info.nightscout.androidaps.database.entities.TherapyEvent + data class InterfaceIDs( var nightscoutSystemId: String? = null, var nightscoutId: String? = null, var pumpType: PumpType? = null, // if == USER pumpSerial & pumpId can be null var pumpSerial: String? = null, + var temporaryId: Long? = null, // temporary id for pump synchronization, when pump id is not available var pumpId: Long? = null, var startId: Long? = null, var endId: Long? = null @@ -40,6 +43,11 @@ data class InterfaceIDs( TANDEM_T_SLIM_X2, YPSOPUMP, MDI, - USER + USER; + + companion object { + + fun fromString(name: String?) = values().firstOrNull { it.name == name } + } } } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt index cabac19c2d..b85f1aabe8 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt @@ -40,6 +40,11 @@ data class Bolus( enum class Type { NORMAL, SMB, - PRIMING + PRIMING; + + companion object { + + fun fromString(name: String?) = values().firstOrNull { it.name == name } ?: NORMAL + } } } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertPumpBolusWithTempIdTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertPumpBolusWithTempIdTransaction.kt new file mode 100644 index 0000000000..97f8286eff --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertPumpBolusWithTempIdTransaction.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.Bolus + +/** + * Creates or updates the Bolus from pump synchronization + */ +class InsertPumpBolusWithTempIdTransaction( + private val bolus: Bolus +) : Transaction() { + + override fun run(): TransactionResult { + bolus.interfaceIDs.temporaryId ?: bolus.interfaceIDs.pumpType ?: bolus.interfaceIDs.pumpSerial ?: + throw IllegalStateException("Some pump ID is null") + val result = TransactionResult() + val current = database.bolusDao.findByPumpTempIds(bolus.interfaceIDs.temporaryId!!, bolus.interfaceIDs.pumpType!!, bolus.interfaceIDs.pumpSerial!!) + if (current == null) { + database.bolusDao.insert(bolus) + result.inserted.add(bolus) + } + return result + } + + class TransactionResult { + + val inserted = mutableListOf() + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateAAPSStartedTherapyEventTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateAAPSStartedTherapyEventTransaction.kt index 79d4ab3073..248b51d412 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateAAPSStartedTherapyEventTransaction.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateAAPSStartedTherapyEventTransaction.kt @@ -8,7 +8,7 @@ class InvalidateAAPSStartedTherapyEventTransaction(private val note: String) : T val result = TransactionResult() val therapyEvents = database.therapyEventDao.getValidByType(TherapyEvent.Type.NOTE) for (event in therapyEvents) { - if (event.note == note) { + if (event.note?.contains(note) == true) { event.isValid = false database.therapyEventDao.updateExistingEntry(event) result.invalidated.add(event) diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsBolusTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsBolusTransaction.kt new file mode 100644 index 0000000000..5c453a3673 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsBolusTransaction.kt @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.Bolus + +/** + * Sync the Bolus from NS + */ +class SyncNsBolusTransaction(private val bolus: Bolus) : Transaction() { + + override fun run(): TransactionResult { + val result = TransactionResult() + + val current: Bolus? = + bolus.interfaceIDs.nightscoutId?.let { + database.bolusDao.findByNSId(it) + } + + if (current != null) { + // nsId exists, allow only invalidation + if (current.isValid && !bolus.isValid) { + current.isValid = false + database.bolusDao.updateExistingEntry(current) + result.invalidated.add(current) + } + return result + } + + // not known nsId + val existing = database.bolusDao.findByTimestamp(bolus.timestamp) + if (existing != null && existing.interfaceIDs.nightscoutId == null) { + // the same record, update nsId only + existing.interfaceIDs.nightscoutId = bolus.interfaceIDs.nightscoutId + existing.isValid = bolus.isValid + database.bolusDao.updateExistingEntry(existing) + result.updatedNsId.add(existing) + } else { + database.bolusDao.insertNewEntry(bolus) + result.inserted.add(bolus) + } + return result + + } + + class TransactionResult { + + val updatedNsId = mutableListOf() + val inserted = mutableListOf() + val invalidated = mutableListOf() + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsCarbsTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsCarbsTransaction.kt new file mode 100644 index 0000000000..9d4378c01b --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsCarbsTransaction.kt @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.Carbs + +/** + * Sync the carbs from NS + */ +class SyncNsCarbsTransaction(private val carbs: Carbs) : Transaction() { + + override fun run(): TransactionResult { + val result = TransactionResult() + + val current: Carbs? = + carbs.interfaceIDs.nightscoutId?.let { + database.carbsDao.findByNSId(it) + } + + if (current != null) { + // nsId exists, allow only invalidation + if (current.isValid && !carbs.isValid) { + current.isValid = false + database.carbsDao.updateExistingEntry(current) + result.invalidated.add(current) + } + return result + } + + // not known nsId + val existing = database.carbsDao.findByTimestamp(carbs.timestamp) + if (existing != null && existing.interfaceIDs.nightscoutId == null) { + // the same record, update nsId only + existing.interfaceIDs.nightscoutId = carbs.interfaceIDs.nightscoutId + existing.isValid = carbs.isValid + database.carbsDao.updateExistingEntry(existing) + result.updatedNsId.add(existing) + } else { + database.carbsDao.insertNewEntry(carbs) + result.inserted.add(carbs) + } + return result + + } + + class TransactionResult { + + val updatedNsId = mutableListOf() + val inserted = mutableListOf() + val invalidated = mutableListOf() + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusTransaction.kt index de4a3d168c..5c531a5bb2 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusTransaction.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusTransaction.kt @@ -1,15 +1,13 @@ package info.nightscout.androidaps.database.transactions -import info.nightscout.androidaps.database.embedments.InsulinConfiguration -import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.Bolus -import java.lang.IllegalStateException /** * Creates or updates the Bolus from pump synchronization */ class SyncPumpBolusTransaction( private val bolus: Bolus, + private val bolusType: Bolus.Type? // extra parameter because field is not nullable in Bolus.class ) : Transaction() { override fun run(): TransactionResult { @@ -21,9 +19,11 @@ class SyncPumpBolusTransaction( database.bolusDao.insertNewEntry(bolus) result.inserted.add(bolus) } else { - bolus.isValid = current.isValid - database.bolusDao.updateExistingEntry(bolus) - result.updated.add(bolus) + current.timestamp = bolus.timestamp + current.amount = bolus.amount + current.type = bolusType ?: current.type + database.bolusDao.updateExistingEntry(current) + result.updated.add(current) } return result } diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusWithTempIdTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusWithTempIdTransaction.kt new file mode 100644 index 0000000000..8fe8eb4fc3 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpBolusWithTempIdTransaction.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.Bolus + +/** + * Creates or updates the Bolus from pump synchronization + */ +class SyncPumpBolusWithTempIdTransaction( + private val bolus: Bolus, + private val newType: Bolus.Type? +) : Transaction() { + + override fun run(): TransactionResult { + bolus.interfaceIDs.temporaryId ?: bolus.interfaceIDs.pumpType ?: bolus.interfaceIDs.pumpSerial ?: + throw IllegalStateException("Some pump ID is null") + val result = TransactionResult() + val current = database.bolusDao.findByPumpTempIds(bolus.interfaceIDs.temporaryId!!, bolus.interfaceIDs.pumpType!!, bolus.interfaceIDs.pumpSerial!!) + if (current != null) { + current.timestamp = bolus.timestamp + current.amount = bolus.amount + current.type = newType ?: current.type + current.interfaceIDs.pumpId = bolus.interfaceIDs.pumpId + database.bolusDao.updateExistingEntry(current) + result.updated.add(current) + } + return result + } + + class TransactionResult { + + val updated = mutableListOf() + } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index ee34a2acee..db7c41121d 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -37,7 +37,6 @@ import info.nightscout.androidaps.db.InsightPumpID; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.insight.R; @@ -591,8 +590,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, bolusCancelled = false; } result.success(true).enacted(true); - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; bolusingEvent.setT(t); bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, 0d, insulin)); diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index 4245533ede..b6bc68a47a 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -18,7 +18,6 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventCustomActionsChanged; import info.nightscout.androidaps.interfaces.ActivePluginProvider; @@ -418,8 +417,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true); EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; - bolusingEvent.setT(new Treatment()); - bolusingEvent.getT().isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; + bolusingEvent.setT(new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB)); bolusingEvent.setPercent(100); rxBus.send(bolusingEvent); From 07d060c2b5420454d1a8af5deed40b893efaa71b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 30 Mar 2021 22:05:44 +0200 Subject: [PATCH 5/5] carbs with duration --- .../data/defaultProfile/DefaultProfile.kt | 0 .../data/defaultProfile/DefaultProfileDPV.kt | 0 .../dependencyInjection/OverviewModule.kt | 2 + .../general/overview/OverviewFragment.kt | 7 +- .../general/overview/graphData/GraphData.kt | 16 +- .../graphExtensions}/BolusDataPoint.kt | 8 +- .../graphExtensions}/CarbsDataPoint.kt | 6 +- .../graphExtensions}/GlucoseValueDataPoint.kt | 27 +- .../graphExtensions}/TherapyEventDataPoint.kt | 22 +- .../general/tidepool/comm/UploadChunk.kt | 2 +- .../wearintegration/WatchUpdaterService.java | 10 +- .../IobCobCalculatorPlugin.kt | 7 +- .../iob/iobCobCalculator/IobCobOref1Thread.kt | 2 +- .../iob/iobCobCalculator/IobCobThread.kt | 2 +- .../fragments/TreatmentsBolusCarbsFragment.kt | 2 +- .../androidaps/utils/stats/TddCalculator.kt | 2 +- .../layout/treatments_bolus_carbs_item.xml | 1 + .../core/di/CoreDataClassesModule.kt | 4 - .../androidaps/plugins/aps/loop/APSResult.kt | 15 +- .../PointsWithLabelGraphSeries.java | 79 +- .../utils/extensions/CarbsExtension.kt | 24 - .../9.json | 2800 +++++++++++++++++ .../androidaps/database/AppRepository.kt | 52 +- .../androidaps/database/daos/CarbsDao.kt | 3 + 24 files changed, 2950 insertions(+), 143 deletions(-) rename {core => app}/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt (100%) rename {core => app}/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt (100%) rename {core/src/main/java/info/nightscout/androidaps/data => app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions}/BolusDataPoint.kt (75%) rename {core/src/main/java/info/nightscout/androidaps/data => app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions}/CarbsDataPoint.kt (76%) rename {core/src/main/java/info/nightscout/androidaps/data => app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions}/GlucoseValueDataPoint.kt (71%) rename {core/src/main/java/info/nightscout/androidaps/data => app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions}/TherapyEventDataPoint.kt (84%) create mode 100644 database/schemas/info.nightscout.androidaps.database.AppDatabase/9.json diff --git a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt rename to app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt diff --git a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt rename to app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt index 196e5b1203..42c55758ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt @@ -3,6 +3,8 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.TherapyEventDataPoint import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction @Module diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index b0dcee802b..df4d0c0d3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -47,10 +47,10 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.source.DexcomPlugin @@ -778,7 +778,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (config.APS && lastRun?.constraintsProcessed != null) { if (lastRun.constraintsProcessed!!.carbsReq > 0) { //only display carbsreq when carbs have not been entered recently - val lastCarbsTime = repository.getLastBolusRecord()?.timestamp ?: 0L + val lastCarb = repository.getLastCarbsRecordWrapped().blockingGet() + val lastCarbsTime = if (lastCarb is ValueWrapper.Existing) lastCarb.value.timestamp else 0L if (lastCarbsTime < lastRun.lastAPSRun) { cobText = cobText + " | " + lastRun.constraintsProcessed!!.carbsReq + " " + resourceHelper.gs(R.string.required) } @@ -862,7 +863,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList // **** BG **** if (predictionsAvailable && menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal]) - graphData.addBgReadings(fromTime, toTime, lowLine, highLine, apsResult?.predictions) + graphData.addBgReadings(fromTime, toTime, lowLine, highLine, apsResult?.predictions?.map { bg-> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper) }?.toMutableList()) else graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null) // Treatments diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index f42f8da7d1..89cb764fd5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -11,7 +11,8 @@ import com.jjoe64.graphview.series.Series import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.data.* +import info.nightscout.androidaps.data.IobTotal +import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.Bolus @@ -22,11 +23,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.general.overview.graphExtensions.* import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* @@ -51,6 +48,7 @@ class GraphData( @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil @Inject lateinit var defaultValueHelper: DefaultValueHelper + @Inject lateinit var translator: Translator var maxY = Double.MIN_VALUE private var minY = Double.MAX_VALUE @@ -77,7 +75,7 @@ class GraphData( for (bg in bgReadingsArray!!) { if (bg.timestamp < fromTime || bg.timestamp > toTime) continue if (bg.value > maxBgValue) maxBgValue = bg.value - bgListArray.add(GlucoseValueDataPoint(injector, bg)) + bgListArray.add(GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) } if (predictions != null) { predictions.sortWith(Comparator { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) }) @@ -247,7 +245,7 @@ class GraphData( it.y = getNearestBg(it.x.toLong()) filteredTreatments.add(it) } - repository.getCarbsIncludingInvalidFromTimeToTime(fromTime, endTime, true).blockingGet() + repository.getCarbsIncludingInvalidFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet() .map { CarbsDataPoint(it, resourceHelper) } .forEach { it.y = getNearestBg(it.x.toLong()) @@ -273,7 +271,7 @@ class GraphData( // Careportal // databaseHelper.getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true) repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() - .map { TherapyEventDataPoint(injector, it) } + .map { TherapyEventDataPoint(it, resourceHelper, profileFunction, translator) } .filterTimeframe(fromTime, endTime) .forEach { if (it.y == 0.0) it.y = getNearestBg(it.x.toLong()) diff --git a/core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt similarity index 75% rename from core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt index 9e01d2340a..f144ebd881 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt @@ -1,12 +1,10 @@ -package info.nightscout.androidaps.data +package info.nightscout.androidaps.plugins.general.overview.graphExtensions import android.graphics.Color import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries -import info.nightscout.androidaps.utils.DecimalFormatter.toPumpSupportedBolus +import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject @@ -22,7 +20,7 @@ class BolusDataPoint @Inject constructor( override fun getX(): Double = data.timestamp.toDouble() override fun getY(): Double = if (data.type == Bolus.Type.SMB) defaultValueHelper.determineLowLine() else yValue - override fun getLabel(): String = toPumpSupportedBolus(data.amount, activePlugin.activePump, resourceHelper) + override fun getLabel(): String = DecimalFormatter.toPumpSupportedBolus(data.amount, activePlugin.activePump, resourceHelper) override fun getDuration(): Long = 0 override fun getSize(): Float = 2f diff --git a/core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt similarity index 76% rename from core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt index b4924968d2..719533da98 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt @@ -1,9 +1,7 @@ -package info.nightscout.androidaps.data +package info.nightscout.androidaps.plugins.general.overview.graphExtensions import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.Carbs -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject @@ -20,7 +18,7 @@ class CarbsDataPoint @Inject constructor( override fun getDuration(): Long = 0 override fun getSize(): Float = 2f - override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.BOLUS + override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.CARBS override fun getColor(): Int = if (data.isValid) resourceHelper.gc(R.color.carbs) diff --git a/core/src/main/java/info/nightscout/androidaps/data/GlucoseValueDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt similarity index 71% rename from core/src/main/java/info/nightscout/androidaps/data/GlucoseValueDataPoint.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt index 9c884b5315..ef48139b52 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/GlucoseValueDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt @@ -1,29 +1,20 @@ -package info.nightscout.androidaps.data +package info.nightscout.androidaps.plugins.general.overview.graphExtensions -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.interfaces.ProfileFunction -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class GlucoseValueDataPoint @Inject constructor( - val injector: HasAndroidInjector, - val data: GlucoseValue + val data: GlucoseValue, + private val defaultValueHelper: DefaultValueHelper, + private val profileFunction: ProfileFunction, + private val resourceHelper: ResourceHelper ) : DataPointWithLabelInterface { - @Inject lateinit var defaultValueHelper: DefaultValueHelper - @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper - - init { - injector.androidInjector().inject(this) - } - fun valueToUnits(units: String): Double = if (units == Constants.MGDL) data.value else data.value * Constants.MGDL_TO_MMOLL @@ -59,11 +50,11 @@ class GlucoseValueDataPoint @Inject constructor( val predictionColor: Int get() { return when (data.sourceSensor) { - GlucoseValue.SourceSensor.IOB_PREDICTION -> resourceHelper.gc(R.color.iob) - GlucoseValue.SourceSensor.COB_PREDICTION -> resourceHelper.gc(R.color.cob) + GlucoseValue.SourceSensor.IOB_PREDICTION -> resourceHelper.gc(R.color.iob) + GlucoseValue.SourceSensor.COB_PREDICTION -> resourceHelper.gc(R.color.cob) GlucoseValue.SourceSensor.aCOB_PREDICTION -> -0x7f000001 and resourceHelper.gc(R.color.cob) - GlucoseValue.SourceSensor.UAM_PREDICTION -> resourceHelper.gc(R.color.uam) - GlucoseValue.SourceSensor.ZT_PREDICTION -> resourceHelper.gc(R.color.zt) + GlucoseValue.SourceSensor.UAM_PREDICTION -> resourceHelper.gc(R.color.uam) + GlucoseValue.SourceSensor.ZT_PREDICTION -> resourceHelper.gc(R.color.zt) else -> R.color.white } } diff --git a/core/src/main/java/info/nightscout/androidaps/data/TherapyEventDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt similarity index 84% rename from core/src/main/java/info/nightscout/androidaps/data/TherapyEventDataPoint.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt index 7c884db7f1..457922d1da 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/TherapyEventDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt @@ -1,35 +1,25 @@ -package info.nightscout.androidaps.data +package info.nightscout.androidaps.plugins.general.overview.graphExtensions import android.graphics.Color -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.interfaces.Interval import info.nightscout.androidaps.interfaces.ProfileFunction -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries -import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class TherapyEventDataPoint @Inject constructor( - val injector: HasAndroidInjector, - val data: TherapyEvent + val data: TherapyEvent, + private val resourceHelper: ResourceHelper, + private val profileFunction: ProfileFunction, + private val translator: Translator ) : DataPointWithLabelInterface, Interval { - @Inject lateinit var defaultValueHelper: DefaultValueHelper - @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var translator: Translator - private var yValue = 0.0 - init { - injector.androidInjector().inject(this) - } - override fun getX(): Double { return data.timestamp.toDouble() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index dd4705b4dc..e8dcd49852 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -120,7 +120,7 @@ class UploadChunk @Inject constructor( .forEach { bolus -> result.add(BolusElement(bolus)) } - repository.getCarbsDataFromTimeToTime(start, end, true) + repository.getCarbsDataFromTimeToTimeExpanded(start, end, true) .blockingGet() .forEach { carb -> result.add(WizardElement(carb)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index 8cb8318c2b..d64cb9a38b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -24,6 +24,7 @@ import com.google.android.gms.wearable.WearableListenerService; import java.util.ArrayList; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import javax.inject.Inject; @@ -31,7 +32,7 @@ import dagger.android.AndroidInjection; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.GlucoseValueDataPoint; +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.database.AppRepository; @@ -530,12 +531,15 @@ public class WatchUpdaterService extends WearableListenerService implements Goog .stream() .filter(bolus -> bolus.getType() != Bolus.Type.PRIMING) .forEach(bolus -> boluses.add(treatmentMap(bolus.getTimestamp(), bolus.getAmount(), 0, bolus.getType() == Bolus.Type.SMB, bolus.isValid()))); - repository.getCarbsIncludingInvalidFromTime(startTimeWindow, true).blockingGet() + repository.getCarbsDataFromTimeExpanded(startTimeWindow, true).blockingGet() .forEach(carb -> boluses.add(treatmentMap(carb.getTimestamp(), 0, carb.getAmount(), false, carb.isValid()))); final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun(); if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) { - List predArray = finalLastRun.getConstraintsProcessed().getPredictions(); + List predArray = + finalLastRun.getConstraintsProcessed().getPredictions() + .stream().map( bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) + .collect(Collectors.toList()); if (!predArray.isEmpty()) { final String units = profileFunction.getUnits(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index 10713c9da9..54ff12c372 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -28,7 +28,6 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.extensions.expandCarbs import info.nightscout.androidaps.utils.extensions.iobCalc import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -532,8 +531,7 @@ open class IobCobCalculatorPlugin @Inject constructor( var displayCob: Double? = null var futureCarbs = 0.0 val now = DateUtil.now() - val carbs = repository.getCarbsDataFromTime(now, true) - .blockingGet() + val carbs = repository.getCarbsDataFromTimeExpanded(now, true).blockingGet() if (autosensData != null) { displayCob = autosensData.cob carbs.forEach { carb -> @@ -603,8 +601,7 @@ open class IobCobCalculatorPlugin @Inject constructor( sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME) } val absorptionTimeAgo = now - (maxAbsorptionHours * T.hours(1).msecs()).toLong() - repository.getCarbsDataFromTimeToTime(absorptionTimeAgo + 1, now, true) - .map { it.map { c -> c.expandCarbs() }.flatten() } + repository.getCarbsDataFromTimeToTimeExpanded(absorptionTimeAgo + 1, now, true) .blockingGet() .forEach { if (it.amount > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt index 89fc40a796..d1d155cbd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt @@ -189,7 +189,7 @@ class IobCobOref1Thread internal constructor( aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null") } } - val recentCarbTreatments = repository.getCarbsDataFromTimeToTime(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() + val recentCarbTreatments = repository.getCarbsDataFromTimeToTimeExpanded(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() for (recentCarbTreatment in recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt index 1c634259df..7d429eda78 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt @@ -188,7 +188,7 @@ class IobCobThread @Inject internal constructor( aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null") } } - val recentCarbTreatments = repository.getCarbsDataFromTimeToTime(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() + val recentCarbTreatments = repository.getCarbsDataFromTimeToTimeExpanded(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() for (recentCarbTreatment in recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt index b5a2cd335e..19f553c1dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt @@ -293,7 +293,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { ml.carbs?.let { carbs -> holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp) holder.binding.carbs.text = resourceHelper.gs(R.string.format_carbs, carbs.amount.toInt()) - holder.binding.carbsDuration.text = resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) + holder.binding.carbsDuration.text = if (carbs.duration> 0) resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) else "" holder.binding.carbsNs.visibility = (NSUpload.isIdValid(carbs.interfaceIDs.nightscoutId)).toVisibility() holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility() holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility() diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 1ece37cabe..366147a92a 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -65,7 +65,7 @@ class TddCalculator @Inject constructor( tdd.bolus += t.amount result.put(midnight, tdd) } - repository.getCarbsDataFromTimeToTime(startTime, endTime, true).blockingGet().forEach { t-> + repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t-> val midnight = MidnightTime.calc(t.timestamp) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) tdd.carbs += t.amount diff --git a/app/src/main/res/layout/treatments_bolus_carbs_item.xml b/app/src/main/res/layout/treatments_bolus_carbs_item.xml index fba6a1e3e5..3257124069 100644 --- a/app/src/main/res/layout/treatments_bolus_carbs_item.xml +++ b/app/src/main/res/layout/treatments_bolus_carbs_item.xml @@ -205,6 +205,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" + android:layout_marginStart="10dp" android:textStyle="bold" /> + val predictions: MutableList get() { - val array: MutableList = ArrayList() + val array: MutableList = ArrayList() val startTime = date json?.let { json -> if (json.has("predBGs")) { @@ -203,7 +202,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { sourceSensor = GlucoseValue.SourceSensor.IOB_PREDICTION, trendArrow = GlucoseValue.TrendArrow.NONE ) - array.add(GlucoseValueDataPoint(injector, gv)) + array.add(gv) } } if (predBGs.has("aCOB")) { @@ -217,7 +216,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { sourceSensor = GlucoseValue.SourceSensor.aCOB_PREDICTION, trendArrow = GlucoseValue.TrendArrow.NONE ) - array.add(GlucoseValueDataPoint(injector, gv)) + array.add(gv) } } if (predBGs.has("COB")) { @@ -231,7 +230,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { sourceSensor = GlucoseValue.SourceSensor.COB_PREDICTION, trendArrow = GlucoseValue.TrendArrow.NONE ) - array.add(GlucoseValueDataPoint(injector, gv)) + array.add(gv) } } if (predBGs.has("UAM")) { @@ -245,7 +244,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { sourceSensor = GlucoseValue.SourceSensor.UAM_PREDICTION, trendArrow = GlucoseValue.TrendArrow.NONE ) - array.add(GlucoseValueDataPoint(injector, gv)) + array.add(gv) } } if (predBGs.has("ZT")) { @@ -259,7 +258,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { sourceSensor = GlucoseValue.SourceSensor.ZT_PREDICTION, trendArrow = GlucoseValue.TrendArrow.NONE ) - array.add(GlucoseValueDataPoint(injector, gv)) + array.add(gv) } } } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/PointsWithLabelGraphSeries.java b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/PointsWithLabelGraphSeries.java index db18fc2a5f..a9acc400c1 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/PointsWithLabelGraphSeries.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/PointsWithLabelGraphSeries.java @@ -18,15 +18,12 @@ package info.nightscout.androidaps.plugins.general.overview.graphExtensions; * You should have received a copy of the GNU General Public License * with the "Linking Exception" along with this program; if not, * write to the author Jonas Gehring . - *

+ */ + +/* * Added by mike */ -/** - * Added by mike - */ - -import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; @@ -61,6 +58,7 @@ public class PointsWithLabelGraphSeries e TRIANGLE, RECTANGLE, BOLUS, + CARBS, SMB, EXTENDEDBOLUS, PROFILE, @@ -233,7 +231,18 @@ public class PointsWithLabelGraphSeries e mPaint.setStyle(Paint.Style.FILL_AND_STROKE); drawArrows(points, canvas, mPaint); if (value.getLabel() != null) { - drawLabel45(endX, endY, value, canvas, scaledPxSize, scaledTextSize); + drawLabel45Right(endX, endY, value, canvas, scaledPxSize, scaledTextSize); + } + } else if (value.getShape() == Shape.CARBS) { + mPaint.setStrokeWidth(0); + Point[] points = new Point[3]; + points[0] = new Point((int) endX, (int) (endY - scaledPxSize)); + points[1] = new Point((int) (endX + scaledPxSize), (int) (endY + scaledPxSize * 0.67)); + points[2] = new Point((int) (endX - scaledPxSize), (int) (endY + scaledPxSize * 0.67)); + mPaint.setStyle(Paint.Style.FILL_AND_STROKE); + drawArrows(points, canvas, mPaint); + if (value.getLabel() != null) { + drawLabel45Left(endX, endY, value, canvas, scaledPxSize, scaledTextSize); } } else if (value.getShape() == Shape.SMB) { mPaint.setStrokeWidth(2); @@ -282,21 +291,21 @@ public class PointsWithLabelGraphSeries e mPaint.setStrokeWidth(0); canvas.drawCircle(endX, endY, scaledPxSize, mPaint); if (value.getLabel() != null) { - drawLabel45(endX, endY, value, canvas, scaledPxSize, scaledTextSize); + drawLabel45Right(endX, endY, value, canvas, scaledPxSize, scaledTextSize); } } else if (value.getShape() == Shape.ANNOUNCEMENT) { mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStrokeWidth(0); canvas.drawCircle(endX, endY, scaledPxSize, mPaint); if (value.getLabel() != null) { - drawLabel45(endX, endY, value, canvas, scaledPxSize, scaledTextSize); + drawLabel45Right(endX, endY, value, canvas, scaledPxSize, scaledTextSize); } } else if (value.getShape() == Shape.GENERAL) { mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStrokeWidth(0); canvas.drawCircle(endX, endY, scaledPxSize, mPaint); if (value.getLabel() != null) { - drawLabel45(endX, endY, value, canvas, scaledPxSize, scaledTextSize); + drawLabel45Right(endX, endY, value, canvas, scaledPxSize, scaledTextSize); } } else if (value.getShape() == Shape.EXERCISE) { mPaint.setStrokeWidth(0); @@ -380,29 +389,29 @@ public class PointsWithLabelGraphSeries e canvas.restore(); } - void drawLabel45(float endX, float endY, E value, Canvas canvas, Float scaledPxSize, Float scaledTextSize) { - if (value.getLabel().startsWith("~")) { - float px = endX; - float py = endY + scaledPxSize; - canvas.save(); - canvas.rotate(-45, px, py); - mPaint.setTextSize((float) (scaledTextSize * 0.8)); - mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); - mPaint.setFakeBoldText(true); - mPaint.setTextAlign(Paint.Align.RIGHT); - canvas.drawText(value.getLabel().substring(1), px - scaledPxSize, py, mPaint); - mPaint.setTextAlign(Paint.Align.LEFT); - canvas.restore(); - } else { - float px = endX; - float py = endY - scaledPxSize; - canvas.save(); - canvas.rotate(-45, px, py); - mPaint.setTextSize((float) (scaledTextSize * 0.8)); - mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); - mPaint.setFakeBoldText(true); - canvas.drawText(value.getLabel(), px + scaledPxSize, py, mPaint); - canvas.restore(); - } + void drawLabel45Right(float endX, float endY, E value, Canvas canvas, Float scaledPxSize, Float scaledTextSize) { + float px = endX; + float py = endY - scaledPxSize; + canvas.save(); + canvas.rotate(-45, px, py); + mPaint.setTextSize((float) (scaledTextSize * 0.8)); + mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); + mPaint.setFakeBoldText(true); + canvas.drawText(value.getLabel(), px + scaledPxSize, py, mPaint); + canvas.restore(); } -} + + void drawLabel45Left(float endX, float endY, E value, Canvas canvas, Float scaledPxSize, Float scaledTextSize) { + float px = endX; + float py = endY + scaledPxSize; + canvas.save(); + canvas.rotate(-45, px, py); + mPaint.setTextSize((float) (scaledTextSize * 0.8)); + mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); + mPaint.setFakeBoldText(true); + mPaint.setTextAlign(Paint.Align.RIGHT); + canvas.drawText(value.getLabel(), px - scaledPxSize, py, mPaint); + mPaint.setTextAlign(Paint.Align.LEFT); + canvas.restore(); + } +} diff --git a/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt b/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt index 87866d9cf3..223d8cb2e6 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/extensions/CarbsExtension.kt @@ -5,31 +5,7 @@ import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.T import org.json.JSONObject -import java.util.concurrent.TimeUnit -import kotlin.math.roundToInt - -fun Carbs.expandCarbs(): List = - mutableListOf().also { carbs -> - if (this.duration == 0L) { - carbs.add(this) - } else { - var remainingCarbs = this.amount - val ticks = T.msecs(this.duration).hours() * 4 //duration guaranteed to be integer greater zero - for (i in 0 until ticks) { - val carbTime = this.timestamp + i * 15 * 60 * 1000 - val smallCarbAmount = (1.0 * remainingCarbs / (ticks - i)).roundToInt() //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs - remainingCarbs -= smallCarbAmount.toLong() - if (smallCarbAmount > 0) - carbs.add(Carbs( - timestamp = carbTime, - amount = smallCarbAmount.toDouble(), - duration = 0 - )) - } - } - } fun Carbs.toJson(): JSONObject = JSONObject() diff --git a/database/schemas/info.nightscout.androidaps.database.AppDatabase/9.json b/database/schemas/info.nightscout.androidaps.database.AppDatabase/9.json new file mode 100644 index 0000000000..ed66e112d9 --- /dev/null +++ b/database/schemas/info.nightscout.androidaps.database.AppDatabase/9.json @@ -0,0 +1,2800 @@ +{ + "formatVersion": 1, + "database": { + "version": 9, + "identityHash": "dab6024e846ee68708e8cfc047c39662", + "entities": [ + { + "tableName": "apsResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `algorithm` TEXT NOT NULL, `glucoseStatusJson` TEXT NOT NULL, `currentTempJson` TEXT NOT NULL, `iobDataJson` TEXT NOT NULL, `profileJson` TEXT NOT NULL, `autosensDataJson` TEXT, `mealDataJson` TEXT NOT NULL, `isMicroBolusAllowed` INTEGER, `resultJson` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "algorithm", + "columnName": "algorithm", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseStatusJson", + "columnName": "glucoseStatusJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentTempJson", + "columnName": "currentTempJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "iobDataJson", + "columnName": "iobDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profileJson", + "columnName": "profileJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "autosensDataJson", + "columnName": "autosensDataJson", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mealDataJson", + "columnName": "mealDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isMicroBolusAllowed", + "columnName": "isMicroBolusAllowed", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "resultJson", + "columnName": "resultJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_apsResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_apsResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "apsResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "boluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `amount` REAL NOT NULL, `type` TEXT NOT NULL, `isBasalInsulin` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT, `insulinEndTime` INTEGER, `peak` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isBasalInsulin", + "columnName": "isBasalInsulin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_boluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_boluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "bolusCalculatorResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `targetBGLow` REAL NOT NULL, `targetBGHigh` REAL NOT NULL, `isf` REAL NOT NULL, `ic` REAL NOT NULL, `bolusIOB` REAL NOT NULL, `wasBolusIOBUsed` INTEGER NOT NULL, `basalIOB` REAL NOT NULL, `wasBasalIOBUsed` INTEGER NOT NULL, `glucoseValue` REAL NOT NULL, `wasGlucoseUsed` INTEGER NOT NULL, `glucoseDifference` REAL NOT NULL, `glucoseInsulin` REAL NOT NULL, `glucoseTrend` REAL NOT NULL, `wasTrendUsed` INTEGER NOT NULL, `trendInsulin` REAL NOT NULL, `cob` REAL NOT NULL, `wasCOBUsed` INTEGER NOT NULL, `cobInsulin` REAL NOT NULL, `carbs` REAL NOT NULL, `wereCarbsUsed` INTEGER NOT NULL, `carbsInsulin` REAL NOT NULL, `otherCorrection` REAL NOT NULL, `wasSuperbolusUsed` INTEGER NOT NULL, `superbolusInsulin` REAL NOT NULL, `wasTempTargetUsed` INTEGER NOT NULL, `totalInsulin` REAL NOT NULL, `percentageCorrection` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `note` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `bolusCalculatorResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetBGLow", + "columnName": "targetBGLow", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "targetBGHigh", + "columnName": "targetBGHigh", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isf", + "columnName": "isf", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "ic", + "columnName": "ic", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bolusIOB", + "columnName": "bolusIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBolusIOBUsed", + "columnName": "wasBolusIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalIOB", + "columnName": "basalIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBasalIOBUsed", + "columnName": "wasBasalIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseValue", + "columnName": "glucoseValue", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasGlucoseUsed", + "columnName": "wasGlucoseUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseDifference", + "columnName": "glucoseDifference", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseInsulin", + "columnName": "glucoseInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseTrend", + "columnName": "glucoseTrend", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTrendUsed", + "columnName": "wasTrendUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "trendInsulin", + "columnName": "trendInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "cob", + "columnName": "cob", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasCOBUsed", + "columnName": "wasCOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cobInsulin", + "columnName": "cobInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wereCarbsUsed", + "columnName": "wereCarbsUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "carbsInsulin", + "columnName": "carbsInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "otherCorrection", + "columnName": "otherCorrection", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasSuperbolusUsed", + "columnName": "wasSuperbolusUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "superbolusInsulin", + "columnName": "superbolusInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTempTargetUsed", + "columnName": "wasTempTargetUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalInsulin", + "columnName": "totalInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "percentageCorrection", + "columnName": "percentageCorrection", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_bolusCalculatorResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_bolusCalculatorResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "bolusCalculatorResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "carbs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `carbs`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_carbs_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_carbs_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "carbs", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "effectiveProfileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `effectiveProfileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_effectiveProfileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_effectiveProfileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "effectiveProfileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "extendedBoluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `isEmulatingTempBasal` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isEmulatingTempBasal", + "columnName": "isEmulatingTempBasal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_extendedBoluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_extendedBoluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "extendedBoluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "glucoseValues", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `raw` REAL, `value` REAL NOT NULL, `trendArrow` TEXT NOT NULL, `noise` REAL, `sourceSensor` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `glucoseValues`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "raw", + "columnName": "raw", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "trendArrow", + "columnName": "trendArrow", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "noise", + "columnName": "noise", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "sourceSensor", + "columnName": "sourceSensor", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_glucoseValues_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_glucoseValues_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "glucoseValues", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "profileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `timeshift` INTEGER NOT NULL, `percentage` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `profileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isfBlocks", + "columnName": "isfBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "icBlocks", + "columnName": "icBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetBlocks", + "columnName": "targetBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeshift", + "columnName": "timeshift", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percentage", + "columnName": "percentage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_profileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_profileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "profileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryBasals", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `type` TEXT NOT NULL, `isAbsolute` INTEGER NOT NULL, `rate` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isAbsolute", + "columnName": "isAbsolute", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rate", + "columnName": "rate", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryBasals_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryBasals_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryBasals", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryTargets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `reason` TEXT NOT NULL, `highTarget` REAL NOT NULL, `lowTarget` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryTargets`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reason", + "columnName": "reason", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highTarget", + "columnName": "highTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "lowTarget", + "columnName": "lowTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryTargets_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryTargets_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryTargets", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "therapyEvents", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `type` TEXT NOT NULL, `note` TEXT, `enteredBy` TEXT, `glucose` REAL, `glucoseType` TEXT, `glucoseUnit` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `therapyEvents`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "enteredBy", + "columnName": "enteredBy", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucose", + "columnName": "glucose", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "glucoseType", + "columnName": "glucoseType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_therapyEvents_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_therapyEvents_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "therapyEvents", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "totalDailyDoses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalAmount` REAL, `bolusAmount` REAL, `totalAmount` REAL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `totalDailyDoses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalAmount", + "columnName": "basalAmount", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "bolusAmount", + "columnName": "bolusAmount", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "totalAmount", + "columnName": "totalAmount", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_totalDailyDoses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_totalDailyDoses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "totalDailyDoses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "apsResultLinks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `apsResultId` INTEGER NOT NULL, `smbId` INTEGER, `tbrId` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`apsResultId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`smbId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`tbrId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `apsResultLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "apsResultId", + "columnName": "apsResultId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "smbId", + "columnName": "smbId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "tbrId", + "columnName": "tbrId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_apsResultLinks_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_apsResultLinks_apsResultId", + "unique": false, + "columnNames": [ + "apsResultId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_apsResultId` ON `${TABLE_NAME}` (`apsResultId`)" + }, + { + "name": "index_apsResultLinks_smbId", + "unique": false, + "columnNames": [ + "smbId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_smbId` ON `${TABLE_NAME}` (`smbId`)" + }, + { + "name": "index_apsResultLinks_tbrId", + "unique": false, + "columnNames": [ + "tbrId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_tbrId` ON `${TABLE_NAME}` (`tbrId`)" + } + ], + "foreignKeys": [ + { + "table": "apsResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "apsResultId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "smbId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "temporaryBasals", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "tbrId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "apsResultLinks", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "multiwaveBolusLinks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `bolusId` INTEGER NOT NULL, `extendedBolusId` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`bolusId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`extendedBolusId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `multiwaveBolusLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "bolusId", + "columnName": "bolusId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "extendedBolusId", + "columnName": "extendedBolusId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_multiwaveBolusLinks_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_multiwaveBolusLinks_bolusId", + "unique": false, + "columnNames": [ + "bolusId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_bolusId` ON `${TABLE_NAME}` (`bolusId`)" + }, + { + "name": "index_multiwaveBolusLinks_extendedBolusId", + "unique": false, + "columnNames": [ + "extendedBolusId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_extendedBolusId` ON `${TABLE_NAME}` (`extendedBolusId`)" + } + ], + "foreignKeys": [ + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "bolusId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "extendedBoluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "extendedBolusId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "multiwaveBolusLinks", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "preferenceChanges", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `key` TEXT NOT NULL, `value` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "versionChanges", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `versionCode` INTEGER NOT NULL, `versionName` TEXT NOT NULL, `gitRemote` TEXT, `commitHash` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "versionCode", + "columnName": "versionCode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "versionName", + "columnName": "versionName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gitRemote", + "columnName": "gitRemote", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "commitHash", + "columnName": "commitHash", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "userEntry", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `action` TEXT NOT NULL, `s` TEXT NOT NULL, `values` TEXT NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "action", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "s", + "columnName": "s", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "values", + "columnName": "values", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "foods", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `name` TEXT NOT NULL, `category` TEXT, `subCategory` TEXT, `portion` REAL NOT NULL, `carbs` INTEGER NOT NULL, `fat` INTEGER, `protein` INTEGER, `energy` INTEGER, `unit` TEXT NOT NULL, `gi` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `foods`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subCategory", + "columnName": "subCategory", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "portion", + "columnName": "portion", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fat", + "columnName": "fat", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "protein", + "columnName": "protein", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "energy", + "columnName": "energy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "unit", + "columnName": "unit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gi", + "columnName": "gi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_foods_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + } + ], + "foreignKeys": [ + { + "table": "foods", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'dab6024e846ee68708e8cfc047c39662')" + ] + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt index 5c0d0de0d2..a467cf1ecd 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -12,6 +12,7 @@ import io.reactivex.subjects.PublishSubject import java.util.concurrent.Callable import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.roundToInt @Singleton open class AppRepository @Inject internal constructor( @@ -310,6 +311,27 @@ open class AppRepository @Inject internal constructor( database.bolusDao.deleteAllEntries() // CARBS + + val timeBackForExpand = 8 * 60 * 60 * 1000 + private fun expandCarbs(carbs: Carbs): List = + if (carbs.duration == 0L) { + listOf(carbs) + } else { + var remainingCarbs = carbs.amount + val ticks = (carbs.duration / 1000 / 60 / 15).coerceAtLeast(1L) + (0 until ticks).map { + val carbTime = carbs.timestamp + it * 15 * 60 * 1000 + val smallCarbAmount = (1.0 * remainingCarbs / (ticks - it)).roundToInt() //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs + remainingCarbs -= smallCarbAmount.toLong() + Carbs(timestamp = carbTime, amount = smallCarbAmount.toDouble(), duration = 0) + }.filter { it.amount != 0.0 } + } + + private fun Single>.expand() = this.map { it.map(::expandCarbs).flatten() } + private fun Single>.filterOutExtended() = this.map { it.filter { c -> c.duration == 0L } } + private fun Single>.fromTo(from: Long, to: Long) = this.map { it.filter { c -> c.timestamp in from..to } } + private fun Single>.sort() = this.map { it.sortedBy { c -> c.timestamp } } + /* * returns a Pair of the next entity to sync and the ID of the "update". * The update id might either be the entry id itself if it is a new entry - or the id @@ -339,6 +361,11 @@ open class AppRepository @Inject internal constructor( fun getLastCarbsRecord(): Carbs? = database.carbsDao.getLastCarbsRecord() + fun getLastCarbsRecordWrapped(): Single> = + database.carbsDao.getLastCarbsRecordMaybe() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + fun getOldestCarbsRecord(): Carbs? = database.carbsDao.getOldestCarbsRecord() @@ -347,18 +374,35 @@ open class AppRepository @Inject internal constructor( .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getCarbsDataFromTimeExpanded(timestamp: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsFromTime(timestamp - timeBackForExpand) + .expand() + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + fun getCarbsDataFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = database.carbsDao.getCarbsFromTimeToTime(from, to) .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) - fun getCarbsIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single> = - database.carbsDao.getCarbsIncludingInvalidFromTime(timestamp) + fun getCarbsDataFromTimeToTimeExpanded(from: Long, to: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsFromTimeToTime(from - timeBackForExpand, to) + .expand() + .fromTo(from, to) + .sort() .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) - fun getCarbsIncludingInvalidFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = - database.carbsDao.getCarbsIncludingInvalidFromTimeToTime(from, to) + fun getCarbsIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsIncludingInvalidFromTime(timestamp - timeBackForExpand) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + fun getCarbsIncludingInvalidFromTimeToTimeExpanded(from: Long, to: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsIncludingInvalidFromTimeToTime(from - timeBackForExpand, to) + .expand() + .fromTo(from, to) + .sort() .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt index be8bf7e368..e85d68885a 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt @@ -26,6 +26,9 @@ internal interface CarbsDao : TraceableDao { @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id DESC LIMIT 1") fun getLastCarbsRecord(): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id DESC LIMIT 1") + fun getLastCarbsRecordMaybe(): Maybe + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") fun getOldestCarbsRecord(): Carbs?