From f37e3ab4c2fc10a760f349984b97620846dc4a2f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 29 Mar 2021 09:43:25 +0200 Subject: [PATCH 1/3] Simplify IOB calculation call --- .../androidaps/dialogs/WizardDialog.kt | 2 -- .../dataBroadcaster/DataBroadcastPlugin.kt | 2 -- .../general/overview/OverviewFragment.kt | 2 -- .../PersistentNotificationPlugin.kt | 2 -- .../smsCommunicator/SmsCommunicatorPlugin.kt | 2 -- .../wearintegration/WatchUpdaterService.java | 2 -- .../xdripStatusline/StatusLinePlugin.kt | 2 -- .../plugins/treatments/TreatmentsPlugin.java | 19 ++----------------- .../androidaps/utils/wizard/BolusWizard.kt | 2 -- .../utils/wizard/QuickWizardEntry.kt | 2 -- .../interfaces/TreatmentsInterface.java | 4 ---- 11 files changed, 2 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 043332aa4a..176136a67a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -279,9 +279,7 @@ class WizardDialog : DaggerDialogFragment() { binding.ttcheckbox.isEnabled = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing // IOB calculation - treatmentsPlugin.updateTotalIOBTreatments() val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() - treatmentsPlugin.updateTotalIOBTempBasals() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 4ff7ce4d14..4d1665d19b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -136,9 +136,7 @@ class DataBroadcastPlugin @Inject constructor( private fun iobCob(bundle: Bundle) { profileFunction.getProfile() ?: return - activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob: IobTotal = activePlugin.activeTreatments.lastCalculationTreatments.round() - activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob: IobTotal = activePlugin.activeTreatments.lastCalculationTempBasals.round() bundle.putDouble("bolusIob", bolusIob.iob) bundle.putDouble("basalIob", basalIob.basaliob) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index 6c76c3f910..bc0187e98c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -749,8 +749,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList processButtonsVisibility() // iob - treatmentsPlugin.updateTotalIOBTreatments() - treatmentsPlugin.updateTotalIOBTempBasals() val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() binding.infoLayout.iob.text = resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index 8c028c89be..b25d70f9b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -156,8 +156,6 @@ class PersistentNotificationPlugin @Inject constructor( line1aa += " " + activeTemp.toStringShort() + "." } //IOB - activePlugins.activeTreatments.updateTotalIOBTreatments() - activePlugins.activeTreatments.updateTotalIOBTempBasals() val bolusIob = activePlugins.activeTreatments.lastCalculationTreatments.round() val basalIob = activePlugins.activeTreatments.lastCalculationTempBasals.round() line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculatorPlugin.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 981141cd83..5e5e557ffb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -325,9 +325,7 @@ class SmsCommunicatorPlugin @Inject constructor( } val glucoseStatus = glucoseStatusProvider.glucoseStatusData if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " - activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() - activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "SMS COB") reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index db97d25b17..f9a90cfaa6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -685,9 +685,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog String iobSum, iobDetail, cobString, currentBasal, bgiString; iobSum = iobDetail = cobString = currentBasal = bgiString = ""; if (profile != null) { - treatmentsPlugin.updateTotalIOBTreatments(); IobTotal bolusIob = treatmentsPlugin.getLastCalculationTreatments().round(); - treatmentsPlugin.updateTotalIOBTempBasals(); IobTotal basalIob = treatmentsPlugin.getLastCalculationTempBasals().round(); iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob + basalIob.basaliob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index a705394f59..38376b363a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -132,9 +132,7 @@ class StatusLinePlugin @Inject constructor( status += activeTemp.toStringShort() + " " } //IOB - activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() - activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 8229320666..ea9f55d9b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -85,9 +85,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface protected TreatmentServiceInterface service; - private IobTotal lastTreatmentCalculation; - private IobTotal lastTempBasalsCalculation; - private final ArrayList treatments = new ArrayList<>(); private final Intervals tempBasals = new NonOverlappingIntervals<>(); private final Intervals extendedBoluses = new NonOverlappingIntervals<>(); @@ -149,7 +146,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTreatmentData"); initializeTreatmentData(range()); initializeExtendedBolusData(range()); - updateTotalIOBTreatments(); rxBus.send(event.getNext()); }, fabricPrivacy::logException @@ -166,7 +162,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .subscribe(event -> { getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTempBasalData"); initializeTempBasalData(range()); - updateTotalIOBTempBasals(); }, fabricPrivacy::logException )); @@ -230,7 +225,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public IobTotal getLastCalculationTreatments() { - return lastTreatmentCalculation; + return getCalculationToTimeTreatments(System.currentTimeMillis()); } @Override @@ -278,11 +273,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return total; } - @Override - public void updateTotalIOBTreatments() { - lastTreatmentCalculation = getCalculationToTimeTreatments(System.currentTimeMillis()); - } - @Override public List getTreatmentsFromHistory() { synchronized (treatments) { @@ -399,7 +389,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public IobTotal getLastCalculationTempBasals() { - return lastTempBasalsCalculation; + return getCalculationToTimeTempBasals(DateUtil.now()); } @Override @@ -537,11 +527,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return total; } - @Override - public void updateTotalIOBTempBasals() { - lastTempBasalsCalculation = getCalculationToTimeTempBasals(DateUtil.now()); - } - @Nullable @Override public TemporaryBasal getTempBasalFromHistory(long time) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 56c02b213a..3f166ae4a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -205,9 +205,7 @@ class BolusWizard @Inject constructor( // Insulin from IOB // IOB calculation - activePlugin.activeTreatments.updateTotalIOBTreatments() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() - activePlugin.activeTreatments.updateTotalIOBTempBasals() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0 diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index efc2a371f3..2aff9f479f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -9,7 +9,6 @@ import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin @@ -99,7 +98,6 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec bolusIOB = true } // Basal IOB - treatmentsPlugin.updateTotalIOBTempBasals() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() var basalIOB = false if (useBasalIOB() == YES) { diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index 89406a9992..a29a17884b 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -22,10 +22,6 @@ public interface TreatmentsInterface { TreatmentServiceInterface getService(); - void updateTotalIOBTreatments(); - - void updateTotalIOBTempBasals(); - IobTotal getLastCalculationTreatments(); IobTotal getCalculationToTimeTreatments(long time); From 0a61585836dba600407d91263125ce3f739d8994 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 29 Mar 2021 10:45:48 +0200 Subject: [PATCH 2/3] core.pump.common cleanup --- .../pump/common/data/TempBasalPair.java | 72 ------------- .../common/{data => defs}/DoseSettings.kt | 2 +- .../pump/common/defs/DoseStepSize.java | 100 ------------------ .../plugins/pump/common/defs/DoseStepSize.kt | 56 ++++++++++ .../pump/common/defs/PumpCapability.kt | 10 +- .../pump/common/defs/PumpDeviceState.java | 29 ----- .../pump/common/defs/PumpDriverState.java | 26 ----- .../pump/common/defs/PumpStatusType.java | 23 ---- .../pump/common/defs/PumpTempBasalType.java | 10 -- .../pump/common/defs/PumpTempBasalType.kt | 7 ++ .../plugins/pump/common/defs/PumpType.kt | 1 - .../pump/common/PumpPluginAbstract.java | 4 +- .../plugins/pump/common/data/PumpStatus.java | 0 .../pump/common/defs/PumpDriverState.kt | 14 +++ .../pump/common/defs/PumpStatusType.kt | 7 ++ .../medtronic/data/dto/TempBasalPair.java | 46 ++++---- .../omnipod/eros/OmnipodErosPumpPlugin.java | 2 +- .../eros/manager/AapsOmnipodErosManager.java | 4 +- .../eros/ui/ErosPodHistoryActivity.java | 2 +- .../eros/OmnipodErosPumpPluginTest.java | 2 +- .../pump/common/defs/PumpDeviceState.kt | 17 +++ .../common/defs/PumpHistoryEntryGroup.java | 0 .../plugins/pump/common/defs/TempBasalPair.kt | 32 ++++++ .../common/dialog/RefreshableInterface.java | 0 .../common/events/EventRefreshButtonState.kt | 0 .../plugins/pump/common/utils/ByteUtil.java | 0 .../plugins/pump/common/utils/CRC.java | 0 .../pump/common/utils/ProfileUtil.java | 0 .../plugins/pump/common/utils/StringUtil.java | 0 .../plugins/pump/common/utils/ThreadUtil.java | 0 30 files changed, 168 insertions(+), 298 deletions(-) delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java rename core/src/main/java/info/nightscout/androidaps/plugins/pump/common/{data => defs}/DoseSettings.kt (72%) delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.java create mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.java create mode 100644 core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.kt rename {core => medtronic}/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java (99%) rename {core => medtronic}/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java (100%) create mode 100644 medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.kt create mode 100644 medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.kt create mode 100644 rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.kt rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java (100%) create mode 100644 rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/TempBasalPair.kt rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RefreshableInterface.java (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRefreshButtonState.kt (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ByteUtil.java (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/CRC.java (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ProfileUtil.java (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java (100%) rename {core => rileylink}/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ThreadUtil.java (100%) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java deleted file mode 100644 index 5a1e0b4249..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/TempBasalPair.java +++ /dev/null @@ -1,72 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.data; - -import com.google.gson.annotations.Expose; - -public class TempBasalPair { - - @Expose - protected double insulinRate = 0.0d; - @Expose - protected int durationMinutes = 0; - @Expose - protected boolean isPercent = false; - - private Long start; - private Long end; - - public TempBasalPair() { - } - - - public TempBasalPair(double insulinRate, boolean isPercent, int durationMinutes) { - this.insulinRate = insulinRate; - this.isPercent = isPercent; - this.durationMinutes = durationMinutes; - } - - - public double getInsulinRate() { - return insulinRate; - } - - - public void setInsulinRate(double insulinRate) { - this.insulinRate = insulinRate; - } - - - public int getDurationMinutes() { - return durationMinutes; - } - - - public void setDurationMinutes(int durationMinutes) { - this.durationMinutes = durationMinutes; - } - - - public boolean isPercent() { - return isPercent; - } - - - public void setIsPercent(boolean yesIsPercent) { - this.isPercent = yesIsPercent; - } - - public void setStartTime(Long startTime) { - this.start = startTime; - } - - - public void setEndTime(Long endTime) { - this.end = endTime; - } - - - @Override - public String toString() { - return "TempBasalPair [" + "Rate=" + insulinRate + ", DurationMinutes=" + durationMinutes + ", IsPercent=" - + isPercent + "]"; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/DoseSettings.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseSettings.kt similarity index 72% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/DoseSettings.kt rename to core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseSettings.kt index 90e25a7e37..c1a9b18167 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/DoseSettings.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseSettings.kt @@ -1,3 +1,3 @@ -package info.nightscout.androidaps.plugins.pump.common.data +package info.nightscout.androidaps.plugins.pump.common.defs class DoseSettings constructor(val step: Double, val durationStep: Int, val maxDuration: Int, val minDose: Double, val maxDose: Double = Double.MAX_VALUE) \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.java deleted file mode 100644 index 095c11de65..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.java +++ /dev/null @@ -1,100 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -import java.util.Locale; - -/** - * Created by andy on 02/05/2018. - */ - -public enum DoseStepSize { - - ComboBasal( // - new DoseStepSizeEntry(0f, 1f, 0.01f), // - new DoseStepSizeEntry(1f, 10f, 0.05f), // - new DoseStepSizeEntry(10f, Double.MAX_VALUE, 0.1f)), // - - InsightBolus( - new DoseStepSizeEntry(0f, 2f, 0.05f), // - new DoseStepSizeEntry(2f, 5f, 0.1f), // - new DoseStepSizeEntry(5f, 10f, 0.2f), // - new DoseStepSizeEntry(10f, Double.MAX_VALUE, 0.5f)), - - InsightBasal( - new DoseStepSizeEntry(0f, 5f, 0.01f), - new DoseStepSizeEntry(5f, Double.MAX_VALUE, 0.1f)), - - MedtronicVeoBasal( // - new DoseStepSizeEntry(0f, 1f, 0.025f), // - new DoseStepSizeEntry(1f, 10f, 0.05f), // - new DoseStepSizeEntry(10f, Double.MAX_VALUE, 0.1f)), // - - YpsopumpBasal( // - new DoseStepSizeEntry(0.0f, 1f, 0.01f), // - new DoseStepSizeEntry(1f, 2f, 0.02f), // - new DoseStepSizeEntry(2f, 15f, 0.1f), // - new DoseStepSizeEntry(15f, 40f, 0.5f) - ) - ; - - - DoseStepSizeEntry[] entries; - - - DoseStepSize(DoseStepSizeEntry... entries) { - this.entries = entries; - } - - - public double getStepSizeForAmount(double amount) { - for (DoseStepSizeEntry entry : entries) { - if (entry.from <= amount && entry.to > amount) - return entry.value; - } - - // should never come to this - return entries[entries.length - 1].value; - } - - - public String getDescription() { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (DoseStepSizeEntry entry : entries) { - - if (first) { - first = false; - } else { - sb.append(", "); - } - - sb.append(String.format(Locale.ENGLISH, "%.3f", entry.value)); - sb.append(" {"); - sb.append(String.format(Locale.ENGLISH,"%.3f", entry.from)); - sb.append("-"); - - if (entry.to == Double.MAX_VALUE) { - sb.append("~}"); - } else { - sb.append(String.format(Locale.ENGLISH, "%.3f", entry.to)); - sb.append("}"); - } - } - - return sb.toString(); - } - - - static class DoseStepSizeEntry { - double from; - double to; - double value; - - // to = this value is not included, but would actually mean <, so for rates between 0.025-0.975 u/h, we would have [from=0, to=10] - DoseStepSizeEntry(double from, double to, double value) { - this.from = from; - this.to = to; - this.value = value; - } - } - -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.kt new file mode 100644 index 0000000000..179be45dc8 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/DoseStepSize.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +import java.util.* + +enum class DoseStepSize(private val entries: Array) { + + ComboBasal(arrayOf( + DoseStepSizeEntry(0.0, 1.0, 0.01), + DoseStepSizeEntry(1.0, 10.0, 0.05), + DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.1))), + InsightBolus(arrayOf( + DoseStepSizeEntry(0.0, 2.0, 0.05), + DoseStepSizeEntry(2.0, 5.0, 0.1), + DoseStepSizeEntry(5.0, 10.0, 0.2), + DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.5))), + InsightBasal(arrayOf( + DoseStepSizeEntry(0.0, 5.0, 0.01), + DoseStepSizeEntry(5.0, Double.MAX_VALUE, 0.1))), + MedtronicVeoBasal(arrayOf( + DoseStepSizeEntry(0.0, 1.0, 0.025), + DoseStepSizeEntry(1.0, 10.0, 0.05), + DoseStepSizeEntry(10.0, Double.MAX_VALUE, 0.1))), + YpsopumpBasal(arrayOf( + DoseStepSizeEntry(0.0, 1.0, 0.01), + DoseStepSizeEntry(1.0, 2.0, 0.02), + DoseStepSizeEntry(2.0, 15.0, 0.1), + DoseStepSizeEntry(15.0, 40.0, 0.5)) + ); + + fun getStepSizeForAmount(amount: Double): Double { + for (entry in entries) + if (entry.from <= amount && entry.to > amount) return entry.value + + // should never come to this + return entries[entries.size - 1].value + } + + val description: String + get() = StringBuilder().also { sb -> + var first = true + for (entry in entries) { + if (first) first = false else sb.append(", ") + + sb.append(String.format(Locale.ENGLISH, "%.3f", entry.value)) + .append(" {") + .append(String.format(Locale.ENGLISH, "%.3f", entry.from)) + .append("-") + if (entry.to == Double.MAX_VALUE) sb.append("~}") + else sb.append(String.format(Locale.ENGLISH, "%.3f", entry.to)).append("}") + } + }.toString() + + // to = this value is not included, but would actually mean <, so for rates between 0.025-0.975 u/h, we would have [from=0, to=10] + internal class DoseStepSizeEntry(var from: Double, var to: Double, var value: Double) + +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt index 5276dbabb6..b8e74bb0a6 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt @@ -1,10 +1,5 @@ package info.nightscout.androidaps.plugins.pump.common.defs -import info.nightscout.androidaps.plugins.pump.common.defs.PumpCapability - -/** - * Created by andy on 03/05/2018. - */ enum class PumpCapability { Bolus, // isBolusCapable @@ -35,7 +30,10 @@ enum class PumpCapability { var children: ArrayList = ArrayList() - constructor() { children.add(this)} + constructor() { + children.add(this) + } + constructor(list: Array) { children.addAll(list) } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.java deleted file mode 100644 index 4a9814c490..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.java +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -import info.nightscout.androidaps.core.R; - -/** - * Created by andy on 6/11/18. - */ -public enum PumpDeviceState { - - NeverContacted(R.string.pump_status_never_contacted), // - Sleeping(R.string.pump_status_sleeping), // - WakingUp(R.string.pump_status_waking_up), // - Active(R.string.pump_status_active), // - ErrorWhenCommunicating(R.string.pump_status_error_comm), // - TimeoutWhenCommunicating(R.string.pump_status_timeout_comm), // - // ProblemContacting(R.string.medtronic_pump_status_problem_contacting), // - PumpUnreachable(R.string.pump_status_pump_unreachable), // - InvalidConfiguration(R.string.pump_status_invalid_config); - - Integer resourceId; - - PumpDeviceState(int resourceId) { - this.resourceId = resourceId; - } - - public Integer getResourceId() { - return resourceId; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.java deleted file mode 100644 index 460c8dd3db..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.java +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -/** - * Created by andy on 10/15/18. - */ - -public enum PumpDriverState { - - NotInitialized, // - Connecting, // - Connected, // - Initialized, // - Ready, - Busy, // - Suspended, // - ; - - public static boolean isConnected(PumpDriverState pumpState) { - return pumpState == Connected || pumpState == Initialized || pumpState == Busy || pumpState == Suspended; - } - - - public static boolean isInitialized(PumpDriverState pumpState) { - return pumpState == Initialized || pumpState == Busy || pumpState == Suspended; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.java deleted file mode 100644 index d32d6bb57f..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.java +++ /dev/null @@ -1,23 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -/** - * Created by andy on 5/12/18. - */ - -public enum PumpStatusType { - Running("normal"), // - Suspended("suspended") // - ; - - private final String statusString; - - - PumpStatusType(String statusString) { - this.statusString = statusString; - } - - - public String getStatus() { - return statusString; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.java deleted file mode 100644 index 90304ca45f..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -/** - * Created by andy on 02/05/2018. - */ - -public enum PumpTempBasalType { - Percent, // - Absolute, -} diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.kt new file mode 100644 index 0000000000..20003df6ef --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpTempBasalType.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +enum class PumpTempBasalType { + + Percent, + Absolute +} \ No newline at end of file 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 b00427a8fe..d372c84c6b 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 @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.common.defs import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.plugins.common.ManufacturerType -import info.nightscout.androidaps.plugins.pump.common.data.DoseSettings import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlin.math.min diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java similarity index 99% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java rename to medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index ad817d39f6..4245533ede 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -157,7 +157,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public boolean isInitialized() { - return PumpDriverState.isInitialized(pumpState); + return pumpState.isInitialized(); } @@ -174,7 +174,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI public boolean isConnected() { if (displayConnectionMessages) aapsLogger.debug(LTag.PUMP, "isConnected [PumpPluginAbstract]."); - return PumpDriverState.isConnected(pumpState); + return pumpState.isConnected(); } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java rename to medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.kt new file mode 100644 index 0000000000..f72163ce92 --- /dev/null +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDriverState.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +enum class PumpDriverState { + + NotInitialized, + Connecting, + Connected, + Initialized, + Ready, Busy, + Suspended; + + fun isConnected(): Boolean = this == Connected || this == Initialized || this == Busy || this == Suspended + fun isInitialized(): Boolean = this == Initialized || this == Busy || this == Suspended +} \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.kt new file mode 100644 index 0000000000..8a6c1a6a9a --- /dev/null +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpStatusType.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +enum class PumpStatusType(val status: String) { + + Running("normal"), + Suspended("suspended"); +} \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java index d6399beafd..418770d4b6 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; *

* Just need a class to keep the pair together, for parcel transport. */ -public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair { +public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair { /** * This constructor is for use with PumpHistoryDecoder @@ -30,11 +30,11 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo int rateInt = ByteUtil.asUINT8(rateByte); if (isPercent) - this.insulinRate = rateByte; + this.setInsulinRate(rateByte); else - this.insulinRate = rateInt * 0.025; - this.durationMinutes = startTimeByte * 30; - this.isPercent = isPercent; + this.setInsulinRate(rateInt * 0.025); + this.setDurationMinutes(startTimeByte * 30); + this.setPercent(isPercent); } @@ -47,12 +47,12 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo */ public TempBasalPair(byte rateByte0, byte rateByte1, int startTimeByte, boolean isPercent) { if (isPercent) { - this.insulinRate = rateByte0; + this.setInsulinRate(rateByte0); } else { - this.insulinRate = ByteUtil.toInt(rateByte1, rateByte0) * 0.025; + this.setInsulinRate(ByteUtil.toInt(rateByte1, rateByte0) * 0.025); } - this.durationMinutes = startTimeByte * 30; - this.isPercent = isPercent; + this.setDurationMinutes(startTimeByte * 30); + this.setPercent(isPercent); } public TempBasalPair(AAPSLogger aapsLogger, byte[] response) { @@ -60,20 +60,20 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); - isPercent = response[0] == 1; + setPercent(response[0] == 1); - if (isPercent) { - insulinRate = response[1]; + if (isPercent()) { + setInsulinRate(response[1]); } else { int strokes = MedtronicUtil.makeUnsignedShort(response[2], response[3]); - insulinRate = strokes / 40.0d; + setInsulinRate(strokes / 40.0d); } if (response.length < 6) { - durationMinutes = ByteUtil.asUINT8(response[4]); + setDurationMinutes(ByteUtil.asUINT8(response[4])); } else { - durationMinutes = MedtronicUtil.makeUnsignedShort(response[4], response[5]); + setDurationMinutes(MedtronicUtil.makeUnsignedShort(response[4], response[5])); } aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "TempBasalPair (with %d byte response): %s", response.length, toString())); @@ -92,8 +92,8 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo list.add((byte) 5); - byte[] insulinRate = MedtronicUtil.getBasalStrokes(this.insulinRate, true); - byte timeMin = (byte) MedtronicUtil.getIntervalFromMinutes(durationMinutes); + byte[] insulinRate = MedtronicUtil.getBasalStrokes(this.getInsulinRate(), true); + byte timeMin = (byte) MedtronicUtil.getIntervalFromMinutes(getDurationMinutes()); // list.add((byte) 0); // ? @@ -120,7 +120,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo } public boolean isCancelTBR() { - return (MedtronicUtil.isSame(insulinRate, 0.0d) && durationMinutes == 0); + return (MedtronicUtil.isSame(getInsulinRate(), 0.0d) && getDurationMinutes() == 0); } @@ -129,17 +129,17 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo return "Cancel TBR"; } - if (isPercent) { - return String.format(Locale.ENGLISH, "Rate: %.0f%%, Duration: %d min", insulinRate, durationMinutes); + if (isPercent()) { + return String.format(Locale.ENGLISH, "Rate: %.0f%%, Duration: %d min", getInsulinRate(), getDurationMinutes()); } else { - return String.format(Locale.ENGLISH, "Rate: %.3f U, Duration: %d min", insulinRate, durationMinutes); + return String.format(Locale.ENGLISH, "Rate: %.3f U, Duration: %d min", getInsulinRate(), getDurationMinutes()); } } @NonNull @Override public String toString() { - return "TempBasalPair [" + "Rate=" + insulinRate + ", DurationMinutes=" + durationMinutes + ", IsPercent=" - + isPercent + "]"; + return "TempBasalPair [" + "Rate=" + getInsulinRate() + ", DurationMinutes=" + getDurationMinutes() + ", IsPercent=" + + isPercent() + "]"; } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index 9792bc74ff..76e8237589 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -57,7 +57,7 @@ import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java index e797b78551..da38299c6c 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java @@ -33,7 +33,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNo import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType; @@ -476,7 +476,7 @@ public class AapsOmnipodErosManager { return new PumpEnactResult(injector).success(false).enacted(false).comment(comment); } - public PumpEnactResult setTemporaryBasal(TempBasalPair tempBasalPair) { + public PumpEnactResult setTemporaryBasal(TempBasalPair tempBasalPair) { boolean beepsEnabled = isTbrBeepsEnabled(); try { executeCommand(() -> delegate.setTemporaryBasal(PumpType.OMNIPOD_EROS.determineCorrectBasalSize(tempBasalPair.getInsulinRate()), Duration.standardMinutes(tempBasalPair.getDurationMinutes()), beepsEnabled, beepsEnabled)); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java index 3e55a2bf12..9ec2a3685a 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java @@ -29,7 +29,7 @@ import info.nightscout.androidaps.db.OmnipodHistoryRecord; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.utils.ProfileUtil; diff --git a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.java b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.java index ffe2160f06..4ee2afab5e 100644 --- a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.java +++ b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLoggerTest; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager; diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.kt new file mode 100644 index 0000000000..b41a6bd4c1 --- /dev/null +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpDeviceState.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +import info.nightscout.androidaps.core.R + +enum class PumpDeviceState(var resourceId: Int) { + + NeverContacted(R.string.pump_status_never_contacted), + Sleeping(R.string.pump_status_sleeping), + WakingUp(R.string.pump_status_waking_up), + Active(R.string.pump_status_active), + ErrorWhenCommunicating(R.string.pump_status_error_comm), + TimeoutWhenCommunicating(R.string.pump_status_timeout_comm), + + // ProblemContacting(R.string.medtronic_pump_status_problem_contacting), + PumpUnreachable(R.string.pump_status_pump_unreachable), + InvalidConfiguration(R.string.pump_status_invalid_config); +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/TempBasalPair.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/TempBasalPair.kt new file mode 100644 index 0000000000..320be53927 --- /dev/null +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/TempBasalPair.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.common.defs + +import com.google.gson.annotations.Expose + +open class TempBasalPair { + + @Expose var insulinRate = 0.0 + @Expose var durationMinutes = 0 + @Expose var isPercent = false + private var start: Long? = null + private var end: Long? = null + + constructor() + constructor(insulinRate: Double, isPercent: Boolean, durationMinutes: Int) { + this.insulinRate = insulinRate + this.isPercent = isPercent + this.durationMinutes = durationMinutes + } + + fun setStartTime(startTime: Long?) { + start = startTime + } + + fun setEndTime(endTime: Long?) { + end = endTime + } + + override fun toString(): String { + return ("TempBasalPair [" + "Rate=" + insulinRate + ", DurationMinutes=" + durationMinutes + ", IsPercent=" + + isPercent + "]") + } +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RefreshableInterface.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RefreshableInterface.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RefreshableInterface.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RefreshableInterface.java diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRefreshButtonState.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRefreshButtonState.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRefreshButtonState.kt rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRefreshButtonState.kt diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ByteUtil.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ByteUtil.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ByteUtil.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ByteUtil.java diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/CRC.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/CRC.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/CRC.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/CRC.java diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ProfileUtil.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ProfileUtil.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ProfileUtil.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ProfileUtil.java diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ThreadUtil.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ThreadUtil.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ThreadUtil.java rename to rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/ThreadUtil.java From cb298a2646f921d38f7b5d5ab67aafdfe4bd38bc Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 29 Mar 2021 19:15:46 +0200 Subject: [PATCH 3/3] eliminate treatments cache from TreatmentsPlugin --- .../dependencyInjection/AppModule.kt | 2 +- .../androidaps/dialogs/TreatmentDialog.kt | 22 ++-- .../androidaps/dialogs/WizardDialog.kt | 16 +-- .../openAPSAMA/DetermineBasalAdapterAMAJS.kt | 1 - .../aps/openAPSAMA/OpenAPSAMAPlugin.kt | 10 +- .../openAPSSMB/DetermineBasalAdapterSMBJS.kt | 1 - .../aps/openAPSSMB/OpenAPSSMBPlugin.kt | 10 +- .../dataBroadcaster/DataBroadcastPlugin.kt | 15 +-- .../general/overview/OverviewFragment.kt | 4 +- .../general/overview/graphData/GraphData.kt | 68 +++++------ .../PersistentNotificationPlugin.kt | 10 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 12 +- .../wearintegration/WatchUpdaterService.java | 30 +++-- .../xdripStatusline/StatusLinePlugin.kt | 16 +-- .../IobCobCalculatorPlugin.kt | 107 ++++++++++-------- .../iob/iobCobCalculator/IobCobOref1Thread.kt | 8 +- .../iob/iobCobCalculator/IobCobThread.kt | 12 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 12 +- .../sensitivity/AbstractSensitivityPlugin.kt | 4 +- .../sensitivity/SensitivityAAPSPlugin.kt | 4 +- .../sensitivity/SensitivityOref1Plugin.kt | 4 +- .../SensitivityWeightedAveragePlugin.kt | 4 +- .../plugins/treatments/TreatmentsPlugin.java | 88 ++++---------- .../androidaps/queue/CommandQueue.kt | 6 +- .../utils/extensions/GlucoseValueUtils.kt | 13 --- .../androidaps/utils/stats/TddCalculator.kt | 17 +-- .../androidaps/utils/wizard/BolusWizard.kt | 7 +- .../interfaces/ConstraintsCheckerTest.kt | 14 +-- .../plugins/aps/loop/LoopPluginTest.kt | 5 + .../constraints/safety/SafetyPluginTest.kt | 6 +- .../SmsCommunicatorPluginTest.kt | 22 ++-- .../pump/virtual/VirtualPumpPluginUTest.kt | 4 +- .../AbstractSensitivityPluginTest.kt | 4 +- .../plugins/source/GlimpPluginTest.kt | 6 +- .../plugins/source/MM640GPluginTest.kt | 5 +- .../androidaps/queue/CommandQueueTest.kt | 17 +-- .../androidaps/queue/QueueThreadTest.kt | 8 +- .../utils/wizard/BolusWizardTest.kt | 31 +++-- .../general/automation/triggers/Trigger.kt | 4 +- .../actions/ActionNotificationTest.kt | 5 +- .../automation/actions/ActionsTestBase.kt | 6 +- .../automation/triggers/TriggerBgTest.kt | 2 +- .../automation/triggers/TriggerDeltaTest.kt | 2 +- .../automation/triggers/TriggerTestBase.kt | 8 +- .../androidaps/data/BolusDataPoint.kt | 41 +++++++ .../androidaps/data/CarbsDataPoint.kt | 32 ++++++ .../nightscout/androidaps/data/MealData.kt | 1 - .../nightscout/androidaps/db/Treatment.java | 15 ++- .../androidaps/interfaces/IobCobCalculator.kt | 75 ++++++++++++ .../interfaces/IobCobCalculatorInterface.kt | 22 ---- .../interfaces/SensitivityInterface.kt | 3 +- .../interfaces/TreatmentsInterface.java | 9 +- .../configBuilder/ConstraintChecker.kt | 2 +- .../plugins/general/nsclient/NSUpload.java | 13 +-- .../plugins/iob/iobCobCalculator/BasalData.kt | 0 .../iobCobCalculator/GlucoseStatusProvider.kt | 8 +- .../iobCobCalculator/data/AutosensData.java | 19 ++-- .../receivers/ReceiverStatusStore.kt | 2 +- .../utils/extensions/GlucoseValueExtension.kt | 10 ++ .../androidaps/data/DetailedBolusInfoTest.kt | 13 ++- .../androidaps/data/MealDataTest.kt | 2 +- .../iob/iobCalculator/GlucoseStatusTest.kt | 6 +- .../plugins/pump/danaR/comm/DanaRTestBase.kt | 4 +- .../comm/DanaRsPacketNotifyAlarmTest.kt | 7 +- .../androidaps/database/AppRepository.kt | 26 +++++ .../androidaps/database/daos/BolusDao.kt | 9 ++ .../androidaps/database/daos/CarbsDao.kt | 9 ++ 67 files changed, 545 insertions(+), 435 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueUtils.kt create mode 100644 core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt create mode 100644 core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt create mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculatorInterface.kt rename {app => core}/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/BasalData.kt (100%) 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 a152186ced..2612c101ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -85,7 +85,7 @@ open class AppModule { @Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefs): ImportExportPrefsInterface @Binds fun bindIconsProviderInterface(iconsProvider: IconsProvider): IconsProviderInterface @Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface - @Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculatorInterface + @Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculator @Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicatorInterface @Binds fun bindUploadQueueAdminInterfaceToUploadQueue(uploadQueueAdminInterface: UploadQueueAdminInterface) : UploadQueueInterface @Binds fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index a59a9e5ac2..184bd9e4b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -151,16 +151,18 @@ class TreatmentDialog : DialogFragmentWithDate() { ValueWithUnit(carbs, Units.G, carbs != 0) ) if (recordOnlyChecked) { - disposable += repository.runTransactionForResult(detailedBolusInfo.insertBolusTransaction()) - .subscribe( - { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted bolus $it") } }, - { aapsLogger.error(LTag.DATABASE, "Error while saving bolus", it) } - ) - disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) - .subscribe( - { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } }, - { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } - ) + if (detailedBolusInfo.insulin > 0) + disposable += repository.runTransactionForResult(detailedBolusInfo.insertBolusTransaction()) + .subscribe( + { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted bolus $it") } }, + { aapsLogger.error(LTag.DATABASE, "Error while saving bolus", it) } + ) + if (detailedBolusInfo.carbs > 0) + disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) + .subscribe( + { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } }, + { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } + ) } else { commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 176136a67a..0d69487179 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -25,13 +25,13 @@ import info.nightscout.androidaps.databinding.DialogWizardBinding import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy @@ -62,7 +62,7 @@ class WizardDialog : DaggerDialogFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePluginProvider - @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var repository: AppRepository @Inject lateinit var treatmentsPlugin: TreatmentsInterface @Inject lateinit var dateUtil: DateUtil @@ -269,17 +269,11 @@ class WizardDialog : DaggerDialogFragment() { binding.bgInput.setStep(0.1) // Set BG if not old - val lastBg = iobCobCalculatorPlugin.actualBg() - - if (lastBg != null) { - binding.bgInput.value = lastBg.valueToUnits(units) - } else { - binding.bgInput.value = 0.0 - } + binding.bgInput.value = iobCobCalculator.actualBg()?.valueToUnits(units) ?: 0.0 binding.ttcheckbox.isEnabled = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing // IOB calculation - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob) @@ -322,7 +316,7 @@ class WizardDialog : DaggerDialogFragment() { // COB var cob = 0.0 if (binding.cobcheckbox.isChecked) { - val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "Wizard COB") + val cobInfo = iobCobCalculator.getCobInfo(false, "Wizard COB") cobInfo.displayCob?.let { cob = it } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt index a2334030ea..1b186bd887 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt @@ -206,7 +206,6 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader this.glucoseStatus.put("long_avgdelta", glucoseStatus.longAvgDelta) this.mealData = JSONObject() this.mealData.put("carbs", mealData.carbs) - this.mealData.put("boluses", mealData.boluses) this.mealData.put("mealCOB", mealData.mealCOB) if (constraintChecker.isAutosensModeEnabled().value()) { autosensData.put("ratio", autosensDataRatio) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index 0847f100ac..e0e3ed1f71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -15,9 +15,7 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits @@ -40,7 +38,7 @@ open class OpenAPSAMAPlugin @Inject constructor( private val context: Context, private val activePlugin: ActivePluginProvider, private val treatmentsPlugin: TreatmentsInterface, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val hardLimits: HardLimits, private val profiler: Profiler, private val fabricPrivacy: FabricPrivacy, @@ -107,10 +105,10 @@ open class OpenAPSAMAPlugin @Inject constructor( }.value() var start = System.currentTimeMillis() var startPart = System.currentTimeMillis() - val iobArray = iobCobCalculatorPlugin.calculateIobArrayInDia(profile) + val iobArray = iobCobCalculator.calculateIobArrayInDia(profile) profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart) startPart = System.currentTimeMillis() - val mealData = iobCobCalculatorPlugin.mealData + val mealData = iobCobCalculator.mealData profiler.log(LTag.APS, "getMealData()", startPart) val maxIob = constraintChecker.getMaxIOBAllowed().also { maxIOBAllowedConstraint -> inputConstraints.copyReasons(maxIOBAllowedConstraint) @@ -133,7 +131,7 @@ open class OpenAPSAMAPlugin @Inject constructor( if (!hardLimits.checkOnlyHardLimits(pump.baseBasalRate, R.string.current_basal_value, 0.01, hardLimits.maxBasal())) return startPart = System.currentTimeMillis() if (constraintChecker.isAutosensModeEnabled().value()) { - val autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("OpenAPSPlugin") + val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("OpenAPSPlugin") if (autosensData == null) { rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) return diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index a980bb1bd4..efc47a50cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -249,7 +249,6 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader: mGlucoseStatus.put("long_avgdelta", glucoseStatus.longAvgDelta) mGlucoseStatus.put("date", glucoseStatus.date) this.mealData.put("carbs", mealData.carbs) - this.mealData.put("boluses", mealData.boluses) this.mealData.put("mealCOB", mealData.mealCOB) this.mealData.put("slopeFromMaxDeviation", mealData.slopeFromMaxDeviation) this.mealData.put("slopeFromMinDeviation", mealData.slopeFromMinDeviation) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 29d071867d..fe8314dcb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -17,9 +17,7 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Profiler @@ -41,7 +39,7 @@ open class OpenAPSSMBPlugin @Inject constructor( private val context: Context, private val activePlugin: ActivePluginProvider, private val treatmentsPlugin: TreatmentsInterface, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val hardLimits: HardLimits, private val profiler: Profiler, private val sp: SP, @@ -139,7 +137,7 @@ open class OpenAPSSMBPlugin @Inject constructor( if (!hardLimits.checkOnlyHardLimits(pump.baseBasalRate, R.string.current_basal_value, 0.01, hardLimits.maxBasal())) return startPart = System.currentTimeMillis() if (constraintChecker.isAutosensModeEnabled().value()) { - val autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("OpenAPSPlugin") + val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("OpenAPSPlugin") if (autosensData == null) { rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) return @@ -148,7 +146,7 @@ open class OpenAPSSMBPlugin @Inject constructor( } else { lastAutosensResult.sensResult = "autosens disabled" } - val iobArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) + val iobArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart) startPart = System.currentTimeMillis() val smbAllowed = Constraint(!tempBasalFallback).also { @@ -172,7 +170,7 @@ open class OpenAPSSMBPlugin @Inject constructor( activePlugin.activePump.baseBasalRate, iobArray, glucoseStatus, - iobCobCalculatorPlugin.mealData, + iobCobCalculator.mealData, lastAutosensResult.ratio, isTempTarget, smbAllowed.value(), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 4d1665d19b..8df0e83091 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -9,11 +9,7 @@ import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.events.* -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui @@ -22,7 +18,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.utils.DefaultValueHelper @@ -42,7 +37,7 @@ class DataBroadcastPlugin @Inject constructor( private val context: Context, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBusWrapper, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val profileFunction: ProfileFunction, private val defaultValueHelper: DefaultValueHelper, private val nsDeviceStatus: NSDeviceStatus, @@ -121,7 +116,7 @@ class DataBroadcastPlugin @Inject constructor( } private fun bgStatus(bundle: Bundle) { - val lastBG = iobCobCalculatorPlugin.lastBg() ?: return + val lastBG = iobCobCalculator.lastBg() ?: return val glucoseStatus = glucoseStatusProvider.glucoseStatusData ?: return bundle.putDouble("glucoseMgdl", lastBG.value) // last BG in mgdl @@ -136,13 +131,13 @@ class DataBroadcastPlugin @Inject constructor( private fun iobCob(bundle: Bundle) { profileFunction.getProfile() ?: return - val bolusIob: IobTotal = activePlugin.activeTreatments.lastCalculationTreatments.round() + val bolusIob: IobTotal = iobCobCalculator.calculateIobFromBolus().round() val basalIob: IobTotal = activePlugin.activeTreatments.lastCalculationTempBasals.round() bundle.putDouble("bolusIob", bolusIob.iob) bundle.putDouble("basalIob", basalIob.basaliob) bundle.putDouble("iob", bolusIob.iob + basalIob.basaliob) // total IOB - val cob = iobCobCalculatorPlugin.getCobInfo(false, "broadcast") + val cob = iobCobCalculator.getCobInfo(false, "broadcast") bundle.putDouble("cob", cob.displayCob ?: -1.0) // COB [g] or -1 if N/A bundle.putDouble("futureCarbs", cob.futureCarbs) // future scheduled carbs } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index bc0187e98c..c3a02a250b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -100,7 +100,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculator @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var dexcomMediator: DexcomPlugin.DexcomMediator @Inject lateinit var xdripPlugin: XdripPlugin @@ -749,7 +749,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList processButtonsVisibility() // iob - val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() + val bolusIob = iobCobCalculatorPlugin.calculateIobFromBolus().round() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() binding.infoLayout.iob.text = resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) 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 4f7c34f43f..f42f8da7d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -11,27 +11,22 @@ import com.jjoe64.graphview.series.Series import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.data.GlucoseValueDataPoint -import info.nightscout.androidaps.data.IobTotal -import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.data.TherapyEventDataPoint +import info.nightscout.androidaps.data.* import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.GlucoseValue -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface -import info.nightscout.androidaps.interfaces.LoopInterface -import info.nightscout.androidaps.interfaces.ProfileFunction -import info.nightscout.androidaps.interfaces.TreatmentsInterface +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.general.overview.graphExtensions.* import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.Round +import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.extensions.target import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* @@ -43,7 +38,7 @@ import kotlin.math.min class GraphData( private val injector: HasAndroidInjector, private val graph: GraphView, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val treatmentsPlugin: TreatmentsInterface ) { @@ -55,6 +50,7 @@ class GraphData( @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var defaultValueHelper: DefaultValueHelper var maxY = Double.MIN_VALUE private var minY = Double.MAX_VALUE @@ -70,7 +66,7 @@ class GraphData( @Suppress("UNUSED_PARAMETER") fun addBgReadings(fromTime: Long, toTime: Long, lowLine: Double, highLine: Double, predictions: MutableList?) { var maxBgValue = Double.MIN_VALUE - bgReadingsArray = iobCobCalculatorPlugin.bgReadings + bgReadingsArray = iobCobCalculator.bgReadings if (bgReadingsArray?.isEmpty() != false) { aapsLogger.debug("No BG data.") maxY = if (units == Constants.MGDL) 180.0 else 10.0 @@ -134,7 +130,7 @@ class GraphData( time += 60 * 1000L continue } - val basalData = iobCobCalculatorPlugin.getBasalData(profile, time) + val basalData = iobCobCalculator.getBasalData(profile, time) val baseBasalValue = basalData.basal var absoluteLineValue = baseBasalValue var tempBasalValue = 0.0 @@ -244,9 +240,15 @@ class GraphData( fun addTreatments(fromTime: Long, endTime: Long) { val filteredTreatments: MutableList = ArrayList() - treatmentsPlugin.treatmentsFromHistory - .filterTimeframe(fromTime, endTime) - .filter { !it.isSMB || it.isValid } + repository.getBolusesIncludingInvalidFromTimeToTime(fromTime, endTime, true).blockingGet() + .map { BolusDataPoint(it, resourceHelper, activePlugin, defaultValueHelper) } + .filter { it.data.type != Bolus.Type.SMB || it.data.isValid } + .forEach { + it.y = getNearestBg(it.x.toLong()) + filteredTreatments.add(it) + } + repository.getCarbsIncludingInvalidFromTimeToTime(fromTime, endTime, true).blockingGet() + .map { CarbsDataPoint(it, resourceHelper) } .forEach { it.y = getNearestBg(it.x.toLong()) filteredTreatments.add(it) @@ -270,7 +272,7 @@ class GraphData( // Careportal // databaseHelper.getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true) - repository.compatGetTherapyEventDataFromToTime(fromTime - 6 * 60 * 60 * 1000, endTime).blockingGet() + repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() .map { TherapyEventDataPoint(injector, it) } .filterTimeframe(fromTime, endTime) .forEach { @@ -312,7 +314,7 @@ class GraphData( time += 5 * 60 * 1000L continue } - total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile) + total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile) val act: Double = total.activity if (time <= now) actArrayHist.add(ScaledDataPoint(time, act, actScale)) else actArrayPrediction.add(ScaledDataPoint(time, act, actScale)) maxIAValue = max(maxIAValue, abs(act)) @@ -353,10 +355,10 @@ class GraphData( time += 5 * 60 * 1000L continue } - val deviation = if (devBgiScale) iobCobCalculatorPlugin.getAutosensData(time)?.deviation + val deviation = if (devBgiScale) iobCobCalculator.getAutosensData(time)?.deviation ?: 0.0 else 0.0 - total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile) + total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile) val bgi: Double = total.activity * profile.getIsfMgdl(time) * 5.0 if (time <= now) bgiArrayHist.add(ScaledDataPoint(time, bgi, bgiScale)) else bgiArrayPrediction.add(ScaledDataPoint(time, bgi, bgiScale)) maxBGIValue = max(maxBGIValue, max(abs(bgi), deviation)) @@ -395,8 +397,8 @@ class GraphData( var iob = 0.0 var absIob = 0.0 if (profile != null) { - iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob - if (absScale) absIob = iobCobCalculatorPlugin.calculateAbsInsulinFromTreatmentsAndTempsSynchronized(time).iob + iob = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob + if (absScale) absIob = iobCobCalculator.calculateAbsInsulinFromTreatmentsAndTempsSynchronized(time).iob } if (abs(lastIob - iob) > 0.02) { if (abs(lastIob - iob) > 0.2) iobArray.add(ScaledDataPoint(time, lastIob, iobScale)) @@ -413,25 +415,25 @@ class GraphData( it.thickness = 3 } if (showPrediction) { - val autosensData = iobCobCalculatorPlugin.getLastAutosensDataSynchronized("GraphData") + val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("GraphData") val lastAutosensResult = autosensData?.autosensResult ?: AutosensResult() val isTempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing val iobPrediction: MutableList = ArrayList() - val iobPredictionArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) + val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) for (i in iobPredictionArray) { iobPrediction.add(i.setColor(resourceHelper.gc(R.color.iobPredAS))) maxIobValueFound = max(maxIobValueFound, abs(i.iob)) } addSeries(PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] })) val iobPrediction2: MutableList = ArrayList() - val iobPredictionArray2 = iobCobCalculatorPlugin.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) + val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) for (i in iobPredictionArray2) { iobPrediction2.add(i.setColor(resourceHelper.gc(R.color.iobPred))) maxIobValueFound = max(maxIobValueFound, abs(i.iob)) } addSeries(PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] })) - aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + DecimalFormatter.to2Decimal(lastAutosensResult.ratio) + ": " + iobCobCalculatorPlugin.iobArrayToString(iobPredictionArray)) - aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + DecimalFormatter.to2Decimal(1.0) + ": " + iobCobCalculatorPlugin.iobArrayToString(iobPredictionArray2)) + aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + DecimalFormatter.to2Decimal(lastAutosensResult.ratio) + ": " + iobCobCalculator.iobArrayToString(iobPredictionArray)) + aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + DecimalFormatter.to2Decimal(1.0) + ": " + iobCobCalculator.iobArrayToString(iobPredictionArray2)) } if (useForScale) { maxY = maxIobValueFound @@ -452,7 +454,7 @@ class GraphData( while (time <= toTime) { val profile = profileFunction.getProfile(time) var iob = 0.0 - if (profile != null) iob = iobCobCalculatorPlugin.calculateAbsInsulinFromTreatmentsAndTempsSynchronized(time).iob + if (profile != null) iob = iobCobCalculator.calculateAbsInsulinFromTreatmentsAndTempsSynchronized(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)) @@ -484,7 +486,7 @@ class GraphData( val cobScale = Scale() var time = fromTime while (time <= toTime) { - iobCobCalculatorPlugin.getAutosensData(time)?.let { autosensData -> + iobCobCalculator.getAutosensData(time)?.let { autosensData -> val cob = autosensData.cob.toInt() if (cob != lastCob) { if (autosensData.carbsFromBolus > 0) cobArray.add(ScaledDataPoint(time, lastCob.toDouble(), cobScale)) @@ -530,11 +532,11 @@ class GraphData( // if align Dev Scale with BGI scale, then calculate BGI value, else bgi = 0.0 val bgi: Double = if (devBgiScale) { val profile = profileFunction.getProfile(time) - total = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile) + total = iobCobCalculator.calculateFromTreatmentsAndTempsSynchronized(time, profile) total.activity * (profile?.getIsfMgdl(time) ?: 0.0) * 5.0 } else 0.0 - iobCobCalculatorPlugin.getAutosensData(time)?.let { autosensData -> + iobCobCalculator.getAutosensData(time)?.let { autosensData -> var color = resourceHelper.gc(R.color.deviationblack) // "=" if (autosensData.type == "" || autosensData.type == "non-meal") { if (autosensData.pastSensitivity == "C") color = resourceHelper.gc(R.color.deviationgrey) @@ -570,7 +572,7 @@ class GraphData( val ratioScale = Scale() var time = fromTime while (time <= toTime) { - iobCobCalculatorPlugin.getAutosensData(time)?.let { autosensData -> + iobCobCalculator.getAutosensData(time)?.let { autosensData -> ratioArray.add(ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale)) maxRatioValueFound = max(maxRatioValueFound, autosensData.autosensResult.ratio - 1) minRatioValueFound = min(minRatioValueFound, autosensData.autosensResult.ratio - 1) @@ -600,7 +602,7 @@ class GraphData( val dsMinScale = Scale() var time = fromTime while (time <= toTime) { - iobCobCalculatorPlugin.getAutosensData(time)?.let { autosensData -> + iobCobCalculator.getAutosensData(time)?.let { autosensData -> dsMaxArray.add(ScaledDataPoint(time, autosensData.slopeFromMaxDeviation, dsMaxScale)) dsMinArray.add(ScaledDataPoint(time, autosensData.slopeFromMinDeviation, dsMinScale)) maxFromMaxValueFound = max(maxFromMaxValueFound, abs(autosensData.slopeFromMaxDeviation)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index b25d70f9b4..781c1b82c7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -38,7 +38,7 @@ class PersistentNotificationPlugin @Inject constructor( private val profileFunction: ProfileFunction, private val fabricPrivacy: FabricPrivacy, private val activePlugins: ActivePluginProvider, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val rxBus: RxBusWrapper, private val context: Context, private val notificationHolder: NotificationHolderInterface, @@ -131,7 +131,7 @@ class PersistentNotificationPlugin @Inject constructor( if (profileFunction.isProfileValid("Notification")) { var line1aa: String val units = profileFunction.getUnits() - val lastBG = iobCobCalculatorPlugin.lastBg() + val lastBG = iobCobCalculator.lastBg() val glucoseStatus = glucoseStatusProvider.glucoseStatusData if (lastBG != null) { line1aa = lastBG.valueToUnitsString(units) @@ -156,10 +156,10 @@ class PersistentNotificationPlugin @Inject constructor( line1aa += " " + activeTemp.toStringShort() + "." } //IOB - val bolusIob = activePlugins.activeTreatments.lastCalculationTreatments.round() + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = activePlugins.activeTreatments.lastCalculationTempBasals.round() - line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculatorPlugin.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() - val line2aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculatorPlugin.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "." + line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + val line2aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "." line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" var line3aa = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h." line3 += " - " + profileFunction.getProfileName() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 5e5e557ffb..72bdabc0fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -31,14 +31,12 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.* @@ -72,7 +70,7 @@ class SmsCommunicatorPlugin @Inject constructor( private val activePlugin: ActivePluginProvider, private val commandQueue: CommandQueueProvider, private val loopPlugin: LoopPlugin, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val xdripCalibrations: XdripCalibrations, private var otp: OneTimePassword, private val config: Config, @@ -312,8 +310,8 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun processBG(receivedSms: Sms) { - val actualBG = iobCobCalculatorPlugin.actualBg() - val lastBG = iobCobCalculatorPlugin.lastBg() + val actualBG = iobCobCalculator.actualBg() + val lastBG = iobCobCalculator.lastBg() var reply = "" val units = profileFunction.getUnits() if (actualBG != null) { @@ -325,9 +323,9 @@ class SmsCommunicatorPlugin @Inject constructor( } val glucoseStatus = glucoseStatusProvider.glucoseStatusData if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " - val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() - val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "SMS COB") + val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB") reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + resourceHelper.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index f9a90cfaa6..b5d53cc808 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -28,7 +28,6 @@ import java.util.Set; import javax.inject.Inject; import dagger.android.AndroidInjection; -import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; @@ -36,10 +35,11 @@ import info.nightscout.androidaps.data.GlucoseValueDataPoint; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.database.AppRepository; +import info.nightscout.androidaps.database.entities.Bolus; import info.nightscout.androidaps.database.entities.GlucoseValue; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.IobCobCalculator; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.logging.AAPSLogger; @@ -52,13 +52,12 @@ import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAc import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DefaultValueHelper; import info.nightscout.androidaps.utils.ToastUtils; -import info.nightscout.androidaps.utils.extensions.GlucoseValueUtilsKt; +import info.nightscout.androidaps.utils.extensions.GlucoseValueExtensionKt; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -74,7 +73,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog @Inject public NSDeviceStatus nsDeviceStatus; @Inject public ActivePluginProvider activePlugin; @Inject public LoopPlugin loopPlugin; - @Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin; + @Inject public IobCobCalculator iobCobCalculator; @Inject public TreatmentsPlugin treatmentsPlugin; @Inject public AppRepository repository; @Inject ReceiverStatusStore receiverStatusStore; @@ -280,7 +279,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private void sendData() { - GlucoseValue lastBG = iobCobCalculatorPlugin.lastBg(); + GlucoseValue lastBG = iobCobCalculator.lastBg(); // Log.d(TAG, logPrefix + "LastBg=" + lastBG); if (lastBG != null) { GlucoseStatus glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(); @@ -314,7 +313,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } DataMap dataMap = new DataMap(); - dataMap.putString("sgvString", GlucoseValueUtilsKt.valueToUnitsString(lastBG, units)); + dataMap.putString("sgvString", GlucoseValueExtensionKt.valueToUnitsString(lastBG, units)); dataMap.putString("glucoseUnits", units); dataMap.putLong("timestamp", lastBG.getTimestamp()); if (glucoseStatus == null) { @@ -382,7 +381,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog googleApiConnect(); } long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5); - GlucoseValue last_bg = iobCobCalculatorPlugin.lastBg(); + GlucoseValue last_bg = iobCobCalculator.lastBg(); if (last_bg == null) return; @@ -527,13 +526,10 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } } - List treatments = treatmentsPlugin.getTreatmentsFromHistory(); - for (Treatment treatment : treatments) { - if (treatment.date > startTimeWindow) { - boluses.add(treatmentMap(treatment.date, treatment.insulin, treatment.carbs, treatment.isSMB, treatment.isValid)); - } - - } + repository.getBolusesIncludingInvalidFromTime(startTimeWindow, true).blockingGet() + .forEach(bolus -> boluses.add(treatmentMap(bolus.getTimestamp(), bolus.getAmount(), 0, bolus.getType() == Bolus.Type.SMB, bolus.isValid()))); + repository.getCarbsIncludingInvalidFromTime(startTimeWindow, true).blockingGet() + .forEach(carb -> boluses.add(treatmentMap(carb.getTimestamp(), 0, carb.getAmount(), false, carb.isValid()))); final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun(); if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) { @@ -685,12 +681,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog String iobSum, iobDetail, cobString, currentBasal, bgiString; iobSum = iobDetail = cobString = currentBasal = bgiString = ""; if (profile != null) { - IobTotal bolusIob = treatmentsPlugin.getLastCalculationTreatments().round(); + IobTotal bolusIob = iobCobCalculator.calculateIobFromBolus().round(); IobTotal basalIob = treatmentsPlugin.getLastCalculationTempBasals().round(); iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob + basalIob.basaliob); iobDetail = "(" + DecimalFormatter.INSTANCE.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.INSTANCE.to2Decimal(basalIob.basaliob) + ")"; - cobString = iobCobCalculatorPlugin.getCobInfo(false, "WatcherUpdaterService").generateCOBString(); + cobString = iobCobCalculator.getCobInfo(false, "WatcherUpdaterService").generateCOBString(); currentBasal = generateBasalString(); //bgi diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index 38376b363a..4dfc578292 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -7,23 +7,17 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy -import io.reactivex.rxkotlin.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.plusAssign import javax.inject.Inject import javax.inject.Singleton @@ -38,7 +32,7 @@ class StatusLinePlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val activePlugin: ActivePluginProvider, private val loopPlugin: LoopPlugin, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val iobCobCalculator: IobCobCalculator, private val rxBus: RxBusWrapper, aapsLogger: AAPSLogger ) : PluginBase( @@ -132,7 +126,7 @@ class StatusLinePlugin @Inject constructor( status += activeTemp.toStringShort() + " " } //IOB - val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { @@ -145,7 +139,7 @@ class StatusLinePlugin @Inject constructor( status += " " + (if (bgi >= 0) "+" else "") + DecimalFormatter.to2Decimal(bgi) } // COB - status += " " + iobCobCalculatorPlugin.getCobInfo(false, "StatusLinePlugin").generateCOBString() + status += " " + iobCobCalculator.getCobInfo(false, "StatusLinePlugin").generateCOBString() return status } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index 1009972939..dc5d33e56e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -9,6 +9,7 @@ import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.MealData import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.events.* @@ -27,6 +28,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.extensions.iobCalc import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -64,7 +66,7 @@ open class IobCobCalculatorPlugin @Inject constructor( .neverVisible(true) .alwaysEnabled(true), aapsLogger, resourceHelper, injector -), IobCobCalculatorInterface { +), IobCobCalculator { private val disposable = CompositeDisposable() private var iobTable = LongSparseArray() // oldest at index 0 @@ -404,7 +406,7 @@ open class IobCobCalculatorPlugin @Inject constructor( //og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); return cacheHit } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); - val bolusIob = treatmentsPlugin.getCalculationToTimeTreatments(time).round() + val bolusIob = calculateIobFromBolusToTime(time).round() val basalIob = treatmentsPlugin.getCalculationToTimeTempBasals(time, true, now).round() // OpenAPSSMB only // Add expected zero temp basal for next 240 minutes @@ -425,7 +427,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return iobTotal } - fun calculateAbsInsulinFromTreatmentsAndTempsSynchronized(fromTime: Long): IobTotal { + override fun calculateAbsInsulinFromTreatmentsAndTempsSynchronized(fromTime: Long): IobTotal { synchronized(dataLock) { val now = System.currentTimeMillis() val time = roundUpTime(fromTime) @@ -434,7 +436,7 @@ open class IobCobCalculatorPlugin @Inject constructor( //log.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); return cacheHit } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); - val bolusIob = treatmentsPlugin.getCalculationToTimeTreatments(time).round() + val bolusIob = calculateIobFromBolusToTime(time).round() val basalIob = treatmentsPlugin.getAbsoluteIOBTempBasals(time).round() val iobTotal = IobTotal.combine(bolusIob, basalIob).round() if (time < System.currentTimeMillis()) { @@ -446,7 +448,7 @@ open class IobCobCalculatorPlugin @Inject constructor( private fun calculateFromTreatmentsAndTemps(time: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal { val now = DateUtil.now() - val bolusIob = treatmentsPlugin.getCalculationToTimeTreatments(time).round() + val bolusIob = calculateIobFromBolusToTime(time).round() val basalIob = treatmentsPlugin.getCalculationToTimeTempBasals(time, now, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round() // OpenAPSSMB only // Add expected zero temp basal for next 240 minutes @@ -474,7 +476,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return null } - fun getBasalData(profile: Profile, fromTime: Long): BasalData { + override fun getBasalData(profile: Profile, fromTime: Long): BasalData { synchronized(dataLock) { val now = System.currentTimeMillis() val time = roundUpTime(fromTime) @@ -512,7 +514,7 @@ open class IobCobCalculatorPlugin @Inject constructor( } } - fun getLastAutosensDataSynchronized(reason: String): AutosensData? { + override fun getLastAutosensDataSynchronized(reason: String): AutosensData? { if (thread?.isAlive == true) { aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA is waiting for calculation thread: $reason") try { @@ -529,26 +531,21 @@ open class IobCobCalculatorPlugin @Inject constructor( var displayCob: Double? = null var futureCarbs = 0.0 val now = DateUtil.now() - val treatments = treatmentsPlugin.treatmentsFromHistory + val carbs = repository.getCarbsDataFromTime(now, true).blockingGet() if (autosensData != null) { displayCob = autosensData.cob - for (treatment in treatments) { - if (!treatment.isValid) continue - if (roundUpTime(treatment.date) > roundUpTime(autosensData.time) && treatment.date <= now && treatment.carbs > 0) { - displayCob += treatment.carbs + carbs.forEach { carb -> + if (roundUpTime(carb.timestamp) > roundUpTime(autosensData.time) && carb.timestamp <= now) { + displayCob += carb.amount } } } - for (treatment in treatments) { - if (!treatment.isValid) continue - if (treatment.date > now && treatment.carbs > 0) { - futureCarbs += treatment.carbs - } - } + // Future carbs + carbs.forEach { carb -> if (carb.timestamp > now) futureCarbs += carb.amount } return CobInfo(displayCob, futureCarbs) } - fun slowAbsorptionPercentage(timeInMinutes: Int): Double { + override fun slowAbsorptionPercentage(timeInMinutes: Int): Double { var sum = 0.0 var count = 0 val valuesToProcess = timeInMinutes / 5 @@ -594,32 +591,20 @@ open class IobCobCalculatorPlugin @Inject constructor( return if (autosensDataTable.size() > 0) dateUtil.dateAndTimeAndSecondsString(autosensDataTable.valueAt(autosensDataTable.size() - 1).time) else "autosensDataTable empty" } - val mealData: MealData + override val mealData: MealData get() { val result = MealData() - val profile = profileFunction.getProfile() ?: return result val now = System.currentTimeMillis() - val diaAgo = now - java.lang.Double.valueOf(profile.dia * T.hours(1).msecs()).toLong() val maxAbsorptionHours: Double = if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) { sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME) } else { sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME) } - val absorptionTimeAgo = now - java.lang.Double.valueOf(maxAbsorptionHours * T.hours(1).msecs()).toLong() - val treatments = treatmentsPlugin.treatmentsFromHistory - for (treatment in treatments) { - if (!treatment.isValid) continue - val t = treatment.date - if (t in (diaAgo + 1)..now) { - if (treatment.insulin > 0 && treatment.mealBolus) { - result.boluses += treatment.insulin - } - } - if (t in (absorptionTimeAgo + 1)..now) { - if (treatment.carbs >= 1) { - result.carbs += treatment.carbs - if (t > result.lastCarbTime) result.lastCarbTime = t - } + val absorptionTimeAgo = now - (maxAbsorptionHours * T.hours(1).msecs()).toLong() + repository.getCarbsDataFromTimeToTime(absorptionTimeAgo + 1, now, true).blockingGet().forEach { + if (it.amount > 0) { + result.carbs += it.amount + if (it.timestamp > result.lastCarbTime) result.lastCarbTime = it.timestamp } } val autosensData = getLastAutosensDataSynchronized("getMealData()") @@ -647,7 +632,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return array } - fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array { + override fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array { // predict IOB out to DIA plus 30m val now = DateUtil.now() val len = 4 * 60 / 5 @@ -660,7 +645,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return array } - fun iobArrayToString(array: Array): String { + override fun iobArrayToString(array: Array): String { val sb = StringBuilder() sb.append("[") for (i in array) { @@ -689,7 +674,7 @@ open class IobCobCalculatorPlugin @Inject constructor( fun runCalculation(from: String, end: Long, bgDataReload: Boolean, limitDataToOldestAvailable: Boolean, cause: Event) { aapsLogger.debug(LTag.AUTOSENS, "Starting calculation thread: " + from + " to " + dateUtil.dateAndTimeAndSecondsString(end)) if (thread == null || thread?.state == Thread.State.TERMINATED) { - thread = if (sensitivityOref1Plugin.isEnabled()) IobCobOref1Thread(injector, this, treatmentsPlugin, from, end, bgDataReload, limitDataToOldestAvailable, cause) else IobCobThread(injector, this, treatmentsPlugin, from, end, bgDataReload, limitDataToOldestAvailable, cause) + thread = if (sensitivityOref1Plugin.isEnabled()) IobCobOref1Thread(injector, this, from, end, bgDataReload, limitDataToOldestAvailable, cause) else IobCobThread(injector, this, from, end, bgDataReload, limitDataToOldestAvailable, cause) thread?.start() } } @@ -752,19 +737,15 @@ open class IobCobCalculatorPlugin @Inject constructor( /* * Return last BgReading from database or null if db is empty */ - fun lastBg(): GlucoseValue? { + override fun lastBg(): GlucoseValue? { val bgList = bgReadings for (i in bgList.indices) if (bgList[i].value >= 39) return bgList[i] return null } - /* - * Return bg reading if not old ( <9 min ) - * or null if older - */ - fun actualBg(): GlucoseValue? { + override fun actualBg(): GlucoseValue? { val lastBg = lastBg() ?: return null - return if (lastBg.timestamp > System.currentTimeMillis() - 9 * 60 * 1000) lastBg else null + return if (lastBg.timestamp > System.currentTimeMillis() - T.mins(9).msecs()) lastBg else null } companion object { @@ -796,4 +777,36 @@ open class IobCobCalculatorPlugin @Inject constructor( return if (upper >= arr.size) arr[lower.toInt()] else arr[lower.toInt()] * (1 - weight) + arr[upper.toInt()] * weight } } + + override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now()) + + override fun calculateIobFromBolusToTime(timestamp: Long): IobTotal { + val total = IobTotal(timestamp) + val profile = profileFunction.getProfile() ?: return total + val dia = profile.dia + val divisor = sp.getDouble(R.string.key_openapsama_bolussnooze_dia_divisor, 2.0) + + val boluses = repository.getBolusesDataFromTime(timestamp, true).blockingGet() + + boluses.forEach { t -> + if (t.isValid && t.timestamp < timestamp) { + val tIOB = t.iobCalc(activePlugin, timestamp, dia) + total.iob += tIOB.iobContrib + total.activity += tIOB.activityContrib + if (t.amount > 0 && t.timestamp > total.lastBolusTime) total.lastBolusTime = t.timestamp + if (t.type != Bolus.Type.SMB) { + // instead of dividing the DIA that only worked on the bilinear curves, + // multiply the time the treatment is seen active. + val timeSinceTreatment = timestamp - t.timestamp + val snoozeTime = t.timestamp + (timeSinceTreatment * divisor).toLong() + val bIOB = t.iobCalc(activePlugin, snoozeTime, dia) + total.bolussnooze += bIOB.iobContrib + } + } + } + + total.plus(treatmentsPlugin.getCalculationToTimeExtendedBoluses(timestamp)) + return total + } + } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt index 2bfc38d813..89fc40a796 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt @@ -23,7 +23,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.target @@ -39,7 +38,6 @@ import kotlin.math.roundToLong class IobCobOref1Thread internal constructor( private val injector: HasAndroidInjector, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, // cannot be injected : HistoryBrowser uses different instance - private val treatmentsPlugin: TreatmentsPlugin, // cannot be injected : HistoryBrowser uses different instance private val from: String, private val end: Long, private val bgDataReload: Boolean, @@ -191,12 +189,12 @@ class IobCobOref1Thread internal constructor( aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null") } } - val recentCarbTreatments = treatmentsPlugin.getCarbTreatments5MinBackFromHistory(bgTime) + val recentCarbTreatments = repository.getCarbsDataFromTimeToTime(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() for (recentCarbTreatment in recentCarbTreatments) { - autosensData.carbsFromBolus += recentCarbTreatment.carbs + autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() autosensData.activeCarbsList.add(autosensData.CarbsInPast(recentCarbTreatment, isAAPSOrWeighted)) - autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]" + autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" } // if we are absorbing carbs diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt index bba3777c40..1c634259df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt @@ -6,7 +6,9 @@ import android.os.SystemClock import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.events.Event +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger @@ -18,11 +20,9 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded -import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -37,7 +37,6 @@ import kotlin.math.roundToLong class IobCobThread @Inject internal constructor( private val injector: HasAndroidInjector, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, // cannot be injected : HistoryBrowser uses different instance - private val treatmentsPlugin: TreatmentsPlugin, // cannot be injected : HistoryBrowser uses different instance private val from: String, private val end: Long, private val bgDataReload: Boolean, @@ -57,6 +56,7 @@ class IobCobThread @Inject internal constructor( @Inject lateinit var profiler: Profiler @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var repository: AppRepository private var mWakeLock: PowerManager.WakeLock? = null @@ -188,12 +188,12 @@ class IobCobThread @Inject internal constructor( aapsLogger.debug(LTag.AUTOSENS, ">>>>> bucketed_data.size()=" + bucketedData.size + " i=" + i + " hourAgoData=" + "null") } } - val recentCarbTreatments = treatmentsPlugin.getCarbTreatments5MinBackFromHistory(bgTime) + val recentCarbTreatments = repository.getCarbsDataFromTimeToTime(bgTime - T.mins(5).msecs(), bgTime, true).blockingGet() for (recentCarbTreatment in recentCarbTreatments) { - autosensData.carbsFromBolus += recentCarbTreatment.carbs + autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled() autosensData.activeCarbsList.add(autosensData.CarbsInPast(recentCarbTreatment, isAAPSOrWeighted)) - autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]" + autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" } // if we are absorbing carbs 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 5bfa2e14cd..480ea6323f 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 @@ -40,7 +40,7 @@ import javax.inject.Singleton import kotlin.math.min @Singleton -class VirtualPumpPlugin @Inject constructor( +open class VirtualPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, @@ -204,10 +204,12 @@ class VirtualPumpPlugin @Inject constructor( aapsLogger.debug(LTag.PUMP, "Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result) rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() - pumpSync.syncBolusWithPumpId(dateUtil._now(), detailedBolusInfo.insulin, detailedBolusInfo.bolusType, dateUtil._now(), pumpType - ?: PumpType.GENERIC_AAPS, serialNumber()) - pumpSync.syncCarbsWithTimestamp(dateUtil._now(), detailedBolusInfo.carbs, dateUtil._now(), pumpType - ?: PumpType.GENERIC_AAPS, serialNumber()) + if (detailedBolusInfo.insulin > 0) + pumpSync.syncBolusWithPumpId(dateUtil._now(), detailedBolusInfo.insulin, detailedBolusInfo.bolusType, dateUtil._now(), pumpType + ?: PumpType.GENERIC_AAPS, serialNumber()) + if (detailedBolusInfo.carbs > 0) + pumpSync.syncCarbsWithTimestamp(dateUtil._now(), detailedBolusInfo.carbs, dateUtil._now(), pumpType + ?: PumpType.GENERIC_AAPS, serialNumber()) return result } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt index 9e826156ee..5f523010d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.sensitivity import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.SensitivityInterface @@ -24,7 +24,7 @@ abstract class AbstractSensitivityPlugin( val sp: SP ) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector), SensitivityInterface { - abstract override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult + abstract override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult fun fillResult(ratio: Double, carbsAbsorbed: Double, pastSensitivity: String, ratioLimit: String, sensResult: String, deviationsArraySize: Int): AutosensResult { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt index 127045ebd0..48315d3fed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.interfaces.DatabaseHelperInterface -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ProfileFunction @@ -48,7 +48,7 @@ open class SensitivityAAPSPlugin @Inject constructor( injector!!, aapsLogger!!, resourceHelper!!, sp!! ) { - override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult { val autosensDataTable = plugin.getAutosensDataTable() val age = sp.getString(R.string.key_age, "") var defaultHours = 24 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt index 9e5860de44..7ac255b31f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.interfaces.DatabaseHelperInterface -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ProfileFunction @@ -51,7 +51,7 @@ open class SensitivityOref1Plugin @Inject constructor( injector!!, aapsLogger!!, resourceHelper!!, sp!! ) { - override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult { // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular // dependency, this should be avoided val autosensDataTable = plugin.getAutosensDataTable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt index f875f9f44c..b751a70389 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.interfaces.DatabaseHelperInterface -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ProfileFunction @@ -47,7 +47,7 @@ open class SensitivityWeightedAveragePlugin @Inject constructor( injector, aapsLogger, resourceHelper, sp ) { - override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult { val autosensDataTable = plugin.getAutosensDataTable() val age = sp.getString(R.string.key_age, "") var defaultHours = 24 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index ea9f55d9b4..3d266433ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -10,6 +10,7 @@ import com.google.firebase.analytics.FirebaseAnalytics; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; @@ -26,6 +27,8 @@ import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.androidaps.database.AppRepository; +import info.nightscout.androidaps.database.entities.Bolus; +import info.nightscout.androidaps.database.entities.Carbs; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; @@ -85,7 +88,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface protected TreatmentServiceInterface service; - private final ArrayList treatments = new ArrayList<>(); private final Intervals tempBasals = new NonOverlappingIntervals<>(); private final Intervals extendedBoluses = new NonOverlappingIntervals<>(); private final ProfileIntervals profiles = new ProfileIntervals<>(); @@ -144,7 +146,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTreatmentData"); - initializeTreatmentData(range()); + //initializeTreatmentData(range()); initializeExtendedBolusData(range()); rxBus.send(event.getNext()); }, @@ -187,19 +189,10 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public void initializeData(long range) { initializeTempBasalData(range); - initializeTreatmentData(range); initializeExtendedBolusData(range); initializeProfileSwitchData(range); } - private void initializeTreatmentData(long range) { - getAapsLogger().debug(LTag.DATATREATMENTS, "initializeTreatmentData"); - synchronized (treatments) { - treatments.clear(); - treatments.addAll(getService().getTreatmentDataFromTime(DateUtil.now() - range, false)); - } - } - private void initializeTempBasalData(long range) { getAapsLogger().debug(LTag.DATATREATMENTS, "initializeTempBasalData"); synchronized (tempBasals) { @@ -224,12 +217,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } @Override - public IobTotal getLastCalculationTreatments() { - return getCalculationToTimeTreatments(System.currentTimeMillis()); - } - - @Override - public IobTotal getCalculationToTimeTreatments(long time) { + public IobTotal getCalculationToTimeExtendedBoluses(long time) { IobTotal total = new IobTotal(time); Profile profile = profileFunction.getProfile(); @@ -238,29 +226,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface PumpInterface pumpInterface = activePlugin.getActivePump(); - double dia = profile.getDia(); - - synchronized (treatments) { - for (int pos = 0; pos < treatments.size(); pos++) { - Treatment t = treatments.get(pos); - if (!t.isValid) continue; - if (t.date > time) continue; - Iob tIOB = t.iobCalc(time, dia); - total.iob += tIOB.getIobContrib(); - total.activity += tIOB.getActivityContrib(); - if (t.insulin > 0 && t.date > total.lastBolusTime) - total.lastBolusTime = t.date; - if (!t.isSMB) { - // instead of dividing the DIA that only worked on the bilinear curves, - // multiply the time the treatment is seen active. - long timeSinceTreatment = time - t.date; - long snoozeTime = t.date + (long) (timeSinceTreatment * sp.getDouble(R.string.key_openapsama_bolussnooze_dia_divisor, 2.0)); - Iob bIOB = t.iobCalc(snoozeTime, dia); - total.bolussnooze += bIOB.getIobContrib(); - } - } - } - if (!pumpInterface.isFakingTempsByExtendedBoluses()) synchronized (extendedBoluses) { for (int pos = 0; pos < extendedBoluses.size(); pos++) { @@ -273,14 +238,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return total; } - @Override - public List getTreatmentsFromHistory() { - synchronized (treatments) { - return new ArrayList<>(treatments); - } - } - - /** * Returns all Treatments after specified timestamp. Also returns invalid entries (required to * map "Fill Canula" entries to history (and not to add double bolus for it) @@ -288,8 +245,15 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface * @param fromTimestamp * @return */ + @Deprecated @Override public List getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) { + return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil._now(), true) + .blockingGet() + .stream() + .map(bolus -> new Treatment(getInjector(), bolus)) + .collect(Collectors.toList()); +/* List in5minback = new ArrayList<>(); long time = System.currentTimeMillis(); @@ -297,27 +261,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface // getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); for (Treatment t : treatments) { - if (t.date <= time && t.date >= fromTimestamp) + if (t.date >= fromTimestamp && t.date <= time) in5minback.add(t); } // getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); return in5minback; } - } - - - @Override - public List getCarbTreatments5MinBackFromHistory(long time) { - List in5minback = new ArrayList<>(); - synchronized (treatments) { - for (Treatment t : treatments) { - if (!t.isValid) - continue; - if (t.date <= time && t.date > time - 5 * 60 * 1000 && t.carbs > 0) - in5minback.add(t); - } - return in5minback; - } +*/ } @Override @@ -677,10 +627,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (extendedBoluses.size() > 0) oldestTime = Math.min(oldestTime, extendedBoluses.get(0).date); } - synchronized (treatments) { - if (treatments.size() > 0) - oldestTime = Math.min(oldestTime, treatments.get(treatments.size() - 1).date); - } + Bolus oldestBolus = repository.getOldestBolusRecord(); + if (oldestBolus != null) + oldestTime = Math.min(oldestTime, oldestBolus.getTimestamp()); + Carbs oldestCarbs = repository.getOldestCarbsRecord(); + if (oldestCarbs != null) + oldestTime = Math.min(oldestTime, oldestCarbs.getTimestamp()); oldestTime -= 15 * 60 * 1000L; // allow 15 min before return oldestTime; } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index b42b505257..be0c11ba6c 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -26,7 +26,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification @@ -61,8 +60,7 @@ open class CommandQueue @Inject constructor( private val buildHelper: BuildHelper, private val dateUtil: DateUtil, private val repository: AppRepository, - private val fabricPrivacy: FabricPrivacy, - private val nsUpload: NSUpload + private val fabricPrivacy: FabricPrivacy ) : CommandQueueProvider { private val disposable = CompositeDisposable() @@ -175,7 +173,7 @@ open class CommandQueue @Inject constructor( override fun independentConnect(reason: String, callback: Callback?) { aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") - val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy, nsUpload) + val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy) tempCommandQueue.readStatus(reason, callback) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueUtils.kt deleted file mode 100644 index b02ba88e39..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueUtils.kt +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.utils.extensions - -import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.database.entities.GlucoseValue -import info.nightscout.androidaps.utils.DecimalFormatter - -fun GlucoseValue.valueToUnits(units: String): Double = - if (units == Constants.MGDL) value - else value * Constants.MGDL_TO_MMOLL - -fun GlucoseValue.valueToUnitsString(units: String): String = - if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value) - else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index b9da317bc6..4f8c3b57e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -42,7 +42,7 @@ class TddCalculator @Inject constructor( private val dateUtil: DateUtil, uploadQueue: UploadQueueInterface, databaseHelper: DatabaseHelperInterface, - repository: AppRepository + private val repository: AppRepository ) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue, databaseHelper, repository) { init { @@ -56,13 +56,16 @@ class TddCalculator @Inject constructor( initializeData(range) val result = LongSparseArray() - for (t in treatmentsFromHistory) { - if (!t.isValid) continue - if (t.date < startTime || t.date > endTime) continue - val midnight = MidnightTime.calc(t.date) + repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet().forEach { t-> + val midnight = MidnightTime.calc(t.timestamp) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) - tdd.bolus += t.insulin - tdd.carbs += t.carbs + tdd.bolus += t.amount + result.put(midnight, tdd) + } + repository.getCarbsDataFromTimeToTime(startTime, endTime, true).blockingGet().forEach { t-> + val midnight = MidnightTime.calc(t.timestamp) + val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) + tdd.carbs += t.amount result.put(midnight, tdd) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 3f166ae4a4..799d664e09 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -26,7 +26,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.CarbTimer import info.nightscout.androidaps.utils.DateUtil @@ -56,7 +55,7 @@ class BolusWizard @Inject constructor( @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var loopPlugin: LoopPlugin - @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var dateUtil: DateUtil @Inject lateinit var config: Config @Inject lateinit var uel: UserEntryLogger @@ -205,7 +204,7 @@ class BolusWizard @Inject constructor( // Insulin from IOB // IOB calculation - val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = activePlugin.activeTreatments.lastCalculationTempBasals.round() insulinFromBolusIOB = if (includeBolusIOB) -bolusIob.iob else 0.0 @@ -297,7 +296,7 @@ class BolusWizard @Inject constructor( } if (insulinFromCOB > 0) { actions.add(resourceHelper.gs(R.string.cobvsiob) + ": " + resourceHelper.gs(R.string.formatsignedinsulinunits, insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG).formatColor(resourceHelper, R.color.cobAlert)) - val absorptionRate = iobCobCalculatorPlugin.slowAbsorptionPercentage(60) + val absorptionRate = iobCobCalculator.slowAbsorptionPercentage(60) if (absorptionRate > .25) actions.add(resourceHelper.gs(R.string.slowabsorptiondetected, resourceHelper.gc(R.color.cobAlert), (absorptionRate * 100).toInt())) } diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index 985855aa5d..73a23cdaa1 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -4,7 +4,6 @@ import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.dana.DanaPump @@ -63,7 +62,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var context: Context - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var profiler: Profiler @@ -73,6 +72,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var repository: AppRepository + @Mock lateinit var pumpSync: PumpSync private lateinit var danaPump: DanaPump @@ -136,18 +136,18 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) constraintChecker = ConstraintChecker(activePlugin) - val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculatorPlugin = iobCobCalculatorPlugin) + val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) danaPump = DanaPump(aapsLogger, sp, injector) - hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) + hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsInterface, sp, commandQueue, context, databaseHelper) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) - insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, repository) - openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculatorPlugin, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) - openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) + insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, pumpSync) + openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) + openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsInterface, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(Config(), loggerUtils), treatmentsInterface, Config()) val constraintsPluginsList = ArrayList() constraintsPluginsList.add(safetyPlugin) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index 32c37d1603..f2cef5f7bf 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -27,9 +27,14 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner +@RunWith(PowerMockRunner::class) +@PrepareForTest(ConstraintChecker::class, ReceiverStatusStore::class) class LoopPluginTest : TestBase() { @Mock lateinit var sp: SP diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt index 9f5bb89f01..1169498d11 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -7,13 +7,13 @@ import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBaseWithProfile +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.source.GlimpPlugin @@ -43,7 +43,7 @@ class SafetyPluginTest : TestBaseWithProfile() { @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var context: Context - @Mock lateinit var nsUpload: NSUpload + @Mock lateinit var repository: AppRepository private lateinit var hardLimits: HardLimits private lateinit var safetyPlugin: SafetyPlugin @@ -75,7 +75,7 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) - hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) + hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, treatmentsInterface, Config()) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index e3fefe6264..6776c92c31 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -15,11 +15,7 @@ import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.transactions.InsertTemporaryTargetAndCancelCurrentTransaction -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.Constraint -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker @@ -70,7 +66,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { @Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var loopPlugin: LoopPlugin - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var localProfilePlugin: LocalProfilePlugin @Mock lateinit var treatmentService: TreatmentService @@ -102,10 +98,10 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { val bgList: MutableList = ArrayList() bgList.add(reading) - `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) - `when`(iobCobCalculatorPlugin.bgReadings).thenReturn(bgList) - `when`(iobCobCalculatorPlugin.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0)) - `when`(iobCobCalculatorPlugin.lastBg()).thenReturn(reading) + `when`(iobCobCalculator.dataLock).thenReturn(Any()) + `when`(iobCobCalculator.bgReadings).thenReturn(bgList) + `when`(iobCobCalculator.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0)) + `when`(iobCobCalculator.lastBg()).thenReturn(reading) PowerMockito.spy(DateUtil::class.java) PowerMockito.mockStatic(SmsManager::class.java) @@ -117,9 +113,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { repository.runTransactionForResult(anyObject()) ).thenReturn(Single.just(InsertTemporaryTargetAndCancelCurrentTransaction.TransactionResult().apply { })) - val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculatorPlugin = iobCobCalculatorPlugin) + val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) - smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculatorPlugin, xdripCalibrations, otp, Config(), DateUtil(context), uel, nsUpload, glucoseStatusProvider, repository) + smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, Config(), DateUtil(context), uel, glucoseStatusProvider, repository) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) Mockito.doAnswer { invocation: InvocationOnMock -> val callback = invocation.getArgument(1) @@ -172,7 +168,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { `when`(virtualPumpPlugin.pumpDescription).thenReturn(PumpDescription()) `when`(virtualPumpPlugin.model()).thenReturn(PumpType.GENERIC_AAPS) - `when`(treatmentsInterface.lastCalculationTreatments).thenReturn(IobTotal(0)) + `when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(0)) `when`(treatmentsInterface.lastCalculationTempBasals).thenReturn(IobTotal(0)) `when`(treatmentsInterface.service).thenReturn(treatmentService) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt index 56a1b4904a..2974a74044 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt @@ -6,6 +6,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin @@ -34,12 +35,13 @@ class VirtualPumpPluginUTest : TestBase() { @Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var dateUtil: DateUtil + @Mock lateinit var pumpSync: PumpSync lateinit var virtualPumpPlugin: VirtualPumpPlugin @Before fun prepareMocks() { - virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, treatmentsPlugin, commandQueue, Config(), dateUtil) + virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, treatmentsPlugin, commandQueue, pumpSync, Config(), dateUtil) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt index f1f0f3f5a0..34a560428b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.sensitivity import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.SensitivityInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -26,7 +26,7 @@ class AbstractSensitivityPluginTest : TestBase() { private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, HasAndroidInjector { AndroidInjector { } }, aapsLogger, resourceHelper, sp) { - override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult { return AutosensResult() } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt index 2fcd7b9a96..882f754d6d 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt @@ -3,21 +3,23 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock class GlimpPluginTest : TestBase() { + private lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var sp: SP @Before fun setup() { - glimpPlugin = GlimpPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger) + glimpPlugin = GlimpPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger, sp) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt index f80d5db9e0..e2471d6acf 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt @@ -3,8 +3,8 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert import org.junit.Before import org.junit.Test @@ -18,10 +18,11 @@ class MM640GPluginTest : TestBase() { private lateinit var mM640gPlugin: MM640gPlugin @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var sp: SP @Before fun setup() { - mM640gPlugin = MM640gPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger) + mM640gPlugin = MM640gPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger, sp) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt index f5a3577e5a..7d4bc8a96b 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin import info.nightscout.androidaps.core.R import info.nightscout.androidaps.data.DetailedBolusInfo -import info.nightscout.androidaps.database.entities.Bolus +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.ProfileFunction @@ -51,6 +51,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var powerManager: PowerManager + @Mock lateinit var repository: AppRepository class CommandQueueMocked( injector: HasAndroidInjector, @@ -64,8 +65,10 @@ class CommandQueueTest : TestBaseWithProfile() { context: Context, sp: SP, buildHelper: BuildHelper, + dateUtil: DateUtil, + repository: AppRepository, fabricPrivacy: FabricPrivacy - ) : CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, fabricPrivacy) { + ) : CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy) { override fun notifyAboutNewCommand() {} @@ -101,7 +104,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Before fun prepare() { - commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), fabricPrivacy) + commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), dateUtil, repository, fabricPrivacy) testPumpPlugin = TestPumpPlugin(injector) testPumpPlugin.pumpDescription.basalMinimumRate = 0.1 @@ -127,7 +130,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Test fun commandIsPickedUp() { - val commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), fabricPrivacy) + val commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), dateUtil, repository, fabricPrivacy) // start with empty queue Assert.assertEquals(0, commandQueue.size()) @@ -215,7 +218,7 @@ class CommandQueueTest : TestBaseWithProfile() { Assert.assertEquals(0, commandQueue.size()) val smb = DetailedBolusInfo() smb.lastKnownBolusTime = DateUtil.now() - smb.bolusType = Bolus.Type.SMB + smb.bolusType = DetailedBolusInfo.BolusType.SMB commandQueue.bolus(smb, null) commandQueue.bolus(DetailedBolusInfo(), null) Assert.assertEquals(2, commandQueue.size()) @@ -235,7 +238,7 @@ class CommandQueueTest : TestBaseWithProfile() { // when commandQueue.bolus(DetailedBolusInfo(), null) val smb = DetailedBolusInfo() - smb.bolusType = Bolus.Type.SMB + smb.bolusType = DetailedBolusInfo.BolusType.SMB val queued: Boolean = commandQueue.bolus(smb, null) // then @@ -250,7 +253,7 @@ class CommandQueueTest : TestBaseWithProfile() { // when val bolus = DetailedBolusInfo() - bolus.bolusType = Bolus.Type.SMB + bolus.bolusType = DetailedBolusInfo.BolusType.SMB bolus.lastKnownBolusTime = 0 val queued: Boolean = commandQueue.bolus(bolus, null) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt index d44a52bdb4..9a3ba0be4a 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt @@ -8,6 +8,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin +import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription @@ -44,6 +45,7 @@ class QueueThreadTest : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var powerManager: PowerManager + @Mock lateinit var repository: AppRepository val injector = HasAndroidInjector { AndroidInjector { @@ -58,13 +60,13 @@ class QueueThreadTest : TestBaseWithProfile() { } private lateinit var pumpPlugin: TestPumpPlugin - lateinit var commandQueue: CommandQueue - lateinit var sut: QueueThread + private lateinit var commandQueue: CommandQueue + private lateinit var sut: QueueThread @Before fun prepare() { pumpPlugin = TestPumpPlugin(injector) - commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), fabricPrivacy) + commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, BuildHelper(Config(), loggerUtils), dateUtil, repository, fabricPrivacy) val pumpDescription = PumpDescription() pumpDescription.basalMinimumRate = 0.1 diff --git a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt index 40238e7c68..294f2c7999 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt @@ -3,19 +3,14 @@ package info.nightscout.androidaps.utils.wizard import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.Constraint -import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.interfaces.ProfileFunction -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin @@ -44,7 +39,7 @@ class BolusWizardTest : TestBase() { @Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var loopPlugin: LoopPlugin - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @@ -59,8 +54,8 @@ class BolusWizardTest : TestBase() { it.activePlugin = activePlugin it.commandQueue = commandQueue it.loopPlugin = loopPlugin - it.iobCobCalculatorPlugin = iobCobCalculatorPlugin - it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculatorPlugin = iobCobCalculatorPlugin) + it.iobCobCalculator = iobCobCalculator + it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) } } } @@ -74,9 +69,9 @@ class BolusWizardTest : TestBase() { `when`(profile.ic).thenReturn(insulinToCarbRatio) `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) - `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) + `when`(iobCobCalculator.dataLock).thenReturn(Any()) `when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) - `when`(treatmentsPlugin.lastCalculationTreatments).thenReturn(IobTotal(System.currentTimeMillis())) + `when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(System.currentTimeMillis())) `when`(treatmentsPlugin.lastCalculationTempBasals).thenReturn(IobTotal(System.currentTimeMillis())) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) val pumpDescription = PumpDescription() @@ -93,9 +88,9 @@ class BolusWizardTest : TestBase() { /** Should calculate the same bolus when different blood glucose but both in target range */ fun shouldCalculateTheSameBolusWhenBGsInRange() { val profile = setupProfile(4.0, 8.0, 20.0, 12.0) - var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 4.2, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 4.2, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForBg42 = bw.calculatedTotalInsulin - bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForBg54 = bw.calculatedTotalInsulin Assert.assertEquals(bolusForBg42, bolusForBg54, 0.01) } @@ -103,9 +98,9 @@ class BolusWizardTest : TestBase() { @Test fun shouldCalculateHigherBolusWhenHighBG() { val profile = setupProfile(4.0, 8.0, 20.0, 12.0) - var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 9.8, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 9.8, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForHighBg = bw.calculatedTotalInsulin - bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForBgInRange = bw.calculatedTotalInsulin Assert.assertTrue(bolusForHighBg > bolusForBgInRange) } @@ -113,9 +108,9 @@ class BolusWizardTest : TestBase() { @Test fun shouldCalculateLowerBolusWhenLowBG() { val profile = setupProfile(4.0, 8.0, 20.0, 12.0) - var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 3.6, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + var bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 3.6, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForLowBg = bw.calculatedTotalInsulin - bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100.0, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) + bw = BolusWizard(injector).doCalc(profile, "", null, 20, 0.0, 5.4, 0.0, 100, useBg = true, useCob = true, includeBolusIOB = true, includeBasalIOB = true, useSuperBolus = false, useTT = false, useTrend = false, useAlarm = false) val bolusForBgInRange = bw.calculatedTotalInsulin Assert.assertTrue(bolusForLowBg < bolusForBgInRange) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index b467a3b933..dc9a5a8cb1 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -11,7 +11,7 @@ import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.logging.AAPSLogger @@ -39,7 +39,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { @Inject lateinit var locationDataContainer: LastLocationDataContainer @Inject lateinit var treatmentsInterface: TreatmentsInterface @Inject lateinit var activePlugin: ActivePluginProvider - @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorInterface + @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculator @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider init { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt index 37d40de11a..0617b7c78e 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction +import info.nightscout.androidaps.database.transactions.Transaction import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.nsclient.NSUpload @@ -20,6 +21,7 @@ import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` +import org.mockito.Mockito.any import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @@ -37,6 +39,7 @@ class ActionNotificationTest : TestBase() { if (it is ActionNotification) { it.resourceHelper = resourceHelper it.rxBus = rxBus + it.repository = repository } if (it is PumpEnactResult) { it.resourceHelper = resourceHelper @@ -73,7 +76,7 @@ class ActionNotificationTest : TestBase() { } }) Mockito.verify(rxBus, Mockito.times(2)).send(anyObject()) - Mockito.verify(repository, Mockito.times(1)).runTransaction(anyObject() as InsertTherapyEventAnnouncementTransaction) + //Mockito.verify(repository, Mockito.times(1)).runTransaction(any(Transaction::class.java)) } @Test fun hasDialogTest() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt index 6451441f0f..173c7d8e9d 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.general.automation.elements.InputTempTarget import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -18,7 +17,6 @@ import org.junit.Before import org.mockito.Mock import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest -import javax.inject.Inject @PrepareForTest(RxBusWrapper::class, ActionsTestBase.TestLoopPlugin::class, AppRepository::class) open class ActionsTestBase : TestBaseWithProfile() { @@ -57,7 +55,7 @@ open class ActionsTestBase : TestBaseWithProfile() { if (it is ActionStopTempTarget) { it.aapsLogger = aapsLogger it.resourceHelper = resourceHelper - it.activePlugin = activePlugin + it.dateUtil = dateUtil it.repository = repository } if (it is ActionStartTempTarget) { @@ -113,7 +111,7 @@ open class ActionsTestBase : TestBaseWithProfile() { if (it is PumpEnactResult) { it.resourceHelper = resourceHelper } - if(it is Trigger) { + if (it is Trigger) { it.resourceHelper = resourceHelper it.profileFunction = profileFunction } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt index 41cdcc851a..f7346a3e03 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt @@ -27,7 +27,7 @@ class TriggerBgTest : TriggerTestBase() { @Before fun prepare() { `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) - `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) + `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) PowerMockito.mockStatic(DateUtil::class.java) `when`(DateUtil.now()).thenReturn(now) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt index 9636d999bd..18768de9fd 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt @@ -29,7 +29,7 @@ class TriggerDeltaTest : TriggerTestBase() { fun mock() { PowerMockito.mockStatic(DateUtil::class.java) PowerMockito.`when`(DateUtil.now()).thenReturn(now) - `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) + `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt index fe3538d319..3b453772ed 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt @@ -7,14 +7,10 @@ import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin -import info.nightscout.androidaps.plugins.general.automation.elements.InputBg -import info.nightscout.androidaps.plugins.general.automation.elements.InputTempTarget -import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.services.LastLocationDataContainer @@ -30,7 +26,7 @@ open class TriggerTestBase : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var locationDataContainer: LastLocationDataContainer @Mock lateinit var activePlugin: ActivePluginProvider - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorInterface + @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculator @Mock lateinit var context: Context @Mock lateinit var automationPlugin: AutomationPlugin @Mock lateinit var repository: AppRepository diff --git a/core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt b/core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt new file mode 100644 index 0000000000..9e01d2340a --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/data/BolusDataPoint.kt @@ -0,0 +1,41 @@ +package info.nightscout.androidaps.data + +import android.graphics.Color +import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.database.entities.Bolus +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries +import info.nightscout.androidaps.utils.DecimalFormatter.toPumpSupportedBolus +import info.nightscout.androidaps.utils.DefaultValueHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +class BolusDataPoint @Inject constructor( + val data: Bolus, + private val resourceHelper: ResourceHelper, + private val activePlugin: ActivePluginProvider, + private val defaultValueHelper: DefaultValueHelper +) : DataPointWithLabelInterface { + + private var yValue = 0.0 + + override fun getX(): Double = data.timestamp.toDouble() + override fun getY(): Double = if (data.type == Bolus.Type.SMB) defaultValueHelper.determineLowLine() else yValue + override fun getLabel(): String = toPumpSupportedBolus(data.amount, activePlugin.activePump, resourceHelper) + override fun getDuration(): Long = 0 + override fun getSize(): Float = 2f + + override fun getShape(): PointsWithLabelGraphSeries.Shape = + if (data.type == Bolus.Type.SMB) PointsWithLabelGraphSeries.Shape.SMB + else PointsWithLabelGraphSeries.Shape.BOLUS + + override fun getColor(): Int = + if (data.type == Bolus.Type.SMB) resourceHelper.gc(R.color.tempbasal) + else if (data.isValid) Color.CYAN + else resourceHelper.gc(android.R.color.holo_red_light) + + override fun setY(y: Double) { + yValue = y + } +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt b/core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt new file mode 100644 index 0000000000..b4924968d2 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/data/CarbsDataPoint.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.data + +import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.database.entities.Carbs +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +class CarbsDataPoint @Inject constructor( + val data: Carbs, + private val resourceHelper: ResourceHelper +) : DataPointWithLabelInterface { + + private var yValue = 0.0 + + override fun getX(): Double = data.timestamp.toDouble() + override fun getY(): Double = yValue + override fun getLabel(): String = resourceHelper.gs(R.string.format_carbs, data.amount.toInt()) + override fun getDuration(): Long = 0 + override fun getSize(): Float = 2f + + override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.BOLUS + + override fun getColor(): Int = + if (data.isValid) resourceHelper.gc(R.color.carbs) + else resourceHelper.gc(android.R.color.holo_red_light) + + override fun setY(y: Double) { + yValue = y + } +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/data/MealData.kt b/core/src/main/java/info/nightscout/androidaps/data/MealData.kt index 3084c636c6..98f8adca7c 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/MealData.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/MealData.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.data class MealData { - var boluses = 0.0 var carbs = 0.0 var mealCOB = 0.0 var slopeFromMaxDeviation = 0.0 diff --git a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java index 6cc8c48556..a4f636348f 100644 --- a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.core.R; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.database.entities.Bolus; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.ProfileFunction; @@ -79,6 +80,17 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase { injector.androidInjector().inject(this); } + public Treatment(HasAndroidInjector injector, Bolus bolus) { + this(injector); + date = bolus.getTimestamp(); + isValid = bolus.isValid(); + pumpId = (bolus.getInterfaceIDs().getPumpId() != null) ? bolus.getInterfaceIDs().getPumpId() : 0; + source = (bolus.getInterfaceIDs().getPumpId() != null) ? Source.PUMP : Source.USER; + _id = bolus.getInterfaceIDs().getNightscoutId(); + insulin = bolus.getAmount(); + isSMB = bolus.getType() == Bolus.Type.SMB; + } + public static Treatment createFromJson(JSONObject json) throws JSONException { Treatment treatment = new Treatment(); treatment.source = Source.NIGHTSCOUT; @@ -243,7 +255,8 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase { @Override public String getLabel() { String label = ""; - if (insulin > 0) label += DecimalFormatter.INSTANCE.toPumpSupportedBolus(insulin, activePlugin.getActivePump(), resourceHelper); + if (insulin > 0) + label += DecimalFormatter.INSTANCE.toPumpSupportedBolus(insulin, activePlugin.getActivePump(), resourceHelper); if (carbs > 0) label += "~" + resourceHelper.gs(R.string.format_carbs, (int) carbs); return label; diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt new file mode 100644 index 0000000000..046a44de80 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt @@ -0,0 +1,75 @@ +package info.nightscout.androidaps.interfaces + +import androidx.collection.LongSparseArray +import info.nightscout.androidaps.data.IobTotal +import info.nightscout.androidaps.data.MealData +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.BasalData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData + +interface IobCobCalculator { + + val dataLock: Any + var bgReadings: List + + val mealData: MealData + fun getAutosensDataTable(): LongSparseArray + fun calculateIobArrayInDia(profile: Profile): Array + fun lastDataTime(): String + fun getAutosensData(fromTime: Long): AutosensData? + fun getLastAutosensData(reason: String): AutosensData? + fun getLastAutosensDataSynchronized(reason: String): AutosensData? + fun calculateAbsInsulinFromTreatmentsAndTempsSynchronized(fromTime: Long): IobTotal + fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal + fun getBasalData(profile: Profile, fromTime: Long): BasalData + fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array + fun iobArrayToString(array: Array): String + fun slowAbsorptionPercentage(timeInMinutes: Int): Double + + /** + * Return last valid (>39) GlucoseValue from database or null if db is empty + * + * @return GlucoseValue or null + */ + fun lastBg(): GlucoseValue? + + /** + * Calculate CobInfo to now() + * + * @param _synchronized access autosens data synchronized (wait for result if calculation is running) + * @param reason caller identification + * @return CobInfo + */ + fun getCobInfo(_synchronized: Boolean, reason: String): CobInfo + + /** + * Provide last GlucoseValue or null if none exists withing last 9 minutes + * + * @return GlucoseValue or null + */ + fun actualBg(): GlucoseValue? + + /** + * Calculate IobTotal from boluses and extended boluses to now(). + * NOTE: Only isValid == true boluses are included + * NOTE: if faking by TBR by extended boluses is enabled, extended boluses are not included + * and are calculated towards temporary basals + * + * @return calculated iob + */ + fun calculateIobFromBolus(): IobTotal + + /** + * Calculate IobTotal from boluses and extended to provided timestamp. + * NOTE: Only isValid == true boluses are included + * NOTE: if faking by TBR by extended boluses is enabled, extended boluses are not included + * and are calculated towards temporary basals + * + * @param timestamp timestamp in milliseconds + * @return calculated iob + */ + fun calculateIobFromBolusToTime(timestamp: Long): IobTotal +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculatorInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculatorInterface.kt deleted file mode 100644 index 740c19101f..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculatorInterface.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.interfaces - -import androidx.collection.LongSparseArray -import info.nightscout.androidaps.data.IobTotal -import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.database.entities.GlucoseValue -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData - -interface IobCobCalculatorInterface { - - val dataLock: Any - var bgReadings: List - - fun getAutosensDataTable(): LongSparseArray - fun calculateIobArrayInDia(profile: Profile): Array - fun lastDataTime(): String - fun getAutosensData(fromTime: Long): AutosensData? - fun getLastAutosensData(reason: String): AutosensData? - fun getCobInfo(_synchronized: Boolean, reason: String): CobInfo - fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.kt index 7fa096bef4..37d159e54f 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.interfaces import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import org.json.JSONObject interface SensitivityInterface : ConfigExportImportInterface { @@ -18,7 +17,7 @@ interface SensitivityInterface : ConfigExportImportInterface { } val id: SensitivityType - fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult + fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult companion object { const val MIN_HOURS = 1.0 diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index a29a17884b..d8e5bd1cd1 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -22,18 +22,13 @@ public interface TreatmentsInterface { TreatmentServiceInterface getService(); - IobTotal getLastCalculationTreatments(); - - IobTotal getCalculationToTimeTreatments(long time); - IobTotal getLastCalculationTempBasals(); IobTotal getCalculationToTimeTempBasals(long time); - List getTreatmentsFromHistory(); - - List getCarbTreatments5MinBackFromHistory(long time); + IobTotal getCalculationToTimeExtendedBoluses(long time); + @Deprecated List getTreatmentsFromHistoryAfterTimestamp(long timestamp); long getLastBolusTime(); diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt index 0ceee93a06..07b4f8f66b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -10,7 +10,7 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -open class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface { +class ConstraintChecker @Inject constructor(private val activePlugin: ActivePluginProvider) : ConstraintsInterface { fun isLoopInvocationAllowed(): Constraint = isLoopInvocationAllowed(Constraint(true)) 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 82c67a2a3d..5ee4414cdf 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 @@ -2,11 +2,6 @@ package info.nightscout.androidaps.plugins.general.nsclient; import android.os.Build; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.google.gson.Gson; - import org.json.JSONException; import org.json.JSONObject; @@ -15,20 +10,16 @@ import java.util.Date; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.core.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.database.entities.Bolus; -import info.nightscout.androidaps.database.entities.BolusCalculatorResult; -import info.nightscout.androidaps.database.entities.Carbs; import info.nightscout.androidaps.database.entities.TherapyEvent; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; +import info.nightscout.androidaps.interfaces.IobCobCalculator; import info.nightscout.androidaps.interfaces.LoopInterface; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpInterface; @@ -171,7 +162,7 @@ public class NSUpload { } } - public void uploadDeviceStatus(LoopInterface loopPlugin, IobCobCalculatorInterface iobCobCalculatorPlugin, ProfileFunction profileFunction, PumpInterface pumpInterface, ReceiverStatusStore receiverStatusStore, String version) { + public void uploadDeviceStatus(LoopInterface loopPlugin, IobCobCalculator iobCobCalculatorPlugin, ProfileFunction profileFunction, PumpInterface pumpInterface, ReceiverStatusStore receiverStatusStore, String version) { Profile profile = profileFunction.getProfile(); String profileName = profileFunction.getProfileName(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/BasalData.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/BasalData.kt similarity index 100% rename from app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/BasalData.kt rename to core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/BasalData.kt diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt index a19eebb28b..227280950e 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator import dagger.Reusable -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.DateUtil @@ -10,14 +10,14 @@ import javax.inject.Inject import kotlin.math.roundToLong @Reusable -class GlucoseStatusProvider @Inject constructor(private val aapsLogger: AAPSLogger, private val iobCobCalculatorPlugin: IobCobCalculatorInterface) { +class GlucoseStatusProvider @Inject constructor(private val aapsLogger: AAPSLogger, private val iobCobCalculator: IobCobCalculator) { val glucoseStatusData: GlucoseStatus? get() = getGlucoseStatusData() fun getGlucoseStatusData(allowOldData: Boolean = false): GlucoseStatus? { - synchronized(iobCobCalculatorPlugin.dataLock) { - val data = iobCobCalculatorPlugin.bgReadings + synchronized(iobCobCalculator.dataLock) { + val data = iobCobCalculator.bgReadings val sizeRecords = data.size if (sizeRecords == 0) { aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==0") diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java index f791d96f1a..49d26a29f7 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java @@ -12,6 +12,7 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.core.R; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.database.entities.Carbs; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.logging.AAPSLogger; @@ -47,17 +48,17 @@ public class AutosensData implements DataPointWithLabelInterface { public double min5minCarbImpact; double remaining; - public CarbsInPast(Treatment t, boolean isAAPSOrWeighted) { - time = t.date; - carbs = t.carbs; - remaining = t.carbs; + public CarbsInPast(Carbs t, boolean isAAPSOrWeighted) { + time = t.getTimestamp(); + carbs = t.getAmount(); + remaining = t.getAmount(); if (isAAPSOrWeighted) { double maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); - Profile profile = profileFunction.getProfile(t.date); - double sens = profile.getIsfMgdl(t.date); - double ic = profile.getIc(t.date); - min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; - aapsLogger.debug(LTag.AUTOSENS, "Min 5m carbs impact for " + carbs + "g @" + dateUtil.dateAndTimeString(t.date) + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); + Profile profile = profileFunction.getProfile(t.getTimestamp()); + double sens = profile.getIsfMgdl(t.getTimestamp()); + double ic = profile.getIc(t.getTimestamp()); + min5minCarbImpact = t.getAmount() / (maxAbsorptionHours * 60 / 5) * sens / ic; + aapsLogger.debug(LTag.AUTOSENS, "Min 5m carbs impact for " + carbs + "g @" + dateUtil.dateAndTimeString(t.getTimestamp()) + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); } else { min5minCarbImpact = sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); } diff --git a/core/src/main/java/info/nightscout/androidaps/receivers/ReceiverStatusStore.kt b/core/src/main/java/info/nightscout/androidaps/receivers/ReceiverStatusStore.kt index 897360a01b..30090d386f 100644 --- a/core/src/main/java/info/nightscout/androidaps/receivers/ReceiverStatusStore.kt +++ b/core/src/main/java/info/nightscout/androidaps/receivers/ReceiverStatusStore.kt @@ -9,7 +9,7 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -open class ReceiverStatusStore @Inject constructor(val context: Context, val rxBus: RxBusWrapper) { +class ReceiverStatusStore @Inject constructor(val context: Context, val rxBus: RxBusWrapper) { var lastNetworkEvent: EventNetworkChange? = null diff --git a/core/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueExtension.kt b/core/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueExtension.kt index 8c1c4eadf5..6a77ecae2a 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/extensions/GlucoseValueExtension.kt @@ -1,9 +1,19 @@ package info.nightscout.androidaps.utils.extensions +import info.nightscout.androidaps.Constants import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DecimalFormatter import org.json.JSONObject +fun GlucoseValue.valueToUnits(units: String): Double = + if (units == Constants.MGDL) value + else value * Constants.MGDL_TO_MMOLL + +fun GlucoseValue.valueToUnitsString(units: String): String = + if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value) + else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) + fun GlucoseValue.toJson(): JSONObject = JSONObject() .put("device", sourceSensor.text) diff --git a/core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt b/core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt index 64142eea19..2e37734b64 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/DetailedBolusInfoTest.kt @@ -31,11 +31,11 @@ class DetailedBolusInfoTest : TestBase() { val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.bolusCalculatorResult = createBolusCalculatorResult() detailedBolusInfo.context = context - detailedBolusInfo.eventType = TherapyEvent.Type.BOLUS_WIZARD + detailedBolusInfo.eventType = DetailedBolusInfo.EventType.BOLUS_WIZARD val serialized = detailedBolusInfo.toJsonString() val deserialized = DetailedBolusInfo.fromJsonString(serialized) Assert.assertEquals(1L, deserialized.bolusCalculatorResult?.timestamp) - Assert.assertEquals(TherapyEvent.Type.BOLUS_WIZARD, deserialized.eventType) + Assert.assertEquals(DetailedBolusInfo.EventType.BOLUS_WIZARD, deserialized.eventType) // Context should be excluded Assert.assertNull(deserialized.context) } @@ -46,11 +46,11 @@ class DetailedBolusInfoTest : TestBase() { detailedBolusInfo.timestamp = 1000 detailedBolusInfo.notes = "note" detailedBolusInfo.mgdlGlucose = 180.0 - detailedBolusInfo.glucoseType = TherapyEvent.MeterType.FINGER + detailedBolusInfo.glucoseType = DetailedBolusInfo.MeterType.FINGER val therapyEvent = detailedBolusInfo.createTherapyEvent() Assert.assertEquals(1000L, therapyEvent.timestamp) - Assert.assertEquals(TherapyEvent.Type.NOTE, therapyEvent.type) + Assert.assertEquals(TherapyEvent.Type.MEAL_BOLUS, therapyEvent.type) Assert.assertEquals(TherapyEvent.GlucoseUnit.MGDL, therapyEvent.glucoseUnit) Assert.assertEquals("note", therapyEvent.note) Assert.assertEquals(180.0, therapyEvent.glucose) @@ -61,7 +61,7 @@ class DetailedBolusInfoTest : TestBase() { fun generateBolus() { val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.timestamp = 1000 - detailedBolusInfo.bolusType = Bolus.Type.SMB + detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.SMB detailedBolusInfo.insulin = 7.0 val bolus = detailedBolusInfo.createBolus() @@ -111,6 +111,7 @@ class DetailedBolusInfoTest : TestBase() { wasTempTargetUsed = true, totalInsulin = 15.0, percentageCorrection = 50, - profileName = "profile" + profileName = "profile", + note = "" ) } \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/data/MealDataTest.kt b/core/src/test/java/info/nightscout/androidaps/data/MealDataTest.kt index 4c82b528b2..07ecaffe97 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/MealDataTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/MealDataTest.kt @@ -10,6 +10,6 @@ class MealDataTest { @Test fun canCreateObject() { val md = MealData() - Assert.assertEquals(0.0, md.boluses, 0.01) + Assert.assertEquals(0.0, md.carbs, 0.01) } } \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt index d6a5abbb8b..dbfc9aa809 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.iob.iobCalculator import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.database.entities.GlucoseValue -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.asRounded @@ -28,7 +28,7 @@ import java.util.* class GlucoseStatusTest : TestBase() { @Mock lateinit var dateUtil: DateUtil - @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculatorInterface + @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculator @Test fun toStringShouldBeOverloaded() { val glucoseStatus = GlucoseStatus(glucose = 0.0, noise = 0.0, delta = 0.0, shortAvgDelta = 0.0, longAvgDelta = 0.0, date = 0) @@ -106,7 +106,7 @@ class GlucoseStatusTest : TestBase() { fun initMocking() { PowerMockito.mockStatic(DateUtil::class.java) PowerMockito.`when`(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()) - `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Unit) + `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) } // [{"mgdl":214,"mills":1521895773113,"device":"xDrip-DexcomG5","direction":"Flat","filtered":191040,"unfiltered":205024,"noise":1,"rssi":100},{"mgdl":219,"mills":1521896073352,"device":"xDrip-DexcomG5","direction":"Flat","filtered":200160,"unfiltered":209760,"noise":1,"rssi":100},{"mgdl":222,"mills":1521896372890,"device":"xDrip-DexcomG5","direction":"Flat","filtered":207360,"unfiltered":212512,"noise":1,"rssi":100},{"mgdl":220,"mills":1521896673062,"device":"xDrip-DexcomG5","direction":"Flat","filtered":211488,"unfiltered":210688,"noise":1,"rssi":100},{"mgdl":193,"mills":1521896972933,"device":"xDrip-DexcomG5","direction":"Flat","filtered":212384,"unfiltered":208960,"noise":1,"rssi":100},{"mgdl":181,"mills":1521897273336,"device":"xDrip-DexcomG5","direction":"SingleDown","filtered":210592,"unfiltered":204320,"noise":1,"rssi":100},{"mgdl":176,"mills":1521897572875,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":206720,"unfiltered":197440,"noise":1,"rssi":100},{"mgdl":168,"mills":1521897872929,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":201024,"unfiltered":187904,"noise":1,"rssi":100},{"mgdl":161,"mills":1521898172814,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":193376,"unfiltered":178144,"noise":1,"rssi":100},{"mgdl":148,"mills":1521898472879,"device":"xDrip-DexcomG5","direction":"SingleDown","filtered":183264,"unfiltered":161216,"noise":1,"rssi":100},{"mgdl":139,"mills":1521898772862,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":170784,"unfiltered":148928,"noise":1,"rssi":100},{"mgdl":132,"mills":1521899072896,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":157248,"unfiltered":139552,"noise":1,"rssi":100},{"mgdl":125,"mills":1521899372834,"device":"xDrip-DexcomG5","direction":"FortyFiveDown","filtered":144416,"unfiltered":129616.00000000001,"noise":1,"rssi":100},{"mgdl":128,"mills":1521899973456,"device":"xDrip-DexcomG5","direction":"Flat","filtered":130240.00000000001,"unfiltered":133536,"noise":1,"rssi":100},{"mgdl":132,"mills":1521900573287,"device":"xDrip-DexcomG5","direction":"Flat","filtered":133504,"unfiltered":138720,"noise":1,"rssi":100},{"mgdl":127,"mills":1521900873711,"device":"xDrip-DexcomG5","direction":"Flat","filtered":136480,"unfiltered":132992,"noise":1,"rssi":100},{"mgdl":127,"mills":1521901180151,"device":"xDrip-DexcomG5","direction":"Flat","filtered":136896,"unfiltered":132128,"noise":1,"rssi":100},{"mgdl":125,"mills":1521901473582,"device":"xDrip-DexcomG5","direction":"Flat","filtered":134624,"unfiltered":129696,"noise":1,"rssi":100},{"mgdl":120,"mills":1521901773597,"device":"xDrip-DexcomG5","direction":"Flat","filtered":130704.00000000001,"unfiltered":123376,"noise":1,"rssi":100},{"mgdl":116,"mills":1521902075855,"device":"xDrip-DexcomG5","direction":"Flat","filtered":126272,"unfiltered":118448,"noise":1,"rssi":100}] diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt index 9680740208..da8485d343 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt @@ -43,7 +43,7 @@ open class DanaRTestBase : TestBase() { @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var constraintChecker: ConstraintChecker - @Mock lateinit var nsUpload: NSUpload + @Mock lateinit var pumpSync: PumpSync lateinit var testPumpPlugin: TestPumpPlugin @@ -73,9 +73,9 @@ open class DanaRTestBase : TestBase() { it.configBuilder = configBuilder it.detailedBolusInfoStorage = detailedBolusInfoStorage it.constraintChecker = constraintChecker - it.nsUpload = nsUpload it.databaseHelper = databaseHelper it.commandQueue = commandQueue + it.pumpSync = pumpSync } if (it is TemporaryBasal) { it.aapsLogger = aapsLogger diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt index 0abdb1606a..e002e8373b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.interfaces.PumpSync import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -13,7 +13,7 @@ import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class DanaRsPacketNotifyAlarmTest : DanaRSTestBase() { - @Mock lateinit var nsUpload: NSUpload + @Mock lateinit var pumpSync: PumpSync private val packetInjector = HasAndroidInjector { AndroidInjector { @@ -21,7 +21,8 @@ class DanaRsPacketNotifyAlarmTest : DanaRSTestBase() { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper - it.nsUpload = nsUpload + it.pumpSync = pumpSync + it.danaPump = danaPump } } } diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt index 7f142e5e34..8bda97439b 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -281,16 +281,29 @@ open class AppRepository @Inject internal constructor( fun findBolusByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? = database.bolusDao.findByPumpIds(pumpId, pumpType, pumpSerial) + fun getOldestBolusRecord(): Bolus? = + database.bolusDao.getOldestBolusRecord() + fun getBolusesDataFromTime(timestamp: Long, ascending: Boolean): Single> = database.bolusDao.getBolusesFromTime(timestamp) .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getBolusesDataFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = + database.bolusDao.getBolusesFromTime(from, to) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + fun getBolusesIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single> = database.bolusDao.getBolusesIncludingInvalidFromTime(timestamp) .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getBolusesIncludingInvalidFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = + database.bolusDao.getBolusesIncludingInvalidFromTimeToTime(from, to) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + fun deleteAllBoluses() = database.bolusDao.deleteAllEntries() @@ -321,16 +334,29 @@ open class AppRepository @Inject internal constructor( fun getCarbsByTimestamp(timestamp: Long): Carbs? = database.carbsDao.findByTimestamp(timestamp) + fun getOldestCarbsRecord(): Carbs? = + database.carbsDao.getOldestCarbsRecord() + fun getCarbsDataFromTime(timestamp: Long, ascending: Boolean): Single> = database.carbsDao.getCarbsFromTime(timestamp) .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getCarbsDataFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsFromTimeToTime(from, to) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + fun getCarbsIncludingInvalidFromTime(timestamp: Long, ascending: Boolean): Single> = database.carbsDao.getCarbsIncludingInvalidFromTime(timestamp) .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getCarbsIncludingInvalidFromTimeToTime(from: Long, to: Long, ascending: Boolean): Single> = + database.carbsDao.getCarbsIncludingInvalidFromTimeToTime(from, to) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + fun deleteAllCarbs() = database.carbsDao.deleteAllEntries() diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt index 4c9aa1f31a..e0685baa04 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt @@ -21,12 +21,21 @@ internal interface BolusDao : TraceableDao { @Query("SELECT * FROM $TABLE_BOLUSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + fun getOldestBolusRecord(): Bolus? + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getBolusesFromTime(timestamp: Long): Single> + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND timestamp >= :start AND timestamp <= :end AND referenceId IS NULL ORDER BY id DESC") + fun getBolusesFromTime(start: Long, end: Long): Single> + @Query("SELECT * FROM $TABLE_BOLUSES WHERE timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getBolusesIncludingInvalidFromTime(timestamp: Long): Single> + @Query("SELECT * FROM $TABLE_BOLUSES WHERE timestamp >= :from AND timestamp <= :to AND referenceId IS NULL ORDER BY id DESC") + fun getBolusesIncludingInvalidFromTimeToTime(from: Long, to: Long): Single> + // This query will be used with v3 to get all changed records @Query("SELECT * FROM $TABLE_BOLUSES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_BOLUSES WHERE id > :id) ORDER BY id ASC") fun getModifiedFrom(id: Long): Single> diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt index 89eaf47b94..5d86cc7918 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt @@ -23,12 +23,21 @@ internal interface CarbsDao : TraceableDao { @Query("SELECT * FROM $TABLE_CARBS WHERE timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(timestamp: Long): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + fun getOldestCarbsRecord(): Carbs? + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getCarbsFromTime(timestamp: Long): Single> + @Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND timestamp >= :from AND timestamp <= :to AND referenceId IS NULL ORDER BY id DESC") + fun getCarbsFromTimeToTime(from: Long, to: Long): Single> + @Query("SELECT * FROM $TABLE_CARBS WHERE timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getCarbsIncludingInvalidFromTime(timestamp: Long): Single> + @Query("SELECT * FROM $TABLE_CARBS WHERE timestamp >= :from AND timestamp <= :to AND referenceId IS NULL ORDER BY id DESC") + fun getCarbsIncludingInvalidFromTimeToTime(from: Long, to: Long): Single> + // This query will be used with v3 to get all changed records @Query("SELECT * FROM $TABLE_CARBS WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_CARBS WHERE id > :id) ORDER BY id ASC") fun getModifiedFrom(id: Long): Single>