From 18e19ae4c901a342f6d40fb57dd565ec612d6ec5 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Thu, 29 Apr 2021 14:47:08 +0200 Subject: [PATCH 01/16] Fix: Insight capabilities; fix reference to basal/bolus. --- .../nightscout/androidaps/plugins/pump/common/defs/PumpType.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index d372c84c6b..147ce98801 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -89,7 +89,7 @@ enum class PumpType { baseBasalMinValue = 0.02, baseBasalMaxValue = null, baseBasalStep = 0.01, - baseBasalSpecialSteps = DoseStepSize.InsightBolus, + baseBasalSpecialSteps = DoseStepSize.InsightBasal, pumpCapability = PumpCapability.InsightCapabilities), ACCU_CHEK_SOLO(description = "Accu-Chek Solo", manufacturer = ManufacturerType.Roche, From 970aebc6db8655937963d89b24d813dc45cea465 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Thu, 29 Apr 2021 14:48:22 +0200 Subject: [PATCH 02/16] Refactor: rename PumpDescription.setPumpDescription to pd.fillFor(). --- .../androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt | 2 +- .../nightscout/androidaps/plugins/pump/combo/ComboPlugin.java | 2 +- .../info/nightscout/androidaps/interfaces/PumpDescription.kt | 4 ++-- .../androidaps/plugins/configBuilder/RunningConfiguration.kt | 2 +- .../nightscout/androidaps/interfaces/PumpDescriptionTest.kt | 2 +- .../nightscout/androidaps/plugins/aps/loop/APSResultTest.kt | 4 ++-- .../nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt | 2 +- .../info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java | 2 +- .../java/info/nightscout/androidaps/danar/DanaRPlugin.java | 2 +- .../androidaps/plugins/pump/insight/LocalInsightPlugin.java | 2 +- .../androidaps/plugins/pump/common/PumpPluginAbstract.java | 4 ++-- 11 files changed, 14 insertions(+), 14 deletions(-) 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 b595da0409..afc7f59b97 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 @@ -400,7 +400,7 @@ open class VirtualPumpPlugin @Inject constructor( aapsLogger.debug(LTag.PUMP, "Pump in configuration: $pumpType, PumpType object: $pumpTypeNew") if (this.pumpType == pumpTypeNew) return aapsLogger.debug(LTag.PUMP, "New pump configuration found ($pumpTypeNew), changing from previous (${this.pumpType})") - pumpDescription.setPumpDescription(pumpTypeNew) + pumpDescription.fillFor(pumpTypeNew) this.pumpType = pumpTypeNew } 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 1f17b035cc..b98ac52f15 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 @@ -160,7 +160,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { this.pumpSync = pumpSync; this.dateUtil = dateUtil; - pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_COMBO); + pumpDescription.fillFor(PumpType.ACCU_CHEK_COMBO); } @Override protected void onStart() { diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.kt index 0aec8d7484..136e899a2c 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType class PumpDescription() { constructor(pumpType: PumpType) : this() { - setPumpDescription(pumpType) + fillFor(pumpType) } var pumpType = PumpType.GENERIC_AAPS @@ -69,7 +69,7 @@ class PumpDescription() { hasCustomUnreachableAlertCheck = false } - fun setPumpDescription(pumpType: PumpType) { + fun fillFor(pumpType: PumpType) { resetSettings() this.pumpType = pumpType val pumpCapability = pumpType.pumpCapability ?: return diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt index cf3b151d4d..7b5cb9c382 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt @@ -82,7 +82,7 @@ class RunningConfiguration @Inject constructor( if (configuration.has("pump")) { val pumpType = JsonHelper.safeGetString(configuration, "pump", PumpType.GENERIC_AAPS.description) sp.putString(R.string.key_virtualpump_type, pumpType) - activePlugin.activePump.pumpDescription.setPumpDescription(PumpType.getByDescription(pumpType)) + activePlugin.activePump.pumpDescription.fillFor(PumpType.getByDescription(pumpType)) aapsLogger.debug(LTag.CORE, "Changing pump type to $pumpType") } diff --git a/core/src/test/java/info/nightscout/androidaps/interfaces/PumpDescriptionTest.kt b/core/src/test/java/info/nightscout/androidaps/interfaces/PumpDescriptionTest.kt index 392c7f9791..397619d21a 100644 --- a/core/src/test/java/info/nightscout/androidaps/interfaces/PumpDescriptionTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/interfaces/PumpDescriptionTest.kt @@ -10,7 +10,7 @@ class PumpDescriptionTest { @Test fun setPumpDescription() { val pumpDescription = PumpDescription() - pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_COMBO) + pumpDescription.fillFor(PumpType.ACCU_CHEK_COMBO) Assert.assertEquals(pumpDescription.bolusStep, PumpType.ACCU_CHEK_COMBO.bolusSize, 0.1) Assert.assertEquals(pumpDescription.basalMinimumRate, PumpType.ACCU_CHEK_COMBO.baseBasalStep, 0.1) Assert.assertEquals(pumpDescription.basalStep, PumpType.ACCU_CHEK_COMBO.baseBasalStep, 0.1) diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt index 40a6cd3c20..aa3b7944b3 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt @@ -51,7 +51,7 @@ class APSResultTest : TestBaseWithProfile() { // BASAL RATE IN TEST PROFILE IS 1U/h // **** PERCENT pump **** - testPumpPlugin.pumpDescription.setPumpDescription(PumpType.CELLNOVO) // % based + testPumpPlugin.pumpDescription.fillFor(PumpType.CELLNOVO) // % based apsResult.usePercent(true) // closed loop mode return original request @@ -109,7 +109,7 @@ class APSResultTest : TestBaseWithProfile() { Assert.assertEquals(true, apsResult.isChangeRequested) // **** ABSOLUTE pump **** - testPumpPlugin.pumpDescription.setPumpDescription(PumpType.MEDTRONIC_515_715) // U/h based + testPumpPlugin.pumpDescription.fillFor(PumpType.MEDTRONIC_515_715) // U/h based apsResult.usePercent(false) // open loop diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt index 0f9669df39..16616efe46 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt @@ -60,7 +60,7 @@ class DanaRKoreanPlugin @Inject constructor( init { pluginDescription.description(R.string.description_pump_dana_r_korean) useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false) - pumpDescription.setPumpDescription(PumpType.DANA_R_KOREAN) + pumpDescription.fillFor(PumpType.DANA_R_KOREAN) } override fun onStart() { 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 34309dd182..86685217ee 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -85,7 +85,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { getPluginDescription().description(R.string.description_pump_dana_r_v2); useExtendedBoluses = false; - pumpDescription.setPumpDescription(PumpType.DANA_RV2); + pumpDescription.fillFor(PumpType.DANA_RV2); } @Override 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 6aaa1f2bf2..17f831893a 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -74,7 +74,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { this.fabricPrivacy = fabricPrivacy; useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false); - pumpDescription.setPumpDescription(PumpType.DANA_R); + pumpDescription.fillFor(PumpType.DANA_R); } @Override 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 2ba8ced252..c211d2380e 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 @@ -242,7 +242,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.pumpSync = pumpSync; pumpDescription = new PumpDescription(); - pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); + pumpDescription.fillFor(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); } public TBROverNotificationBlock getTBROverNotificationBlock() { 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 47077d5135..d785153d49 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 @@ -99,7 +99,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements Pump, this.sp = sp; this.commandQueue = commandQueue; - pumpDescription.setPumpDescription(pumpType); + pumpDescription.fillFor(pumpType); this.pumpType = pumpType; this.dateUtil = dateUtil; this.aapsSchedulers = aapsSchedulers; @@ -457,7 +457,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements Pump, public void setPumpType(PumpType pumpType) { this.pumpType = pumpType; - this.pumpDescription.setPumpDescription(pumpType); + this.pumpDescription.fillFor(pumpType); } From c52526cf6fb66823dc8c667071697157d3f14eac Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Thu, 29 Apr 2021 14:49:55 +0200 Subject: [PATCH 03/16] Fix: Insight; change references to correct Pumpdescription. --- .../plugins/pump/insight/LocalInsightPlugin.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 c211d2380e..1bd72c2245 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 @@ -606,7 +606,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); detailedBolusInfo.setBolusTimestamp(insightBolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(insightBolusID.id); if (detailedBolusInfo.carbs > 0 && detailedBolusInfo.carbTime != 0) { @@ -1388,7 +1388,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.timestamp = bolusID.timestamp; - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(bolusID.id); detailedBolusInfo.insulin = event.getImmediateAmount(); @@ -1423,7 +1423,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(bolusID.id); detailedBolusInfo.insulin = event.getImmediateAmount(); @@ -1551,7 +1551,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void logNote(long date, String note) { - pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber()); + pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH, serialNumber()); } private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, int relativeMinute, int relativeSecond) { @@ -1568,7 +1568,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) { - pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber()); + pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH, serialNumber()); } @NonNull @Override From 884eb497bde15cfb79f336d2920f193976a06b1e Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Thu, 29 Apr 2021 14:50:41 +0200 Subject: [PATCH 04/16] Refactor: Rename ACCU_CHEK_INSIGHT -> ACCU_CHEK_VIRTUAL. --- .../info/nightscout/androidaps/activities/TDDStatsActivity.kt | 2 +- .../androidaps/plugins/pump/common/defs/PumpType.kt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt index 353f808935..34fdbfba62 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt @@ -422,7 +422,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { private fun isOldData(historyList: List): Boolean { val type = activePlugin.activePump.pumpDescription.pumpType - val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT + val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT_VIRTUAL val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index 147ce98801..4f73ef0d6a 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -64,7 +64,7 @@ enum class PumpType { baseBasalStep = 0.1, baseBasalSpecialSteps = null, pumpCapability = PumpCapability.VirtualPumpCapabilities), - ACCU_CHEK_INSIGHT(description = "Accu-Chek Insight", + ACCU_CHEK_INSIGHT_VIRTUAL(description = "Accu-Chek Insight", manufacturer = ManufacturerType.Roche, model = "Insight", bolusSize = 0.05, @@ -418,7 +418,7 @@ enum class PumpType { CELLNOVO -> InterfaceIDs.PumpType.CELLNOVO ACCU_CHEK_COMBO -> InterfaceIDs.PumpType.ACCU_CHEK_COMBO ACCU_CHEK_SPIRIT -> InterfaceIDs.PumpType.ACCU_CHEK_SPIRIT - ACCU_CHEK_INSIGHT -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT + ACCU_CHEK_INSIGHT_VIRTUAL -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT ACCU_CHEK_INSIGHT_BLUETOOTH -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH ACCU_CHEK_SOLO -> InterfaceIDs.PumpType.ACCU_CHEK_SOLO ANIMAS_VIBE -> InterfaceIDs.PumpType.ANIMAS_VIBE From c62d92e984fba73a544e13cf063af1bf51143b30 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Thu, 29 Apr 2021 14:58:58 +0200 Subject: [PATCH 05/16] Refactor: Remove (now) superflous BLUETOOTH from ACCU_CHEK_INSIGHT_BLUETHOOTH. This aligns with the naming of other pumps and BLUETOOTH doesn't provide much information. --- .../plugins/pump/common/defs/PumpType.kt | 8 ++++---- .../plugins/pump/insight/LocalInsightPlugin.java | 14 +++++++------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index 4f73ef0d6a..387386f927 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -77,7 +77,7 @@ enum class PumpType { baseBasalStep = 0.01, baseBasalSpecialSteps = null, pumpCapability = PumpCapability.InsightCapabilities), - ACCU_CHEK_INSIGHT_BLUETOOTH(description = "Accu-Chek Insight", + ACCU_CHEK_INSIGHT(description = "Accu-Chek Insight", manufacturer = ManufacturerType.Roche, model = "Insight", bolusSize = 0.01, @@ -418,9 +418,9 @@ enum class PumpType { CELLNOVO -> InterfaceIDs.PumpType.CELLNOVO ACCU_CHEK_COMBO -> InterfaceIDs.PumpType.ACCU_CHEK_COMBO ACCU_CHEK_SPIRIT -> InterfaceIDs.PumpType.ACCU_CHEK_SPIRIT - ACCU_CHEK_INSIGHT_VIRTUAL -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT - ACCU_CHEK_INSIGHT_BLUETOOTH -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH - ACCU_CHEK_SOLO -> InterfaceIDs.PumpType.ACCU_CHEK_SOLO + ACCU_CHEK_INSIGHT_VIRTUAL -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT + ACCU_CHEK_INSIGHT -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH + ACCU_CHEK_SOLO -> InterfaceIDs.PumpType.ACCU_CHEK_SOLO ANIMAS_VIBE -> InterfaceIDs.PumpType.ANIMAS_VIBE ANIMAS_PING -> InterfaceIDs.PumpType.ANIMAS_PING DANA_R -> InterfaceIDs.PumpType.DANA_R 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 1bd72c2245..f9a333e39a 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 @@ -242,7 +242,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.pumpSync = pumpSync; pumpDescription = new PumpDescription(); - pumpDescription.fillFor(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); + pumpDescription.fillFor(PumpType.ACCU_CHEK_INSIGHT); } public TBROverNotificationBlock getTBROverNotificationBlock() { @@ -606,7 +606,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); detailedBolusInfo.setBolusTimestamp(insightBolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(insightBolusID.id); if (detailedBolusInfo.carbs > 0 && detailedBolusInfo.carbTime != 0) { @@ -1027,7 +1027,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public PumpType model() { - return PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH; + return PumpType.ACCU_CHEK_INSIGHT; } @NonNull @Override @@ -1388,7 +1388,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.timestamp = bolusID.timestamp; - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(bolusID.id); detailedBolusInfo.insulin = event.getImmediateAmount(); @@ -1423,7 +1423,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(bolusID.id); detailedBolusInfo.insulin = event.getImmediateAmount(); @@ -1551,7 +1551,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void logNote(long date, String note) { - pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH, serialNumber()); + pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber()); } private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, int relativeMinute, int relativeSecond) { @@ -1568,7 +1568,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) { - pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH, serialNumber()); + pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber()); } @NonNull @Override From dc2d64ceb7c7a086e5e82c3c96301ae2a0d141c6 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Sat, 1 May 2021 00:22:45 +0200 Subject: [PATCH 06/16] Fix: turn APSResult.bolusRequested into a function. Previously this var was set while parsing determine-basal output, setting it to true if determine-basal provided a value which was assigned to var smb. However, the variable smb is changed when constraints are applied, making the val bolusRequested invalid afterwards. Hence, dynamically evaluate the smb var by turning bolusRequested into a function. --- .../nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt | 4 ++-- .../plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt | 1 - .../plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt | 1 - .../nightscout/androidaps/plugins/aps/loop/APSResult.kt | 8 ++++---- 4 files changed, 6 insertions(+), 8 deletions(-) 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 6c7e8a3ac5..4795283ec1 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 @@ -403,7 +403,7 @@ open class LoopPlugin @Inject constructor( val waiting = PumpEnactResult(injector) waiting.queued = true if (resultAfterConstraints.tempBasalRequested) lastRun.tbrSetByPump = waiting - if (resultAfterConstraints.bolusRequested) lastRun.smbSetByPump = waiting + if (resultAfterConstraints.bolusRequested()) lastRun.smbSetByPump = waiting rxBus.send(EventLoopUpdateGui()) fabricPrivacy.logCustom("APSRequest") applyTBRRequest(resultAfterConstraints, profile, object : Callback() { @@ -600,7 +600,7 @@ open class LoopPlugin @Inject constructor( } private fun applySMBRequest(request: APSResult, callback: Callback?) { - if (!request.bolusRequested) { + if (!request.bolusRequested()) { return } val pump = activePlugin.activePump 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 6f66dd235f..5411bd2fa3 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 @@ -40,7 +40,6 @@ class DetermineBasalResultAMA private constructor(injector: HasAndroidInjector) tempBasalRequested = false } } - bolusRequested = false } override fun newAndClone(injector: HasAndroidInjector): DetermineBasalResultAMA { 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 996621b8db..aa5dff4b38 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 @@ -35,7 +35,6 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector) duration = -1 } if (result.has("units")) { - bolusRequested = true smb = result.getDouble("units") } else { smb = 0.0 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 989ecdcdd0..eb110e9391 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 @@ -48,7 +48,6 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { var usePercent = false var duration = 0 var tempBasalRequested = false - var bolusRequested = false var iob: IobTotal? = null var json: JSONObject? = JSONObject() var hasPredictions = false @@ -161,7 +160,6 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { newResult.rate = rate newResult.duration = duration newResult.tempBasalRequested = tempBasalRequested - newResult.bolusRequested = bolusRequested newResult.iob = iob newResult.json = JSONObject(json.toString()) newResult.hasPredictions = hasPredictions @@ -309,11 +307,11 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { // closed loop mode: handle change at driver level if (closedLoopEnabled.value()) { aapsLogger.debug(LTag.APS, "DEFAULT: Closed mode") - return tempBasalRequested || bolusRequested + return tempBasalRequested || bolusRequested() } // open loop mode: try to limit request - if (!tempBasalRequested && !bolusRequested) { + if (!tempBasalRequested && !bolusRequested()) { aapsLogger.debug(LTag.APS, "FALSE: No request") return false } @@ -399,4 +397,6 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { } } } + + fun bolusRequested(): Boolean = smb > 0.0 } \ No newline at end of file From 5747f972014937eeb3d0fff8ecbeffac7440f551 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 3 May 2021 09:33:14 +0200 Subject: [PATCH 07/16] DanaHistoryDatabase --- .../androidaps/db/DatabaseHelper.java | 466 ------------------ .../androidaps/db/DatabaseHelperProvider.java | 28 +- .../dependencyInjection/AppComponent.kt | 2 + .../dependencyInjection/AppModule.kt | 5 +- .../maintenance/MaintenanceFragment.kt | 6 +- .../general/nsclient/NSClientFragment.kt | 17 - .../plugins/general/nsclient/UploadQueue.java | 56 +-- .../general/openhumans/OpenHumansUploader.kt | 90 ++-- .../general/overview/graphData/GraphData.kt | 6 +- .../plugins/treatments/TreatmentService.java | 15 - .../main/res/layout/ns_client_fragment.xml | 29 -- .../androidaps/db/DanaRHistoryRecord.java | 77 --- .../androidaps/di/CoreDataClassesModule.kt | 6 - .../interfaces/DatabaseHelperInterface.kt | 3 - .../androidaps/interfaces/IobCobCalculator.kt | 2 +- .../androidaps/interfaces/ProfileStore.kt | 4 +- .../interfaces/UploadQueueAdminInterface.kt | 6 - .../interfaces/UploadQueueInterface.java | 4 - .../plugins/general/nsclient/NSUpload.java | 52 -- dana/build.gradle | 6 + .../dana/activities/DanaHistoryActivity.kt | 190 ++++--- .../dana/database/DanaHistoryDatabase.kt | 33 ++ .../dana/database/DanaHistoryRecord.kt | 19 + .../dana/database/DanaHistoryRecordDao.kt | 17 + .../androidaps/dana/di/DanaHistoryModule.kt | 21 + .../androidaps/dana/di/DanaModule.kt | 5 + .../res/layout/danar_history_activity.xml | 112 +++-- .../main/res/layout/danar_history_item.xml | 152 +++--- .../androidaps/danar/comm/MessageBase.java | 3 +- .../androidaps/danar/comm/MsgHistoryAll.kt | 77 +-- .../danars/comm/DanaRS_Packet_History_.kt | 90 ++-- .../comm/DanaRSPacketHistoryAlarmTest.kt | 16 +- .../pump/insight/LocalInsightPlugin.java | 10 +- 33 files changed, 506 insertions(+), 1119 deletions(-) delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/DanaRHistoryRecord.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueAdminInterface.kt create mode 100644 dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryDatabase.kt create mode 100644 dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecord.kt create mode 100644 dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecordDao.kt create mode 100644 dana/src/main/java/info/nightscout/androidaps/dana/di/DanaHistoryModule.kt diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 1520dd0bbd..c241d65732 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -4,8 +4,6 @@ import android.content.Context; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; -import androidx.annotation.Nullable; - import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.CloseableIterator; import com.j256.ormlite.dao.Dao; @@ -20,9 +18,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; import javax.inject.Inject; @@ -76,10 +71,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { aapsLogger.info(LTag.DATABASE, "onCreate"); - TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DbRequest.class); - TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); - TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); @@ -103,10 +95,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (oldVersion < 7) { aapsLogger.info(LTag.DATABASE, "onUpgrade"); - TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); TableUtils.dropTable(connectionSource, DbRequest.class, true); - TableUtils.dropTable(connectionSource, TemporaryBasal.class, true); - TableUtils.dropTable(connectionSource, ExtendedBolus.class, true); onCreate(database, connectionSource); } else if (oldVersion < 10) { TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); @@ -149,15 +138,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void resetDatabases() { try { - TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); TableUtils.dropTable(connectionSource, DbRequest.class, true); - TableUtils.dropTable(connectionSource, TemporaryBasal.class, true); - TableUtils.dropTable(connectionSource, ExtendedBolus.class, true); TableUtils.dropTable(connectionSource, OmnipodHistoryRecord.class, true); - TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DbRequest.class); - TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); - TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); updateEarliestDataChange(0); } catch (SQLException e) { @@ -177,22 +160,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // ------------------ getDao ------------------------------------------- - private Dao getDaoDanaRHistory() throws SQLException { - return getDao(DanaRHistoryRecord.class); - } - private Dao getDaoDbRequest() throws SQLException { return getDao(DbRequest.class); } - private Dao getDaoTemporaryBasal() throws SQLException { - return getDao(TemporaryBasal.class); - } - - private Dao getDaoExtendedBolus() throws SQLException { - return getDao(ExtendedBolus.class); - } - private Dao getDaoInsightPumpID() throws SQLException { return getDao(InsightPumpID.class); } @@ -293,433 +264,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } - // ----------------- DanaRHistory handling -------------------- - - public void createOrUpdate(DanaRHistoryRecord record) { - try { - getDaoDanaRHistory().createOrUpdate(record); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public List getDanaRHistoryRecordsByType(byte type) { - List historyList; - try { - QueryBuilder queryBuilder = getDaoDanaRHistory().queryBuilder(); - queryBuilder.orderBy("recordDate", false); - Where where = queryBuilder.where(); - where.eq("recordCode", type); - queryBuilder.limit(200L); - PreparedQuery preparedQuery = queryBuilder.prepare(); - historyList = getDaoDanaRHistory().query(preparedQuery); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - historyList = new ArrayList<>(); - } - return historyList; - } - - // ------------ TemporaryBasal handling --------------- - - //return true if new record was created - public boolean createOrUpdate(TemporaryBasal tempBasal) { - try { - TemporaryBasal old; - tempBasal.date = roundDateToSec(tempBasal.date); - - if (tempBasal.source == Source.PUMP) { - // check for changed from pump change in NS - QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("pumpId", tempBasal.pumpId); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = getDaoTemporaryBasal().query(preparedQuery); - if (trList.size() > 0) { - // do nothing, pump history record cannot be changed - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); - return false; - } - - // search by date (in case its standard record that has become pump record) - QueryBuilder queryBuilder2 = getDaoTemporaryBasal().queryBuilder(); - Where where2 = queryBuilder2.where(); - where2.eq("date", tempBasal.date); - PreparedQuery preparedQuery2 = queryBuilder2.prepare(); - List trList2 = getDaoTemporaryBasal().query(preparedQuery2); - - if (trList2.size() > 0) { - old = trList2.get(0); - - old.copyFromPump(tempBasal); - old.source = Source.PUMP; - - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); - - getDaoTemporaryBasal().update(old); - openHumansUploader.enqueueTemporaryBasal(old); - - updateEarliestDataChange(tempBasal.date); -// scheduleTemporaryBasalChange(); - - return false; - } - - getDaoTemporaryBasal().create(tempBasal); - openHumansUploader.enqueueTemporaryBasal(tempBasal); - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); - updateEarliestDataChange(tempBasal.date); -// scheduleTemporaryBasalChange(); - return true; - } - if (tempBasal.source == Source.NIGHTSCOUT) { - old = getDaoTemporaryBasal().queryForId(tempBasal.date); - if (old != null) { - if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute" - // so far ignore, do not convert back because it may not be accurate - return false; - } - if (!old.isEqual(tempBasal)) { - long oldDate = old.date; - getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too - old.copyFrom(tempBasal); - getDaoTemporaryBasal().create(old); - openHumansUploader.enqueueTemporaryBasal(old); - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); - updateEarliestDataChange(oldDate); - updateEarliestDataChange(old.date); -// scheduleTemporaryBasalChange(); - return true; - } - return false; - } - // find by NS _id - if (tempBasal._id != null) { - QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", tempBasal._id); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = getDaoTemporaryBasal().query(preparedQuery); - if (trList.size() > 0) { - old = trList.get(0); - if (!old.isEqual(tempBasal)) { - long oldDate = old.date; - getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too - old.copyFrom(tempBasal); - getDaoTemporaryBasal().create(old); - openHumansUploader.enqueueTemporaryBasal(old); - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); - updateEarliestDataChange(oldDate); - updateEarliestDataChange(old.date); -// scheduleTemporaryBasalChange(); - return true; - } - } - } - getDaoTemporaryBasal().create(tempBasal); - openHumansUploader.enqueueTemporaryBasal(tempBasal); - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); - updateEarliestDataChange(tempBasal.date); -// scheduleTemporaryBasalChange(); - return true; - } - if (tempBasal.source == Source.USER) { - getDaoTemporaryBasal().create(tempBasal); - openHumansUploader.enqueueTemporaryBasal(tempBasal); - aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); - updateEarliestDataChange(tempBasal.date); -// scheduleTemporaryBasalChange(); - return true; - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return false; - } - - public void delete(TemporaryBasal tempBasal) { - try { - getDaoTemporaryBasal().delete(tempBasal); - openHumansUploader.enqueueTemporaryBasal(tempBasal, true); - updateEarliestDataChange(tempBasal.date); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } -// scheduleTemporaryBasalChange(); - } - - public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { - try { - List tempbasals; - QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder(); - queryBuilder.orderBy("date", ascending); - Where where = queryBuilder.where(); - where.ge("date", mills); - PreparedQuery preparedQuery = queryBuilder.prepare(); - tempbasals = getDaoTemporaryBasal().query(preparedQuery); - return tempbasals; - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return new ArrayList(); - } - - /* - { - "_id": "59232e1ddd032d04218dab00", - "eventType": "Temp Basal", - "duration": 60, - "percent": -50, - "created_at": "2017-05-22T18:29:57Z", - "enteredBy": "AndroidAPS", - "notes": "Basal Temp Start 50% 60.0 min", - "NSCLIENT_ID": 1495477797863, - "mills": 1495477797000, - "mgdl": 194.5, - "endmills": 1495481397000 - } - */ - - public TemporaryBasal findTempBasalByPumpId(Long pumpId) { - try { - QueryBuilder queryBuilder = null; - queryBuilder = getDaoTemporaryBasal().queryBuilder(); - queryBuilder.orderBy("date", false); - Where where = queryBuilder.where(); - where.eq("pumpId", pumpId); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoTemporaryBasal().query(preparedQuery); - - if (list.size() > 0) - return list.get(0); - else - return null; - - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - - // ------------ ExtendedBolus handling --------------- - - public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { - try { - return getDaoExtendedBolus().queryBuilder() - .where().eq("pumpId", pumpId) - .queryForFirst(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - public void delete(ExtendedBolus extendedBolus) { - try { - getDaoExtendedBolus().delete(extendedBolus); - openHumansUploader.enqueueExtendedBolus(extendedBolus, true); - updateEarliestDataChange(extendedBolus.date); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } -// scheduleExtendedBolusChange(); - } - - /* -{ - "_id": "5924898d577eb0880e355337", - "eventType": "Combo Bolus", - "duration": 120, - "splitNow": 0, - "splitExt": 100, - "enteredinsulin": 1, - "relative": 1, - "created_at": "2017-05-23T19:12:14Z", - "enteredBy": "AndroidAPS", - "NSCLIENT_ID": 1495566734628, - "mills": 1495566734000, - "mgdl": 106 -} - */ - - // ---------------- ProfileSwitch handling --------------- - -/* - public boolean createOrUpdate(ProfileSwitch profileSwitch) { - try { - ProfileSwitch old; - profileSwitch.date = roundDateToSec(profileSwitch.date); - - if (profileSwitch.source == Source.NIGHTSCOUT) { - old = getDaoProfileSwitch().queryForId(profileSwitch.date); - if (old != null) { - if (!old.isEqual(profileSwitch)) { - profileSwitch.source = old.source; - profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension - getDaoProfileSwitch().delete(old); // need to delete/create because date may change too - getDaoProfileSwitch().create(profileSwitch); - aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); - openHumansUploader.enqueueProfileSwitch(profileSwitch); - scheduleProfileSwitchChange(); - return true; - } - return false; - } - // find by NS _id - if (profileSwitch._id != null) { - QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", profileSwitch._id); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = getDaoProfileSwitch().query(preparedQuery); - if (trList.size() > 0) { - old = trList.get(0); - if (!old.isEqual(profileSwitch)) { - getDaoProfileSwitch().delete(old); // need to delete/create because date may change too - old.copyFrom(profileSwitch); - getDaoProfileSwitch().create(old); - aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); - openHumansUploader.enqueueProfileSwitch(old); - scheduleProfileSwitchChange(); - return true; - } - } - } - // look for already added percentage from NS - profileSwitch.profileName = PercentageSplitter.INSTANCE.pureName(profileSwitch.profileName); - getDaoProfileSwitch().create(profileSwitch); - aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); - openHumansUploader.enqueueProfileSwitch(profileSwitch); - scheduleProfileSwitchChange(); - return true; - } - if (profileSwitch.source == Source.USER) { - getDaoProfileSwitch().create(profileSwitch); - aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); - openHumansUploader.enqueueProfileSwitch(profileSwitch); - scheduleProfileSwitchChange(); - return true; - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return false; - } - - public void delete(ProfileSwitch profileSwitch) { - try { - getDaoProfileSwitch().delete(profileSwitch); - openHumansUploader.enqueueProfileSwitch(profileSwitch, true); - scheduleProfileSwitchChange(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - private void scheduleProfileSwitchChange() { - class PostRunnable implements Runnable { - public void run() { - aapsLogger.debug(LTag.DATABASE, "Firing EventProfileNeedsUpdate"); - rxBus.send(new EventReloadProfileSwitchData()); - rxBus.send(new EventProfileNeedsUpdate()); - scheduledProfileSwitchEventPost = null; - } - } - // prepare task for execution in 1 sec - // cancel waiting task to prevent sending multiple posts - if (scheduledProfileSwitchEventPost != null) - scheduledProfileSwitchEventPost.cancel(false); - Runnable task = new PostRunnable(); - final int sec = 1; - scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS); - - } -*/ - /* -{ - "_id":"592fa43ed97496a80da913d2", - "created_at":"2017-06-01T05:20:06Z", - "eventType":"Profile Switch", - "profile":"2016 +30%", - "units":"mmol", - "enteredBy":"sony", - "NSCLIENT_ID":1496294454309, -} - */ -/* - - public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) { - try { - ProfileSwitch profileSwitch = new ProfileSwitch(StaticInjector.Companion.getInstance()); - profileSwitch.date = trJson.getLong("mills"); - if (trJson.has("duration")) - profileSwitch.durationInMinutes = trJson.getInt("duration"); - profileSwitch._id = trJson.getString("_id"); - profileSwitch.profileName = trJson.getString("profile"); - profileSwitch.isCPP = trJson.has("CircadianPercentageProfile"); - profileSwitch.source = Source.NIGHTSCOUT; - if (trJson.has("timeshift")) - profileSwitch.timeshift = trJson.getInt("timeshift"); - if (trJson.has("percentage")) - profileSwitch.percentage = trJson.getInt("percentage"); - if (trJson.has("profileJson")) - profileSwitch.profileJson = trJson.getString("profileJson"); - else { - ProfileSource profileSource = activePlugin.getActiveProfileSource(); - ProfileStore store = profileSource.getProfile(); - if (store != null) { - PureProfile profile = store.getSpecificProfile(profileSwitch.profileName); - if (profile != null) { - profileSwitch.profileJson = profile.getJsonObject().toString(); - aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store"); - // Update data in NS - nsUpload.updateProfileSwitch(profileSwitch, dateUtil); - } else { - aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); - return; - } - } else { - aapsLogger.debug(LTag.DATABASE, "Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); - return; - } - } - if (trJson.has("profilePlugin")) - profileSwitch.profilePlugin = trJson.getString("profilePlugin"); - createOrUpdate(profileSwitch); - } catch (JSONException e) { - aapsLogger.error("Unhandled exception: " + trJson.toString(), e); - } - } - - public void deleteProfileSwitchById(String _id) { - ProfileSwitch stored = findProfileSwitchById(_id); - if (stored != null) { - aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); - delete(stored); - scheduleProfileSwitchChange(); - } - } - - public ProfileSwitch findProfileSwitchById(String _id) { - try { - QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", _id); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoProfileSwitch().query(preparedQuery); - - if (list.size() == 1) { - return list.get(0); - } else { - return null; - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } -*/ // ---------------- Insight history handling --------------- public void createOrUpdate(InsightHistoryOffset offset) { @@ -924,14 +468,4 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } return 0L; } - - public long getCountOfAllRows() { - try { - return getDaoExtendedBolus().countOf() - + getDaoTemporaryBasal().countOf(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return 0L; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java index 4c3816c934..68ec8ca62b 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -5,8 +5,6 @@ import androidx.annotation.Nullable; import com.j256.ormlite.dao.CloseableIterator; -import org.json.JSONObject; - import java.sql.SQLException; import java.util.List; @@ -23,18 +21,10 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { @Inject DatabaseHelperProvider() { } - @Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - @Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) { MainApp.Companion.getDbHelper().createOrUpdate(record); } - @NonNull @Override public List getDanaRHistoryRecordsByType(byte type) { - return MainApp.Companion.getDbHelper().getDanaRHistoryRecordsByType(type); - } - @Override public long size(@NonNull String table) { return MainApp.Companion.getDbHelper().size(table); } @@ -68,16 +58,19 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { } @Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) { - return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal); +// return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal); + return false; } @Nullable @Override public TemporaryBasal findTempBasalByPumpId(long id) { - return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id); +// return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id); + return null; } @Deprecated @NonNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { - return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); +// return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); + return null; } @NonNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { @@ -101,11 +94,12 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { } @Override public void delete(@NonNull ExtendedBolus extendedBolus) { - MainApp.Companion.getDbHelper().delete(extendedBolus); +// MainApp.Companion.getDbHelper().delete(extendedBolus); } @Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { - return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId); +// return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId); + return null; } @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) { @@ -140,10 +134,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { MainApp.Companion.getDbHelper().clearOpenHumansQueue(); } - @Override public long getCountOfAllRows() { - return MainApp.Companion.getDbHelper().getCountOfAllRows(); - } - @Override public void removeAllOHQueueItemsWithIdSmallerThan(long id) { MainApp.Companion.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(id); } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index b7881ca7f4..05b5974bb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -7,6 +7,7 @@ import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.automation.di.AutomationModule import info.nightscout.androidaps.combo.di.ComboModule +import info.nightscout.androidaps.dana.di.DanaHistoryModule import info.nightscout.androidaps.di.CoreModule import info.nightscout.androidaps.dana.di.DanaModule import info.nightscout.androidaps.danar.di.DanaRModule @@ -45,6 +46,7 @@ import javax.inject.Singleton UIModule::class, CoreModule::class, DanaModule::class, + DanaHistoryModule::class, DanaRModule::class, DanaRSModule::class, ComboModule::class, diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 740426792c..ed55beb8e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -6,7 +6,6 @@ import dagger.Lazy import dagger.Module import dagger.Provides import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.db.DatabaseHelperProvider import info.nightscout.androidaps.interfaces.* @@ -32,6 +31,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.Storage import javax.inject.Singleton + @Suppress("unused") @Module(includes = [ AppModule.AppBindings::class @@ -70,7 +70,7 @@ open class AppModule { context: Context, sp: SP, rxBus: RxBusWrapper - ): UploadQueueAdminInterface = UploadQueue(aapsLogger, databaseHelper, context, sp, rxBus) + ): UploadQueueInterface = UploadQueue(aapsLogger, databaseHelper, context, sp, rxBus) @Module interface AppBindings { @@ -88,7 +88,6 @@ open class AppModule { @Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface @Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculator @Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicator - @Binds fun bindUploadQueueAdminInterfaceToUploadQueue(uploadQueueAdminInterface: UploadQueueAdminInterface) : UploadQueueInterface @Binds fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector @Binds fun bindPumpSync(pumpSyncImplementation: PumpSyncImplementation): PumpSync 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 4337808106..8ff8dac818 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 @@ -7,13 +7,13 @@ import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R +import info.nightscout.androidaps.dana.database.DanaHistoryDatabase import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.events.EventNewBG import info.nightscout.androidaps.interfaces.DataSyncSelector -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger @@ -38,7 +38,7 @@ class MaintenanceFragment : DaggerFragment() { @Inject lateinit var importExportPrefs: ImportExportPrefs @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository - @Inject lateinit var databaseHelper: DatabaseHelperInterface + @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase @Inject lateinit var uel: UserEntryLogger @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var pumpSync: PumpSync @@ -68,8 +68,8 @@ class MaintenanceFragment : DaggerFragment() { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.maintenance), resourceHelper.gs(R.string.reset_db_confirm), Runnable { compositeDisposable.add( fromAction { - databaseHelper.resetDatabases() repository.clearDatabases() + danaHistoryDatabase.clearAllTables() dataSyncSelector.resetToNextFullSync() pumpSync.connectNewPump() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt index d2e77a4f95..80b508766d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt @@ -12,14 +12,11 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.NsClientFragmentBinding import info.nightscout.androidaps.interfaces.DataSyncSelector -import info.nightscout.androidaps.interfaces.UploadQueueAdminInterface import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.HtmlHelper.fromHtml import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -33,7 +30,6 @@ class NSClientFragment : DaggerFragment() { @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var uploadQueue: UploadQueueAdminInterface @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var dataSyncSelector: DataSyncSelector @@ -72,18 +68,6 @@ class NSClientFragment : DaggerFragment() { binding.restart.paintFlags = binding.restart.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.deliverNow.setOnClickListener { nsClientPlugin.resend("GUI") } binding.deliverNow.paintFlags = binding.deliverNow.paintFlags or Paint.UNDERLINE_TEXT_FLAG - binding.clearQueue.setOnClickListener { - context?.let { context -> - OKDialog.showConfirmation(context, resourceHelper.gs(R.string.nsclientinternal), resourceHelper.gs(R.string.clearqueueconfirm), Runnable { - uel.log(Action.NS_QUEUE_CLEARED, Sources.NSClient) - uploadQueue.clearQueue() - updateGui() - }) - } - } - binding.clearQueue.paintFlags = binding.clearQueue.paintFlags or Paint.UNDERLINE_TEXT_FLAG - binding.showQueue.setOnClickListener { rxBus.send(EventNSClientNewLog("QUEUE", uploadQueue.textList())) } - binding.showQueue.paintFlags = binding.showQueue.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.fullSync.setOnClickListener { context?.let { context -> OKDialog.showConfirmation(context, resourceHelper.gs(R.string.nsclientinternal), resourceHelper.gs(R.string.full_sync), Runnable { @@ -116,7 +100,6 @@ class NSClientFragment : DaggerFragment() { binding.log.text = nsClientPlugin.textLog if (nsClientPlugin.autoscroll) binding.logScrollview.fullScroll(ScrollView.FOCUS_DOWN) binding.url.text = nsClientPlugin.url() - binding.queue.text = fromHtml(resourceHelper.gs(R.string.queue) + " " + uploadQueue.size() + "") binding.status.text = nsClientPlugin.status } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java index f7669b182d..d217c1bd15 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java @@ -4,18 +4,10 @@ import android.content.Context; import android.content.Intent; import android.os.SystemClock; -import com.j256.ormlite.dao.CloseableIterator; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.sql.SQLException; - import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; -import info.nightscout.androidaps.interfaces.UploadQueueAdminInterface; import info.nightscout.androidaps.interfaces.UploadQueueInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -27,7 +19,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 21.02.2016. */ -public class UploadQueue implements UploadQueueAdminInterface { +public class UploadQueue implements UploadQueueInterface { private final AAPSLogger aapsLogger; private final DatabaseHelperInterface databaseHelper; private final Context context; @@ -75,50 +67,4 @@ public class UploadQueue implements UploadQueueAdminInterface { rxBus.send(new EventNSClientResend("newdata")); } - @Override public void clearQueue() { - startService(); - if (NSClientService.handler != null) { - NSClientService.handler.post(() -> { - aapsLogger.debug(LTag.NSCLIENT, "ClearQueue"); - databaseHelper.deleteAllDbRequests(); - aapsLogger.debug(LTag.NSCLIENT, status()); - }); - } - } - - @Override - public void removeByMongoId(final String action, final String _id) { - if (_id == null || _id.equals("")) - return; - startService(); - if (NSClientService.handler != null) { - NSClientService.handler.post(() -> { - databaseHelper.deleteDbRequestbyMongoId(action, _id); - aapsLogger.debug(LTag.NSCLIENT, "Removing " + _id + " from UploadQueue. " + status()); - }); - } - } - - @Override public String textList() { - String result = ""; - CloseableIterator iterator; - try { - iterator = databaseHelper.getDbRequestIterator(); - try { - while (iterator.hasNext()) { - DbRequest dbr = iterator.next(); - result += "
"; - result += dbr.action.toUpperCase() + " "; - result += dbr.collection + ": "; - result += dbr.data; - } - } finally { - iterator.close(); - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return result; - } - } 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 cf4f0c62fa..a331fcd88d 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 @@ -178,24 +178,24 @@ class OpenHumansUploader @Inject constructor( } } - @JvmOverloads - fun enqueueTreatment(treatment: Treatment?, deleted: Boolean = false) = treatment?.let { - insertQueueItem("Treatments") { - put("date", treatment.date) - put("isValid", treatment.isValid) - put("source", treatment.source) - put("nsId", treatment._id) - put("boluscalc", treatment.boluscalc) - put("carbs", treatment.carbs) - put("dia", treatment.dia) - put("insulin", treatment.insulin) - put("insulinInterfaceID", treatment.insulinInterfaceID) - put("isSMB", treatment.isSMB) - put("mealBolus", treatment.mealBolus) - put("bolusCalcJson", treatment.getBoluscalc()) - put("isDeletion", deleted) - } - } + // @JvmOverloads + // fun enqueueTreatment(treatment: Treatment?, deleted: Boolean = false) = treatment?.let { + // insertQueueItem("Treatments") { + // put("date", treatment.date) + // put("isValid", treatment.isValid) + // put("source", treatment.source) + // put("nsId", treatment._id) + // put("boluscalc", treatment.boluscalc) + // put("carbs", treatment.carbs) + // put("dia", treatment.dia) + // put("insulin", treatment.insulin) + // put("insulinInterfaceID", treatment.insulinInterfaceID) + // put("isSMB", treatment.isSMB) + // put("mealBolus", treatment.mealBolus) + // put("bolusCalcJson", treatment.getBoluscalc()) + // put("isDeletion", deleted) + // } + // } @JvmOverloads fun enqueueTherapyEvent(therapyEvent: TherapyEvent, deleted: Boolean = false) = insertQueueItem("TherapyEvents") { @@ -210,17 +210,17 @@ class OpenHumansUploader @Inject constructor( put("isDeletion", deleted) } - @JvmOverloads - fun enqueueExtendedBolus(extendedBolus: ExtendedBolus, deleted: Boolean = false) = insertQueueItem("ExtendedBoluses") { - put("date", extendedBolus.date) - put("isValid", extendedBolus.isValid) - put("source", extendedBolus.source) - put("nsId", extendedBolus._id) - put("pumpId", extendedBolus.pumpId) - put("insulin", extendedBolus.insulin) - put("durationInMinutes", extendedBolus.durationInMinutes) - put("isDeletion", deleted) - } + // @JvmOverloads + // fun enqueueExtendedBolus(extendedBolus: ExtendedBolus, deleted: Boolean = false) = insertQueueItem("ExtendedBoluses") { + // put("date", extendedBolus.date) + // put("isValid", extendedBolus.isValid) + // put("source", extendedBolus.source) + // put("nsId", extendedBolus._id) + // put("pumpId", extendedBolus.pumpId) + // put("insulin", extendedBolus.insulin) + // put("durationInMinutes", extendedBolus.durationInMinutes) + // put("isDeletion", deleted) + // } // @JvmOverloads // fun enqueueProfileSwitch(profileSwitch: ProfileSwitch, deleted: Boolean = false) = insertQueueItem("ProfileSwitches") { @@ -244,22 +244,22 @@ class OpenHumansUploader @Inject constructor( // put("double", tdd.total) // } - @JvmOverloads - fun enqueueTemporaryBasal(temporaryBasal: TemporaryBasal?, deleted: Boolean = false) = temporaryBasal?.let { - insertQueueItem("TemporaryBasals") { - put("date", temporaryBasal.date) - put("isValid", temporaryBasal.isValid) - put("source", temporaryBasal.source) - put("nsId", temporaryBasal._id) - put("pumpId", temporaryBasal.pumpId) - put("durationInMinutes", temporaryBasal.durationInMinutes) - put("durationInMinutes", temporaryBasal.durationInMinutes) - put("isAbsolute", temporaryBasal.isAbsolute) - put("percentRate", temporaryBasal.percentRate) - put("absoluteRate", temporaryBasal.absoluteRate) - put("isDeletion", deleted) - } - } + // @JvmOverloads + // fun enqueueTemporaryBasal(temporaryBasal: TemporaryBasal?, deleted: Boolean = false) = temporaryBasal?.let { + // insertQueueItem("TemporaryBasals") { + // put("date", temporaryBasal.date) + // put("isValid", temporaryBasal.isValid) + // put("source", temporaryBasal.source) + // put("nsId", temporaryBasal._id) + // put("pumpId", temporaryBasal.pumpId) + // put("durationInMinutes", temporaryBasal.durationInMinutes) + // put("durationInMinutes", temporaryBasal.durationInMinutes) + // put("isAbsolute", temporaryBasal.isAbsolute) + // put("percentRate", temporaryBasal.percentRate) + // put("absoluteRate", temporaryBasal.absoluteRate) + // put("isDeletion", deleted) + // } + // } @JvmOverloads fun enqueueTempTarget(tempTarget: TemporaryTarget?, deleted: Boolean = false) = tempTarget?.let { 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 a4da17f159..4d17a119be 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 @@ -400,9 +400,8 @@ class GraphData( time += 5 * 60 * 1000L continue } - var iob = 0.0 var absIob = 0.0 - iob = iobCobCalculator.calculateFromTreatmentsAndTemps(time, profile).iob + val iob: Double = iobCobCalculator.calculateFromTreatmentsAndTemps(time, profile).iob if (absScale) absIob = iobCobCalculator.calculateAbsInsulinFromTreatmentsAndTemps(time).iob if (abs(lastIob - iob) > 0.02) { if (abs(lastIob - iob) > 0.2) iobArray.add(ScaledDataPoint(time, lastIob, iobScale)) @@ -461,8 +460,7 @@ class GraphData( time += 5 * 60 * 1000L continue } - var iob = 0.0 - iob = iobCobCalculator.calculateAbsInsulinFromTreatmentsAndTemps(time).iob + val iob: Double = iobCobCalculator.calculateAbsInsulinFromTreatmentsAndTemps(time).iob if (abs(lastIob - iob) > 0.02) { if (abs(lastIob - iob) > 0.2) iobArray.add(ScaledDataPoint(time, lastIob, iobScale)) iobArray.add(ScaledDataPoint(time, iob, iobScale)) 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 3619e209f6..a8293002f8 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 @@ -105,25 +105,10 @@ public class TreatmentService extends OrmLiteBaseService impleme return wrapped.queryForAll(); } - public void delete(Treatment data) throws SQLException { - wrapped.delete(data); - openHumansUploader.enqueueTreatment(data, true); - } - - public void create(Treatment data) throws SQLException { - wrapped.create(data); - openHumansUploader.enqueueTreatment(data); - } - public Treatment queryForId(long id) throws SQLException { return wrapped.queryForId(id); } - public void update(Treatment data) throws SQLException { - wrapped.update(data); - openHumansUploader.enqueueTreatment(data); - } - public QueryBuilder queryBuilder() { return wrapped.queryBuilder(); } diff --git a/app/src/main/res/layout/ns_client_fragment.xml b/app/src/main/res/layout/ns_client_fragment.xml index a4b625d2a7..e10791bb52 100644 --- a/app/src/main/res/layout/ns_client_fragment.xml +++ b/app/src/main/res/layout/ns_client_fragment.xml @@ -75,15 +75,6 @@ android:layout_height="wrap_content" android:textStyle="normal|bold" /> - - - - - - >> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } -} - diff --git a/core/src/main/java/info/nightscout/androidaps/di/CoreDataClassesModule.kt b/core/src/main/java/info/nightscout/androidaps/di/CoreDataClassesModule.kt index dcf5e99967..0c37e3e32c 100644 --- a/core/src/main/java/info/nightscout/androidaps/di/CoreDataClassesModule.kt +++ b/core/src/main/java/info/nightscout/androidaps/di/CoreDataClassesModule.kt @@ -4,9 +4,6 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.data.ProfileImplOld 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.interfaces.ProfileStore import info.nightscout.androidaps.plugins.aps.loop.APSResult import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg @@ -24,7 +21,4 @@ abstract class CoreDataClassesModule { @ContributesAndroidInjector abstract fun profileInjector(): ProfileImplOld @ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore - @ContributesAndroidInjector abstract fun treatmentInjector(): Treatment - @ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal - @ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus } diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt index e4a5582d49..9a11451fc2 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt @@ -8,14 +8,12 @@ interface DatabaseHelperInterface { fun resetDatabases() - fun createOrUpdate(record: DanaRHistoryRecord) fun createOrUpdate(record: OmnipodHistoryRecord) fun createOrUpdate(record: InsightBolusID) fun createOrUpdate(record: InsightPumpID) fun createOrUpdate(record: InsightHistoryOffset) fun createOrUpdate(record: OHQueueItem) fun create(record: DbRequest) - fun getDanaRHistoryRecordsByType(type: Byte): List fun size(table: String): Long fun deleteAllDbRequests() fun deleteDbRequest(id: String): Int @@ -41,7 +39,6 @@ interface DatabaseHelperInterface { fun getOHQueueSize(): Long fun clearOpenHumansQueue() - fun getCountOfAllRows(): Long fun removeAllOHQueueItemsWithIdSmallerThan(id: Long) companion object { diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt index 7f505674eb..0dbe420b24 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt @@ -20,7 +20,7 @@ interface IobCobCalculator { fun getLastAutosensDataWithWaitForCalculationFinish(reason: String): AutosensData? fun calculateAbsInsulinFromTreatmentsAndTemps(fromTime: Long): IobTotal - fun calculateFromTreatmentsAndTemps(time: Long, profile: Profile): IobTotal + fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile): IobTotal fun getBasalData(profile: Profile, fromTime: Long): BasalData diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt index 13d8c008ff..64dc9099a8 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.interfaces import androidx.collection.ArrayMap import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.data.ProfileImplOld import info.nightscout.androidaps.data.PureProfile import info.nightscout.androidaps.extensions.pureProfileFromJson import info.nightscout.androidaps.logging.AAPSLogger @@ -67,8 +66,7 @@ class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject, val d return profile } - fun getSpecificProfileJson(profileName: String): JSONObject? { - var profile: PureProfile? = null + private fun getSpecificProfileJson(profileName: String): JSONObject? { getStore()?.let { store -> if (store.has(profileName)) return JsonHelper.safeGetJSONObject(store, profileName, null) diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueAdminInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueAdminInterface.kt deleted file mode 100644 index e749854c0a..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueAdminInterface.kt +++ /dev/null @@ -1,6 +0,0 @@ -package info.nightscout.androidaps.interfaces - -interface UploadQueueAdminInterface : UploadQueueInterface { - - fun clearQueue() -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueInterface.java b/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueInterface.java index 65e02dcdb8..903bffd4c2 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueInterface.java +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/UploadQueueInterface.java @@ -9,8 +9,4 @@ public interface UploadQueueInterface { long size(); void add(DbRequest dbRequest); - - void removeByMongoId(final String action, final String _id); - - String textList(); } 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 c65ca85828..f143ad92b0 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 @@ -31,62 +31,10 @@ public class NSUpload { this.sp = sp; this.uploadQueue = uploadQueue; } -/* - public void uploadProfileSwitch(ProfileSwitch profileSwitch, long nsClientId, DateUtil dateUtil) { - try { - JSONObject data = getJson(profileSwitch, dateUtil); - DbRequest dbr = new DbRequest("dbAdd", "treatments", data, nsClientId); - aapsLogger.debug("Prepared: " + dbr.log()); - uploadQueue.add(dbr); - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public void updateProfileSwitch(ProfileSwitch profileSwitch, DateUtil dateUtil) { - try { - JSONObject data = getJson(profileSwitch, dateUtil); - if (profileSwitch._id != null) { - uploadQueue.add(new DbRequest("dbUpdate", "treatments", profileSwitch._id, data, profileSwitch.date)); - } - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - private static JSONObject getJson(ProfileSwitch profileSwitch, DateUtil dateUtil) throws JSONException { - JSONObject data = new JSONObject(); - data.put("eventType", TherapyEvent.Type.PROFILE_SWITCH.getText()); - data.put("duration", profileSwitch.durationInMinutes); - data.put("profile", profileSwitch.getCustomizedName()); - data.put("profileJson", profileSwitch.profileJson); - data.put("profilePlugin", profileSwitch.profilePlugin); - if (profileSwitch.isCPP) { - data.put("CircadianPercentageProfile", true); - data.put("timeshift", profileSwitch.timeshift); - data.put("percentage", profileSwitch.percentage); - } - data.put("created_at", dateUtil.toISOString(profileSwitch.date)); - data.put("enteredBy", "AndroidAPS"); - - return data; - } -*/ - // TODO replace with setting isValid = false - public void removeCareportalEntryFromNS(String _id) { - uploadQueue.add(new DbRequest("dbRemove", "treatments", _id, System.currentTimeMillis())); - } public void uploadProfileStore(JSONObject profileStore) { if (sp.getBoolean(R.string.key_ns_uploadlocalprofile, false)) { uploadQueue.add(new DbRequest("dbAdd", "profile", profileStore, System.currentTimeMillis())); } } - - public static boolean isIdValid(String _id) { - if (_id == null) - return false; - return _id.length() == 24; - } - } diff --git a/dana/build.gradle b/dana/build.gradle index 8020051b31..e36ef61f0d 100644 --- a/dana/build.gradle +++ b/dana/build.gradle @@ -17,4 +17,10 @@ android { dependencies { implementation project(':core') + + api "androidx.room:room-ktx:$room_version" + api "androidx.room:room-runtime:$room_version" + api "androidx.room:room-rxjava2:$room_version" + kapt "androidx.room:room-compiler:$room_version" + kapt "android.arch.persistence.room:compiler:$room_version" } \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt index ae01f4d2d4..0c6111e14e 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt @@ -6,21 +6,21 @@ import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter -import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.dana.R import info.nightscout.androidaps.dana.comm.RecordTypes +import info.nightscout.androidaps.dana.database.DanaHistoryRecord +import info.nightscout.androidaps.dana.database.DanaHistoryRecordDao import info.nightscout.androidaps.dana.databinding.DanarHistoryActivityBinding -import info.nightscout.androidaps.interfaces.Profile -import info.nightscout.androidaps.db.DanaRHistoryRecord +import info.nightscout.androidaps.dana.databinding.DanarHistoryItemBinding import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface +import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -30,6 +30,7 @@ import info.nightscout.androidaps.queue.Callback 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.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign @@ -44,14 +45,13 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueueProvider - @Inject lateinit var databaseHelper: DatabaseHelperInterface + @Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() private var showingType = RecordTypes.RECORD_TYPE_ALARM - private var historyList: List = ArrayList() class TypeList internal constructor(var type: Byte, var name: String) { @@ -73,6 +73,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { aapsLogger.debug(LTag.PUMP, "EventDanaRSyncStatus: " + it.message) binding.status.text = it.message }, fabricPrivacy::logException) + swapAdapter(showingType) } override fun onPause() { @@ -87,7 +88,6 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { binding.recyclerview.setHasFixedSize(true) binding.recyclerview.layoutManager = LinearLayoutManager(this) - binding.recyclerview.adapter = RecyclerViewAdapter(historyList) binding.status.visibility = View.GONE val pump = activePlugin.activePump @@ -115,14 +115,12 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { binding.reload.setOnClickListener { val selected = binding.spinner.selectedItem as TypeList? ?: return@setOnClickListener - runOnUiThread { - binding.reload.visibility = View.GONE - binding.status.visibility = View.VISIBLE - } + binding.reload.visibility = View.GONE + binding.status.visibility = View.VISIBLE clearCardView() commandQueue.loadHistory(selected.type, object : Callback() { override fun run() { - loadDataFromDB(selected.type) + swapAdapter(selected.type) runOnUiThread { binding.reload.visibility = View.VISIBLE binding.status.visibility = View.GONE @@ -133,7 +131,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val selected = typeList[position] - loadDataFromDB(selected.type) + swapAdapter(selected.type) showingType = selected.type } @@ -143,95 +141,95 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { } } - inner class RecyclerViewAdapter internal constructor(private var historyList: List) : RecyclerView.Adapter() { + inner class RecyclerViewAdapter internal constructor(private var historyList: List) : RecyclerView.Adapter() { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): HistoryViewHolder = HistoryViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.danar_history_item, viewGroup, false)) override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { val record = historyList[position] - holder.time.text = dateUtil.dateAndTimeString(record.recordDate) - holder.value.text = DecimalFormatter.to2Decimal(record.recordValue) - holder.stringValue.text = record.stringRecordValue - holder.bolusType.text = record.bolusType - holder.duration.text = DecimalFormatter.to0Decimal(record.recordDuration.toDouble()) - holder.alarm.text = record.recordAlarm + holder.binding.time.text = dateUtil.dateAndTimeString(record.timestamp) + holder.binding.value.text = DecimalFormatter.to2Decimal(record.value) + holder.binding.stringValue.text = record.stringValue + holder.binding.bolusType.text = record.bolusType + holder.binding.duration.text = record.duration.toString() + holder.binding.alarm.text = record.alarm when (showingType) { - RecordTypes.RECORD_TYPE_ALARM -> { - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.VISIBLE - holder.stringValue.visibility = View.GONE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.VISIBLE + RecordTypes.RECORD_TYPE_ALARM -> { + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.VISIBLE + holder.binding.stringValue.visibility = View.GONE + holder.binding.bolusType.visibility = View.GONE + holder.binding.duration.visibility = View.GONE + holder.binding.dailyBasal.visibility = View.GONE + holder.binding.dailyBolus.visibility = View.GONE + holder.binding.dailyTotal.visibility = View.GONE + holder.binding.alarm.visibility = View.VISIBLE } - RecordTypes.RECORD_TYPE_BOLUS -> { - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.VISIBLE - holder.stringValue.visibility = View.GONE - holder.bolusType.visibility = View.VISIBLE - holder.duration.visibility = View.VISIBLE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.GONE + RecordTypes.RECORD_TYPE_BOLUS -> { + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.VISIBLE + holder.binding.stringValue.visibility = View.GONE + holder.binding.bolusType.visibility = View.VISIBLE + holder.binding.duration.visibility = View.VISIBLE + holder.binding.dailyBasal.visibility = View.GONE + holder.binding.dailyBolus.visibility = View.GONE + holder.binding.dailyTotal.visibility = View.GONE + holder.binding.alarm.visibility = View.GONE } - RecordTypes.RECORD_TYPE_DAILY -> { - holder.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBasal) - holder.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBolus) - holder.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBolus + record.recordDailyBasal) - holder.time.text = dateUtil.dateString(record.recordDate) - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.GONE - holder.stringValue.visibility = View.GONE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.VISIBLE - holder.dailyBolus.visibility = View.VISIBLE - holder.dailyTotal.visibility = View.VISIBLE - holder.alarm.visibility = View.GONE + RecordTypes.RECORD_TYPE_DAILY -> { + holder.binding.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBasal) + holder.binding.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus) + holder.binding.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) + holder.binding.time.text = dateUtil.dateString(record.timestamp) + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.GONE + holder.binding.stringValue.visibility = View.GONE + holder.binding.bolusType.visibility = View.GONE + holder.binding.duration.visibility = View.GONE + holder.binding.dailyBasal.visibility = View.VISIBLE + holder.binding.dailyBolus.visibility = View.VISIBLE + holder.binding.dailyTotal.visibility = View.VISIBLE + holder.binding.alarm.visibility = View.GONE } - RecordTypes.RECORD_TYPE_GLUCOSE -> { - holder.value.text = Profile.toUnitsString(record.recordValue, record.recordValue * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.VISIBLE - holder.stringValue.visibility = View.GONE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.GONE + RecordTypes.RECORD_TYPE_GLUCOSE -> { + holder.binding.value.text = Profile.toUnitsString(record.value, record.value * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.VISIBLE + holder.binding.stringValue.visibility = View.GONE + holder.binding.bolusType.visibility = View.GONE + holder.binding.duration.visibility = View.GONE + holder.binding.dailyBasal.visibility = View.GONE + holder.binding.dailyBolus.visibility = View.GONE + holder.binding.dailyTotal.visibility = View.GONE + holder.binding.alarm.visibility = View.GONE } RecordTypes.RECORD_TYPE_CARBO, RecordTypes.RECORD_TYPE_BASALHOUR, RecordTypes.RECORD_TYPE_ERROR, RecordTypes.RECORD_TYPE_PRIME, RecordTypes.RECORD_TYPE_REFILL, RecordTypes.RECORD_TYPE_TB -> { - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.VISIBLE - holder.stringValue.visibility = View.GONE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.GONE + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.VISIBLE + holder.binding.stringValue.visibility = View.GONE + holder.binding.bolusType.visibility = View.GONE + holder.binding.duration.visibility = View.GONE + holder.binding.dailyBasal.visibility = View.GONE + holder.binding.dailyBolus.visibility = View.GONE + holder.binding.dailyTotal.visibility = View.GONE + holder.binding.alarm.visibility = View.GONE } - RecordTypes.RECORD_TYPE_SUSPEND -> { - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.GONE - holder.stringValue.visibility = View.VISIBLE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.GONE + RecordTypes.RECORD_TYPE_SUSPEND -> { + holder.binding.time.visibility = View.VISIBLE + holder.binding.value.visibility = View.GONE + holder.binding.stringValue.visibility = View.VISIBLE + holder.binding.bolusType.visibility = View.GONE + holder.binding.duration.visibility = View.GONE + holder.binding.dailyBasal.visibility = View.GONE + holder.binding.dailyBolus.visibility = View.GONE + holder.binding.dailyTotal.visibility = View.GONE + holder.binding.alarm.visibility = View.GONE } } } @@ -242,25 +240,17 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { inner class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { - var time: TextView = itemView.findViewById(R.id.danar_history_time) - var value: TextView = itemView.findViewById(R.id.danar_history_value) - var bolusType: TextView = itemView.findViewById(R.id.danar_history_bolustype) - var stringValue: TextView = itemView.findViewById(R.id.danar_history_stringvalue) - var duration: TextView = itemView.findViewById(R.id.danar_history_duration) - var dailyBasal: TextView = itemView.findViewById(R.id.danar_history_dailybasal) - var dailyBolus: TextView = itemView.findViewById(R.id.danar_history_dailybolus) - var dailyTotal: TextView = itemView.findViewById(R.id.danar_history_dailytotal) - var alarm: TextView = itemView.findViewById(R.id.danar_history_alarm) + val binding = DanarHistoryItemBinding.bind(itemView) } } - private fun loadDataFromDB(type: Byte) { - historyList = databaseHelper.getDanaRHistoryRecordsByType(type) - runOnUiThread { binding.recyclerview.swapAdapter(RecyclerViewAdapter(historyList), false) } + private fun swapAdapter(type: Byte) { + disposable += danaHistoryRecordDao + .allFromByType(dateUtil.now() - T.months(1).msecs(), type) + .subscribeOn(aapsSchedulers.io) + .observeOn(aapsSchedulers.main) + .subscribe { historyList -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(historyList), false) } } - private fun clearCardView() { - historyList = ArrayList() - runOnUiThread { binding.recyclerview.swapAdapter(RecyclerViewAdapter(historyList), false) } - } + private fun clearCardView() = binding.recyclerview.swapAdapter(RecyclerViewAdapter(ArrayList()), false) } \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryDatabase.kt b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryDatabase.kt new file mode 100644 index 0000000000..f04779c4ec --- /dev/null +++ b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryDatabase.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.dana.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters + +const val TABLE_DANA_HISTORY = "danaHistory" + +@Database( + entities = [DanaHistoryRecord::class], + exportSchema = true, + version = DanaHistoryDatabase.VERSION +) +abstract class DanaHistoryDatabase : RoomDatabase() { + + abstract fun historyRecordDao(): DanaHistoryRecordDao + + companion object { + + const val VERSION = 1 + + fun build(context: Context) = + Room.databaseBuilder( + context.applicationContext, + DanaHistoryDatabase::class.java, + "dana_database.db" + ) + .fallbackToDestructiveMigration() + .build() + } +} diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecord.kt b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecord.kt new file mode 100644 index 0000000000..8aaf3e32f4 --- /dev/null +++ b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecord.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.dana.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = TABLE_DANA_HISTORY, + indices = [Index("code", "timestamp")]) +data class DanaHistoryRecord( + @PrimaryKey var timestamp: Long, + var code: Byte = 0x0F, + var value: Double = 0.0, + var bolusType: String = "None", + var stringValue: String = "", + var duration: Long = 0, + var dailyBasal: Double = 0.0, + var dailyBolus: Double = 0.0, + var alarm: String = "" +) diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecordDao.kt b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecordDao.kt new file mode 100644 index 0000000000..276d73fbac --- /dev/null +++ b/dana/src/main/java/info/nightscout/androidaps/dana/database/DanaHistoryRecordDao.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.dana.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import io.reactivex.Single + +@Dao +abstract class DanaHistoryRecordDao { + + @Query("SELECT * from $TABLE_DANA_HISTORY WHERE timestamp >= :timestamp AND code = :type") + abstract fun allFromByType(timestamp: Long, type: Byte): Single> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(danaHistoryRecord: DanaHistoryRecord) +} diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaHistoryModule.kt b/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaHistoryModule.kt new file mode 100644 index 0000000000..1d52df3139 --- /dev/null +++ b/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaHistoryModule.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.dana.di + +import android.content.Context +import dagger.Module +import dagger.Provides +import info.nightscout.androidaps.dana.database.DanaHistoryDatabase +import info.nightscout.androidaps.dana.database.DanaHistoryRecordDao +import javax.inject.Singleton + +@Module +class DanaHistoryModule { + + @Provides + @Singleton + internal fun provideDatabase(context: Context): DanaHistoryDatabase = DanaHistoryDatabase.build(context) + + @Provides + @Singleton + internal fun provideHistoryRecordDao(danaHistoryDatabase: DanaHistoryDatabase): DanaHistoryRecordDao = + danaHistoryDatabase.historyRecordDao() +} diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaModule.kt b/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaModule.kt index 224838979b..472feef422 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaModule.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/di/DanaModule.kt @@ -1,10 +1,15 @@ package info.nightscout.androidaps.dana.di +import android.content.Context import dagger.Module +import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.dana.DanaFragment import info.nightscout.androidaps.dana.activities.DanaHistoryActivity import info.nightscout.androidaps.dana.activities.DanaUserOptionsActivity +import info.nightscout.androidaps.dana.database.DanaHistoryDatabase +import info.nightscout.androidaps.dana.database.DanaHistoryRecordDao +import javax.inject.Singleton @Module @Suppress("unused") diff --git a/dana/src/main/res/layout/danar_history_activity.xml b/dana/src/main/res/layout/danar_history_activity.xml index 5839c37dc0..f49c841bb9 100644 --- a/dana/src/main/res/layout/danar_history_activity.xml +++ b/dana/src/main/res/layout/danar_history_activity.xml @@ -1,94 +1,110 @@ - - + android:padding="5dp" + app:layout_constraintBottom_toTopOf="@+id/spinner" + app:layout_constraintEnd_toEndOf="parent" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toTopOf="parent"> + android:textAppearance="?android:attr/textAppearanceLarge" + app:layout_constraintBottom_toBottomOf="parent" + app:layout_constraintLeft_toLeftOf="parent" + app:layout_constraintRight_toRightOf="parent" + app:layout_constraintTop_toTopOf="parent" /> - + - + android:layout_marginStart="10dp" + android:layout_marginEnd="20dp" + android:text="@string/eventtype" + android:textAppearance="?android:attr/textAppearanceSmall" + app:layout_constraintBottom_toBottomOf="@+id/spinner" + app:layout_constraintEnd_toStartOf="@+id/spinner" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toTopOf="@+id/spinner" /> - - - - - - - + android:layout_marginEnd="10dp" + app:layout_constraintBottom_toTopOf="@+id/status" + app:layout_constraintEnd_toEndOf="parent" + app:layout_constraintStart_toEndOf="@+id/textView" + app:layout_constraintTop_toBottomOf="@+id/header" /> + android:layout_marginTop="10dp" + android:layout_marginBottom="5dp" + android:gravity="center_horizontal" + app:layout_constraintBottom_toTopOf="@+id/recyclerview" + app:layout_constraintEnd_toEndOf="parent" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toBottomOf="@+id/textView" /> + android:layout_width="0dp" + android:layout_height="0dp" + app:layout_constraintBottom_toTopOf="@+id/reload" + app:layout_constraintEnd_toEndOf="parent" + app:layout_constraintStart_toStartOf="parent" + app:layout_constraintTop_toBottomOf="@+id/status" />