From e7578b4c8f37d610bb1554203cc3da9501bbb6e7 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 23 Apr 2021 00:31:40 +0200 Subject: [PATCH 01/27] Loop Dialog, hide loop buttons if pump disconnected or loop suspended --- .../main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt | 1 + app/src/main/res/layout/dialog_loop.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt index 9b10142c8c..e412998cd4 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt @@ -195,6 +195,7 @@ class LoopDialog : DaggerDialogFragment() { binding.overviewDisconnectButtons.visibility = View.GONE binding.overviewReconnect.visibility = View.VISIBLE } + binding.overviewLoop.visibility = (!loopPlugin.isSuspended && !loopPlugin.isDisconnected).toVisibility() } val profile = profileFunction.getProfile() val profileStore = activePlugin.activeProfileInterface.profile diff --git a/app/src/main/res/layout/dialog_loop.xml b/app/src/main/res/layout/dialog_loop.xml index b0658e56e1..594d1855e3 100644 --- a/app/src/main/res/layout/dialog_loop.xml +++ b/app/src/main/res/layout/dialog_loop.xml @@ -51,6 +51,7 @@ From 261fbbc7596909b772303a9ba390099a0d66e325 Mon Sep 17 00:00:00 2001 From: Philoul Date: Tue, 4 May 2021 18:41:11 +0200 Subject: [PATCH 02/27] Replace Hardcoded key by string --- .../pump/insight/LocalInsightPlugin.java | 18 +++++++------- .../InsightConnectionService.java | 7 +++--- insight/src/main/res/values/strings.xml | 14 +++++++++-- .../main/res/xml/pref_insight_local_full.xml | 24 +++++++++---------- .../xml/pref_insight_local_pumpcontrol.xml | 22 ++++++++--------- 5 files changed, 48 insertions(+), 37 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 5626f4cdb1..6f230dee15 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -579,7 +579,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusMessage.setDuration(0); bolusMessage.setExtendedAmount(0); bolusMessage.setImmediateAmount(insulin); - bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? R.string.key_disable_vibration_auto : R.string.key_disable_vibration, false)); + bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? R.string.key_insight_disable_vibration_auto : R.string.key_insight_disable_vibration, false)); bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); bolusCancelled = false; } @@ -701,7 +701,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (cancelTBRResult.getSuccess()) { PumpEnactResult ebResult = setExtendedBolusOnly((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes, - sp.getBoolean(R.string.key_disable_vibration_auto, false)); + sp.getBoolean(R.string.key_insight_disable_vibration_auto, false)); if (ebResult.getSuccess()) { result.success(true) .enacted(true) @@ -780,7 +780,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) { PumpEnactResult result = cancelExtendedBolusOnly(); if (result.getSuccess()) - result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_disable_vibration, false)); + result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_insight_disable_vibration, false)); try { fetchStatus(); readHistory(); @@ -1130,7 +1130,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @Override public boolean isFakingTempsByExtendedBoluses() { - return sp.getBoolean("insight_enable_tbr_emulation", false); + return sp.getBoolean(R.string.key_insight_enable_tbr_emulation, false); } @NonNull @Override @@ -1254,7 +1254,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void processCannulaFilledEvent(CannulaFilledEvent event) { - if (!sp.getBoolean("insight_log_site_changes", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_site_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); @@ -1278,21 +1278,21 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void processTubeFilledEvent(TubeFilledEvent event) { - if (!sp.getBoolean("insight_log_tube_changes", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_tube_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); } private void processSniffingDoneEvent(SniffingDoneEvent event) { - if (!sp.getBoolean("insight_log_reservoir_changes", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_reservoir_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE); } private void processPowerUpEvent(PowerUpEvent event) { - if (!sp.getBoolean("insight_log_battery_changes", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_battery_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE); @@ -1446,7 +1446,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } private void processOccurrenceOfAlertEvent(OccurrenceOfAlertEvent event) { - if (!sp.getBoolean("insight_log_alerts", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_alerts, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; Integer code = null; diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java index cddceb1ddd..40edeebc7b 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java @@ -20,6 +20,7 @@ import java.util.List; import javax.inject.Inject; import dagger.android.DaggerService; +import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.insight.app_layer.AppLayerMessage; @@ -141,10 +142,10 @@ public class InsightConnectionService extends DaggerService implements Connectio } private void increaseRecoveryDuration() { - long maxRecoveryDuration = sp.getInt("insight_max_recovery_duration", 20); + long maxRecoveryDuration = sp.getInt(R.string.key_insight_max_recovery_duration, 20); maxRecoveryDuration = Math.min(maxRecoveryDuration, 20); maxRecoveryDuration = Math.max(maxRecoveryDuration, 0); - long minRecoveryDuration = sp.getInt("insight_min_recovery_duration", 5); + long minRecoveryDuration = sp.getInt(R.string.key_insight_min_recovery_duration, 5); minRecoveryDuration = Math.min(minRecoveryDuration, 20); minRecoveryDuration = Math.max(minRecoveryDuration, 0); recoveryDuration += 1000; @@ -295,7 +296,7 @@ public class InsightConnectionService extends DaggerService implements Connectio setState(InsightState.DISCONNECTED); cleanup(true); } else if (state != InsightState.DISCONNECTED) { - long disconnectTimeout = sp.getInt("insight_disconnect_delay", 5); + long disconnectTimeout = sp.getInt(R.string.key_insight_disconnect_delay, 5); disconnectTimeout = Math.min(disconnectTimeout, 15); disconnectTimeout = Math.max(disconnectTimeout, 0); aapsLogger.info(LTag.PUMP, "Last connection lock released, will disconnect in " + disconnectTimeout + " seconds"); diff --git a/insight/src/main/res/values/strings.xml b/insight/src/main/res/values/strings.xml index 8b235730bc..dd12e644a3 100644 --- a/insight/src/main/res/values/strings.xml +++ b/insight/src/main/res/values/strings.xml @@ -31,10 +31,20 @@ Tube changed Sight Insight Pump Alerts - insight_disable_vibration Disable vibrations on manual bolus delivery For bolus and extended bolus (only available with Insight firmware 3.x) - insight_disable_vibration_auto + insight_disable_vibration + insight_disable_vibration_auto + insight_enable_tbr_emulation + insight_log_site_changes + insight_log_tube_changes + insight_log_reservoir_changes + insight_log_battery_changes + insight_log_operating_mode_changes + insight_log_alerts + insight_min_recovery_duration + insight_max_recovery_duration + insight_disconnect_delay Disable vibrations on automated bolus delivery For SMB and Temp Basal with TBR emulation (only available with Insight firmware 3.x) Timeout during handshake - reset bluetooth diff --git a/insight/src/main/res/xml/pref_insight_local_full.xml b/insight/src/main/res/xml/pref_insight_local_full.xml index 1329db7de3..69fbec43a0 100644 --- a/insight/src/main/res/xml/pref_insight_local_full.xml +++ b/insight/src/main/res/xml/pref_insight_local_full.xml @@ -15,68 +15,68 @@ diff --git a/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml b/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml index b73c01f1f7..ca7743ec3a 100644 --- a/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml +++ b/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml @@ -15,62 +15,62 @@ From 8592ed3249b24f7eb6f2c9d6323274254d6183a2 Mon Sep 17 00:00:00 2001 From: Philoul Date: Tue, 4 May 2021 22:40:00 +0200 Subject: [PATCH 03/27] Update driver with pumpSync for boluses and TBR --- .../pump/insight/LocalInsightPlugin.java | 269 +++++++++++------- 1 file changed, 166 insertions(+), 103 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 6f230dee15..ad06a368f0 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -33,12 +33,9 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.InsightBolusID; import info.nightscout.androidaps.db.InsightHistoryOffset; import info.nightscout.androidaps.db.InsightPumpID; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.insight.R; @@ -54,7 +51,7 @@ import info.nightscout.androidaps.interfaces.Pump; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpSync; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.interfaces.PumpSync.PumpState.TemporaryBasal; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -131,6 +128,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -140,7 +138,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private final AAPSLogger aapsLogger; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; - private final TreatmentsInterface treatmentsPlugin; private final SP sp; private final CommandQueueProvider commandQueue; private final ProfileFunction profileFunction; @@ -199,7 +196,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, - TreatmentsInterface treatmentsPlugin, SP sp, CommandQueueProvider commandQueue, ProfileFunction profileFunction, @@ -223,7 +219,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; - this.treatmentsPlugin = treatmentsPlugin; this.sp = sp; this.commandQueue = commandQueue; this.profileFunction = profileFunction; @@ -376,7 +371,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai calendar.set(Calendar.HOUR_OF_DAY, pumpTime.getHour()); calendar.set(Calendar.MINUTE, pumpTime.getMinute()); calendar.set(Calendar.SECOND, pumpTime.getSecond()); - if (calendar.get(Calendar.HOUR_OF_DAY) != pumpTime.getHour() || Math.abs(calendar.getTimeInMillis() - System.currentTimeMillis()) > 10000) { + if (calendar.get(Calendar.HOUR_OF_DAY) != pumpTime.getHour() || Math.abs(calendar.getTimeInMillis() - dateUtil.now()) > 10000) { calendar.setTime(new Date()); pumpTime.setYear(calendar.get(Calendar.YEAR)); pumpTime.setMonth(calendar.get(Calendar.MONTH) + 1); @@ -544,7 +539,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @Override public long lastDataTime() { - if (connectionService == null || alertService == null) return System.currentTimeMillis(); + if (connectionService == null || alertService == null) return dateUtil.now(); return connectionService.getLastDataTime(); } @@ -569,6 +564,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { + if (detailedBolusInfo.insulin == 0 || detailedBolusInfo.carbs > 0) { + throw new IllegalArgumentException(detailedBolusInfo.toString(), new Exception()); + } PumpEnactResult result = new PumpEnactResult(getInjector()); double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01; if (insulin > 0) { @@ -591,25 +589,21 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusingEvent.setPercent(0); rxBus.send(bolusingEvent); int trials = 0; + // Move to Insight room database InsightBolusID insightBolusID = new InsightBolusID(); insightBolusID.bolusID = bolusID; insightBolusID.timestamp = System.currentTimeMillis(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); + aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); + /* detailedBolusInfo.setBolusTimestamp(insightBolusID.timestamp); detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); detailedBolusInfo.setPumpSerial(serialNumber()); detailedBolusInfo.setBolusPumpId(insightBolusID.id); - if (detailedBolusInfo.carbs > 0 && detailedBolusInfo.carbTime != 0) { - DetailedBolusInfo carbInfo = new DetailedBolusInfo(); - carbInfo.carbs = detailedBolusInfo.carbs; - carbInfo.setCarbsTimestamp(detailedBolusInfo.timestamp + detailedBolusInfo.carbTime * 60L * 1000L); - carbInfo.setPumpType(PumpType.USER); - treatmentsPlugin.addToHistoryTreatment(carbInfo, false); - detailedBolusInfo.carbTime = 0; - detailedBolusInfo.carbs = 0; - } treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + + */ while (true) { synchronized ($bolusLock) { if (bolusCancelled) break; @@ -657,10 +651,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai aapsLogger.error("Exception while delivering bolus", e); result.comment(ExceptionTranslator.getString(context, e)); } - } else if (detailedBolusInfo.carbs > 0) { - result.success(true).enacted(true); + result.bolusDelivered(insulin); } - result.carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(insulin); return result; } @@ -676,6 +668,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusCancelled = true; confirmAlert(AlertType.WARNING_38); alertService.ignore(null); + aapsLogger.debug(LTag.PUMP, "XXXX Stop Bolus : " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now())); } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -761,8 +754,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai .success(true) .enacted(true) .comment(R.string.virtualpump_resultok); + aapsLogger.debug(LTag.PUMP, "XXXX Set Temp Basal timestamp: " + dateUtil.now() + " rate: " + percent + " duration: " + durationInMinutes); + fetchStatus(); // here I switched fetchStatus and readHistory (I noticed that we could miss the latest command sent to the pump if readHistory is before readHistory(); - fetchStatus(); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment(ExceptionTranslator.getString(context, e)); @@ -809,13 +803,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai insightBolusID.timestamp = System.currentTimeMillis(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = insightBolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = durationInMinutes; - extendedBolus.insulin = insulin; - extendedBolus.pumpId = insightBolusID.id; - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + aapsLogger.debug(LTag.PUMP, "XXXX Set Extended timestamp: " + dateUtil.now() + " amount: " + insulin + "U duration: " + durationInMinutes + "BolusId: " + bolusID); result.success(true).enacted(true).comment(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -836,7 +824,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai PumpEnactResult cancelEBResult = null; if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly(); PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); - result.success((cancelEBResult != null && cancelEBResult.getSuccess()) && cancelTBRResult.getSuccess()); + result.success((cancelEBResult == null || (cancelEBResult != null && cancelEBResult.getSuccess())) && cancelTBRResult.getSuccess()); //Fix a bug when Fake TBR is disabled and click on Cancel TBR button result.enacted((cancelEBResult != null && cancelEBResult.getEnacted()) || cancelTBRResult.getEnacted()); result.comment(cancelEBResult != null ? cancelEBResult.getComment() : cancelTBRResult.getComment()); try { @@ -863,6 +851,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai confirmAlert(AlertType.WARNING_36); alertService.ignore(null); result.comment(R.string.virtualpump_resultok); + aapsLogger.debug(LTag.PUMP, "XXXX cancel Temp Basal time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now())); } catch (NoActiveTBRToCanceLException e) { result.success(true); result.comment(R.string.virtualpump_resultok); @@ -909,18 +898,18 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai InsightBolusID insightBolusID = databaseHelper.getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(), activeBolus.getBolusID(), System.currentTimeMillis()); if (insightBolusID != null) { - ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); + /* Search in Insight room database + PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); if (extendedBolus != null) { extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000); if (extendedBolus.durationInMinutes <= 0) { final String _id = extendedBolus._id; -// if (NSUpload.isIdValid(_id)) -// nsUpload.removeCareportalEntryFromNS(_id); -// else uploadQueue.removeByMongoId("dbAdd", _id); databaseHelper.delete(extendedBolus); } else treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); } + */ + aapsLogger.debug(LTag.PUMP, "XXXX cancel Extended Bolus time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " BolusId: " + activeBolus.getBolusID()); result.enacted(true).success(true); } } @@ -941,8 +930,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void confirmAlert(AlertType alertType) { try { - long started = System.currentTimeMillis(); - while (System.currentTimeMillis() - started < 10000) { + long started = dateUtil.now(); + while (dateUtil.now() - started < 10000) { GetActiveAlertMessage activeAlertMessage = connectionService.requestMessage(new GetActiveAlertMessage()).await(); if (activeAlertMessage.getAlert() != null) { if (activeAlertMessage.getAlert().getAlertType() == alertType) { @@ -963,9 +952,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public JSONObject getJSONStatus(@NonNull Profile profile, @NonNull String profileName, @NonNull String version) { - long now = System.currentTimeMillis(); + long now = dateUtil.now(); if (connectionService == null) return new JSONObject(); - if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { + if (dateUtil.now() - connectionService.getLastConnected() > (60 * 60 * 1000)) { return new JSONObject(); } @@ -1103,7 +1092,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai public String shortStatus(boolean veryShort) { StringBuilder ret = new StringBuilder(); if (connectionService.getLastConnected() != 0) { - long agoMsec = System.currentTimeMillis() - connectionService.getLastConnected(); + long agoMsec = dateUtil.now() - connectionService.getLastConnected(); int agoMin = (int) (agoMsec / 60d / 1000d); ret.append(resourceHelper.gs(R.string.short_status_last_connected, agoMin)).append("\n"); } @@ -1144,6 +1133,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai String pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); + // Move to Insight room database InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial); try { List historyEvents = new ArrayList<>(); @@ -1168,6 +1158,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Collections.reverse(historyEvents); if (historyOffset != null) processHistoryEvents(pumpSerial, historyEvents); if (historyEvents.size() > 0) { + // Move to Insight room database historyOffset = new InsightHistoryOffset(); historyOffset.pumpSerial = pumpSerial; historyOffset.offset = historyEvents.get(0).getEventPosition(); @@ -1202,22 +1193,42 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (!processHistoryEvent(serial, temporaryBasals, pumpStartedEvents, historyEvent)) break; Collections.reverse(temporaryBasals); + for (InsightPumpID pumpID : pumpStartedEvents) { InsightPumpID stoppedEvent = databaseHelper.getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp); if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue; long tbrStart = stoppedEvent.timestamp + 10000; - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = (int) ((pumpID.timestamp - tbrStart) / 60000); - temporaryBasal.date = tbrStart; - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.percentRate = 0; - temporaryBasal.isAbsolute = false; + TemporaryBasal temporaryBasal = new TemporaryBasal( + tbrStart, + pumpID.timestamp - tbrStart, + 0, + false, + PumpSync.TemporaryBasalType.NORMAL, + pumpID.id, + pumpID.id); temporaryBasals.add(temporaryBasal); } - temporaryBasals.sort((o1, o2) -> (int) (o1.date - o2.date)); - for (TemporaryBasal temporaryBasal : temporaryBasals) - treatmentsPlugin.addToHistoryTempBasal(temporaryBasal); + temporaryBasals.sort((o1, o2) -> (int) (o1.getTimestamp() - o2.getTimestamp())); + for (TemporaryBasal temporaryBasal : temporaryBasals) { + if (temporaryBasal.getRate() == 100.0) { // for Stop TBR event rate = 100.0 + pumpSync.syncStopTemporaryBasalWithPumpId( + temporaryBasal.getTimestamp(), + temporaryBasal.getPumpId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); + } + if (temporaryBasal.getRate() != 100.0){ + Boolean resultdb = pumpSync.syncTemporaryBasalWithPumpId( + temporaryBasal.getTimestamp(), + temporaryBasal.getRate(), + temporaryBasal.getDuration(), + temporaryBasal.isAbsolute(), + temporaryBasal.getType(), + temporaryBasal.getPumpId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); + } + } } private boolean processHistoryEvent(String serial, List temporaryBasals, List pumpStartedEvents, HistoryEvent event) { @@ -1225,13 +1236,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai else if (event instanceof DateTimeChangedEvent) processDateTimeChangedEvent((DateTimeChangedEvent) event); else if (event instanceof CannulaFilledEvent) - processCannulaFilledEvent((CannulaFilledEvent) event); + processCannulaFilledEvent(serial, (CannulaFilledEvent) event); else if (event instanceof TotalDailyDoseEvent) - processTotalDailyDoseEvent((TotalDailyDoseEvent) event); - else if (event instanceof TubeFilledEvent) processTubeFilledEvent((TubeFilledEvent) event); + processTotalDailyDoseEvent(serial, (TotalDailyDoseEvent) event); + else if (event instanceof TubeFilledEvent) processTubeFilledEvent(serial, (TubeFilledEvent) event); else if (event instanceof SniffingDoneEvent) - processSniffingDoneEvent((SniffingDoneEvent) event); - else if (event instanceof PowerUpEvent) processPowerUpEvent((PowerUpEvent) event); + processSniffingDoneEvent(serial, (SniffingDoneEvent) event); + else if (event instanceof PowerUpEvent) processPowerUpEvent(serial, (PowerUpEvent) event); else if (event instanceof OperatingModeChangedEvent) processOperatingModeChangedEvent(serial, pumpStartedEvents, (OperatingModeChangedEvent) event); else if (event instanceof StartOfTBREvent) @@ -1253,19 +1264,28 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timeOffset -= timeAfter - timeBefore; } - private void processCannulaFilledEvent(CannulaFilledEvent event) { + private void processCannulaFilledEvent(String serial, CannulaFilledEvent event) { if (!sp.getBoolean(R.string.key_insight_log_site_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); + aapsLogger.debug(LTag.PUMP, "XXXX event Site Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp, + DetailedBolusInfo.EventType.CANNULA_CHANGE, + "", + event.getEventPosition(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } - private void processTotalDailyDoseEvent(TotalDailyDoseEvent event) { + private void processTotalDailyDoseEvent(String serial, TotalDailyDoseEvent event) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(0)); calendar.set(Calendar.YEAR, event.getTotalYear()); calendar.set(Calendar.MONTH, event.getTotalMonth() - 1); calendar.set(Calendar.DAY_OF_MONTH, event.getTotalDay()); + aapsLogger.debug(LTag.PUMP, "XXXX event Daily Dose event day: " + event.getTotalYear() + "/" + (event.getTotalMonth() - 1) + "/" + event.getTotalDay() + " Basal: " + event.getBasalTotal() + " Bolus: " + event.getBolusTotal()); pumpSync.createOrUpdateTotalDailyDose( calendar.getTimeInMillis(), event.getBolusTotal(), @@ -1273,29 +1293,52 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai 0.0, // will be calculated automatically null, PumpType.ACCU_CHEK_INSIGHT, - serialNumber() - ); + serial); } - private void processTubeFilledEvent(TubeFilledEvent event) { + private void processTubeFilledEvent(String serial, TubeFilledEvent event) { if (!sp.getBoolean(R.string.key_insight_log_tube_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); + aapsLogger.debug(LTag.PUMP, "XXXX event Tube Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp, + DetailedBolusInfo.EventType.INSULIN_CHANGE, + "", + event.getEventPosition(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } - private void processSniffingDoneEvent(SniffingDoneEvent event) { + private void processSniffingDoneEvent(String serial, SniffingDoneEvent event) { if (!sp.getBoolean(R.string.key_insight_log_reservoir_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE); + aapsLogger.debug(LTag.PUMP, "XXXX event Reservoir Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp, + DetailedBolusInfo.EventType.INSULIN_CHANGE, + "", + event.getEventPosition(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } - private void processPowerUpEvent(PowerUpEvent event) { + private void processPowerUpEvent(String serial, PowerUpEvent event) { if (!sp.getBoolean(R.string.key_insight_log_battery_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE); + aapsLogger.debug(LTag.PUMP, "XXXX event Battery Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp, + DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE, + "", + null, + PumpType.ACCU_CHEK_INSIGHT, + serial); } private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, OperatingModeChangedEvent event) { @@ -1311,60 +1354,72 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_started)); + aapsLogger.debug(LTag.PUMP, "XXXX event START Event TimeStamp: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case STOPPED: pumpID.eventType = "PumpStopped"; if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); + aapsLogger.debug(LTag.PUMP, "XXXX event STOP: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case PAUSED: pumpID.eventType = "PumpPaused"; if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); + aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; } + // Move to Insight room database databaseHelper.createOrUpdate(pumpID); } private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; + // Move to Insight room database InsightPumpID pumpID = new InsightPumpID(); pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; pumpID.timestamp = timestamp; pumpID.eventType = "StartOfTBR"; databaseHelper.createOrUpdate(pumpID); - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = event.getDuration(); - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.percentRate = event.getAmount(); - temporaryBasal.isAbsolute = false; - temporaryBasal.date = timestamp; + // + TemporaryBasal temporaryBasal = new TemporaryBasal( + timestamp, + T.mins(event.getDuration()).msecs(), + event.getAmount(), + false, + PumpSync.TemporaryBasalType.NORMAL, + pumpID.id, + pumpID.eventID); // margin added because on several reeadHistory, timestamp could vary temporaryBasals.add(temporaryBasal); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; + // Move to Insight room database InsightPumpID pumpID = new InsightPumpID(); pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; pumpID.eventType = "EndOfTBR"; pumpID.timestamp = timestamp; databaseHelper.createOrUpdate(pumpID); - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = 0; - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.date = timestamp - 1500L; + TemporaryBasal temporaryBasal = new PumpSync.PumpState.TemporaryBasal( + timestamp - 1500L, + 0L, + 100.0, + false, + PumpSync.TemporaryBasalType.NORMAL, + pumpID.id, + pumpID.eventID); temporaryBasals.add(temporaryBasal); } private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; + // Move to Insight room database InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID != null && bolusID.endID != null) { bolusID.startID = event.getEventPosition(); @@ -1379,24 +1434,26 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } bolusID.startID = event.getEventPosition(); databaseHelper.createOrUpdate(bolusID); + // if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.timestamp = bolusID.timestamp; - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + pumpSync.syncBolusWithPumpId( + bolusID.timestamp, + event.getImmediateAmount(), + null, + bolusID.id, + PumpType.ACCU_CHEK_INSIGHT, + serial); } if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + if (profileFunction.getProfile(bolusID.timestamp) != null) + pumpSync.syncExtendedBolusWithPumpId( + bolusID.timestamp, + event.getExtendedAmount(), + T.mins(event.getDuration()).msecs(), + isFakingTempsByExtendedBoluses(), + bolusID.id, + PumpType.ACCU_CHEK_INSIGHT, + serial); } } @@ -1405,6 +1462,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; + // Move to Insight room database InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID == null || bolusID.endID != null) { bolusID = new InsightBolusID(); @@ -1414,17 +1472,19 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } bolusID.endID = event.getEventPosition(); databaseHelper.createOrUpdate(bolusID); + // if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + pumpSync.syncBolusWithPumpId( + bolusID.timestamp, + event.getImmediateAmount(), + null, + bolusID.id, + PumpType.ACCU_CHEK_INSIGHT, + serial); } if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { if (event.getDuration() == 0) { + /* ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(bolusID.id); if (extendedBolus != null) { final String _id = extendedBolus._id; @@ -1432,15 +1492,18 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai // else uploadQueue.removeByMongoId("dbAdd", _id); databaseHelper.delete(extendedBolus); } + + */ } else { - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + if (profileFunction.getProfile(bolusID.timestamp) != null) + pumpSync.syncExtendedBolusWithPumpId( + bolusID.timestamp, + event.getExtendedAmount(), + T.mins(event.getDuration()).msecs(), + isFakingTempsByExtendedBoluses(), + bolusID.id, + PumpType.ACCU_CHEK_INSIGHT, + serial); } } } From 117fda424473c4dec073b337fdfb24d199ff6f59 Mon Sep 17 00:00:00 2001 From: Philoul Date: Wed, 5 May 2021 08:27:41 +0200 Subject: [PATCH 04/27] Fix SMB remove comment linked to previous version --- .../pump/insight/LocalInsightPlugin.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index ad06a368f0..de069a1f31 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -592,18 +592,17 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai // Move to Insight room database InsightBolusID insightBolusID = new InsightBolusID(); insightBolusID.bolusID = bolusID; - insightBolusID.timestamp = System.currentTimeMillis(); + insightBolusID.timestamp = dateUtil.now(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); - /* - detailedBolusInfo.setBolusTimestamp(insightBolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(insightBolusID.id); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); - - */ + pumpSync.syncBolusWithPumpId( + insightBolusID.timestamp, + detailedBolusInfo.insulin, + detailedBolusInfo.getBolusType(), + insightBolusID.id, + PumpType.ACCU_CHEK_INSIGHT, + serialNumber()); while (true) { synchronized ($bolusLock) { if (bolusCancelled) break; @@ -755,7 +754,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai .enacted(true) .comment(R.string.virtualpump_resultok); aapsLogger.debug(LTag.PUMP, "XXXX Set Temp Basal timestamp: " + dateUtil.now() + " rate: " + percent + " duration: " + durationInMinutes); - fetchStatus(); // here I switched fetchStatus and readHistory (I noticed that we could miss the latest command sent to the pump if readHistory is before + fetchStatus(); readHistory(); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -1492,7 +1491,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai // else uploadQueue.removeByMongoId("dbAdd", _id); databaseHelper.delete(extendedBolus); } - */ } else { if (profileFunction.getProfile(bolusID.timestamp) != null) From f789888afd8cc989900d66fff13b3cbc0d75e3ec Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 7 May 2021 10:21:34 +0200 Subject: [PATCH 05/27] Fix SMB remove comment linked to previous version --- .../dependencyInjection/AppComponent.kt | 4 +- .../maintenance/MaintenanceFragment.kt | 3 + insight/build.gradle | 12 + .../insight/di/InsightActivitiesModule.kt | 2 +- .../insight/di/InsightCommModule.kt | 2 +- .../insight/di/InsightDatabaseModule.kt | 23 ++ .../androidaps/insight/di/InsightModule.kt | 10 +- .../insight/di/InsightServicesModule.kt | 2 +- .../pump/insight/LocalInsightPlugin.java | 267 +++++++++++++----- .../pump/insight/database/InsightBolusID.kt | 18 ++ .../pump/insight/database/InsightDatabase.kt | 34 +++ .../insight/database/InsightDatabaseDao.kt | 28 ++ .../insight/database/InsightHistoryOffset.kt | 12 + .../pump/insight/database/InsightPumpID.kt | 17 ++ 14 files changed, 356 insertions(+), 78 deletions(-) create mode 100644 insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt create mode 100644 insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt create mode 100644 insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt create mode 100644 insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt create mode 100644 insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt create mode 100644 insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 05b5974bb5..1421d586ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -12,8 +12,9 @@ import info.nightscout.androidaps.di.CoreModule import info.nightscout.androidaps.dana.di.DanaModule import info.nightscout.androidaps.danar.di.DanaRModule import info.nightscout.androidaps.danars.di.DanaRSModule -import info.nightscout.androidaps.danars.di.InsightModule import info.nightscout.androidaps.database.DatabaseModule +import info.nightscout.androidaps.insight.di.InsightDatabaseModule +import info.nightscout.androidaps.insight.di.InsightModule import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.dagger.OmnipodErosModule @@ -51,6 +52,7 @@ import javax.inject.Singleton DanaRSModule::class, ComboModule::class, InsightModule::class, + InsightDatabaseModule::class, WorkersModule::class, OHUploaderModule::class ] diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 8ff8dac818..67ea1166e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -21,6 +21,7 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData +import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabase import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -39,6 +40,7 @@ class MaintenanceFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase + @Inject lateinit var insightDatabase: InsightDatabase @Inject lateinit var uel: UserEntryLogger @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var pumpSync: PumpSync @@ -70,6 +72,7 @@ class MaintenanceFragment : DaggerFragment() { fromAction { repository.clearDatabases() danaHistoryDatabase.clearAllTables() + insightDatabase.clearAllTables() dataSyncSelector.resetToNextFullSync() pumpSync.connectNewPump() } diff --git a/insight/build.gradle b/insight/build.gradle index 8020051b31..14391efbea 100644 --- a/insight/build.gradle +++ b/insight/build.gradle @@ -12,9 +12,21 @@ android { defaultConfig { versionCode 1 versionName "1.0" + kapt { + arguments { + arg("room.incremental", "true") + arg("room.schemaLocation", "$projectDir/schemas") + } + } } } dependencies { implementation project(':core') + + api "androidx.room:room-ktx:$room_version" + api "androidx.room:room-runtime:$room_version" + api "androidx.room:room-rxjava2:$room_version" + kapt "androidx.room:room-compiler:$room_version" + kapt "android.arch.persistence.room:compiler:$room_version" } \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt index 7a3024a501..b65a707469 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module import dagger.android.ContributesAndroidInjector diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt index 4aeed99770..7073ad14ae 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt new file mode 100644 index 0000000000..c55a0481ad --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.insight.di + +import android.content.Context +import dagger.Module +import dagger.Provides +import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabase +import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabaseDao +import javax.inject.Singleton + +@Module +class InsightDatabaseModule { + + @Provides + @Singleton + internal fun provideDatabase(context: Context): InsightDatabase = InsightDatabase.build(context) + + @Provides + @Singleton + internal fun provideInsightDatabaseDao(insightDatabase: InsightDatabase): InsightDatabaseDao = + insightDatabase.insightDatabaseDao() + + +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt index 59d3a3de2a..af2a086dbf 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt @@ -1,10 +1,14 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module +import dagger.android.ContributesAndroidInjector @Module(includes = [ InsightCommModule::class, InsightActivitiesModule::class, - InsightServicesModule::class + InsightServicesModule::class, + InsightDatabaseModule::class ]) -open class InsightModule \ No newline at end of file + +@Suppress("unused") +abstract class InsightModule \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt index 3d9a4bc52e..1684d6f9de 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module import dagger.android.ContributesAndroidInjector diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index de069a1f31..0f605e87f5 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -33,9 +33,9 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.InsightBolusID; -import info.nightscout.androidaps.db.InsightHistoryOffset; -import info.nightscout.androidaps.db.InsightPumpID; +//import info.nightscout.androidaps.db.InsightBolusID; +//import info.nightscout.androidaps.db.InsightHistoryOffset; +//import info.nightscout.androidaps.db.InsightPumpID; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.insight.R; @@ -43,7 +43,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Config; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraints; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; +//import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileFunction; @@ -108,6 +108,10 @@ import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetPumpS import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetTotalDailyDoseMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.ResetPumpStatusRegisterMessage; import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService; +import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; +import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabaseDao; +import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; +import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR; @@ -143,7 +147,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private final ProfileFunction profileFunction; private final Context context; private final DateUtil dateUtil; - private final DatabaseHelperInterface databaseHelper; + private final InsightDatabaseDao insightDatabaseDao; private final PumpSync pumpSync; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -202,7 +206,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Context context, Config config, DateUtil dateUtil, - DatabaseHelperInterface databaseHelper, + InsightDatabaseDao insightDatabaseDao, PumpSync pumpSync ) { super(new PluginDescription() @@ -224,7 +228,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.profileFunction = profileFunction; this.context = context; this.dateUtil = dateUtil; - this.databaseHelper = databaseHelper; + this.insightDatabaseDao = insightDatabaseDao; this.pumpSync = pumpSync; pumpDescription = new PumpDescription(); @@ -589,18 +593,28 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusingEvent.setPercent(0); rxBus.send(bolusingEvent); int trials = 0; - // Move to Insight room database - InsightBolusID insightBolusID = new InsightBolusID(); + Long now = dateUtil.now(); + String serial = serialNumber(); + insightDatabaseDao.createOrUpdate( new InsightBolusID( + now, + serial, + bolusID, + null, + null + )); + InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serial, bolusID, now); + /* insightBolusID.bolusID = bolusID; insightBolusID.timestamp = dateUtil.now(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); + */ aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); pumpSync.syncBolusWithPumpId( - insightBolusID.timestamp, + insightBolusID.getTimestamp(), detailedBolusInfo.insulin, detailedBolusInfo.getBolusType(), - insightBolusID.id, + insightBolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serialNumber()); while (true) { @@ -754,8 +768,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai .enacted(true) .comment(R.string.virtualpump_resultok); aapsLogger.debug(LTag.PUMP, "XXXX Set Temp Basal timestamp: " + dateUtil.now() + " rate: " + percent + " duration: " + durationInMinutes); - fetchStatus(); readHistory(); + fetchStatus(); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while setting TBR: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); result.comment(ExceptionTranslator.getString(context, e)); @@ -797,11 +811,19 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusMessage.setImmediateAmount(0); bolusMessage.setVibration(disableVibration); int bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); - InsightBolusID insightBolusID = new InsightBolusID(); + insightDatabaseDao.createOrUpdate(new InsightBolusID( + dateUtil.now(), + serialNumber(), + bolusID, + null, + null + )); + /* insightBolusID.bolusID = bolusID; insightBolusID.timestamp = System.currentTimeMillis(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); databaseHelper.createOrUpdate(insightBolusID); + */ aapsLogger.debug(LTag.PUMP, "XXXX Set Extended timestamp: " + dateUtil.now() + " amount: " + insulin + "U duration: " + durationInMinutes + "BolusId: " + bolusID); result.success(true).enacted(true).comment(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { @@ -894,9 +916,22 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai connectionService.requestMessage(cancelBolusMessage).await(); confirmAlert(AlertType.WARNING_38); alertService.ignore(null); + InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); + /* InsightBolusID insightBolusID = databaseHelper.getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(), activeBolus.getBolusID(), System.currentTimeMillis()); + + */ if (insightBolusID != null) { + PumpSync.PumpState.ExtendedBolus extendedBolus = pumpSync.expectedPumpState().getExtendedBolus(); + if (extendedBolus != null) { + if ((dateUtil.now()- extendedBolus.getTimestamp()) / 60000 <= 0) { + //final String _id = extendedBolus._id; + //databaseHelper.delete(extendedBolus); + } else { + //treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + } + } /* Search in Insight room database PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); if (extendedBolus != null) { @@ -1129,11 +1164,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void readHistory() { try { PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime(); - String pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); + String serial = serialNumber(); timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); - // Move to Insight room database - InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial); + InsightHistoryOffset historyOffset = insightDatabaseDao.getInsightHistoryOffset(serial); + //InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial); try { List historyEvents = new ArrayList<>(); if (historyOffset == null) { @@ -1145,7 +1180,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } else { StartReadingHistoryMessage startMessage = new StartReadingHistoryMessage(); startMessage.setDirection(HistoryReadingDirection.FORWARD); - startMessage.setOffset(historyOffset.offset + 1); + startMessage.setOffset(historyOffset.getOffset() + 1); connectionService.requestMessage(startMessage).await(); while (true) { List newEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents(); @@ -1155,13 +1190,18 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } Collections.sort(historyEvents); Collections.reverse(historyEvents); - if (historyOffset != null) processHistoryEvents(pumpSerial, historyEvents); + if (historyOffset != null) processHistoryEvents(serial, historyEvents); if (historyEvents.size() > 0) { - // Move to Insight room database + historyOffset = new InsightHistoryOffset( + serial, + historyEvents.get(0).getEventPosition()); + insightDatabaseDao.createOrUpdate(historyOffset); + /* historyOffset = new InsightHistoryOffset(); historyOffset.pumpSerial = pumpSerial; historyOffset.offset = historyEvents.get(0).getEventPosition(); databaseHelper.createOrUpdate(historyOffset); + */ } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -1194,22 +1234,29 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Collections.reverse(temporaryBasals); for (InsightPumpID pumpID : pumpStartedEvents) { - InsightPumpID stoppedEvent = databaseHelper.getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp); - if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue; - long tbrStart = stoppedEvent.timestamp + 10000; + InsightPumpID stoppedEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), pumpID.getTimestamp()); + if (stoppedEvent != null && stoppedEvent.getEventType().equals("PumpStopped")) { // Search if Stop event is after 15min of Pause + InsightPumpID pauseEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), stoppedEvent.getTimestamp() - T.mins(1).msecs()); + if (pauseEvent != null && pauseEvent.getEventType().equals("PumpPaused") && (stoppedEvent.getTimestamp() - pauseEvent.getTimestamp() < T.mins(16).msecs())) { + stoppedEvent = pauseEvent; + stoppedEvent.setEventType("PumpStopped"); + } + } + if (stoppedEvent == null || stoppedEvent.getEventType().equals("PumpPaused")) continue; + long tbrStart = stoppedEvent.getTimestamp() + 10000; TemporaryBasal temporaryBasal = new TemporaryBasal( tbrStart, - pumpID.timestamp - tbrStart, + pumpID.getTimestamp() - tbrStart, 0, false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.id, - pumpID.id); + pumpID.getId(), + pumpID.getEventID()); temporaryBasals.add(temporaryBasal); } temporaryBasals.sort((o1, o2) -> (int) (o1.getTimestamp() - o2.getTimestamp())); for (TemporaryBasal temporaryBasal : temporaryBasals) { - if (temporaryBasal.getRate() == 100.0) { // for Stop TBR event rate = 100.0 + if (temporaryBasal.getDuration() == 0L) { // for Stop TBR event duration = 0L pumpSync.syncStopTemporaryBasalWithPumpId( temporaryBasal.getTimestamp(), temporaryBasal.getPumpId(), @@ -1217,7 +1264,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai serial); } if (temporaryBasal.getRate() != 100.0){ - Boolean resultdb = pumpSync.syncTemporaryBasalWithPumpId( + pumpSync.syncTemporaryBasalWithPumpId( temporaryBasal.getTimestamp(), temporaryBasal.getRate(), temporaryBasal.getDuration(), @@ -1290,7 +1337,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getBolusTotal(), event.getBasalTotal(), 0.0, // will be calculated automatically - null, + event.getEventPosition(), PumpType.ACCU_CHEK_INSIGHT, serial); } @@ -1335,7 +1382,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE, "", - null, + event.getEventPosition(), PumpType.ACCU_CHEK_INSIGHT, serial); } @@ -1343,45 +1390,57 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, OperatingModeChangedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID(); - pumpID.eventID = event.getEventPosition(); + InsightPumpID pumpID = new InsightPumpID( + timestamp, + "", + serial, + event.getEventPosition()); + /* + pumpID.EventID = event.getEventPosition(); pumpID.pumpSerial = serial; pumpID.timestamp = timestamp; + */ switch (event.getNewValue()) { case STARTED: - pumpID.eventType = "PumpStarted"; + pumpID.setEventType("PumpStarted"); pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_started)); aapsLogger.debug(LTag.PUMP, "XXXX event START Event TimeStamp: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case STOPPED: - pumpID.eventType = "PumpStopped"; + pumpID.setEventType("PumpStopped"); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); aapsLogger.debug(LTag.PUMP, "XXXX event STOP: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case PAUSED: - pumpID.eventType = "PumpPaused"; + pumpID.setEventType("PumpPaused"); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; } - // Move to Insight room database - databaseHelper.createOrUpdate(pumpID); + // databaseHelper.createOrUpdate(pumpID); + insightDatabaseDao.createOrUpdate(pumpID); } private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - // Move to Insight room database - InsightPumpID pumpID = new InsightPumpID(); + InsightPumpID pumpID = new InsightPumpID( + timestamp, + "StartOfTBR", + serial, + event.getEventPosition()); + insightDatabaseDao.createOrUpdate(pumpID); + /* pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; pumpID.timestamp = timestamp; pumpID.eventType = "StartOfTBR"; databaseHelper.createOrUpdate(pumpID); + */ // TemporaryBasal temporaryBasal = new TemporaryBasal( timestamp, @@ -1389,70 +1448,107 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getAmount(), false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.id, - pumpID.eventID); // margin added because on several reeadHistory, timestamp could vary + pumpID.getEventID(), + pumpID.getEventID()); // margin added because on several reeadHistory, timestamp could vary temporaryBasals.add(temporaryBasal); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - // Move to Insight room database - InsightPumpID pumpID = new InsightPumpID(); + InsightPumpID pumpID = new InsightPumpID( + timestamp - 1500L, + "EndOfTBR", + serial, + event.getEventPosition()); + insightDatabaseDao.createOrUpdate(pumpID); + /* pumpID.eventID = event.getEventPosition(); pumpID.pumpSerial = serial; pumpID.eventType = "EndOfTBR"; pumpID.timestamp = timestamp; databaseHelper.createOrUpdate(pumpID); + */ TemporaryBasal temporaryBasal = new PumpSync.PumpState.TemporaryBasal( timestamp - 1500L, 0L, 100.0, false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.id, - pumpID.eventID); + pumpID.getId(), + pumpID.getEventID()); temporaryBasals.add(temporaryBasal); } private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - // Move to Insight room database - InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID != null && bolusID.endID != null) { - bolusID.startID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); + InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + //InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); + if (bolusID != null && bolusID.getEndID() != null) { + bolusID.setStartID(event.getEventPosition()); + insightDatabaseDao.createOrUpdate(bolusID); + //databaseHelper.createOrUpdate(bolusID); return; } - if (bolusID == null || bolusID.startID != null) { - bolusID = new InsightBolusID(); + if (bolusID == null || bolusID.getStartID() != null) { + insightDatabaseDao.createOrUpdate(new InsightBolusID( + timestamp, + serial, + event.getBolusID(), + event.getEventPosition(), + null + )); + bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + /* + bolusID = new info.nightscout.androidaps.db.InsightBolusID(); bolusID.timestamp = timestamp; bolusID.bolusID = event.getBolusID(); bolusID.pumpSerial = serial; + */ } - bolusID.startID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); - // + bolusID.setStartID(event.getEventPosition()); + insightDatabaseDao.createOrUpdate(bolusID); + + //databaseHelper.createOrUpdate(bolusID); if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( - bolusID.timestamp, + bolusID.getTimestamp(), event.getImmediateAmount(), null, - bolusID.id, + bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); + /* + DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); + detailedBolusInfo.timestamp = bolusID.timestamp; + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); + detailedBolusInfo.setPumpSerial(serialNumber()); + detailedBolusInfo.setBolusPumpId(bolusID.id); + detailedBolusInfo.insulin = event.getImmediateAmount(); + treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + */ } if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { - if (profileFunction.getProfile(bolusID.timestamp) != null) + if (profileFunction.getProfile(bolusID.getTimestamp()) != null) pumpSync.syncExtendedBolusWithPumpId( - bolusID.timestamp, + bolusID.getTimestamp(), event.getExtendedAmount(), T.mins(event.getDuration()).msecs(), isFakingTempsByExtendedBoluses(), - bolusID.id, + bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); + /* + ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); + extendedBolus.date = bolusID.timestamp; + extendedBolus.source = Source.PUMP; + extendedBolus.durationInMinutes = event.getDuration(); + extendedBolus.insulin = event.getExtendedAmount(); + extendedBolus.pumpId = bolusID.id; + if (profileFunction.getProfile(extendedBolus.date) != null) + treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + */ } } @@ -1461,25 +1557,44 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; - // Move to Insight room database - InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID == null || bolusID.endID != null) { - bolusID = new InsightBolusID(); + InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + //InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); + if (bolusID == null || bolusID.getEndID() != null) { + bolusID = new InsightBolusID( + startTimestamp, + serial, + event.getBolusID(), + bolusID == null ? event.getEventPosition() : bolusID.getStartID(), + event.getEventPosition() + ); + /* + bolusID = new InsightBolusID(); bolusID.timestamp = startTimestamp; bolusID.bolusID = event.getBolusID(); bolusID.pumpSerial = serial; + */ } - bolusID.endID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); - // + bolusID.setEndID(event.getEventPosition()); + insightDatabaseDao.createOrUpdate(bolusID); + bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id + //databaseHelper.createOrUpdate(bolusID); if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( - bolusID.timestamp, + bolusID.getTimestamp(), event.getImmediateAmount(), null, - bolusID.id, + bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); + /* + DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); + detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); + detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); + detailedBolusInfo.setPumpSerial(serialNumber()); + detailedBolusInfo.setBolusPumpId(bolusID.id); + detailedBolusInfo.insulin = event.getImmediateAmount(); + treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + */ } if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { if (event.getDuration() == 0) { @@ -1493,15 +1608,25 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } */ } else { - if (profileFunction.getProfile(bolusID.timestamp) != null) + if (profileFunction.getProfile(bolusID.getTimestamp()) != null) pumpSync.syncExtendedBolusWithPumpId( - bolusID.timestamp, + bolusID.getTimestamp(), event.getExtendedAmount(), T.mins(event.getDuration()).msecs(), isFakingTempsByExtendedBoluses(), - bolusID.id, + bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); + /* + ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); + extendedBolus.date = bolusID.timestamp; + extendedBolus.source = Source.PUMP; + extendedBolus.durationInMinutes = event.getDuration(); + extendedBolus.insulin = event.getExtendedAmount(); + extendedBolus.pumpId = bolusID.id; + if (profileFunction.getProfile(extendedBolus.date) != null) + treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + */ } } } diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt new file mode 100644 index 0000000000..fba16c1767 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.plugins.pump.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_BOLUS_IDS, + indices = [Index("bolusID")]) +data class InsightBolusID( + var timestamp: Long, + var pumpSerial: String? = "None", + var bolusID: Int? = null, + var startID: Long? = null, + var endID: Long? = null +) { + @PrimaryKey(autoGenerate = true) + var id: Long = 0 +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt new file mode 100644 index 0000000000..0ea04dd351 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.plugins.pump.insight.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase + +const val DATABASE_INSIGHT_BOLUS_IDS = "insightBolusIDs" +const val DATABASE_INSIGHT_PUMP_IDS = "insightPumpIDs" +const val DATABASE_INSIGHT_HISTORY_OFFSETS = "insightHistoryOffsets" + +@Database( + entities = [InsightBolusID::class, InsightHistoryOffset::class, InsightPumpID::class], + exportSchema = true, + version = InsightDatabase.VERSION +) +abstract class InsightDatabase : RoomDatabase() { + + abstract fun insightDatabaseDao(): InsightDatabaseDao + + companion object { + + const val VERSION = 1 + + fun build(context: Context) = + Room.databaseBuilder( + context.applicationContext, + InsightDatabase::class.java, + "insight_database.db" + ) + .fallbackToDestructiveMigration() + .build() + } +} diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt new file mode 100644 index 0000000000..9d00b3a49f --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.plugins.pump.insight.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query + +@Dao +abstract class InsightDatabaseDao { + + @Query("SELECT * from $DATABASE_INSIGHT_BOLUS_IDS WHERE pumpSerial = :pumpSerial AND timestamp >= :timestamp - 259200000 AND timestamp <= :timestamp + 259200000 AND bolusID = :bolusID") + abstract fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightBolusID: InsightBolusID) + + @Query("SELECT * from $DATABASE_INSIGHT_HISTORY_OFFSETS WHERE pumpSerial = :pumpSerial") + abstract fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) + + @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = 'PumpStopped' OR eventType = 'PumpPaused') AND timestamp < :timestamp ORDER BY timestamp DESC") + abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightPumpID: InsightPumpID) +} diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt new file mode 100644 index 0000000000..9a94d37175 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.plugins.pump.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_HISTORY_OFFSETS, + indices = [Index("pumpSerial")]) +data class InsightHistoryOffset( + @PrimaryKey val pumpSerial: String, + var offset: Long + ) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt new file mode 100644 index 0000000000..24e38862cc --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_PUMP_IDS, + indices = [Index("timestamp")]) +data class InsightPumpID( + var timestamp: Long, + var eventType: String? = null, + var pumpSerial: String? = "None", + @PrimaryKey + var eventID: Long +) { + fun getId(): Long = eventID +} \ No newline at end of file From ed7dcea38ee756e739c89c5f2eda484e2c9c5cb9 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 7 May 2021 10:41:45 +0200 Subject: [PATCH 06/27] Clean Code, remove old code and add some Todo for verification and tests --- .../pump/insight/LocalInsightPlugin.java | 151 +++--------------- 1 file changed, 19 insertions(+), 132 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 0f605e87f5..71a71f3f8b 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -33,9 +33,6 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -//import info.nightscout.androidaps.db.InsightBolusID; -//import info.nightscout.androidaps.db.InsightHistoryOffset; -//import info.nightscout.androidaps.db.InsightPumpID; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.insight.R; @@ -43,7 +40,6 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Config; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraints; -//import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileFunction; @@ -603,12 +599,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai null )); InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serial, bolusID, now); - /* - insightBolusID.bolusID = bolusID; - insightBolusID.timestamp = dateUtil.now(); - insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); - databaseHelper.createOrUpdate(insightBolusID); - */ aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); pumpSync.syncBolusWithPumpId( insightBolusID.getTimestamp(), @@ -818,12 +808,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai null, null )); - /* - insightBolusID.bolusID = bolusID; - insightBolusID.timestamp = System.currentTimeMillis(); - insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); - databaseHelper.createOrUpdate(insightBolusID); - */ aapsLogger.debug(LTag.PUMP, "XXXX Set Extended timestamp: " + dateUtil.now() + " amount: " + insulin + "U duration: " + durationInMinutes + "BolusId: " + bolusID); result.success(true).enacted(true).comment(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { @@ -917,22 +901,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai confirmAlert(AlertType.WARNING_38); alertService.ignore(null); InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); - /* - InsightBolusID insightBolusID = databaseHelper.getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(), - activeBolus.getBolusID(), System.currentTimeMillis()); - - */ if (insightBolusID != null) { - PumpSync.PumpState.ExtendedBolus extendedBolus = pumpSync.expectedPumpState().getExtendedBolus(); - if (extendedBolus != null) { - if ((dateUtil.now()- extendedBolus.getTimestamp()) / 60000 <= 0) { - //final String _id = extendedBolus._id; - //databaseHelper.delete(extendedBolus); - } else { - //treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - } - } - /* Search in Insight room database + /* TODO() I don't know if we can remove bolck below (there is a readHistory after that will update AAPS database) PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); if (extendedBolus != null) { extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000); @@ -1168,7 +1138,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); InsightHistoryOffset historyOffset = insightDatabaseDao.getInsightHistoryOffset(serial); - //InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial); try { List historyEvents = new ArrayList<>(); if (historyOffset == null) { @@ -1192,16 +1161,10 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Collections.reverse(historyEvents); if (historyOffset != null) processHistoryEvents(serial, historyEvents); if (historyEvents.size() > 0) { - historyOffset = new InsightHistoryOffset( + insightDatabaseDao.createOrUpdate(new InsightHistoryOffset( serial, - historyEvents.get(0).getEventPosition()); - insightDatabaseDao.createOrUpdate(historyOffset); - /* - historyOffset = new InsightHistoryOffset(); - historyOffset.pumpSerial = pumpSerial; - historyOffset.offset = historyEvents.get(0).getEventPosition(); - databaseHelper.createOrUpdate(historyOffset); - */ + historyEvents.get(0).getEventPosition()) + ); } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -1395,11 +1358,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai "", serial, event.getEventPosition()); - /* - pumpID.EventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.timestamp = timestamp; - */ switch (event.getNewValue()) { case STARTED: pumpID.setEventType("PumpStarted"); @@ -1421,62 +1379,47 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; } - // databaseHelper.createOrUpdate(pumpID); insightDatabaseDao.createOrUpdate(pumpID); } private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID( + insightDatabaseDao.createOrUpdate(new InsightPumpID( timestamp, "StartOfTBR", serial, - event.getEventPosition()); - insightDatabaseDao.createOrUpdate(pumpID); - /* - pumpID.eventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.timestamp = timestamp; - pumpID.eventType = "StartOfTBR"; - databaseHelper.createOrUpdate(pumpID); - */ - // + event.getEventPosition()) + ); TemporaryBasal temporaryBasal = new TemporaryBasal( timestamp, T.mins(event.getDuration()).msecs(), event.getAmount(), false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.getEventID(), - pumpID.getEventID()); // margin added because on several reeadHistory, timestamp could vary + event.getEventPosition(), + event.getEventPosition()); temporaryBasals.add(temporaryBasal); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID( + insightDatabaseDao.createOrUpdate(new InsightPumpID( timestamp - 1500L, "EndOfTBR", serial, - event.getEventPosition()); - insightDatabaseDao.createOrUpdate(pumpID); - /* - pumpID.eventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.eventType = "EndOfTBR"; - pumpID.timestamp = timestamp; - databaseHelper.createOrUpdate(pumpID); - */ + event.getEventPosition()) + ); + TemporaryBasal temporaryBasal = new PumpSync.PumpState.TemporaryBasal( timestamp - 1500L, 0L, 100.0, false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.getId(), - pumpID.getEventID()); + event.getEventPosition(), + event.getEventPosition()); temporaryBasals.add(temporaryBasal); } @@ -1484,14 +1427,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); - //InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID != null && bolusID.getEndID() != null) { + if (bolusID != null && bolusID.getEndID() != null) { // TODO() Check if test EndID is necessary bolusID.setStartID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); - //databaseHelper.createOrUpdate(bolusID); return; } - if (bolusID == null || bolusID.getStartID() != null) { + if (bolusID == null || bolusID.getStartID() != null) { // TODO() Check StartID test is necessary insightDatabaseDao.createOrUpdate(new InsightBolusID( timestamp, serial, @@ -1500,17 +1441,10 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai null )); bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); - /* - bolusID = new info.nightscout.androidaps.db.InsightBolusID(); - bolusID.timestamp = timestamp; - bolusID.bolusID = event.getBolusID(); - bolusID.pumpSerial = serial; - */ } bolusID.setStartID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); - //databaseHelper.createOrUpdate(bolusID); if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( bolusID.getTimestamp(), @@ -1519,15 +1453,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - /* - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.timestamp = bolusID.timestamp; - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); - */ } if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { if (profileFunction.getProfile(bolusID.getTimestamp()) != null) @@ -1539,16 +1464,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - /* - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - */ } } @@ -1558,8 +1473,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); - //InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID == null || bolusID.getEndID() != null) { + if (bolusID == null || bolusID.getEndID() != null) { // TODO() Check if test EndID is necessary bolusID = new InsightBolusID( startTimestamp, serial, @@ -1567,12 +1481,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID == null ? event.getEventPosition() : bolusID.getStartID(), event.getEventPosition() ); - /* - bolusID = new InsightBolusID(); - bolusID.timestamp = startTimestamp; - bolusID.bolusID = event.getBolusID(); - bolusID.pumpSerial = serial; - */ } bolusID.setEndID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); @@ -1586,24 +1494,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - /* - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); - */ } if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { if (event.getDuration() == 0) { - /* + /* TODO() Check if we can remove this block ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(bolusID.id); if (extendedBolus != null) { final String _id = extendedBolus._id; -// if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id); -// else uploadQueue.removeByMongoId("dbAdd", _id); databaseHelper.delete(extendedBolus); } */ @@ -1617,16 +1514,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - /* - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - */ } } } From dfd6c6e859d14788dc6d0af8011a69169c8ede19 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 7 May 2021 11:21:47 +0200 Subject: [PATCH 07/27] Move Insight database package outside plugins\pump --- .../plugins/general/maintenance/MaintenanceFragment.kt | 2 +- .../{plugins/pump => }/insight/database/InsightBolusID.kt | 2 +- .../pump => }/insight/database/InsightDatabase.kt | 2 +- .../pump => }/insight/database/InsightDatabaseDao.kt | 2 +- .../pump => }/insight/database/InsightHistoryOffset.kt | 2 +- .../{plugins/pump => }/insight/database/InsightPumpID.kt | 2 +- .../androidaps/insight/di/InsightDatabaseModule.kt | 4 ++-- .../plugins/pump/insight/LocalInsightPlugin.java | 8 ++++---- 8 files changed, 12 insertions(+), 12 deletions(-) rename insight/src/main/java/info/nightscout/androidaps/{plugins/pump => }/insight/database/InsightBolusID.kt (86%) rename insight/src/main/java/info/nightscout/androidaps/{plugins/pump => }/insight/database/InsightDatabase.kt (93%) rename insight/src/main/java/info/nightscout/androidaps/{plugins/pump => }/insight/database/InsightDatabaseDao.kt (95%) rename insight/src/main/java/info/nightscout/androidaps/{plugins/pump => }/insight/database/InsightHistoryOffset.kt (81%) rename insight/src/main/java/info/nightscout/androidaps/{plugins/pump => }/insight/database/InsightPumpID.kt (85%) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 67ea1166e5..36df705147 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -13,6 +13,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.events.EventNewBG +import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.PumpSync @@ -21,7 +22,6 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData -import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabase import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt similarity index 86% rename from insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt rename to insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt index fba16c1767..4546409145 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightBolusID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.insight.database +package info.nightscout.androidaps.insight.database import androidx.room.Entity import androidx.room.Index diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt similarity index 93% rename from insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt rename to insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt index 0ea04dd351..e7e45423a4 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabase.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.insight.database +package info.nightscout.androidaps.insight.database import android.content.Context import androidx.room.Database diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt similarity index 95% rename from insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt rename to insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt index 9d00b3a49f..7bffe694ef 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightDatabaseDao.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.insight.database +package info.nightscout.androidaps.insight.database import androidx.room.Dao import androidx.room.Insert diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt similarity index 81% rename from insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt rename to insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt index 9a94d37175..8c1d45111c 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightHistoryOffset.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.insight.database +package info.nightscout.androidaps.insight.database import androidx.room.Entity import androidx.room.Index diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt similarity index 85% rename from insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt rename to insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt index 24e38862cc..901c04a2b8 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/database/InsightPumpID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.insight.database +package info.nightscout.androidaps.insight.database import androidx.room.Entity import androidx.room.Index diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt index c55a0481ad..251c372cbd 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt @@ -3,8 +3,8 @@ package info.nightscout.androidaps.insight.di import android.content.Context import dagger.Module import dagger.Provides -import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabase -import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabaseDao +import info.nightscout.androidaps.insight.database.InsightDatabase +import info.nightscout.androidaps.insight.database.InsightDatabaseDao import javax.inject.Singleton @Module diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 71a71f3f8b..f6f80dcb4c 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -35,6 +35,10 @@ import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; +import info.nightscout.androidaps.insight.database.InsightBolusID; +import info.nightscout.androidaps.insight.database.InsightDatabaseDao; +import info.nightscout.androidaps.insight.database.InsightHistoryOffset; +import info.nightscout.androidaps.insight.database.InsightPumpID; import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Config; @@ -104,10 +108,6 @@ import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetPumpS import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.GetTotalDailyDoseMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.status.ResetPumpStatusRegisterMessage; import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightDatabaseDao; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBolus; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR; From 0ea9c984693c76a6381ed44326d297d4789ad12d Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 7 May 2021 23:54:02 +0200 Subject: [PATCH 08/27] Replace hard coded strings for EventType by enum --- .../androidaps/insight/database/Converters.kt | 11 ++++++ .../insight/database/InsightBolusID.kt | 4 +-- .../insight/database/InsightDatabase.kt | 2 ++ .../insight/database/InsightDatabaseDao.kt | 7 ++-- .../insight/database/InsightPumpID.kt | 13 +++++-- .../pump/insight/LocalInsightPlugin.java | 36 +++++++++---------- 6 files changed, 48 insertions(+), 25 deletions(-) create mode 100644 insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt new file mode 100644 index 0000000000..76a60cd1e6 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.TypeConverter + +class Converters { + @TypeConverter + fun fromEventType(evenType: InsightPumpID.EventType) = evenType.name + + @TypeConverter + fun toEventType(evenType: String?) = evenType?.let { InsightPumpID.EventType.valueOf(it) } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt index 4546409145..99b6055c7f 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt @@ -8,8 +8,8 @@ import androidx.room.PrimaryKey indices = [Index("bolusID")]) data class InsightBolusID( var timestamp: Long, - var pumpSerial: String? = "None", - var bolusID: Int? = null, + val pumpSerial: String? = null, + val bolusID: Int? = null, var startID: Long? = null, var endID: Long? = null ) { diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt index e7e45423a4..7be27eae76 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -4,6 +4,7 @@ import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase +import androidx.room.TypeConverters const val DATABASE_INSIGHT_BOLUS_IDS = "insightBolusIDs" const val DATABASE_INSIGHT_PUMP_IDS = "insightPumpIDs" @@ -14,6 +15,7 @@ const val DATABASE_INSIGHT_HISTORY_OFFSETS = "insightHistoryOffsets" exportSchema = true, version = InsightDatabase.VERSION ) +@TypeConverters(Converters::class) abstract class InsightDatabase : RoomDatabase() { abstract fun insightDatabaseDao(): InsightDatabaseDao diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt index 7bffe694ef..e602b3bf77 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt @@ -4,6 +4,7 @@ import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query +import info.nightscout.androidaps.insight.database.InsightPumpID.EventType @Dao abstract class InsightDatabaseDao { @@ -20,8 +21,10 @@ abstract class InsightDatabaseDao { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) - @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = 'PumpStopped' OR eventType = 'PumpPaused') AND timestamp < :timestamp ORDER BY timestamp DESC") - abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? + @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :PumpStopped OR eventType = :PumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") + abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, PumpStopped: EventType, PumpPaused: EventType): InsightPumpID? + + fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = getPumpStoppedEvent(pumpSerial, timestamp, EventType.PumpStopped, EventType.PumpPaused) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun createOrUpdate(insightPumpID: InsightPumpID) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt index 901c04a2b8..71e5b3502e 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt @@ -8,10 +8,17 @@ import androidx.room.PrimaryKey indices = [Index("timestamp")]) data class InsightPumpID( var timestamp: Long, - var eventType: String? = null, - var pumpSerial: String? = "None", + var eventType: EventType = EventType.None, + val pumpSerial: String? = null, @PrimaryKey var eventID: Long ) { - fun getId(): Long = eventID + enum class EventType { + PumpStarted, + PumpStopped, + PumpPaused, + StartOfTBR, + EndOfTBR, + None; + } } \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index f6f80dcb4c..f9f4fa676e 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -39,6 +39,7 @@ import info.nightscout.androidaps.insight.database.InsightBolusID; import info.nightscout.androidaps.insight.database.InsightDatabaseDao; import info.nightscout.androidaps.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.insight.database.InsightPumpID; +import info.nightscout.androidaps.insight.database.InsightPumpID.EventType; import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Config; @@ -1198,11 +1199,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai for (InsightPumpID pumpID : pumpStartedEvents) { InsightPumpID stoppedEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), pumpID.getTimestamp()); - if (stoppedEvent != null && stoppedEvent.getEventType().equals("PumpStopped")) { // Search if Stop event is after 15min of Pause + if (stoppedEvent != null && stoppedEvent.getEventType().equals(EventType.PumpStopped)) { // Search if Stop event is after 15min of Pause InsightPumpID pauseEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), stoppedEvent.getTimestamp() - T.mins(1).msecs()); - if (pauseEvent != null && pauseEvent.getEventType().equals("PumpPaused") && (stoppedEvent.getTimestamp() - pauseEvent.getTimestamp() < T.mins(16).msecs())) { + if (pauseEvent != null && pauseEvent.getEventType().equals(EventType.PumpPaused) && (stoppedEvent.getTimestamp() - pauseEvent.getTimestamp() < T.mins(16).msecs())) { stoppedEvent = pauseEvent; - stoppedEvent.setEventType("PumpStopped"); + stoppedEvent.setEventType(EventType.PumpStopped); } } if (stoppedEvent == null || stoppedEvent.getEventType().equals("PumpPaused")) continue; @@ -1213,7 +1214,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai 0, false, PumpSync.TemporaryBasalType.NORMAL, - pumpID.getId(), + pumpID.getEventID(), pumpID.getEventID()); temporaryBasals.add(temporaryBasal); } @@ -1355,25 +1356,25 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightPumpID pumpID = new InsightPumpID( timestamp, - "", + EventType.None, serial, event.getEventPosition()); switch (event.getNewValue()) { case STARTED: - pumpID.setEventType("PumpStarted"); + pumpID.setEventType(EventType.PumpStarted); pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_started)); aapsLogger.debug(LTag.PUMP, "XXXX event START Event TimeStamp: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case STOPPED: - pumpID.setEventType("PumpStopped"); + pumpID.setEventType(EventType.PumpStopped); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); aapsLogger.debug(LTag.PUMP, "XXXX event STOP: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case PAUSED: - pumpID.setEventType("PumpPaused"); + pumpID.setEventType(EventType.PumpPaused); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); @@ -1387,19 +1388,19 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; insightDatabaseDao.createOrUpdate(new InsightPumpID( timestamp, - "StartOfTBR", + EventType.StartOfTBR, serial, event.getEventPosition()) ); - TemporaryBasal temporaryBasal = new TemporaryBasal( + temporaryBasals.add(new TemporaryBasal( timestamp, T.mins(event.getDuration()).msecs(), event.getAmount(), false, PumpSync.TemporaryBasalType.NORMAL, event.getEventPosition(), - event.getEventPosition()); - temporaryBasals.add(temporaryBasal); + event.getEventPosition()) + ); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { @@ -1407,27 +1408,27 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; insightDatabaseDao.createOrUpdate(new InsightPumpID( timestamp - 1500L, - "EndOfTBR", + EventType.EndOfTBR, serial, event.getEventPosition()) ); - TemporaryBasal temporaryBasal = new PumpSync.PumpState.TemporaryBasal( + temporaryBasals.add(new PumpSync.PumpState.TemporaryBasal( timestamp - 1500L, 0L, 100.0, false, PumpSync.TemporaryBasalType.NORMAL, event.getEventPosition(), - event.getEventPosition()); - temporaryBasals.add(temporaryBasal); + event.getEventPosition()) + ); } private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID != null && bolusID.getEndID() != null) { // TODO() Check if test EndID is necessary + if (bolusID != null && bolusID.getEndID() != null) { bolusID.setStartID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); return; @@ -1485,7 +1486,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.setEndID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id - //databaseHelper.createOrUpdate(bolusID); if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( bolusID.getTimestamp(), From a146d54a50647ac59e496ecab8065b94a4e7b8fe Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 8 May 2021 16:18:47 +0200 Subject: [PATCH 09/27] Trail Add abstraction layer between InsightPlugin and dao --- .../insight/database/InsightDatabase.kt | 2 + .../insight/database/InsightDatabaseDao.kt | 6 +-- .../insight/database/InsightDbHelper.kt | 23 ++++++++++ .../insight/di/InsightDatabaseModule.kt | 5 ++ .../pump/insight/LocalInsightPlugin.java | 46 +++++++++---------- 5 files changed, 55 insertions(+), 27 deletions(-) create mode 100644 insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt index 7be27eae76..5cc47f32ba 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -20,6 +20,8 @@ abstract class InsightDatabase : RoomDatabase() { abstract fun insightDatabaseDao(): InsightDatabaseDao + abstract fun insightDbHelper(): InsightDbHelper + companion object { const val VERSION = 1 diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt index e602b3bf77..051f56803b 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt @@ -21,10 +21,8 @@ abstract class InsightDatabaseDao { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) - @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :PumpStopped OR eventType = :PumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") - abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, PumpStopped: EventType, PumpPaused: EventType): InsightPumpID? - - fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = getPumpStoppedEvent(pumpSerial, timestamp, EventType.PumpStopped, EventType.PumpPaused) + @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :pumpStopped OR eventType = :pumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") + abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, pumpStopped: EventType, pumpPaused: EventType): InsightPumpID? @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun createOrUpdate(insightPumpID: InsightPumpID) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt new file mode 100644 index 0000000000..b7bf395206 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.Dao +import javax.inject.Inject + +@Dao +abstract class InsightDbHelper { + + @Inject lateinit var insightDatabaseDao: InsightDatabaseDao + + fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? = insightDatabaseDao.getInsightBolusID(pumpSerial, bolusID, timestamp) + + fun createOrUpdate(insightBolusID: InsightBolusID) = insightDatabaseDao.createOrUpdate(insightBolusID) + + fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? = insightDatabaseDao.getInsightHistoryOffset(pumpSerial) + + fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) = insightDatabaseDao.createOrUpdate(insightHistoryOffset) + + fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = insightDatabaseDao.getPumpStoppedEvent(pumpSerial, timestamp, InsightPumpID.EventType.PumpStopped, InsightPumpID.EventType.PumpPaused) + + fun createOrUpdate(insightPumpID: InsightPumpID) = insightDatabaseDao.createOrUpdate(insightPumpID) + +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt index 251c372cbd..2425db378b 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt @@ -5,6 +5,7 @@ import dagger.Module import dagger.Provides import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.insight.database.InsightDatabaseDao +import info.nightscout.androidaps.insight.database.InsightDbHelper import javax.inject.Singleton @Module @@ -19,5 +20,9 @@ class InsightDatabaseModule { internal fun provideInsightDatabaseDao(insightDatabase: InsightDatabase): InsightDatabaseDao = insightDatabase.insightDatabaseDao() + @Provides + @Singleton + internal fun provideInsightDbHelper(insightDatabase: InsightDatabase): InsightDbHelper = + insightDatabase.insightDbHelper() } \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index f9f4fa676e..fc613f4f28 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -36,7 +36,7 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.insight.database.InsightBolusID; -import info.nightscout.androidaps.insight.database.InsightDatabaseDao; +import info.nightscout.androidaps.insight.database.InsightDbHelper; import info.nightscout.androidaps.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.insight.database.InsightPumpID; import info.nightscout.androidaps.insight.database.InsightPumpID.EventType; @@ -144,7 +144,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private final ProfileFunction profileFunction; private final Context context; private final DateUtil dateUtil; - private final InsightDatabaseDao insightDatabaseDao; + private final InsightDbHelper insightDbHelper; private final PumpSync pumpSync; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -203,7 +203,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Context context, Config config, DateUtil dateUtil, - InsightDatabaseDao insightDatabaseDao, + InsightDbHelper insightDbHelper, PumpSync pumpSync ) { super(new PluginDescription() @@ -225,7 +225,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.profileFunction = profileFunction; this.context = context; this.dateUtil = dateUtil; - this.insightDatabaseDao = insightDatabaseDao; + this.insightDbHelper = insightDbHelper; this.pumpSync = pumpSync; pumpDescription = new PumpDescription(); @@ -592,14 +592,14 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai int trials = 0; Long now = dateUtil.now(); String serial = serialNumber(); - insightDatabaseDao.createOrUpdate( new InsightBolusID( + insightDbHelper.createOrUpdate( new InsightBolusID( now, serial, bolusID, null, null )); - InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serial, bolusID, now); + InsightBolusID insightBolusID = insightDbHelper.getInsightBolusID(serial, bolusID, now); aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); pumpSync.syncBolusWithPumpId( insightBolusID.getTimestamp(), @@ -802,7 +802,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusMessage.setImmediateAmount(0); bolusMessage.setVibration(disableVibration); int bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); - insightDatabaseDao.createOrUpdate(new InsightBolusID( + insightDbHelper.createOrUpdate(new InsightBolusID( dateUtil.now(), serialNumber(), bolusID, @@ -901,7 +901,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai connectionService.requestMessage(cancelBolusMessage).await(); confirmAlert(AlertType.WARNING_38); alertService.ignore(null); - InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); + InsightBolusID insightBolusID = insightDbHelper.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); if (insightBolusID != null) { /* TODO() I don't know if we can remove bolck below (there is a readHistory after that will update AAPS database) PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); @@ -1138,7 +1138,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai String serial = serialNumber(); timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); - InsightHistoryOffset historyOffset = insightDatabaseDao.getInsightHistoryOffset(serial); + InsightHistoryOffset historyOffset = insightDbHelper.getInsightHistoryOffset(serial); try { List historyEvents = new ArrayList<>(); if (historyOffset == null) { @@ -1162,7 +1162,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Collections.reverse(historyEvents); if (historyOffset != null) processHistoryEvents(serial, historyEvents); if (historyEvents.size() > 0) { - insightDatabaseDao.createOrUpdate(new InsightHistoryOffset( + insightDbHelper.createOrUpdate(new InsightHistoryOffset( serial, historyEvents.get(0).getEventPosition()) ); @@ -1198,9 +1198,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai Collections.reverse(temporaryBasals); for (InsightPumpID pumpID : pumpStartedEvents) { - InsightPumpID stoppedEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), pumpID.getTimestamp()); + InsightPumpID stoppedEvent = insightDbHelper.getPumpStoppedEvent(pumpID.getPumpSerial(), pumpID.getTimestamp()); if (stoppedEvent != null && stoppedEvent.getEventType().equals(EventType.PumpStopped)) { // Search if Stop event is after 15min of Pause - InsightPumpID pauseEvent = insightDatabaseDao.getPumpStoppedEvent(pumpID.getPumpSerial(), stoppedEvent.getTimestamp() - T.mins(1).msecs()); + InsightPumpID pauseEvent = insightDbHelper.getPumpStoppedEvent(pumpID.getPumpSerial(), stoppedEvent.getTimestamp() - T.mins(1).msecs()); if (pauseEvent != null && pauseEvent.getEventType().equals(EventType.PumpPaused) && (stoppedEvent.getTimestamp() - pauseEvent.getTimestamp() < T.mins(16).msecs())) { stoppedEvent = pauseEvent; stoppedEvent.setEventType(EventType.PumpStopped); @@ -1380,13 +1380,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; } - insightDatabaseDao.createOrUpdate(pumpID); + insightDbHelper.createOrUpdate(pumpID); } private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - insightDatabaseDao.createOrUpdate(new InsightPumpID( + insightDbHelper.createOrUpdate(new InsightPumpID( timestamp, EventType.StartOfTBR, serial, @@ -1406,7 +1406,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - insightDatabaseDao.createOrUpdate(new InsightPumpID( + insightDbHelper.createOrUpdate(new InsightPumpID( timestamp - 1500L, EventType.EndOfTBR, serial, @@ -1427,24 +1427,24 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + InsightBolusID bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID != null && bolusID.getEndID() != null) { bolusID.setStartID(event.getEventPosition()); - insightDatabaseDao.createOrUpdate(bolusID); + insightDbHelper.createOrUpdate(bolusID); return; } if (bolusID == null || bolusID.getStartID() != null) { // TODO() Check StartID test is necessary - insightDatabaseDao.createOrUpdate(new InsightBolusID( + insightDbHelper.createOrUpdate(new InsightBolusID( timestamp, serial, event.getBolusID(), event.getEventPosition(), null )); - bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); } bolusID.setStartID(event.getEventPosition()); - insightDatabaseDao.createOrUpdate(bolusID); + insightDbHelper.createOrUpdate(bolusID); if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( @@ -1473,7 +1473,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; - InsightBolusID bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), timestamp); + InsightBolusID bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); if (bolusID == null || bolusID.getEndID() != null) { // TODO() Check if test EndID is necessary bolusID = new InsightBolusID( startTimestamp, @@ -1484,8 +1484,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai ); } bolusID.setEndID(event.getEventPosition()); - insightDatabaseDao.createOrUpdate(bolusID); - bolusID = insightDatabaseDao.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id + insightDbHelper.createOrUpdate(bolusID); + bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { pumpSync.syncBolusWithPumpId( bolusID.getTimestamp(), From 931980bcb6f6cf52c45422a925b9b78bcf2c2316 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 8 May 2021 16:20:01 +0200 Subject: [PATCH 10/27] Typo in variable names --- .../androidaps/insight/database/InsightDatabaseDao.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt index e602b3bf77..c941eb76e2 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt @@ -21,8 +21,8 @@ abstract class InsightDatabaseDao { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) - @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :PumpStopped OR eventType = :PumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") - abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, PumpStopped: EventType, PumpPaused: EventType): InsightPumpID? + @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :pumpStopped OR eventType = :pumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") + abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, pumpStopped: EventType, pumpPaused: EventType): InsightPumpID? fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = getPumpStoppedEvent(pumpSerial, timestamp, EventType.PumpStopped, EventType.PumpPaused) From dd527d9908d3a29bbf2cf7c1df4333a6dd2243d2 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 8 May 2021 16:35:12 +0200 Subject: [PATCH 11/27] Cleaning --- .../pump/insight/LocalInsightPlugin.java | 42 ++++--------------- 1 file changed, 8 insertions(+), 34 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index f9f4fa676e..0d815be2a8 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -830,7 +830,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai PumpEnactResult cancelEBResult = null; if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly(); PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); - result.success((cancelEBResult == null || (cancelEBResult != null && cancelEBResult.getSuccess())) && cancelTBRResult.getSuccess()); //Fix a bug when Fake TBR is disabled and click on Cancel TBR button + result.success((cancelEBResult == null || (cancelEBResult != null && cancelEBResult.getSuccess())) && cancelTBRResult.getSuccess()); result.enacted((cancelEBResult != null && cancelEBResult.getEnacted()) || cancelTBRResult.getEnacted()); result.comment(cancelEBResult != null ? cancelEBResult.getComment() : cancelTBRResult.getComment()); try { @@ -903,17 +903,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai alertService.ignore(null); InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); if (insightBolusID != null) { - /* TODO() I don't know if we can remove bolck below (there is a readHistory after that will update AAPS database) - PumpSync.PumpState.ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); - if (extendedBolus != null) { - extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000); - if (extendedBolus.durationInMinutes <= 0) { - final String _id = extendedBolus._id; - databaseHelper.delete(extendedBolus); - } else - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - } - */ aapsLogger.debug(LTag.PUMP, "XXXX cancel Extended Bolus time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " BolusId: " + activeBolus.getBolusID()); result.enacted(true).success(true); } @@ -1390,8 +1379,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timestamp, EventType.StartOfTBR, serial, - event.getEventPosition()) - ); + event.getEventPosition())); temporaryBasals.add(new TemporaryBasal( timestamp, T.mins(event.getDuration()).msecs(), @@ -1399,8 +1387,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai false, PumpSync.TemporaryBasalType.NORMAL, event.getEventPosition(), - event.getEventPosition()) - ); + event.getEventPosition())); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { @@ -1410,8 +1397,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timestamp - 1500L, EventType.EndOfTBR, serial, - event.getEventPosition()) - ); + event.getEventPosition())); temporaryBasals.add(new PumpSync.PumpState.TemporaryBasal( timestamp - 1500L, @@ -1420,8 +1406,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai false, PumpSync.TemporaryBasalType.NORMAL, event.getEventPosition(), - event.getEventPosition()) - ); + event.getEventPosition())); } private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { @@ -1433,7 +1418,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai insightDatabaseDao.createOrUpdate(bolusID); return; } - if (bolusID == null || bolusID.getStartID() != null) { // TODO() Check StartID test is necessary + if (bolusID == null || bolusID.getStartID() != null) { //In rare edge cases two boluses can share the same ID insightDatabaseDao.createOrUpdate(new InsightBolusID( timestamp, serial, @@ -1480,8 +1465,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai serial, event.getBolusID(), bolusID == null ? event.getEventPosition() : bolusID.getStartID(), - event.getEventPosition() - ); + event.getEventPosition()); } bolusID.setEndID(event.getEventPosition()); insightDatabaseDao.createOrUpdate(bolusID); @@ -1496,16 +1480,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai serial); } if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { - if (event.getDuration() == 0) { - /* TODO() Check if we can remove this block - ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(bolusID.id); - if (extendedBolus != null) { - final String _id = extendedBolus._id; - databaseHelper.delete(extendedBolus); - } - */ - } else { - if (profileFunction.getProfile(bolusID.getTimestamp()) != null) + if (event.getDuration() > 0 && profileFunction.getProfile(bolusID.getTimestamp()) != null) pumpSync.syncExtendedBolusWithPumpId( bolusID.getTimestamp(), event.getExtendedAmount(), @@ -1514,7 +1489,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - } } } From 153168a4d491b6ee25080a92b9e9e06d736cc6a3 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sat, 8 May 2021 19:48:10 +0200 Subject: [PATCH 12/27] Remove additional aapsLogger (3 left for further analysis with Insight V3 and site change) --- .../plugins/pump/insight/LocalInsightPlugin.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 0d815be2a8..bd0aad2212 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -600,7 +600,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai null )); InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serial, bolusID, now); - aapsLogger.debug(LTag.PUMP, "XXXX set Bolus: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " amount: " + insulin); pumpSync.syncBolusWithPumpId( insightBolusID.getTimestamp(), detailedBolusInfo.insulin, @@ -672,7 +671,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusCancelled = true; confirmAlert(AlertType.WARNING_38); alertService.ignore(null); - aapsLogger.debug(LTag.PUMP, "XXXX Stop Bolus : " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now())); } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while canceling bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -758,7 +756,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai .success(true) .enacted(true) .comment(R.string.virtualpump_resultok); - aapsLogger.debug(LTag.PUMP, "XXXX Set Temp Basal timestamp: " + dateUtil.now() + " rate: " + percent + " duration: " + durationInMinutes); readHistory(); fetchStatus(); } catch (AppLayerErrorException e) { @@ -809,7 +806,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai null, null )); - aapsLogger.debug(LTag.PUMP, "XXXX Set Extended timestamp: " + dateUtil.now() + " amount: " + insulin + "U duration: " + durationInMinutes + "BolusId: " + bolusID); result.success(true).enacted(true).comment(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -857,7 +853,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai confirmAlert(AlertType.WARNING_36); alertService.ignore(null); result.comment(R.string.virtualpump_resultok); - aapsLogger.debug(LTag.PUMP, "XXXX cancel Temp Basal time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now())); } catch (NoActiveTBRToCanceLException e) { result.success(true); result.comment(R.string.virtualpump_resultok); @@ -903,7 +898,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai alertService.ignore(null); InsightBolusID insightBolusID = insightDatabaseDao.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); if (insightBolusID != null) { - aapsLogger.debug(LTag.PUMP, "XXXX cancel Extended Bolus time: " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) + " BolusId: " + activeBolus.getBolusID()); result.enacted(true).success(true); } } @@ -1284,7 +1278,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai calendar.set(Calendar.YEAR, event.getTotalYear()); calendar.set(Calendar.MONTH, event.getTotalMonth() - 1); calendar.set(Calendar.DAY_OF_MONTH, event.getTotalDay()); - aapsLogger.debug(LTag.PUMP, "XXXX event Daily Dose event day: " + event.getTotalYear() + "/" + (event.getTotalMonth() - 1) + "/" + event.getTotalDay() + " Basal: " + event.getBasalTotal() + " Bolus: " + event.getBolusTotal()); pumpSync.createOrUpdateTotalDailyDose( calendar.getTimeInMillis(), event.getBolusTotal(), @@ -1330,7 +1323,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE); - aapsLogger.debug(LTag.PUMP, "XXXX event Battery Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE, @@ -1354,19 +1346,16 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_started)); - aapsLogger.debug(LTag.PUMP, "XXXX event START Event TimeStamp: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case STOPPED: pumpID.setEventType(EventType.PumpStopped); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); - aapsLogger.debug(LTag.PUMP, "XXXX event STOP: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; case PAUSED: pumpID.setEventType(EventType.PumpPaused); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); - aapsLogger.debug(LTag.PUMP, "XXXX event Pause: " + timestamp + " HMS: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); break; } insightDatabaseDao.createOrUpdate(pumpID); From 62901923550b5ff8a8012b70388c12ad32b977dd Mon Sep 17 00:00:00 2001 From: Philoul Date: Sun, 9 May 2021 00:55:05 +0200 Subject: [PATCH 13/27] Remove redundant CPevents, Fix Site Change with Insight V3 --- .../pump/insight/LocalInsightPlugin.java | 40 +++---------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index bd0aad2212..8771032287 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1189,7 +1189,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai stoppedEvent.setEventType(EventType.PumpStopped); } } - if (stoppedEvent == null || stoppedEvent.getEventType().equals("PumpPaused")) continue; + if (stoppedEvent == null || stoppedEvent.getEventType().equals(EventType.PumpPaused) || pumpID.getTimestamp() - stoppedEvent.getTimestamp() < 10000) + continue; long tbrStart = stoppedEvent.getTimestamp() + 10000; TemporaryBasal temporaryBasal = new TemporaryBasal( tbrStart, @@ -1261,15 +1262,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (!sp.getBoolean(R.string.key_insight_log_site_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); - aapsLogger.debug(LTag.PUMP, "XXXX event Site Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); - pumpSync.insertTherapyEventIfNewWithTimestamp( - timestamp, - DetailedBolusInfo.EventType.CANNULA_CHANGE, - "", - event.getEventPosition(), - PumpType.ACCU_CHEK_INSIGHT, - serial); + if (event.getAmount() > 0.0) // Don't record event if amount is null => Fix Site Change with Insight v3 (event is always sent when Reservoir is changed) + uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); } private void processTotalDailyDoseEvent(String serial, TotalDailyDoseEvent event) { @@ -1292,15 +1286,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (!sp.getBoolean(R.string.key_insight_log_tube_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); - aapsLogger.debug(LTag.PUMP, "XXXX event Tube Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); - pumpSync.insertTherapyEventIfNewWithTimestamp( - timestamp, - DetailedBolusInfo.EventType.INSULIN_CHANGE, - "", - event.getEventPosition(), - PumpType.ACCU_CHEK_INSIGHT, - serial); + if (event.getAmount() > 0.0) // Don't record event if amount is null + logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); } private void processSniffingDoneEvent(String serial, SniffingDoneEvent event) { @@ -1308,14 +1295,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE); - aapsLogger.debug(LTag.PUMP, "XXXX event Reservoir Change time: " + dateUtil.dateAndTimeAndSecondsString(timestamp)); - pumpSync.insertTherapyEventIfNewWithTimestamp( - timestamp, - DetailedBolusInfo.EventType.INSULIN_CHANGE, - "", - event.getEventPosition(), - PumpType.ACCU_CHEK_INSIGHT, - serial); } private void processPowerUpEvent(String serial, PowerUpEvent event) { @@ -1323,13 +1302,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE); - pumpSync.insertTherapyEventIfNewWithTimestamp( - timestamp, - DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE, - "", - event.getEventPosition(), - PumpType.ACCU_CHEK_INSIGHT, - serial); } private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, OperatingModeChangedEvent event) { From 0020856aae093108396a465c27583f772c72fa74 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sun, 9 May 2021 16:20:55 +0200 Subject: [PATCH 14/27] Fix Injection for InsightDbHelper Thanks Adrian for your help --- .../androidaps/insight/database/InsightDatabase.kt | 2 -- .../androidaps/insight/database/InsightDbHelper.kt | 8 +------- .../androidaps/insight/di/InsightDatabaseModule.kt | 3 +-- 3 files changed, 2 insertions(+), 11 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt index 5cc47f32ba..7be27eae76 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -20,8 +20,6 @@ abstract class InsightDatabase : RoomDatabase() { abstract fun insightDatabaseDao(): InsightDatabaseDao - abstract fun insightDbHelper(): InsightDbHelper - companion object { const val VERSION = 1 diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt index b7bf395206..592acd5a73 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt @@ -1,12 +1,6 @@ package info.nightscout.androidaps.insight.database -import androidx.room.Dao -import javax.inject.Inject - -@Dao -abstract class InsightDbHelper { - - @Inject lateinit var insightDatabaseDao: InsightDatabaseDao +class InsightDbHelper (val insightDatabaseDao: InsightDatabaseDao) { fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? = insightDatabaseDao.getInsightBolusID(pumpSerial, bolusID, timestamp) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt index 2425db378b..2e47f3891c 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt @@ -22,7 +22,6 @@ class InsightDatabaseModule { @Provides @Singleton - internal fun provideInsightDbHelper(insightDatabase: InsightDatabase): InsightDbHelper = - insightDatabase.insightDbHelper() + internal fun provideInsightDbHelper(insightDatabaseDao: InsightDatabaseDao): InsightDbHelper = InsightDbHelper(insightDatabaseDao) } \ No newline at end of file From afb16210aec430e00b7f5b9f769960c2b596e218 Mon Sep 17 00:00:00 2001 From: Philoul Date: Sun, 9 May 2021 17:02:20 +0200 Subject: [PATCH 15/27] Remove old insight db tables --- .../androidaps/db/DatabaseHelper.java | 93 ------------------- .../androidaps/db/DatabaseHelperProvider.java | 24 ----- .../interfaces/DatabaseHelperInterface.kt | 12 --- 3 files changed, 129 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 4496928738..c323a475be 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -23,7 +23,6 @@ import javax.inject.Inject; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -67,15 +66,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { aapsLogger.info(LTag.DATABASE, "onCreate"); - TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); - TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); - TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); } catch (SQLException e) { aapsLogger.error("Can't create database", e); throw new RuntimeException(e); @@ -91,17 +83,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (oldVersion < 7) { aapsLogger.info(LTag.DATABASE, "onUpgrade"); onCreate(database, connectionSource); - } else if (oldVersion < 10) { - TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); - TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); - TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); - } else if (oldVersion < 11) { - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\""); - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\""); } TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); } catch (SQLException e) { @@ -152,18 +133,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // ------------------ getDao ------------------------------------------- - private Dao getDaoInsightPumpID() throws SQLException { - return getDao(InsightPumpID.class); - } - - private Dao getDaoInsightBolusID() throws SQLException { - return getDao(InsightBolusID.class); - } - - private Dao getDaoInsightHistoryOffset() throws SQLException { - return getDao(InsightHistoryOffset.class); - } - private Dao getDaoPodHistory() throws SQLException { return getDao(OmnipodHistoryRecord.class); } @@ -182,68 +151,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } - // ---------------- Insight history handling --------------- - - public void createOrUpdate(InsightHistoryOffset offset) { - try { - getDaoInsightHistoryOffset().createOrUpdate(offset); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) { - try { - return getDaoInsightHistoryOffset().queryForId(pumpSerial); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - public void createOrUpdate(InsightBolusID bolusID) { - try { - getDaoInsightBolusID().createOrUpdate(bolusID); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) { - try { - return getDaoInsightBolusID().queryBuilder() - .where().eq("pumpSerial", pumpSerial) - .and().eq("bolusID", bolusID) - .and().between("timestamp", timestamp - 259200000, timestamp + 259200000) - .queryForFirst(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - public void createOrUpdate(InsightPumpID pumpID) { - try { - getDaoInsightPumpID().createOrUpdate(pumpID); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) { - try { - return getDaoInsightPumpID().queryBuilder() - .orderBy("timestamp", false) - .where().eq("pumpSerial", pumpSerial) - .and().in("eventType", "PumpStopped", "PumpPaused") - .and().lt("timestamp", before) - .queryForFirst(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - // ---------------- Food handling --------------- // ---------------- PodHistory handling --------------- diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java index 89d892fe97..da0b2479cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -49,18 +49,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); } - @Override public void createOrUpdate(@NonNull InsightBolusID record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @Override public void createOrUpdate(@NonNull InsightPumpID record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - @Override public void delete(@NonNull ExtendedBolus extendedBolus) { // MainApp.Companion.getDbHelper().delete(extendedBolus); } @@ -70,18 +58,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return null; } - @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) { - return MainApp.Companion.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp); - } - - @Nullable @Override public InsightHistoryOffset getInsightHistoryOffset(@NonNull String pumpSerial) { - return MainApp.Companion.getDbHelper().getInsightHistoryOffset(pumpSerial); - } - - @Nullable @Override public InsightPumpID getPumpStoppedEvent(@NonNull String pumpSerial, long before) { - return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before); - } - @Override public void resetDatabases() { MainApp.Companion.getDbHelper().resetDatabases(); } diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt index e49f4cdf51..fe783413a0 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt @@ -7,9 +7,6 @@ interface DatabaseHelperInterface { fun resetDatabases() fun createOrUpdate(record: OmnipodHistoryRecord) - fun createOrUpdate(record: InsightBolusID) - fun createOrUpdate(record: InsightPumpID) - fun createOrUpdate(record: InsightHistoryOffset) fun createOrUpdate(record: OHQueueItem) fun delete(extendedBolus: ExtendedBolus) fun createOrUpdate(tempBasal: TemporaryBasal): Boolean @@ -24,18 +21,9 @@ interface DatabaseHelperInterface { fun getAllOHQueueItems(maxEntries: Long): List // old DB model - fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? - fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? - fun getPumpStoppedEvent(pumpSerial: String, before: Long): InsightPumpID? fun getOHQueueSize(): Long fun clearOpenHumansQueue() fun removeAllOHQueueItemsWithIdSmallerThan(id: Long) - companion object { - - const val DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets" - const val DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs" - const val DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs" - } } From d5a9c2b6288465ff29ada6ec47ab0b0ca4481682 Mon Sep 17 00:00:00 2001 From: Philoul Date: Tue, 11 May 2021 18:38:57 +0200 Subject: [PATCH 16/27] Fix tests --- .../androidaps/interfaces/ConstraintsCheckerTest.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 f9bacb7bbd..9b0f002cd7 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.insight.database.InsightDbHelper import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin @@ -68,6 +69,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var repository: AppRepository @Mock lateinit var pumpSync: PumpSync + @Mock lateinit var insightDbHelper: InsightDbHelper private lateinit var danaPump: DanaPump @@ -141,7 +143,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync, dateUtil) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) - insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, databaseHelper, pumpSync) + insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, insightDbHelper, pumpSync) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(ConfigImpl(), loggerUtils), iobCobCalculator, ConfigImpl(), dateUtil) From 50720b8497e250be2ae03f19c958cd4ddf24e464 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 11 May 2021 21:24:39 +0200 Subject: [PATCH 17/27] NSClient mode sync --- .../androidaps/dependencyInjection/PluginsModule.kt | 2 +- .../nsclient/DataSyncSelectorImplementation.kt | 6 +++--- .../plugins/profile/local/LocalProfilePlugin.kt | 2 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 3 ++- .../info/nightscout/androidaps/data/ProfileSealed.kt | 12 ++++++++++++ .../info/nightscout/androidaps/interfaces/Profile.kt | 5 +++++ 6 files changed, 24 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index 5cb174b533..4401623286 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -192,7 +192,7 @@ abstract class PluginsModule { abstract fun bindOpenAPSSMBPlugin(plugin: OpenAPSSMBPlugin): PluginBase @Binds - @NotNSClient + @AllConfigs @IntoMap @IntKey(240) abstract fun bindLocalProfilePlugin(plugin: LocalProfilePlugin): PluginBase diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index 7e3dd1bb8f..9e124bfcca 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -279,7 +279,7 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) } return true - } + } else confirmLastGlucoseValueIdIfGreater(gv.second) } return false } @@ -385,7 +385,7 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) } return true - } + } ?: confirmLastTemporaryBasalIdIfGreater(tb.second) } return false } @@ -424,7 +424,7 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) } return true - } + } ?: confirmLastExtendedBolusIdIfGreater(eb.second) } return false } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index 86b56591ff..c21cc86463 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -413,7 +413,7 @@ class LocalProfilePlugin @Inject constructor( if (sp.getBoolean(R.string.key_ns_receive_profile_store, false) || config.NSCLIENT) { localProfilePlugin.loadFromStore(ProfileStore(injector, profileJson, dateUtil)) aapsLogger.debug(LTag.PROFILE, "Received profileStore: $profileJson") - return Result.success(workDataOf("Data" to profileJson.toString())) + return Result.success(workDataOf("Data" to profileJson.toString().substring(1..5000))) } return Result.success() } 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 76da448516..cd352a63c0 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 @@ -155,7 +155,8 @@ open class VirtualPumpPlugin @Inject constructor( } override fun isThisProfileSet(profile: Profile): Boolean { - return true + val running = pumpSync.expectedPumpState().profile + return running?.isEqual(profile) ?: false } override fun lastDataTime(): Long { diff --git a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt index b308bd6132..8a30319b67 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt @@ -145,6 +145,18 @@ sealed class ProfileSealed( override val timeshift: Int get() = ts + override fun isEqual(profile: Profile): Boolean { + for (hour in 0..23) { + val seconds = T.hours(hour.toLong()).secs().toInt() + if (getBasalTimeFromMidnight(seconds) != profile.getBasalTimeFromMidnight(seconds)) return false + if (getIsfMgdlTimeFromMidnight(seconds) != profile.getIsfMgdlTimeFromMidnight(seconds)) return false + if (getIcTimeFromMidnight(seconds) != profile.getIcTimeFromMidnight(seconds)) return false + if (getTargetLowMgdlTimeFromMidnight(seconds) != profile.getTargetLowMgdlTimeFromMidnight(seconds)) return false + if (getTargetHighMgdlTimeFromMidnight(seconds) != profile.getTargetHighMgdlTimeFromMidnight(seconds)) return false + } + return true + } + override val percentage: Int get() = pct diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt index 7e371284f1..a3b1328cb9 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt @@ -30,6 +30,11 @@ interface Profile { */ val timeshift: Int + /** + * is equal to another profile? + */ + fun isEqual(profile: Profile): Boolean + /** * Basal value according to "now" */ From 3b581dce49d3721a0d102728d5763a11b0ab1646 Mon Sep 17 00:00:00 2001 From: Philoul Date: Wed, 12 May 2021 01:24:03 +0200 Subject: [PATCH 18/27] uel.log Fix Source for Dexcom calibration and Sensor insertion --- .../info/nightscout/androidaps/plugins/source/DexcomPlugin.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index e7c9f06407..d1f02d3871 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -158,14 +158,14 @@ class DexcomPlugin @Inject constructor( } result.sensorInsertionsInserted.forEach { uel.log(Action.CAREPORTAL, - Sources.BG, + Sources.Dexcom, ValueWithUnit.Timestamp(it.timestamp), ValueWithUnit.TherapyEventType(it.type)) aapsLogger.debug(LTag.DATABASE, "Inserted sensor insertion $it") } result.calibrationsInserted.forEach { uel.log(Action.CAREPORTAL, - Sources.BG, + Sources.Dexcom, ValueWithUnit.Timestamp(it.timestamp), ValueWithUnit.TherapyEventType(it.type)) aapsLogger.debug(LTag.DATABASE, "Inserted calibration $it") From 02e923d3ed11d08ffa5cf4d3261a9d5baf01053a Mon Sep 17 00:00:00 2001 From: Philoul Date: Wed, 12 May 2021 09:43:34 +0200 Subject: [PATCH 19/27] Fix test 2 --- .../androidaps/interfaces/ConstraintsCheckerTest.kt | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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 9b0f002cd7..449ea3c5e6 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.insight.database.InsightDatabaseDao import info.nightscout.androidaps.insight.database.InsightDbHelper import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin @@ -52,7 +53,7 @@ import java.util.* ConstraintChecker::class, SP::class, Context::class, OpenAPSAMAPlugin::class, OpenAPSSMBPlugin::class, TreatmentsPlugin::class, TreatmentService::class, VirtualPumpPlugin::class, DetailedBolusInfoStorage::class, TemporaryBasalStorage::class, GlimpPlugin::class, Profiler::class, - UserEntryLogger::class, LoggerUtils::class, AppRepository::class) + UserEntryLogger::class, LoggerUtils::class, AppRepository::class, InsightDatabaseDao::class) class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var activePlugin: ActivePlugin @@ -69,10 +70,10 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var repository: AppRepository @Mock lateinit var pumpSync: PumpSync - @Mock lateinit var insightDbHelper: InsightDbHelper + @Mock lateinit var insightDatabaseDao: InsightDatabaseDao private lateinit var danaPump: DanaPump - + private lateinit var insightDbHelper: InsightDbHelper private lateinit var constraintChecker: ConstraintChecker private lateinit var safetyPlugin: SafetyPlugin private lateinit var objectivesPlugin: ObjectivesPlugin @@ -136,7 +137,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) - + insightDbHelper = InsightDbHelper(insightDatabaseDao) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, ConfigImpl(), dateUtil, uel) From 9d87dec574072d74ee749fc505af7594923cb3c6 Mon Sep 17 00:00:00 2001 From: Philoul Date: Wed, 12 May 2021 18:28:52 +0200 Subject: [PATCH 20/27] NSClient Fix Use Absolute --- .../general/nsclient/DataSyncSelectorImplementation.kt | 10 ++++++---- .../androidaps/extensions/ExtendedBolusExtension.kt | 4 ++-- .../androidaps/extensions/TemporaryBasalExtension.kt | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index 9e124bfcca..3e27bb8c4e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -368,6 +368,7 @@ class DataSyncSelectorImplementation @Inject constructor( override fun processChangedTemporaryBasalsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) appRepository.getNextSyncElementTemporaryBasal(startId).blockingGet()?.let { tb -> aapsLogger.info(LTag.DATABASE, "Loading TemporaryBasal data Start: $startId ID: ${tb.first.id} HistoryID: ${tb.second} ") profileFunction.getProfile(tb.first.timestamp)?.let { profile -> @@ -379,10 +380,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", tb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) // existing without nsId = create new tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) // existing with nsId = update tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) } return true } ?: confirmLastTemporaryBasalIdIfGreater(tb.second) @@ -407,6 +408,7 @@ class DataSyncSelectorImplementation @Inject constructor( override fun processChangedExtendedBolusesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) appRepository.getNextSyncElementExtendedBolus(startId).blockingGet()?.let { eb -> aapsLogger.info(LTag.DATABASE, "Loading ExtendedBolus data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ") profileFunction.getProfile(eb.first.timestamp)?.let { profile -> @@ -418,10 +420,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) // existing without nsId = create new eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) // existing with nsId = update eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) } return true } ?: confirmLastExtendedBolusIdIfGreater(eb.second) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt index df0802ed19..09f5c9d9a5 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt @@ -50,10 +50,10 @@ fun ExtendedBolus.toTemporaryBasal(profile: Profile): TemporaryBasal = type = TemporaryBasal.Type.FAKE_EXTENDED ) -fun ExtendedBolus.toJson(profile: Profile, dateUtil: DateUtil): JSONObject = +fun ExtendedBolus.toJson(profile: Profile, dateUtil: DateUtil, useAbsolute: Boolean): JSONObject = if (isEmulatingTempBasal) toTemporaryBasal(profile) - .toJson(profile, dateUtil) + .toJson(profile, dateUtil, useAbsolute) .put("extendedEmulated", toRealJson(dateUtil)) else toRealJson(dateUtil) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt index e25a6284d1..2522f930b4 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt @@ -62,7 +62,7 @@ fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil): String { } } -fun TemporaryBasal.toJson(profile: Profile, dateUtil: DateUtil): JSONObject = +fun TemporaryBasal.toJson(profile: Profile, dateUtil: DateUtil, useAbsolute: Boolean): JSONObject = JSONObject() .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", "openaps://" + "AndroidAPS") @@ -71,7 +71,7 @@ fun TemporaryBasal.toJson(profile: Profile, dateUtil: DateUtil): JSONObject = .put("rate", rate) .put("type", type.name) .also { - if (isAbsolute) it.put("absolute", rate) + if (useAbsolute) it.put("absolute", convertedToAbsolute(timestamp, profile)) else it.put("percent", convertedToPercent(timestamp, profile) - 100) if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) if (interfaceIDs.endId != null) it.put("endId", interfaceIDs.endId) From da444c20430b2e523f11278a7bc6322248d9280b Mon Sep 17 00:00:00 2001 From: Philoul Date: Thu, 13 May 2021 12:15:00 +0200 Subject: [PATCH 21/27] Missing note in InsertTherapyEventNewWithTimestamp --- .../androidaps/plugins/pump/PumpSyncImplementation.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index b313af90ef..4ea4d4d712 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -203,7 +203,7 @@ class PumpSyncImplementation @Inject constructor( timestamp = timestamp, type = type.toDBbEventType(), duration = 0, - note = null, + note = note, enteredBy = "AndroidAPS", glucose = null, glucoseType = null, From 2657830f0d0b09e21b5c3e94209b550f113494ce Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 13 May 2021 14:11:38 +0200 Subject: [PATCH 22/27] add indexes --- .../20.json | 3424 +++++++++++++++++ .../androidaps/database/AppDatabase.kt | 2 +- .../androidaps/database/entities/Bolus.kt | 11 +- .../entities/BolusCalculatorResult.kt | 7 +- .../androidaps/database/entities/Carbs.kt | 8 +- .../database/entities/DeviceStatus.kt | 6 +- .../entities/EffectiveProfileSwitch.kt | 9 +- .../database/entities/ExtendedBolus.kt | 11 +- .../androidaps/database/entities/Food.kt | 7 +- .../database/entities/GlucoseValue.kt | 8 +- .../database/entities/ProfileSwitch.kt | 11 +- .../database/entities/TemporaryBasal.kt | 12 +- .../database/entities/TemporaryTarget.kt | 8 +- .../database/entities/TherapyEvent.kt | 9 +- .../database/entities/TotalDailyDose.kt | 10 +- .../androidaps/database/entities/UserEntry.kt | 7 +- .../2.json | 187 + .../insight/database/InsightBolusID.kt | 6 +- .../insight/database/InsightDatabase.kt | 2 +- .../insight/database/InsightPumpID.kt | 6 +- 20 files changed, 3731 insertions(+), 20 deletions(-) create mode 100644 database/schemas/info.nightscout.androidaps.database.AppDatabase/20.json create mode 100644 insight/schemas/info.nightscout.androidaps.insight.database.InsightDatabase/2.json diff --git a/database/schemas/info.nightscout.androidaps.database.AppDatabase/20.json b/database/schemas/info.nightscout.androidaps.database.AppDatabase/20.json new file mode 100644 index 0000000000..9ee949cf15 --- /dev/null +++ b/database/schemas/info.nightscout.androidaps.database.AppDatabase/20.json @@ -0,0 +1,3424 @@ +{ + "formatVersion": 1, + "database": { + "version": 20, + "identityHash": "9d3f2becffaecc2ee9508749be498ae4", + "entities": [ + { + "tableName": "apsResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `algorithm` TEXT NOT NULL, `glucoseStatusJson` TEXT NOT NULL, `currentTempJson` TEXT NOT NULL, `iobDataJson` TEXT NOT NULL, `profileJson` TEXT NOT NULL, `autosensDataJson` TEXT, `mealDataJson` TEXT NOT NULL, `isMicroBolusAllowed` INTEGER, `resultJson` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "algorithm", + "columnName": "algorithm", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseStatusJson", + "columnName": "glucoseStatusJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentTempJson", + "columnName": "currentTempJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "iobDataJson", + "columnName": "iobDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profileJson", + "columnName": "profileJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "autosensDataJson", + "columnName": "autosensDataJson", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mealDataJson", + "columnName": "mealDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isMicroBolusAllowed", + "columnName": "isMicroBolusAllowed", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "resultJson", + "columnName": "resultJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_apsResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_apsResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "apsResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "boluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `amount` REAL NOT NULL, `type` TEXT NOT NULL, `isBasalInsulin` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT, `insulinEndTime` INTEGER, `peak` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isBasalInsulin", + "columnName": "isBasalInsulin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_boluses_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_boluses_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_boluses_temporaryId", + "unique": false, + "columnNames": [ + "temporaryId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_temporaryId` ON `${TABLE_NAME}` (`temporaryId`)" + }, + { + "name": "index_boluses_pumpId", + "unique": false, + "columnNames": [ + "pumpId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_pumpId` ON `${TABLE_NAME}` (`pumpId`)" + }, + { + "name": "index_boluses_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_boluses_pumpType", + "unique": false, + "columnNames": [ + "pumpType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_pumpType` ON `${TABLE_NAME}` (`pumpType`)" + }, + { + "name": "index_boluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_boluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "bolusCalculatorResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `targetBGLow` REAL NOT NULL, `targetBGHigh` REAL NOT NULL, `isf` REAL NOT NULL, `ic` REAL NOT NULL, `bolusIOB` REAL NOT NULL, `wasBolusIOBUsed` INTEGER NOT NULL, `basalIOB` REAL NOT NULL, `wasBasalIOBUsed` INTEGER NOT NULL, `glucoseValue` REAL NOT NULL, `wasGlucoseUsed` INTEGER NOT NULL, `glucoseDifference` REAL NOT NULL, `glucoseInsulin` REAL NOT NULL, `glucoseTrend` REAL NOT NULL, `wasTrendUsed` INTEGER NOT NULL, `trendInsulin` REAL NOT NULL, `cob` REAL NOT NULL, `wasCOBUsed` INTEGER NOT NULL, `cobInsulin` REAL NOT NULL, `carbs` REAL NOT NULL, `wereCarbsUsed` INTEGER NOT NULL, `carbsInsulin` REAL NOT NULL, `otherCorrection` REAL NOT NULL, `wasSuperbolusUsed` INTEGER NOT NULL, `superbolusInsulin` REAL NOT NULL, `wasTempTargetUsed` INTEGER NOT NULL, `totalInsulin` REAL NOT NULL, `percentageCorrection` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `note` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `bolusCalculatorResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetBGLow", + "columnName": "targetBGLow", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "targetBGHigh", + "columnName": "targetBGHigh", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isf", + "columnName": "isf", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "ic", + "columnName": "ic", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bolusIOB", + "columnName": "bolusIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBolusIOBUsed", + "columnName": "wasBolusIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalIOB", + "columnName": "basalIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBasalIOBUsed", + "columnName": "wasBasalIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseValue", + "columnName": "glucoseValue", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasGlucoseUsed", + "columnName": "wasGlucoseUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseDifference", + "columnName": "glucoseDifference", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseInsulin", + "columnName": "glucoseInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseTrend", + "columnName": "glucoseTrend", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTrendUsed", + "columnName": "wasTrendUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "trendInsulin", + "columnName": "trendInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "cob", + "columnName": "cob", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasCOBUsed", + "columnName": "wasCOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cobInsulin", + "columnName": "cobInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wereCarbsUsed", + "columnName": "wereCarbsUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "carbsInsulin", + "columnName": "carbsInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "otherCorrection", + "columnName": "otherCorrection", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasSuperbolusUsed", + "columnName": "wasSuperbolusUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "superbolusInsulin", + "columnName": "superbolusInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTempTargetUsed", + "columnName": "wasTempTargetUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalInsulin", + "columnName": "totalInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "percentageCorrection", + "columnName": "percentageCorrection", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_bolusCalculatorResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_bolusCalculatorResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + }, + { + "name": "index_bolusCalculatorResults_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_bolusCalculatorResults_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_isValid` ON `${TABLE_NAME}` (`isValid`)" + } + ], + "foreignKeys": [ + { + "table": "bolusCalculatorResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "carbs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `carbs`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_carbs_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_carbs_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_carbs_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_carbs_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_carbs_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "carbs", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "effectiveProfileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `originalProfileName` TEXT NOT NULL, `originalCustomizedName` TEXT NOT NULL, `originalTimeshift` INTEGER NOT NULL, `originalPercentage` INTEGER NOT NULL, `originalDuration` INTEGER NOT NULL, `originalEnd` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `effectiveProfileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isfBlocks", + "columnName": "isfBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "icBlocks", + "columnName": "icBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetBlocks", + "columnName": "targetBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalProfileName", + "columnName": "originalProfileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalCustomizedName", + "columnName": "originalCustomizedName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "originalTimeshift", + "columnName": "originalTimeshift", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "originalPercentage", + "columnName": "originalPercentage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "originalDuration", + "columnName": "originalDuration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "originalEnd", + "columnName": "originalEnd", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_effectiveProfileSwitches_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_effectiveProfileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_effectiveProfileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + }, + { + "name": "index_effectiveProfileSwitches_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_isValid` ON `${TABLE_NAME}` (`isValid`)" + } + ], + "foreignKeys": [ + { + "table": "effectiveProfileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "extendedBoluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `isEmulatingTempBasal` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isEmulatingTempBasal", + "columnName": "isEmulatingTempBasal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_extendedBoluses_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_extendedBoluses_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_extendedBoluses_endId", + "unique": false, + "columnNames": [ + "endId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_endId` ON `${TABLE_NAME}` (`endId`)" + }, + { + "name": "index_extendedBoluses_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_extendedBoluses_pumpId", + "unique": false, + "columnNames": [ + "pumpId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_pumpId` ON `${TABLE_NAME}` (`pumpId`)" + }, + { + "name": "index_extendedBoluses_pumpType", + "unique": false, + "columnNames": [ + "pumpType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_pumpType` ON `${TABLE_NAME}` (`pumpType`)" + }, + { + "name": "index_extendedBoluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_extendedBoluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "extendedBoluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "glucoseValues", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `raw` REAL, `value` REAL NOT NULL, `trendArrow` TEXT NOT NULL, `noise` REAL, `sourceSensor` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `glucoseValues`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "raw", + "columnName": "raw", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "trendArrow", + "columnName": "trendArrow", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "noise", + "columnName": "noise", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "sourceSensor", + "columnName": "sourceSensor", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_glucoseValues_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_glucoseValues_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_glucoseValues_sourceSensor", + "unique": false, + "columnNames": [ + "sourceSensor" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_sourceSensor` ON `${TABLE_NAME}` (`sourceSensor`)" + }, + { + "name": "index_glucoseValues_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_glucoseValues_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "glucoseValues", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "profileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `profileName` TEXT NOT NULL, `timeshift` INTEGER NOT NULL, `percentage` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `profileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isfBlocks", + "columnName": "isfBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "icBlocks", + "columnName": "icBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetBlocks", + "columnName": "targetBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeshift", + "columnName": "timeshift", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percentage", + "columnName": "percentage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_profileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_profileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + }, + { + "name": "index_profileSwitches_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_profileSwitches_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_profileSwitches_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + } + ], + "foreignKeys": [ + { + "table": "profileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryBasals", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `type` TEXT NOT NULL, `isAbsolute` INTEGER NOT NULL, `rate` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isAbsolute", + "columnName": "isAbsolute", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rate", + "columnName": "rate", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryBasals_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_temporaryBasals_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_temporaryBasals_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_temporaryBasals_pumpType", + "unique": false, + "columnNames": [ + "pumpType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_pumpType` ON `${TABLE_NAME}` (`pumpType`)" + }, + { + "name": "index_temporaryBasals_endId", + "unique": false, + "columnNames": [ + "endId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_endId` ON `${TABLE_NAME}` (`endId`)" + }, + { + "name": "index_temporaryBasals_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_temporaryBasals_temporaryId", + "unique": false, + "columnNames": [ + "temporaryId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_temporaryId` ON `${TABLE_NAME}` (`temporaryId`)" + }, + { + "name": "index_temporaryBasals_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryBasals_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryBasals", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryTargets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `reason` TEXT NOT NULL, `highTarget` REAL NOT NULL, `lowTarget` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryTargets`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reason", + "columnName": "reason", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highTarget", + "columnName": "highTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "lowTarget", + "columnName": "lowTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryTargets_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_temporaryTargets_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_temporaryTargets_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_temporaryTargets_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryTargets_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryTargets", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "therapyEvents", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `type` TEXT NOT NULL, `note` TEXT, `enteredBy` TEXT, `glucose` REAL, `glucoseType` TEXT, `glucoseUnit` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `therapyEvents`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "enteredBy", + "columnName": "enteredBy", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucose", + "columnName": "glucose", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "glucoseType", + "columnName": "glucoseType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_therapyEvents_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_therapyEvents_type", + "unique": false, + "columnNames": [ + "type" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_type` ON `${TABLE_NAME}` (`type`)" + }, + { + "name": "index_therapyEvents_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_therapyEvents_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_therapyEvents_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_therapyEvents_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "therapyEvents", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "totalDailyDoses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalAmount` REAL NOT NULL, `bolusAmount` REAL NOT NULL, `totalAmount` REAL NOT NULL, `carbs` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `totalDailyDoses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalAmount", + "columnName": "basalAmount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bolusAmount", + "columnName": "bolusAmount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "totalAmount", + "columnName": "totalAmount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_totalDailyDoses_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_totalDailyDoses_pumpId", + "unique": false, + "columnNames": [ + "pumpId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_pumpId` ON `${TABLE_NAME}` (`pumpId`)" + }, + { + "name": "index_totalDailyDoses_pumpType", + "unique": false, + "columnNames": [ + "pumpType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_pumpType` ON `${TABLE_NAME}` (`pumpType`)" + }, + { + "name": "index_totalDailyDoses_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_totalDailyDoses_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_isValid` ON `${TABLE_NAME}` (`isValid`)" + }, + { + "name": "index_totalDailyDoses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_totalDailyDoses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_totalDailyDoses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "totalDailyDoses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "apsResultLinks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `apsResultId` INTEGER NOT NULL, `smbId` INTEGER, `tbrId` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`apsResultId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`smbId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`tbrId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `apsResultLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "apsResultId", + "columnName": "apsResultId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "smbId", + "columnName": "smbId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "tbrId", + "columnName": "tbrId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_apsResultLinks_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_apsResultLinks_apsResultId", + "unique": false, + "columnNames": [ + "apsResultId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_apsResultId` ON `${TABLE_NAME}` (`apsResultId`)" + }, + { + "name": "index_apsResultLinks_smbId", + "unique": false, + "columnNames": [ + "smbId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_smbId` ON `${TABLE_NAME}` (`smbId`)" + }, + { + "name": "index_apsResultLinks_tbrId", + "unique": false, + "columnNames": [ + "tbrId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResultLinks_tbrId` ON `${TABLE_NAME}` (`tbrId`)" + } + ], + "foreignKeys": [ + { + "table": "apsResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "apsResultId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "smbId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "temporaryBasals", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "tbrId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "apsResultLinks", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "multiwaveBolusLinks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `bolusId` INTEGER NOT NULL, `extendedBolusId` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`bolusId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`extendedBolusId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION , FOREIGN KEY(`referenceId`) REFERENCES `multiwaveBolusLinks`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "bolusId", + "columnName": "bolusId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "extendedBolusId", + "columnName": "extendedBolusId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_multiwaveBolusLinks_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_multiwaveBolusLinks_bolusId", + "unique": false, + "columnNames": [ + "bolusId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_bolusId` ON `${TABLE_NAME}` (`bolusId`)" + }, + { + "name": "index_multiwaveBolusLinks_extendedBolusId", + "unique": false, + "columnNames": [ + "extendedBolusId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_multiwaveBolusLinks_extendedBolusId` ON `${TABLE_NAME}` (`extendedBolusId`)" + } + ], + "foreignKeys": [ + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "bolusId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "extendedBoluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "extendedBolusId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "multiwaveBolusLinks", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "preferenceChanges", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `key` TEXT NOT NULL, `value` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "versionChanges", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `versionCode` INTEGER NOT NULL, `versionName` TEXT NOT NULL, `gitRemote` TEXT, `commitHash` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "versionCode", + "columnName": "versionCode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "versionName", + "columnName": "versionName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gitRemote", + "columnName": "gitRemote", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "commitHash", + "columnName": "commitHash", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "userEntry", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `action` TEXT NOT NULL, `source` TEXT NOT NULL, `note` TEXT NOT NULL, `values` TEXT NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "action", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "values", + "columnName": "values", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_userEntry_source", + "unique": false, + "columnNames": [ + "source" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_userEntry_source` ON `${TABLE_NAME}` (`source`)" + }, + { + "name": "index_userEntry_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_userEntry_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "foods", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `name` TEXT NOT NULL, `category` TEXT, `subCategory` TEXT, `portion` REAL NOT NULL, `carbs` INTEGER NOT NULL, `fat` INTEGER, `protein` INTEGER, `energy` INTEGER, `unit` TEXT NOT NULL, `gi` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `foods`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subCategory", + "columnName": "subCategory", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "portion", + "columnName": "portion", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fat", + "columnName": "fat", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "protein", + "columnName": "protein", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "energy", + "columnName": "energy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "unit", + "columnName": "unit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gi", + "columnName": "gi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_foods_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_foods_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_foods_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_foods_isValid", + "unique": false, + "columnNames": [ + "isValid" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_isValid` ON `${TABLE_NAME}` (`isValid`)" + } + ], + "foreignKeys": [ + { + "table": "foods", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "deviceStatus", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `device` TEXT, `pump` TEXT, `enacted` TEXT, `suggested` TEXT, `iob` TEXT, `uploaderBattery` INTEGER NOT NULL, `configuration` TEXT, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "device", + "columnName": "device", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "pump", + "columnName": "pump", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "enacted", + "columnName": "enacted", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "suggested", + "columnName": "suggested", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "iob", + "columnName": "iob", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploaderBattery", + "columnName": "uploaderBattery", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "configuration", + "columnName": "configuration", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_deviceStatus_id", + "unique": false, + "columnNames": [ + "id" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_deviceStatus_id` ON `${TABLE_NAME}` (`id`)" + }, + { + "name": "index_deviceStatus_nightscoutId", + "unique": false, + "columnNames": [ + "nightscoutId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_deviceStatus_nightscoutId` ON `${TABLE_NAME}` (`nightscoutId`)" + }, + { + "name": "index_deviceStatus_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_deviceStatus_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '9d3f2becffaecc2ee9508749be498ae4')" + ] + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt index c779c0a886..163590525c 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt @@ -6,7 +6,7 @@ import androidx.room.TypeConverters import info.nightscout.androidaps.database.daos.* import info.nightscout.androidaps.database.entities.* -const val DATABASE_VERSION = 18 +const val DATABASE_VERSION = 20 @Database(version = DATABASE_VERSION, entities = [APSResult::class, Bolus::class, BolusCalculatorResult::class, Carbs::class, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt index afc6108867..d174f9b25d 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt @@ -18,7 +18,16 @@ import java.util.* entity = Bolus::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("isValid"), + Index("temporaryId"), + Index("pumpId"), + Index("pumpSerial"), + Index("pumpType"), + Index("referenceId"), + Index("timestamp") + ]) data class Bolus( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt index e88699f9ea..8e1f0b0532 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt @@ -12,7 +12,12 @@ import java.util.TimeZone entity = BolusCalculatorResult::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("referenceId"), + Index("timestamp"), + Index("id"), + Index("isValid") + ]) data class BolusCalculatorResult( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt index cd5a41ab87..c068da1bfe 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt @@ -16,7 +16,13 @@ import java.util.* entity = Carbs::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("isValid"), + Index("nightscoutId"), + Index("referenceId"), + Index("timestamp") + ]) data class Carbs( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/DeviceStatus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/DeviceStatus.kt index 87763245fc..516be6f9ce 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/DeviceStatus.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/DeviceStatus.kt @@ -11,7 +11,11 @@ import java.util.* @Entity(tableName = TABLE_DEVICE_STATUS, foreignKeys = [], - indices = [Index("timestamp")]) + indices = [ + Index("id"), + Index("nightscoutId"), + Index("timestamp") + ]) data class DeviceStatus( @PrimaryKey(autoGenerate = true) var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt index a38e254c5b..7a2285831e 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt @@ -19,7 +19,12 @@ import java.util.* entity = EffectiveProfileSwitch::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("referenceId"), + Index("timestamp"), + Index("isValid") + ]) data class EffectiveProfileSwitch( @PrimaryKey(autoGenerate = true) override var id: Long = 0, @@ -45,7 +50,7 @@ data class EffectiveProfileSwitch( var originalEnd: Long, @Embedded var insulinConfiguration: InsulinConfiguration -) : TraceableDBEntry, DBEntryWithTime{ +) : TraceableDBEntry, DBEntryWithTime { enum class GlucoseUnit { MGDL, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt index 08a218aea8..c59afdd34c 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt @@ -16,7 +16,16 @@ import java.util.* entity = ExtendedBolus::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("isValid"), + Index("endId"), + Index("pumpSerial"), + Index("pumpId"), + Index("pumpType"), + Index("referenceId"), + Index("timestamp") + ]) data class ExtendedBolus( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Food.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Food.kt index 9c4cfc9129..762edf38c7 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/Food.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Food.kt @@ -14,7 +14,12 @@ import info.nightscout.androidaps.database.interfaces.TraceableDBEntry entity = Food::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId")]) + indices = [ + Index("id"), + Index("nightscoutId"), + Index("referenceId"), + Index("isValid") + ]) data class Food( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt index 85fab0a92c..d7140a7900 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt @@ -13,7 +13,13 @@ import java.util.TimeZone entity = GlucoseValue::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("nightscoutId"), + Index("sourceSensor"), + Index("referenceId"), + Index("timestamp") + ]) data class GlucoseValue( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt index 791c32abe0..569a895301 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt @@ -19,7 +19,13 @@ import java.util.* entity = ProfileSwitch::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("referenceId"), + Index("timestamp"), + Index("isValid"), + Index("id"), + Index("nightscoutId") + ]) data class ProfileSwitch( @PrimaryKey(autoGenerate = true) override var id: Long = 0, @@ -47,6 +53,7 @@ data class ProfileSwitch( enum class GlucoseUnit { MGDL, MMOL; - companion object {} + + companion object } } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt index 8f5e709790..2e3b002476 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt @@ -16,7 +16,17 @@ import java.util.* entity = TemporaryBasal::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("isValid"), + Index("nightscoutId"), + Index("pumpType"), + Index("endId"), + Index("pumpSerial"), + Index("temporaryId"), + Index("referenceId"), + Index("timestamp") + ]) data class TemporaryBasal( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt index f70fe145cc..7e6c2774fc 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt @@ -17,7 +17,13 @@ import java.util.* entity = TemporaryTarget::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("isValid"), + Index("nightscoutId"), + Index("referenceId"), + Index("timestamp") + ]) data class TemporaryTarget( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt index 15e7a1a7fd..8a701e1e21 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt @@ -17,7 +17,14 @@ import java.util.* entity = TherapyEvent::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("type"), + Index("nightscoutId"), + Index("isValid"), + Index("referenceId"), + Index("timestamp") + ]) data class TherapyEvent( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt index fb386312a5..a45330c844 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt @@ -16,7 +16,15 @@ import java.util.* entity = TotalDailyDose::class, parentColumns = ["id"], childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + indices = [ + Index("id"), + Index("pumpId"), + Index("pumpType"), + Index("pumpSerial"), + Index("isValid"), + Index("referenceId"), + Index("timestamp") + ]) data class TotalDailyDose( @PrimaryKey(autoGenerate = true) override var id: Long = 0, diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt index 4e98e31686..1672944892 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt @@ -1,13 +1,18 @@ package info.nightscout.androidaps.database.entities import androidx.room.Entity +import androidx.room.Index import androidx.room.PrimaryKey import info.nightscout.androidaps.database.TABLE_USER_ENTRY import info.nightscout.androidaps.database.interfaces.DBEntry import info.nightscout.androidaps.database.interfaces.DBEntryWithTime import java.util.* -@Entity(tableName = TABLE_USER_ENTRY) +@Entity(tableName = TABLE_USER_ENTRY, + indices = [ + Index("source"), + Index("timestamp") + ]) data class UserEntry( @PrimaryKey(autoGenerate = true) override var id: Long = 0L, diff --git a/insight/schemas/info.nightscout.androidaps.insight.database.InsightDatabase/2.json b/insight/schemas/info.nightscout.androidaps.insight.database.InsightDatabase/2.json new file mode 100644 index 0000000000..7e0ef8b6fd --- /dev/null +++ b/insight/schemas/info.nightscout.androidaps.insight.database.InsightDatabase/2.json @@ -0,0 +1,187 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "391daa1e25629bafef27e6247e788e74", + "entities": [ + { + "tableName": "insightBolusIDs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `pumpSerial` TEXT, `bolusID` INTEGER, `startID` INTEGER, `endID` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "bolusID", + "columnName": "bolusID", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "startID", + "columnName": "startID", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "endID", + "columnName": "endID", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_insightBolusIDs_bolusID", + "unique": false, + "columnNames": [ + "bolusID" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightBolusIDs_bolusID` ON `${TABLE_NAME}` (`bolusID`)" + }, + { + "name": "index_insightBolusIDs_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightBolusIDs_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_insightBolusIDs_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightBolusIDs_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "insightHistoryOffsets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`pumpSerial` TEXT NOT NULL, `offset` INTEGER NOT NULL, PRIMARY KEY(`pumpSerial`))", + "fields": [ + { + "fieldPath": "pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "offset", + "columnName": "offset", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "pumpSerial" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_insightHistoryOffsets_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightHistoryOffsets_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "insightPumpIDs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `eventType` TEXT NOT NULL, `pumpSerial` TEXT, `eventID` INTEGER NOT NULL, PRIMARY KEY(`eventID`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventType", + "columnName": "eventType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "eventID", + "columnName": "eventID", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "eventID" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_insightPumpIDs_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightPumpIDs_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + }, + { + "name": "index_insightPumpIDs_pumpSerial", + "unique": false, + "columnNames": [ + "pumpSerial" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightPumpIDs_pumpSerial` ON `${TABLE_NAME}` (`pumpSerial`)" + }, + { + "name": "index_insightPumpIDs_eventType", + "unique": false, + "columnNames": [ + "eventType" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_insightPumpIDs_eventType` ON `${TABLE_NAME}` (`eventType`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '391daa1e25629bafef27e6247e788e74')" + ] + } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt index 99b6055c7f..38ba7c708c 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt @@ -5,7 +5,11 @@ import androidx.room.Index import androidx.room.PrimaryKey @Entity(tableName = DATABASE_INSIGHT_BOLUS_IDS, - indices = [Index("bolusID")]) + indices = [ + Index("bolusID"), + Index("pumpSerial"), + Index("timestamp") + ]) data class InsightBolusID( var timestamp: Long, val pumpSerial: String? = null, diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt index 7be27eae76..006980e4ff 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -22,7 +22,7 @@ abstract class InsightDatabase : RoomDatabase() { companion object { - const val VERSION = 1 + const val VERSION = 2 fun build(context: Context) = Room.databaseBuilder( diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt index 71e5b3502e..6ac8e00eca 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt @@ -5,7 +5,11 @@ import androidx.room.Index import androidx.room.PrimaryKey @Entity(tableName = DATABASE_INSIGHT_PUMP_IDS, - indices = [Index("timestamp")]) + indices = [ + Index("timestamp"), + Index("pumpSerial"), + Index("eventType") + ]) data class InsightPumpID( var timestamp: Long, var eventType: EventType = EventType.None, From 4cadec78e54ec1a7d3e3056e892a951a4c15dfc5 Mon Sep 17 00:00:00 2001 From: Philoul Date: Thu, 13 May 2021 14:38:04 +0200 Subject: [PATCH 23/27] Improvement Action String (TT) --- core/src/main/res/values/strings.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index 0c7d888f47..58a5795f1f 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -413,7 +413,7 @@ CARBS EXTENDED CARBS TEMP BASAL - TT + TEMP TARGET NEW PROFILE CLONE PROFILE STORE PROFILE @@ -434,7 +434,7 @@ CANCEL TEMP BASAL CANCEL BOLUS CANCEL EXTENDED BOLUS - CANCEL TT + CANCEL TEMP TARGET CAREPORTAL SITE CHANGE RESERVOIR CHANGE @@ -444,7 +444,7 @@ CAREPORTAL NS REFRESH PROFILE SWITCH NS REFRESH TREATMENTS NS REFRESH - TT NS REFRESH + TEMP TARGET NS REFRESH AUTOMATION REMOVED BG REMOVED CAREPORTAL REMOVED @@ -458,7 +458,7 @@ PROFILE SWITCH REMOVED RESTART EVENTS REMOVED TREATMENT REMOVED - TT REMOVED + TEMP TARGET REMOVED NS PAUSED NS RESUME NS QUEUE CLEARED From 4f5a407a2fc0158721e231e8a1077f910ac86634 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 13 May 2021 14:56:10 +0200 Subject: [PATCH 24/27] fix PS sync --- .../androidaps/extensions/ProfileSwitchExtension.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt index 921d38e2e7..ae22865f04 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt @@ -25,8 +25,8 @@ fun ProfileSwitch.toJson(dateUtil: DateUtil): JSONObject = .put("duration", T.msecs(duration).mins()) .put("profile", getCustomizedName()) .put("profileJson", ProfileSealed.PS(this).toPureNsJson(dateUtil).toString()) - .put("timeshift", T.msecs(timeshift).hours()) - .put("percentage", percentage) + .put("timeshift", 0) + .put("percentage", 100) // customization already applied to json .also { if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) if (interfaceIDs.pumpType != null) it.put("pumpType", interfaceIDs.pumpType!!.name) From 98aac56c1c7891bcba6f89834084168abade4b48 Mon Sep 17 00:00:00 2001 From: Philoul Date: Thu, 13 May 2021 15:10:53 +0200 Subject: [PATCH 25/27] UserEntryPresentationHelper / csv improvement --- .../userEntry/UserEntryPresentationHelper.kt | 30 +++++++++---------- core/src/main/res/values/strings.xml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt index 0211fcf550..0faf232c17 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt @@ -152,7 +152,7 @@ class UserEntryPresentationHelper @Inject constructor( csvString(R.string.eventtype), csvString(R.string.ue_source), csvString(R.string.careportal_note), - csvString(R.string.ue_formated_string), + csvString(R.string.ue_string), csvString(R.string.event_time_label), csvString(if (profileFunction.getUnits() == GlucoseUnit.MGDL) R.string.mgdl else R.string.mmol), csvString(R.string.shortgram), @@ -165,15 +165,15 @@ class UserEntryPresentationHelper @Inject constructor( ) + "\n" private fun getCsvEntry(entry: UserEntry): String { - val fullvalueWithUnitList = ArrayList(entry.values) - var timestampRec = "" + entry.timestamp - var dateTimestampRev = dateUtil.dateAndTimeAndSecondsString(entry.timestamp) - var utcOffset = dateUtil.timeStringFromSeconds((entry.utcOffset/1000).toInt()) - var action = csvString(entry.action) + val fullvalueWithUnitList = ArrayList(entry.values) + val timestampRec = entry.timestamp.toString() + val dateTimestampRev = dateUtil.dateAndTimeAndSecondsString(entry.timestamp) + val utcOffset = dateUtil.timeStringFromSeconds((entry.utcOffset/1000).toInt()) + val action = csvString(entry.action) var therapyEvent = "" - var source = translator.translate(entry.source) - var note = csvString(entry.note) - var stringResource = "" + val source = translator.translate(entry.source) + val note = csvString(entry.note) + var simpleString = "" var timestamp = "" var bg = "" var gram = "" @@ -182,7 +182,7 @@ class UserEntryPresentationHelper @Inject constructor( var percent = "" var hour = "" var minute = "" - var other = "" + var noUnit = "" for (valueWithUnit in fullvalueWithUnitList.filterNotNull()) { when (valueWithUnit) { @@ -192,8 +192,8 @@ class UserEntryPresentationHelper @Inject constructor( is ValueWithUnit.Percent -> percent = valueWithUnit.value.toString() is ValueWithUnit.Insulin -> insulin = DecimalFormatter.to2Decimal(valueWithUnit.value) is ValueWithUnit.UnitPerHour -> unitPerHour = DecimalFormatter.to2Decimal(valueWithUnit.value) - is ValueWithUnit.SimpleInt -> other = other.addWithSeparator(valueWithUnit.value) - is ValueWithUnit.SimpleString -> other = other.addWithSeparator(valueWithUnit.value) + is ValueWithUnit.SimpleInt -> noUnit = noUnit.addWithSeparator(valueWithUnit.value) + is ValueWithUnit.SimpleString -> simpleString = simpleString.addWithSeparator(valueWithUnit.value) is ValueWithUnit.TherapyEventMeterType -> therapyEvent = therapyEvent.addWithSeparator(translator.translate(valueWithUnit.value)) is ValueWithUnit.TherapyEventTTReason -> therapyEvent = therapyEvent.addWithSeparator(translator.translate(valueWithUnit.value)) is ValueWithUnit.TherapyEventType -> therapyEvent = therapyEvent.addWithSeparator(translator.translate(valueWithUnit.value)) @@ -210,9 +210,9 @@ class UserEntryPresentationHelper @Inject constructor( } therapyEvent = csvString(therapyEvent) - stringResource = csvString(stringResource) - other = csvString(other) - return "$timestampRec;$dateTimestampRev;$utcOffset;$action;$therapyEvent;$source;$note;$stringResource;$timestamp;$bg;$gram;$insulin;$unitPerHour;$percent;$hour;$minute;$other" + simpleString = csvString(simpleString) + noUnit = csvString(noUnit) + return "$timestampRec;$dateTimestampRev;$utcOffset;$action;$therapyEvent;$source;$note;$simpleString;$timestamp;$bg;$gram;$insulin;$unitPerHour;$percent;$hour;$minute;$noUnit" } private fun csvString(action: Action): String = "\"" + translator.translate(action).replace("\"", "\"\"").replace("\n"," / ") + "\"" diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index 58a5795f1f..8742f92523 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -486,7 +486,7 @@ PLUGIN ENABLED PLUGIN DISABLED UNKNOWN - Formated string + String Source UTC Offset Action From e83375f754ea6e4c48e79ae23b0ca64dcae5f017 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 13 May 2021 17:44:07 +0200 Subject: [PATCH 26/27] NSClient update --- .../DataSyncSelectorImplementation.kt | 207 +++++++++--------- .../nsclient/NSClientUpdateRemoveAckWorker.kt | 20 +- .../nsclient/services/NSClientService.kt | 50 ++--- 3 files changed, 136 insertions(+), 141 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index 9e124bfcca..e726c41d01 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -75,21 +75,21 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastBolusId = -1L + private var lastBolusTime = -1L override fun processChangedBolusesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) + if (startId == lastBolusId && dateUtil.now() - lastBolusTime < 5000) return false + lastBolusId = startId + lastBolusTime = dateUtil.now() appRepository.getNextSyncElementBolus(startId).blockingGet()?.let { bolus -> aapsLogger.info(LTag.DATABASE, "Loading Bolus data Start: $startId ID: ${bolus.first.id} HistoryID: ${bolus.second} ") when { - // removed and not uploaded yet = ignore - !bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", bolus.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolus(bolus.first, bolus.second)) - // existing without nsId = create new - bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + bolus.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) - // existing with nsId = update - bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + bolus.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) } return true @@ -112,21 +112,21 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastCarbsId = -1L + private var lastCarbsTime = -1L override fun processChangedCarbsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) + if (startId == lastCarbsId && dateUtil.now() - lastCarbsTime < 5000) return false + lastCarbsId = startId + lastCarbsTime = dateUtil.now() appRepository.getNextSyncElementCarbs(startId).blockingGet()?.let { carb -> aapsLogger.info(LTag.DATABASE, "Loading Carbs data Start: $startId ID: ${carb.first.id} HistoryID: ${carb.second} ") when { - // removed and not uploaded yet = ignore - !carb.first.isValid && carb.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !carb.first.isValid && carb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", carb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairCarbs(carb.first, carb.second)) - // existing without nsId = create new - carb.first.isValid && carb.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + carb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) - // existing with nsId = update - carb.first.isValid && carb.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + carb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) } return true @@ -149,21 +149,21 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastBcrId = -1L + private var lastBcrTime = -1L override fun processChangedBolusCalculatorResultsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + if (startId == lastBcrId && dateUtil.now() - lastBcrTime < 5000) return false + lastBcrId = startId + lastBcrTime = dateUtil.now() appRepository.getNextSyncElementBolusCalculatorResult(startId).blockingGet()?.let { bolusCalculatorResult -> aapsLogger.info(LTag.DATABASE, "Loading BolusCalculatorResult data Start: $startId ID: ${bolusCalculatorResult.first.id} HistoryID: ${bolusCalculatorResult.second} ") when { - // removed and not uploaded yet = ignore - !bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) - // existing without nsId = create new - bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) - // existing with nsId = update - bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) } return true @@ -186,21 +186,21 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastTtId = -1L + private var lastTtTime = -1L override fun processChangedTempTargetsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) + if (startId == lastTtId && dateUtil.now() - lastTtTime < 5000) return false + lastTtId = startId + lastTtTime = dateUtil.now() appRepository.getNextSyncElementTemporaryTarget(startId).blockingGet()?.let { tt -> aapsLogger.info(LTag.DATABASE, "Loading TemporaryTarget data Start: $startId ID: ${tt.first.id} HistoryID: ${tt.second} ") when { - // removed and not uploaded yet = ignore - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) - // existing without nsId = create new - tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + tt.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) // existing with nsId = update - tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> + tt.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) } return true @@ -223,22 +223,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastFoodId = -1L + private var lastFoodTime = -1L override fun processChangedFoodsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) - appRepository.getNextSyncElementFood(startId).blockingGet()?.let { tt -> - aapsLogger.info(LTag.DATABASE, "Loading Food data Start: $startId ID: ${tt.first.id} HistoryID: ${tt.second} ") + if (startId == lastFoodId && dateUtil.now() - lastFoodTime < 5000) return false + lastFoodId = startId + lastFoodTime = dateUtil.now() + appRepository.getNextSyncElementFood(startId).blockingGet()?.let { food -> + aapsLogger.info(LTag.DATABASE, "Loading Food data Start: $startId ID: ${food.first.id} HistoryID: ${food.second} ") when { - // removed and not uploaded yet = ignore - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("food", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairFood(tt.first, tt.second)) - // existing without nsId = create new - tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("food", tt.first.toJson(), DataSyncSelector.PairFood(tt.first, tt.second)) - // existing with nsId = update - tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("food", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(), DataSyncSelector.PairFood(tt.first, tt.second)) + // without nsId = create new + food.first.interfaceIDs.nightscoutId == null -> + nsClientPlugin.nsClientService?.dbAdd("food", food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second)) + // with nsId = update + food.first.interfaceIDs.nightscoutId != null -> + nsClientPlugin.nsClientService?.dbUpdate("food", food.first.interfaceIDs.nightscoutId, food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second)) } return true } @@ -260,22 +260,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastGvId = -1L + private var lastGvTime = -1L override fun processChangedGlucoseValuesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) + if (startId == lastGvId && dateUtil.now() - lastGvTime < 5000) return false + lastGvId = startId + lastGvTime = dateUtil.now() appRepository.getNextSyncElementGlucoseValue(startId).blockingGet()?.let { gv -> aapsLogger.info(LTag.DATABASE, "Loading GlucoseValue data Start: $startId ID: ${gv.first.id} HistoryID: ${gv.second} ") if (activePlugin.activeBgSource.shouldUploadToNs(gv.first)) { when { - // removed and not uploaded yet = ignore - !gv.first.isValid && gv.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !gv.first.isValid && gv.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("entries", gv.first.interfaceIDs.nightscoutId, DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) - // existing without nsId = create new - gv.first.isValid && gv.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + gv.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) - // existing with nsId = update - gv.first.isValid && gv.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + gv.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) } return true @@ -299,22 +299,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastTeId = -1L + private var lastTeTime = -1L override fun processChangedTherapyEventsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) - appRepository.getNextSyncElementTherapyEvent(startId).blockingGet()?.let { tt -> - aapsLogger.info(LTag.DATABASE, "Loading TherapyEvents data Start: $startId ID: ${tt.first.id} HistoryID: ${tt.second} ") + if (startId == lastTeId && dateUtil.now() - lastTeTime < 5000) return false + lastTeId = startId + lastTeTime = dateUtil.now() + appRepository.getNextSyncElementTherapyEvent(startId).blockingGet()?.let { te -> + aapsLogger.info(LTag.DATABASE, "Loading TherapyEvents data Start: $startId ID: ${te.first.id} HistoryID: ${te.second} ") when { - // removed and not uploaded yet = ignore - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTherapyEvent(tt.first, tt.second)) - // existing without nsId = create new - tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(), DataSyncSelector.PairTherapyEvent(tt.first, tt.second)) - // existing with nsId = update - tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(), DataSyncSelector.PairTherapyEvent(tt.first, tt.second)) + // without nsId = create new + te.first.interfaceIDs.nightscoutId == null -> + nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second)) + // nsId = update + te.first.interfaceIDs.nightscoutId != null -> + nsClientPlugin.nsClientService?.dbUpdate("treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second)) } return true } @@ -335,8 +335,13 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastDsId = -1L + private var lastDsTime = -1L override fun processChangedDeviceStatusesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) + if (startId == lastDsId && dateUtil.now() - lastDsTime < 5000) return false + lastDsId = startId + lastDsTime = dateUtil.now() appRepository.getNextSyncElementDeviceStatus(startId).blockingGet()?.let { deviceStatus -> aapsLogger.info(LTag.DATABASE, "Loading DeviceStatus data Start: $startId ID: ${deviceStatus.id}") when { @@ -366,22 +371,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastTbrId = -1L + private var lastTbrTime = -1L override fun processChangedTemporaryBasalsCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + if (startId == lastTbrId && dateUtil.now() - lastTbrTime < 5000) return false + lastTbrId = startId + lastTbrTime = dateUtil.now() appRepository.getNextSyncElementTemporaryBasal(startId).blockingGet()?.let { tb -> aapsLogger.info(LTag.DATABASE, "Loading TemporaryBasal data Start: $startId ID: ${tb.first.id} HistoryID: ${tb.second} ") profileFunction.getProfile(tb.first.timestamp)?.let { profile -> when { - // removed and not uploaded yet = ignore - !tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", tb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) - // existing without nsId = create new - tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + tb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) - // existing with nsId = update - tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + tb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) } return true @@ -405,22 +410,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastEbId = -1L + private var lastEbTime = -1L override fun processChangedExtendedBolusesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + if (startId == lastEbId && dateUtil.now() - lastEbTime < 5000) return false + lastEbId = startId + lastEbTime = dateUtil.now() appRepository.getNextSyncElementExtendedBolus(startId).blockingGet()?.let { eb -> aapsLogger.info(LTag.DATABASE, "Loading ExtendedBolus data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ") profileFunction.getProfile(eb.first.timestamp)?.let { profile -> when { - // removed and not uploaded yet = ignore - !eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) - // existing without nsId = create new - eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> + // without nsId = create new + eb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) - // existing with nsId = update - eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> + // with nsId = update + eb.first.interfaceIDs.nightscoutId != null -> nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) } return true @@ -443,22 +448,22 @@ class DataSyncSelectorImplementation @Inject constructor( } } + private var lastPsId = -1L + private var lastPsTime = -1L override fun processChangedProfileSwitchesCompat(): Boolean { val startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) - appRepository.getNextSyncElementProfileSwitch(startId).blockingGet()?.let { eb -> - aapsLogger.info(LTag.DATABASE, "Loading ProfileSwitch data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ") + if (startId == lastPsId && dateUtil.now() - lastPsTime < 5000) return false + lastPsId = startId + lastPsTime = dateUtil.now() + appRepository.getNextSyncElementProfileSwitch(startId).blockingGet()?.let { ps -> + aapsLogger.info(LTag.DATABASE, "Loading ProfileSwitch data Start: $startId ID: ${ps.first.id} HistoryID: ${ps.second} ") when { - // removed and not uploaded yet = ignore - !eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> Any() - // removed and already uploaded = send for removal - !eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairProfileSwitch(eb.first, eb.second)) - // existing without nsId = create new - eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(eb.first, eb.second)) - // existing with nsId = update - eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(eb.first, eb.second)) + // without nsId = create new + ps.first.interfaceIDs.nightscoutId == null -> + nsClientPlugin.nsClientService?.dbAdd("treatments", ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second)) + // with nsId = update + ps.first.interfaceIDs.nightscoutId != null -> + nsClientPlugin.nsClientService?.dbUpdate("treatments", ps.first.interfaceIDs.nightscoutId, ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientUpdateRemoveAckWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientUpdateRemoveAckWorker.kt index cd818d4461..a7f51cbc70 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientUpdateRemoveAckWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientUpdateRemoveAckWorker.kt @@ -39,7 +39,7 @@ class NSClientUpdateRemoveAckWorker( is PairTemporaryTarget -> { val pair = ack.originalObject dataSyncSelector.confirmLastTempTargetsIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked TemporaryTarget" + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked TemporaryTarget" + ack._id)) // Send new if waiting dataSyncSelector.processChangedTempTargetsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -48,7 +48,7 @@ class NSClientUpdateRemoveAckWorker( is PairGlucoseValue -> { val pair = ack.originalObject dataSyncSelector.confirmLastGlucoseValueIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked GlucoseValue " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked GlucoseValue " + ack._id)) // Send new if waiting dataSyncSelector.processChangedGlucoseValuesCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -57,7 +57,7 @@ class NSClientUpdateRemoveAckWorker( is PairFood -> { val pair = ack.originalObject dataSyncSelector.confirmLastFoodIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked Food " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked Food " + ack._id)) // Send new if waiting dataSyncSelector.processChangedFoodsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -66,7 +66,7 @@ class NSClientUpdateRemoveAckWorker( is PairTherapyEvent -> { val pair = ack.originalObject dataSyncSelector.confirmLastTherapyEventIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked TherapyEvent " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked TherapyEvent " + ack._id)) // Send new if waiting dataSyncSelector.processChangedTherapyEventsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -75,7 +75,7 @@ class NSClientUpdateRemoveAckWorker( is PairBolus -> { val pair = ack.originalObject dataSyncSelector.confirmLastBolusIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked Bolus " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked Bolus " + ack._id)) // Send new if waiting dataSyncSelector.processChangedBolusesCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -84,7 +84,7 @@ class NSClientUpdateRemoveAckWorker( is PairCarbs -> { val pair = ack.originalObject dataSyncSelector.confirmLastCarbsIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked Carbs " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked Carbs " + ack._id)) // Send new if waiting dataSyncSelector.processChangedCarbsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -93,7 +93,7 @@ class NSClientUpdateRemoveAckWorker( is PairBolusCalculatorResult -> { val pair = ack.originalObject dataSyncSelector.confirmLastBolusCalculatorResultsIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked BolusCalculatorResult " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked BolusCalculatorResult " + ack._id)) // Send new if waiting dataSyncSelector.processChangedBolusCalculatorResultsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -102,7 +102,7 @@ class NSClientUpdateRemoveAckWorker( is PairTemporaryBasal -> { val pair = ack.originalObject dataSyncSelector.confirmLastTemporaryBasalIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked TemporaryBasal " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked TemporaryBasal " + ack._id)) // Send new if waiting dataSyncSelector.processChangedTemporaryBasalsCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -111,7 +111,7 @@ class NSClientUpdateRemoveAckWorker( is PairExtendedBolus -> { val pair = ack.originalObject dataSyncSelector.confirmLastExtendedBolusIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked ExtendedBolus " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked ExtendedBolus " + ack._id)) // Send new if waiting dataSyncSelector.processChangedExtendedBolusesCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -120,7 +120,7 @@ class NSClientUpdateRemoveAckWorker( is PairProfileSwitch -> { val pair = ack.originalObject dataSyncSelector.confirmLastProfileSwitchIdIfGreater(pair.updateRecordId) - rxBus.send(EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked ProfileSwitch " + ack._id)) + rxBus.send(EventNSClientNewLog("DBUPDATE", "Acked ProfileSwitch " + ack._id)) // Send new if waiting dataSyncSelector.processChangedProfileSwitchesCompat() ret = Result.success(workDataOf("ProcessedData" to pair.toString())) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt index ad73e4160b..9a12b70670 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.general.nsclient.services +import android.annotation.SuppressLint +import android.content.Context import android.content.Intent import android.os.* import androidx.work.OneTimeWorkRequest @@ -83,6 +85,7 @@ class NSClientService : DaggerService() { @Inject lateinit var repository: AppRepository companion object { + private const val WATCHDOG_INTERVAL_MINUTES = 2 private const val WATCHDOG_RECONNECT_IN = 15 private const val WATCHDOG_MAX_CONNECTIONS = 5 @@ -90,7 +93,7 @@ class NSClientService : DaggerService() { private val disposable = CompositeDisposable() - // public PowerManager.WakeLock mWakeLock; + private var wakeLock: PowerManager.WakeLock? = null private val binder: IBinder = LocalBinder() private var handler: Handler? = null private var socket: Socket? = null @@ -108,11 +111,12 @@ class NSClientService : DaggerService() { var hasWriteAuth = false var nsURL = "" var latestDateInReceivedData: Long = 0 + + @SuppressLint("WakelockTimeout") override fun onCreate() { super.onCreate() - // PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); -// mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService"); -// mWakeLock.acquire(); + wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService") + wakeLock?.acquire() initialize() disposable.add(rxBus .toObservable(EventConfigBuilderChange::class.java) @@ -163,7 +167,7 @@ class NSClientService : DaggerService() { disposable.add(rxBus .toObservable(NSUpdateAck::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException) + .subscribe({ ack -> processUpdateAck(ack) }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(NSAddAck::class.java) @@ -175,7 +179,7 @@ class NSClientService : DaggerService() { override fun onDestroy() { super.onDestroy() disposable.clear() - // if (mWakeLock.isHeld()) mWakeLock.release(); + if (wakeLock?.isHeld == true) wakeLock?.release() } private fun processAddAck(ack: NSAddAck) { @@ -449,10 +453,10 @@ class NSClientService : DaggerService() { } private val onDataUpdate = Emitter.Listener { args -> handler?.post { - val powerManager = getSystemService(POWER_SERVICE) as PowerManager - val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "AndroidAPS:NSClientService_onDataUpdate") - wakeLock.acquire(3000) + // val powerManager = getSystemService(POWER_SERVICE) as PowerManager + // val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + // "AndroidAPS:NSClientService_onDataUpdate") + // wakeLock.acquire(3000) try { val data = args[0] as JSONObject try { @@ -585,7 +589,7 @@ class NSClientService : DaggerService() { } //rxBus.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { - if (wakeLock.isHeld) wakeLock.release() + // if (wakeLock.isHeld) wakeLock.release() } } } @@ -605,20 +609,6 @@ class NSClientService : DaggerService() { } } - fun dbRemove(collection: String, _id: String?, originalObject: Any) { - try { - if (_id == null) return - if (!isConnected || !hasWriteAuth) return - val message = JSONObject() - message.put("collection", collection) - message.put("_id", _id) - socket?.emit("dbRemove", message, NSUpdateAck("dbRemove", _id, aapsLogger, rxBus, originalObject)) - rxBus.send(EventNSClientNewLog("DBREMOVE $collection", "Sent " + originalObject.javaClass.simpleName + " " + _id)) - } catch (e: JSONException) { - aapsLogger.error("Unhandled exception", e) - } - } - fun dbAdd(collection: String, data: JSONObject, originalObject: Any) { try { if (!isConnected || !hasWriteAuth) return @@ -646,16 +636,16 @@ class NSClientService : DaggerService() { aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastAckTime: " + (System.currentTimeMillis() - lastAckTime) / 1000L + " sec") return@post } - val powerManager = getSystemService(POWER_SERVICE) as PowerManager - val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "AndroidAPS:NSClientService_onDataUpdate") - wakeLock.acquire(mins(10).msecs()) + // val powerManager = getSystemService(POWER_SERVICE) as PowerManager + // val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, + // "AndroidAPS:NSClientService_onDataUpdate") + // wakeLock.acquire(mins(10).msecs()) try { rxBus.send(EventNSClientNewLog("QUEUE", "Resend started: $reason")) dataSyncSelector.doUpload() rxBus.send(EventNSClientNewLog("QUEUE", "Resend ended: $reason")) } finally { - if (wakeLock.isHeld) wakeLock.release() + // if (wakeLock.isHeld) wakeLock.release() } } } From 1af0cc5aebfc95c8063ec548e50e26c21cb205a9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 14 May 2021 08:54:11 +0200 Subject: [PATCH 27/27] NSClient sync improvement --- .../DataSyncSelectorImplementation.kt | 157 +++++++++++++----- .../general/nsclient/NSClientAddAckWorker.kt | 4 +- .../nsclient/services/NSClientService.kt | 8 +- .../androidaps/database/AppRepository.kt | 58 +++++++ .../database/daos/BolusCalculatorResultDao.kt | 3 + .../androidaps/database/daos/BolusDao.kt | 3 + .../androidaps/database/daos/CarbsDao.kt | 3 + .../database/daos/DeviceStatusDao.kt | 3 + .../daos/EffectiveProfileSwitchDao.kt | 3 + .../database/daos/ExtendedBolusDao.kt | 3 + .../androidaps/database/daos/FoodDao.kt | 3 + .../database/daos/GlucoseValueDao.kt | 3 + .../database/daos/ProfileSwitchDao.kt | 3 + .../database/daos/TemporaryBasalDao.kt | 3 + .../database/daos/TemporaryTargetDao.kt | 3 + .../database/daos/TherapyEventDao.kt | 3 + 16 files changed, 219 insertions(+), 44 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index 697192f485..debcb920a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.general.nsclient import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.* import info.nightscout.androidaps.extensions.toJson import info.nightscout.androidaps.interfaces.ActivePlugin @@ -78,7 +79,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastBolusId = -1L private var lastBolusTime = -1L override fun processChangedBolusesCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastBolusIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_bolus_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_bolus_last_synced_id, 0) + startId = 0 + } if (startId == lastBolusId && dateUtil.now() - lastBolusTime < 5000) return false lastBolusId = startId lastBolusTime = dateUtil.now() @@ -87,10 +94,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new bolus.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second), "$startId/$lastDbId") // with nsId = update bolus.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second), "$startId/$lastDbId") } return true } @@ -115,7 +122,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastCarbsId = -1L private var lastCarbsTime = -1L override fun processChangedCarbsCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastCarbsIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_carbs_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_carbs_last_synced_id, 0) + startId = 0 + } if (startId == lastCarbsId && dateUtil.now() - lastCarbsTime < 5000) return false lastCarbsId = startId lastCarbsTime = dateUtil.now() @@ -124,10 +137,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new carb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second), "$startId/$lastDbId") // with nsId = update carb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second), "$startId/$lastDbId") } return true } @@ -152,7 +165,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastBcrId = -1L private var lastBcrTime = -1L override fun processChangedBolusCalculatorResultsCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastBolusCalculatorResultIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_bolus_calculator_result_last_synced_id, 0) + startId = 0 + } if (startId == lastBcrId && dateUtil.now() - lastBcrTime < 5000) return false lastBcrId = startId lastBcrTime = dateUtil.now() @@ -161,10 +180,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second), "$startId/$lastDbId") // with nsId = update bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second), "$startId/$lastDbId") } return true } @@ -189,7 +208,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastTtId = -1L private var lastTtTime = -1L override fun processChangedTempTargetsCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastTempTargetIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_temporary_target_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_temporary_target_last_synced_id, 0) + startId = 0 + } if (startId == lastTtId && dateUtil.now() - lastTtTime < 5000) return false lastTtId = startId lastTtTime = dateUtil.now() @@ -198,10 +223,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new tt.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second), "$startId/$lastDbId") // existing with nsId = update tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second), "$startId/$lastDbId") } return true } @@ -226,7 +251,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastFoodId = -1L private var lastFoodTime = -1L override fun processChangedFoodsCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastFoodIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_food_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_food_last_synced_id, 0) + startId = 0 + } if (startId == lastFoodId && dateUtil.now() - lastFoodTime < 5000) return false lastFoodId = startId lastFoodTime = dateUtil.now() @@ -235,10 +266,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new food.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("food", food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second)) + nsClientPlugin.nsClientService?.dbAdd("food", food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second), "$startId/$lastDbId") // with nsId = update food.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("food", food.first.interfaceIDs.nightscoutId, food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second)) + nsClientPlugin.nsClientService?.dbUpdate("food", food.first.interfaceIDs.nightscoutId, food.first.toJson(), DataSyncSelector.PairFood(food.first, food.second), "$startId/$lastDbId") } return true } @@ -263,7 +294,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastGvId = -1L private var lastGvTime = -1L override fun processChangedGlucoseValuesCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastGlucoseValueIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_glucose_value_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_glucose_value_last_synced_id, 0) + startId = 0 + } if (startId == lastGvId && dateUtil.now() - lastGvTime < 5000) return false lastGvId = startId lastGvTime = dateUtil.now() @@ -273,13 +310,17 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new gv.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) + nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second), "$startId/$lastDbId") // with nsId = update gv.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) + nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second), "$startId/$lastDbId") } return true - } else confirmLastGlucoseValueIdIfGreater(gv.second) + } else { + confirmLastGlucoseValueIdIfGreater(gv.second) + lastGvId = -1 + processChangedGlucoseValuesCompat() + } } return false } @@ -302,7 +343,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastTeId = -1L private var lastTeTime = -1L override fun processChangedTherapyEventsCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastTherapyEventIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_therapy_event_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_therapy_event_last_synced_id, 0) + startId = 0 + } if (startId == lastTeId && dateUtil.now() - lastTeTime < 5000) return false lastTeId = startId lastTeTime = dateUtil.now() @@ -311,10 +358,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new te.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId") // nsId = update te.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId") } return true } @@ -338,7 +385,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastDsId = -1L private var lastDsTime = -1L override fun processChangedDeviceStatusesCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastDeviceStatusIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_device_status_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_device_status_last_synced_id, 0) + startId = 0 + } if (startId == lastDsId && dateUtil.now() - lastDsTime < 5000) return false lastDsId = startId lastDsTime = dateUtil.now() @@ -347,7 +400,7 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new deviceStatus.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(dateUtil), deviceStatus) + nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(dateUtil), deviceStatus, "$startId/$lastDbId") // with nsId = ignore deviceStatus.interfaceIDs.nightscoutId != null -> Any() } @@ -375,23 +428,34 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastTbrTime = -1L override fun processChangedTemporaryBasalsCompat(): Boolean { val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) - val startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastTemporaryBasalIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_temporary_basal_last_synced_id, 0) + startId = 0 + } if (startId == lastTbrId && dateUtil.now() - lastTbrTime < 5000) return false lastTbrId = startId lastTbrTime = dateUtil.now() appRepository.getNextSyncElementTemporaryBasal(startId).blockingGet()?.let { tb -> aapsLogger.info(LTag.DATABASE, "Loading TemporaryBasal data Start: $startId ID: ${tb.first.id} HistoryID: ${tb.second} ") - profileFunction.getProfile(tb.first.timestamp)?.let { profile -> + val profile = profileFunction.getProfile(tb.first.timestamp) + if (profile != null) { when { // without nsId = create new tb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second), "$startId/$lastDbId") // with nsId = update tb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second), "$startId/$lastDbId") } return true - } ?: confirmLastTemporaryBasalIdIfGreater(tb.second) + } else { + confirmLastTemporaryBasalIdIfGreater(tb.second) + lastTbrId = -1 + processChangedTemporaryBasalsCompat() + } } return false } @@ -415,23 +479,34 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastEbTime = -1L override fun processChangedExtendedBolusesCompat(): Boolean { val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) - val startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastExtendedBolusIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_extended_bolus_last_synced_id, 0) + startId = 0 + } if (startId == lastEbId && dateUtil.now() - lastEbTime < 5000) return false lastEbId = startId lastEbTime = dateUtil.now() appRepository.getNextSyncElementExtendedBolus(startId).blockingGet()?.let { eb -> aapsLogger.info(LTag.DATABASE, "Loading ExtendedBolus data Start: $startId ID: ${eb.first.id} HistoryID: ${eb.second} ") - profileFunction.getProfile(eb.first.timestamp)?.let { profile -> + val profile = profileFunction.getProfile(eb.first.timestamp) + if (profile != null) { when { // without nsId = create new eb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second), "$startId/$lastDbId") // with nsId = update eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil, useAbsolute), DataSyncSelector.PairExtendedBolus(eb.first, eb.second), "$startId/$lastDbId") } return true - } ?: confirmLastExtendedBolusIdIfGreater(eb.second) + } else { + confirmLastExtendedBolusIdIfGreater(eb.second) + lastEbId = -1 + processChangedExtendedBolusesCompat() + } } return false } @@ -453,7 +528,13 @@ class DataSyncSelectorImplementation @Inject constructor( private var lastPsId = -1L private var lastPsTime = -1L override fun processChangedProfileSwitchesCompat(): Boolean { - val startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) + val lastDbIdWrapped = appRepository.getLastProfileSwitchIdWrapped().blockingGet() + val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L + var startId = sp.getLong(R.string.key_ns_profile_switch_last_synced_id, 0) + if (startId > lastDbId) { + sp.putLong(R.string.key_ns_profile_switch_last_synced_id, 0) + startId = 0 + } if (startId == lastPsId && dateUtil.now() - lastPsTime < 5000) return false lastPsId = startId lastPsTime = dateUtil.now() @@ -462,10 +543,10 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new ps.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second), "$startId/$lastDbId") // with nsId = update ps.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", ps.first.interfaceIDs.nightscoutId, ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", ps.first.interfaceIDs.nightscoutId, ps.first.toJson(dateUtil), DataSyncSelector.PairProfileSwitch(ps.first, ps.second), "$startId/$lastDbId") } return true } @@ -483,6 +564,6 @@ class DataSyncSelectorImplementation @Inject constructor( localProfilePlugin.createProfileStore() val profileJson = localProfilePlugin.profile?.data ?: return if (lastChange > lastSync) - nsClientPlugin.nsClientService?.dbAdd("profile", profileJson, DataSyncSelector.PairProfileStore(profileJson, dateUtil.now())) + nsClientPlugin.nsClientService?.dbAdd("profile", profileJson, DataSyncSelector.PairProfileStore(profileJson, dateUtil.now()), "") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt index 3404d2008f..cc3c6b6aea 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt @@ -206,7 +206,7 @@ class NSClientAddAckWorker( .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ExtendedBolus " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting - dataSyncSelector.processChangedTemporaryBasalsCompat() + dataSyncSelector.processChangedExtendedBolusesCompat() } is PairProfileSwitch -> { @@ -225,7 +225,7 @@ class NSClientAddAckWorker( .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked ProfileSwitch " + pair.value.interfaceIDs.nightscoutId)) // Send new if waiting - dataSyncSelector.processChangedTemporaryBasalsCompat() + dataSyncSelector.processChangedProfileSwitchesCompat() } is DeviceStatus -> { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt index 9a12b70670..4a765e49e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt @@ -594,7 +594,7 @@ class NSClientService : DaggerService() { } } - fun dbUpdate(collection: String, _id: String?, data: JSONObject?, originalObject: Any) { + fun dbUpdate(collection: String, _id: String?, data: JSONObject?, originalObject: Any, progress: String) { try { if (_id == null) return if (!isConnected || !hasWriteAuth) return @@ -603,20 +603,20 @@ class NSClientService : DaggerService() { message.put("_id", _id) message.put("data", data) socket?.emit("dbUpdate", message, NSUpdateAck("dbUpdate", _id, aapsLogger, rxBus, originalObject)) - rxBus.send(EventNSClientNewLog("DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " + _id)) + rxBus.send(EventNSClientNewLog("DBUPDATE $collection", "Sent " + originalObject.javaClass.simpleName + " " + _id + " " + progress)) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } } - fun dbAdd(collection: String, data: JSONObject, originalObject: Any) { + fun dbAdd(collection: String, data: JSONObject, originalObject: Any, progress: String) { try { if (!isConnected || !hasWriteAuth) return val message = JSONObject() message.put("collection", collection) message.put("data", data) socket?.emit("dbAdd", message, NSAddAck(aapsLogger, rxBus, originalObject)) - rxBus.send(EventNSClientNewLog("DBADD $collection", "Sent " + originalObject.javaClass.simpleName + " " + data)) + rxBus.send(EventNSClientNewLog("DBADD $collection", "Sent " + originalObject.javaClass.simpleName + " " + data + " " + progress)) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } 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 d2150de8bc..5529d23655 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -78,6 +78,11 @@ open class AppRepository @Inject internal constructor( database.glucoseValueDao.getModifiedFrom(lastId) .subscribeOn(Schedulers.io()) + fun getLastGlucoseValueIdWrapped(): Single> = + database.glucoseValueDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + /* * returns a Pair of the next entity to sync and the ID of the "update". * The update id might either be the entry id itself if it is a new entry - or the id @@ -151,6 +156,11 @@ open class AppRepository @Inject internal constructor( fun deleteAllTempTargetEntries() = database.temporaryTargetDao.deleteAllEntries() + fun getLastTempTargetIdWrapped(): Single> = + database.temporaryTargetDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // USER ENTRY fun getAllUserEntries(): Single> = database.userEntryDao.getAll() @@ -217,6 +227,11 @@ open class AppRepository @Inject internal constructor( .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getLastProfileSwitchIdWrapped(): Single> = + database.profileSwitchDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // EFFECTIVE PROFILE SWITCH /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -267,6 +282,11 @@ open class AppRepository @Inject internal constructor( fun deleteAllEffectiveProfileSwitches() = database.effectiveProfileSwitchDao.deleteAllEntries() + fun getLastEffectiveProfileSwitchIdWrapped(): Single> = + database.effectiveProfileSwitchDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // THERAPY EVENT /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -329,6 +349,11 @@ open class AppRepository @Inject internal constructor( database.therapyEventDao.compatGetTherapyEventDataFromToTime(from, to) .subscribeOn(Schedulers.io()) + fun getLastTherapyEventIdWrapped(): Single> = + database.therapyEventDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // FOOD /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -360,6 +385,11 @@ open class AppRepository @Inject internal constructor( fun deleteAllFoods() = database.foodDao.deleteAllEntries() + fun getLastFoodIdWrapped(): Single> = + database.foodDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // BOLUS /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -421,6 +451,10 @@ open class AppRepository @Inject internal constructor( fun deleteAllBoluses() = database.bolusDao.deleteAllEntries() + fun getLastBolusIdWrapped(): Single> = + database.bolusDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() // CARBS private fun expandCarbs(carbs: Carbs): List = @@ -529,6 +563,11 @@ open class AppRepository @Inject internal constructor( fun deleteAllCarbs() = database.carbsDao.deleteAllEntries() + fun getLastCarbsIdWrapped(): Single> = + database.carbsDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // BOLUS CALCULATOR RESULT /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -566,6 +605,11 @@ open class AppRepository @Inject internal constructor( fun deleteAllBolusCalculatorResults() = database.bolusCalculatorResultDao.deleteAllEntries() + fun getLastBolusCalculatorResultIdWrapped(): Single> = + database.bolusCalculatorResultDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // DEVICE STATUS fun insert(deviceStatus: DeviceStatus): Long = database.deviceStatusDao.insert(deviceStatus) @@ -586,6 +630,11 @@ open class AppRepository @Inject internal constructor( database.deviceStatusDao.getModifiedFrom(lastId) .subscribeOn(Schedulers.io()) + fun getLastDeviceStatusIdWrapped(): Single> = + database.deviceStatusDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // TEMPORARY BASAL /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -643,6 +692,11 @@ open class AppRepository @Inject internal constructor( fun getOldestTemporaryBasalRecord(): TemporaryBasal? = database.temporaryBasalDao.getOldestRecord() + fun getLastTemporaryBasalIdWrapped(): Single> = + database.temporaryBasalDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() + // EXTENDED BOLUS /* * returns a Pair of the next entity to sync and the ID of the "update". @@ -707,6 +761,10 @@ open class AppRepository @Inject internal constructor( .map { if (!ascending) it.reversed() else it } .subscribeOn(Schedulers.io()) + fun getLastExtendedBolusIdWrapped(): Single> = + database.extendedBolusDao.getLastId() + .subscribeOn(Schedulers.io()) + .toWrappedSingle() } @Suppress("USELESS_CAST") diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt index a1f5788368..600a01de0b 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt @@ -18,6 +18,9 @@ internal interface BolusCalculatorResultDao : TraceableDao + @Query("SELECT * FROM $TABLE_BOLUS_CALCULATOR_RESULTS WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") fun getBolusCalculatorResultsFromTime(timestamp: Long): Single> 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 326e08e1dd..2483cb04cc 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt @@ -18,6 +18,9 @@ internal interface BolusDao : TraceableDao { @Query("DELETE FROM $TABLE_BOLUSES") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_BOLUSES ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_BOLUSES WHERE timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(timestamp: Long): Bolus? 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 025eb04a02..fabed9ae77 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 @@ -17,6 +17,9 @@ internal interface CarbsDao : TraceableDao { @Query("DELETE FROM $TABLE_CARBS") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_CARBS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_CARBS WHERE nightscoutId = :nsId AND referenceId IS NULL") fun findByNSId(nsId: String): Carbs? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/DeviceStatusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/DeviceStatusDao.kt index 239081d607..23fdc1a05c 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/DeviceStatusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/DeviceStatusDao.kt @@ -25,6 +25,9 @@ internal interface DeviceStatusDao { @Query("DELETE FROM $TABLE_DEVICE_STATUS") fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_DEVICE_STATUS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("DELETE FROM $TABLE_DEVICE_STATUS WHERE id NOT IN (SELECT MAX(id) FROM $TABLE_DEVICE_STATUS)") fun deleteAllEntriesExceptLast() diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt index c6944d05ad..592c21bd0b 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt @@ -17,6 +17,9 @@ internal interface EffectiveProfileSwitchDao : TraceableDao + @Query("SELECT * FROM $TABLE_EFFECTIVE_PROFILE_SWITCHES WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1") fun getOldestEffectiveProfileSwitchRecord(): EffectiveProfileSwitch? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt index 8f318577f8..657ee3b7ff 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt @@ -18,6 +18,9 @@ internal interface ExtendedBolusDao : TraceableDao { @Query("DELETE FROM $TABLE_EXTENDED_BOLUSES") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_EXTENDED_BOLUSES ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(timestamp: Long): ExtendedBolus? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/FoodDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/FoodDao.kt index b7fe24d3a0..bac97a3cb6 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/FoodDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/FoodDao.kt @@ -17,6 +17,9 @@ internal interface FoodDao : TraceableDao { @Query("DELETE FROM $TABLE_FOODS") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_FOODS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_FOODS WHERE nightscoutId = :nsId AND referenceId IS NULL") fun findByNSId(nsId: String): Food? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt index 0738101140..608eec3093 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt @@ -16,6 +16,9 @@ internal interface GlucoseValueDao : TraceableDao { @Query("DELETE FROM $TABLE_GLUCOSE_VALUES") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_GLUCOSE_VALUES ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE nightscoutId = :nsId AND referenceId IS NULL") fun findByNSIdMaybe(nsId: String): Maybe diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt index c992e592be..598679864b 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt @@ -19,6 +19,9 @@ internal interface ProfileSwitchDao : ProfileSwitchDaoWorkaround { @Query("DELETE FROM $TABLE_PROFILE_SWITCHES") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_PROFILE_SWITCHES ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(timestamp: Long): ProfileSwitch? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt index a6c46075c5..f2cdd2617e 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt @@ -18,6 +18,9 @@ internal interface TemporaryBasalDao : TraceableDao { @Query("DELETE FROM $TABLE_TEMPORARY_BASALS") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_TEMPORARY_BASALS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_TEMPORARY_BASALS WHERE temporaryId = :temporaryId") fun findByTempId(temporaryId: Long): TemporaryBasal? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt index 7a5eaee720..065eb76595 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt @@ -17,6 +17,9 @@ internal interface TemporaryTargetDao : TraceableDao { @Query("DELETE FROM $TABLE_TEMPORARY_TARGETS") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_TEMPORARY_TARGETS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE nightscoutId = :nsId AND referenceId IS NULL") fun findByNSId(nsId: String): TemporaryTarget? diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt index fcec0b020d..dea04b81b2 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt @@ -16,6 +16,9 @@ internal interface TherapyEventDao : TraceableDao { @Query("DELETE FROM $TABLE_THERAPY_EVENTS") override fun deleteAllEntries() + @Query("SELECT id FROM $TABLE_THERAPY_EVENTS ORDER BY id DESC limit 1") + fun getLastId(): Maybe + @Query("SELECT * FROM $TABLE_THERAPY_EVENTS WHERE type = :type AND timestamp = :timestamp AND referenceId IS NULL") fun findByTimestamp(type: TherapyEvent.Type, timestamp: Long): TherapyEvent?