diff --git a/.travis.yml b/.travis.yml index d08c3bf279..57f0a8f3ee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: android -jdk: oraclejdk8 +jdk: openjdk11 dist: trusty env: matrix: diff --git a/app/src/main/java/info/nightscout/androidaps/ConfigImpl.kt b/app/src/main/java/info/nightscout/androidaps/ConfigImpl.kt deleted file mode 100644 index 0371902901..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/ConfigImpl.kt +++ /dev/null @@ -1,2 +0,0 @@ -package info.nightscout.androidaps - 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 2aaec095a0..0204effaff 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -97,7 +97,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); - TableUtils.createTableIfNotExists(connectionSource, TDD.class); TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); @@ -173,14 +172,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, TemporaryBasal.class, true); TableUtils.dropTable(connectionSource, ExtendedBolus.class, true); TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); - TableUtils.dropTable(connectionSource, TDD.class, true); TableUtils.dropTable(connectionSource, OmnipodHistoryRecord.class, true); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DbRequest.class); TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); - TableUtils.createTableIfNotExists(connectionSource, TDD.class); TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); updateEarliestDataChange(0); } catch (SQLException e) { @@ -209,25 +206,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { scheduleProfileSwitchChange(); } - public void resetTDDs() { - try { - TableUtils.dropTable(connectionSource, TDD.class, true); - TableUtils.createTableIfNotExists(connectionSource, TDD.class); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - // ------------------ getDao ------------------------------------------- private Dao getDaoDanaRHistory() throws SQLException { return getDao(DanaRHistoryRecord.class); } - private Dao getDaoTDD() throws SQLException { - return getDao(TDD.class); - } - private Dao getDaoDbRequest() throws SQLException { return getDao(DbRequest.class); } @@ -271,60 +255,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return rounded; } - // ------------------- TDD handling ----------------------- - public void createOrUpdateTDD(TDD tdd) { - try { - Dao dao = getDaoTDD(); - dao.createOrUpdate(tdd); - openHumansUploader.enqueueTotalDailyDose(tdd); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public List getTDDs() { - List tddList; - try { - QueryBuilder queryBuilder = getDaoTDD().queryBuilder(); - queryBuilder.orderBy("date", false); - queryBuilder.limit(10L); - PreparedQuery preparedQuery = queryBuilder.prepare(); - tddList = getDaoTDD().query(preparedQuery); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - tddList = new ArrayList<>(); - } - return tddList; - } - - public List getAllTDDs() { - try { - return getDaoTDD().queryForAll(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return Collections.emptyList(); - } - - public List getTDDsForLastXDays(int days) { - List tddList; - GregorianCalendar gc = new GregorianCalendar(); - gc.add(Calendar.DAY_OF_YEAR, (-1) * days); - - try { - QueryBuilder queryBuilder = getDaoTDD().queryBuilder(); - queryBuilder.orderBy("date", false); - Where where = queryBuilder.where(); - where.ge("date", gc.getTimeInMillis()); - PreparedQuery preparedQuery = queryBuilder.prepare(); - tddList = getDaoTDD().query(preparedQuery); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - tddList = new ArrayList<>(); - } - return tddList; - } - // ------------- DbRequests handling ------------------- public void create(DbRequest dbr) throws SQLException { @@ -403,12 +333,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createOrUpdate(DanaRHistoryRecord record) { try { getDaoDanaRHistory().createOrUpdate(record); - - //If it is a TDD, store it for stats also. - if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) { - createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0)); - } - } catch (SQLException e) { aapsLogger.error("Unhandled exception", e); } @@ -1136,7 +1060,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoExtendedBolus().countOf() + getDaoProfileSwitch().countOf() - + getDaoTDD().countOf() + getDaoTemporaryBasal().countOf(); } catch (SQLException e) { aapsLogger.error("Unhandled exception", e); 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 bdea090609..9ed770958e 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -35,10 +35,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().getDanaRHistoryRecordsByType(type); } - @NonNull @Override public List getTDDs() { - return MainApp.Companion.getDbHelper().getTDDs(); - } - @Override public long size(@NonNull String table) { return MainApp.Companion.getDbHelper().size(table); } @@ -71,10 +67,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().roundDateToSec(date); } - @Override public void createOrUpdateTDD(@NonNull TDD record) { - MainApp.Companion.getDbHelper().createOrUpdateTDD(record); - } - @Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) { return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal); } @@ -96,10 +88,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); } - @NonNull @Override public List getTDDsForLastXDays(int days) { - return MainApp.Companion.getDbHelper().getTDDsForLastXDays(days); - } - @NonNull @Override public List getProfileSwitchData(long from, boolean ascending) { return MainApp.Companion.getDbHelper().getProfileSwitchData(from, ascending); } @@ -172,10 +160,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().getAllProfileSwitches(); } - @NonNull @Override public List getAllTDDs() { - return MainApp.Companion.getDbHelper().getAllTDDs(); - } - @NonNull @Override public List getAllOHQueueItems(long maxEntries) { return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt index a459b9c00c..0f6029064b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt @@ -110,7 +110,7 @@ class PluginStore @Inject constructor( (activeBgSourceStore as PluginBase).setPluginEnabled(PluginType.BGSOURCE, true) aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting BgInterface") } - setFragmentVisibilities((activeBgSourceStore as PluginBase).name, pluginsInCategory, PluginType.PUMP) + setFragmentVisibilities((activeBgSourceStore as PluginBase).name, pluginsInCategory, PluginType.BGSOURCE) // PluginType.PUMP pluginsInCategory = getSpecificPluginsList(PluginType.PUMP) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index fefc9009c1..7b9de28680 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -78,7 +78,7 @@ class FoodPlugin @Inject constructor( repository.runTransactionForResult(SyncNsFoodTransaction(delFood, true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while removing food", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { @@ -92,7 +92,7 @@ class FoodPlugin @Inject constructor( repository.runTransactionForResult(SyncNsFoodTransaction(food, false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while adding/updating food", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> 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 e07346e85b..4b89e51d0b 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 @@ -44,7 +44,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdTemporaryTargetTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryTarget failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -63,7 +63,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdGlucoseValueTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of GlucoseValue failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -82,7 +82,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdFoodTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Food failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -101,7 +101,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdTherapyEventTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TherapyEvent failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -120,7 +120,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Bolus failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -139,7 +139,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdCarbsTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of Carbs failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -158,7 +158,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdBolusCalculatorResultTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of BolusCalculatorResult failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -177,7 +177,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdTemporaryBasalTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of TemporaryBasal failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -196,7 +196,7 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdExtendedBolusTransaction(pair.value)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of ExtendedBolus failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { ret = Result.success(workDataOf("ProcessedData" to pair.toString())) @@ -215,17 +215,17 @@ class NSClientAddAckWorker( repository.runTransactionForResult(UpdateNsIdDeviceStatusTransaction(deviceStatus)) .doOnError { error -> aapsLogger.error(LTag.DATABASE, "Updated ns id of DeviceStatus failed", error) - ret = Result.failure((workDataOf("Error" to error))) + ret = Result.failure((workDataOf("Error" to error.toString()))) } .doOnSuccess { - ret = Result.success(workDataOf("ProcessedData" to deviceStatus)) + ret = Result.success(workDataOf("ProcessedData" to deviceStatus.toString())) aapsLogger.debug(LTag.DATABASE, "Updated ns id of DeviceStatus $deviceStatus") dataSyncSelector.confirmLastDeviceStatusIdIfGreater(deviceStatus.id) } .blockingGet() rxBus.send(EventNSClientNewLog("DBADD", "Acked DeviceStatus" + deviceStatus.interfaceIDs.nightscoutId)) // Send new if waiting - dataSyncSelector.processChangedBolusCalculatorResultsCompat() + dataSyncSelector.processChangedDeviceStatusesCompat() } } return ret diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt index 89b30d8b8e..5f46565977 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt @@ -79,7 +79,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsBolusTransaction(bolus, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving bolus", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -108,7 +108,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsCarbsTransaction(carb, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -146,7 +146,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -196,7 +196,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEvent, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -231,7 +231,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsExtendedBolusTransaction(extendedBolus, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving extended bolus", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -272,7 +272,7 @@ class NSClientAddUpdateWorker( repository.runTransactionForResult(SyncNsTemporaryBasalTransaction(temporaryBasal, invalidateByNsOnly = false)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving temporary basal", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt index 9f61cf6092..a769f2ec38 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientMbgWorker.kt @@ -44,7 +44,7 @@ class NSClientMbgWorker( repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEventFromNsMbg(nsMbg), false)) .doOnError { aapsLogger.error("Error while saving therapy event", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt index e18708f7a0..014c49dea5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientRemoveWorker.kt @@ -61,7 +61,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating temporary target", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -81,7 +81,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEvent, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -98,7 +98,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsBolusTransaction(bolus, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -114,7 +114,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsCarbsTransaction(carbs, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -130,7 +130,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsTemporaryBasalTransaction(temporaryBasal, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating temporary basal", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -146,7 +146,7 @@ class NSClientRemoveWorker( repository.runTransactionForResult(SyncNsExtendedBolusTransaction(extendedBolus, invalidateByNsOnly = true)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating extended bolus", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt index 92e008ca91..0142a4b964 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt @@ -237,12 +237,12 @@ class OpenHumansUploader @Inject constructor( put("isDeletion", deleted) } - fun enqueueTotalDailyDose(tdd: TDD) = insertQueueItem("TotalDailyDoses") { - put("double", tdd.date) - put("double", tdd.bolus) - put("double", tdd.basal) - put("double", tdd.total) - } + // fun enqueueTotalDailyDose(tdd: TDD) = insertQueueItem("TotalDailyDoses") { + // put("double", tdd.date) + // put("double", tdd.bolus) + // put("double", tdd.basal) + // put("double", tdd.total) + // } @JvmOverloads fun enqueueTemporaryBasal(temporaryBasal: TemporaryBasal?, deleted: Boolean = false) = temporaryBasal?.let { @@ -371,9 +371,9 @@ class OpenHumansUploader @Inject constructor( .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) }) .map { enqueueProfileSwitch(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) }) - .map { enqueueTotalDailyDose(it); increaseCounter() } - .ignoreElements() + // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) }) + // .map { enqueueTotalDailyDose(it); increaseCounter() } + // .ignoreElements() // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) }) // .map { enqueueTemporaryBasal(it); increaseCounter() } // .ignoreElements() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index 99d8d57a03..9f87d3d0b0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -33,7 +33,7 @@ import kotlin.math.max import kotlin.math.min class GraphData( - private val injector: HasAndroidInjector, + injector: HasAndroidInjector, private val graph: GraphView, private val iobCobCalculator: IobCobCalculator, private val treatmentsPlugin: TreatmentsInterface @@ -577,15 +577,22 @@ class GraphData( // scale in % of vertical size (like 0.3) fun addRatio(fromTime: Long, toTime: Long, useForScale: Boolean, scale: Double) { val ratioArray: MutableList = ArrayList() - var maxRatioValueFound = Double.MIN_VALUE - var minRatioValueFound = Double.MAX_VALUE - val ratioScale = Scale() + var maxRatioValueFound = 5.0 //even if sens data equals 0 for all the period, minimum scale is between 95% and 105% + var minRatioValueFound = - maxRatioValueFound + val ratioScale = if (useForScale) Scale(100.0) else Scale() var time = fromTime while (time <= toTime) { +<<<<<<<<< Temporary merge branch 1 iobCobCalculator.ads.getAutosensDataAtTime(time)?.let { autosensData -> ratioArray.add(ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale)) maxRatioValueFound = max(maxRatioValueFound, autosensData.autosensResult.ratio - 1) minRatioValueFound = min(minRatioValueFound, autosensData.autosensResult.ratio - 1) +========= + iobCobCalculatorPlugin.getAutosensData(time)?.let { autosensData -> + ratioArray.add(ScaledDataPoint(time, 100.0 * (autosensData.autosensResult.ratio - 1 ), ratioScale)) + maxRatioValueFound = max(maxRatioValueFound, 100.0 * (autosensData.autosensResult.ratio - 1)) + minRatioValueFound = min(minRatioValueFound, 100.0 * (autosensData.autosensResult.ratio - 1)) +>>>>>>>>> Temporary merge branch 2 } time += 5 * 60 * 1000L } @@ -596,10 +603,11 @@ class GraphData( it.thickness = 3 }) if (useForScale) { - maxY = max(maxRatioValueFound, abs(minRatioValueFound)) - minY = -maxY - } - ratioScale.setMultiplier(maxY * scale / max(maxRatioValueFound, abs(minRatioValueFound))) + maxY = 100.0 + max(maxRatioValueFound, abs(minRatioValueFound)) + minY = 100.0 - max(maxRatioValueFound, abs(minRatioValueFound)) + ratioScale.setMultiplier(1.0) + } else + ratioScale.setMultiplier(maxY * scale / max(maxRatioValueFound, abs(minRatioValueFound))) } // scale in % of vertical size (like 0.3) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 4785d0653d..616df644cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -16,13 +16,14 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.TemporaryTarget +import info.nightscout.androidaps.database.entities.TotalDailyDose import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.interfaces.end import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction import info.nightscout.androidaps.database.transactions.InsertTemporaryTargetAndCancelCurrentTransaction -import info.nightscout.androidaps.db.TDD +import info.nightscout.androidaps.extensions.total import info.nightscout.androidaps.extensions.valueToUnits import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger @@ -79,7 +80,6 @@ class ActionStringHandler @Inject constructor( private val danaPump: DanaPump, private val dateUtil: DateUtil, private val config: Config, - private val databaseHelper: DatabaseHelperInterface, private val repository: AppRepository, private val uel: UserEntryLogger ) { @@ -274,7 +274,7 @@ class ActionStringHandler @Inject constructor( } else if ("tddstats" == act[0]) { val activePump = activePlugin.activePump // check if DB up to date - val dummies: MutableList = LinkedList() + val dummies: MutableList = LinkedList() val historyList = getTDDList(dummies) if (isOldData(historyList)) { rTitle = "TDD" @@ -287,7 +287,7 @@ class ActionStringHandler @Inject constructor( rMessage += "trying to fetch data from pump." commandQueue.loadTDDs(object : Callback() { override fun run() { - val dummies1: MutableList = LinkedList() + val dummies1: MutableList = LinkedList() val historyList1 = getTDDList(dummies1) if (isOldData(historyList1)) { sendStatusMessage("TDD: Still old data! Cannot load from pump.\n" + generateTDDMessage(historyList1, dummies1)) @@ -340,7 +340,7 @@ class ActionStringHandler @Inject constructor( lastConfirmActionString = rAction } - private fun generateTDDMessage(historyList: MutableList, dummies: MutableList): String { + private fun generateTDDMessage(historyList: MutableList, dummies: MutableList): String { val profile = profileFunction.getProfile() ?: return "No profile loaded :(" if (historyList.isEmpty()) { return "No history data!" @@ -349,8 +349,8 @@ class ActionStringHandler @Inject constructor( var message = "" val refTDD = profile.baseBasalSum() * 2 val pump = activePlugin.activePump - if (df.format(Date(historyList[0].date)) == df.format(Date())) { - val tdd = historyList[0].getTotal() + if (df.format(Date(historyList[0].timestamp)) == df.format(Date())) { + val tdd = historyList[0].total historyList.removeAt(0) message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "\n" @@ -364,7 +364,7 @@ class ActionStringHandler @Inject constructor( var weighted07 = 0.0 historyList.reverse() for ((i, record) in historyList.withIndex()) { - val tdd = record.getTotal() + val tdd = record.total if (i == 0) { weighted03 = tdd weighted05 = tdd @@ -383,40 +383,38 @@ class ActionStringHandler @Inject constructor( historyList.reverse() //add TDDs: for (record in historyList) { - val tdd = record.getTotal() - message += df.format(Date(record.date)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (if (dummies.contains(record)) "x" else "") + "\n" + val tdd = record.total + message += df.format(Date(record.timestamp)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (if (dummies.contains(record)) "x" else "") + "\n" } return message } - private fun isOldData(historyList: List): Boolean { + private fun isOldData(historyList: List): Boolean { val activePump = activePlugin.activePump val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === localInsightPlugin val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) - return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) + return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } - private fun getTDDList(returnDummies: MutableList): MutableList { - var historyList = databaseHelper.getTDDs().toMutableList() + private fun getTDDList(returnDummies: MutableList): MutableList { + var historyList = repository.getLastTotalDailyDoses(10, false).blockingGet().toMutableList() + //var historyList = databaseHelper.getTDDs().toMutableList() historyList = historyList.subList(0, min(10, historyList.size)) //fill single gaps - only needed for Dana*R data - val dummies: MutableList = returnDummies + val dummies: MutableList = returnDummies val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) for (i in 0 until historyList.size - 1) { val elem1 = historyList[i] val elem2 = historyList[i + 1] - if (df.format(Date(elem1.date)) != df.format(Date(elem2.date + 25 * 60 * 60 * 1000))) { - val dummy = TDD() - dummy.date = elem1.date - 24 * 60 * 60 * 1000 - dummy.basal = elem1.basal / 2 - dummy.bolus = elem1.bolus / 2 + if (df.format(Date(elem1.timestamp)) != df.format(Date(elem2.timestamp + 25 * 60 * 60 * 1000))) { + val dummy = TotalDailyDose(timestamp = elem1.timestamp - T.hours(24).msecs(), bolusAmount = elem1.bolusAmount / 2, basalAmount = elem1.basalAmount / 2) dummies.add(dummy) - elem1.basal /= 2.0 - elem1.bolus /= 2.0 + elem1.basalAmount /= 2.0 + elem1.bolusAmount /= 2.0 } } historyList.addAll(dummies) - historyList.sortWith { lhs, rhs -> (rhs.date - lhs.date).toInt() } + historyList.sortWith { lhs, rhs -> (rhs.timestamp - lhs.timestamp).toInt() } return historyList } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index b93a772a0f..5df38eb764 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -168,34 +168,36 @@ open class IobCobCalculatorPlugin @Inject constructor( } override fun calculateFromTreatmentsAndTemps(fromTime: Long, profile: Profile): IobTotal { - val now = System.currentTimeMillis() - val time = ads.roundUpTime(fromTime) - val cacheHit = iobTable[time] - if (time < now && cacheHit != null) { - //og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); - return cacheHit - } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); - val bolusIob = calculateIobFromBolusToTime(time).round() - val basalIob = calculateIobToTimeFromTempBasalsIncludingConvertedExtended(time).round() - // OpenAPSSMB only - // Add expected zero temp basal for next 240 minutes - val basalIobWithZeroTemp = basalIob.copy() - val t = TemporaryBasal( - timestamp = now + 60 * 1000L, - duration = 240, - rate = 0.0, - isAbsolute = true, - type = TemporaryBasal.Type.NORMAL) - if (t.timestamp < time) { - val calc = t.iobCalc(time, profile, activePlugin.activeInsulin) - basalIobWithZeroTemp.plus(calc) + synchronized(dataLock) { + val now = System.currentTimeMillis() + val time = ads.roundUpTime(fromTime) + val cacheHit = iobTable[time] + if (time < now && cacheHit != null) { + //og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString()); + return cacheHit + } // else log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); + val bolusIob = calculateIobFromBolusToTime(time).round() + val basalIob = calculateIobToTimeFromTempBasalsIncludingConvertedExtended(time).round() + // OpenAPSSMB only + // Add expected zero temp basal for next 240 minutes + val basalIobWithZeroTemp = basalIob.copy() + val t = TemporaryBasal( + timestamp = now + 60 * 1000L, + duration = 240, + rate = 0.0, + isAbsolute = true, + type = TemporaryBasal.Type.NORMAL) + if (t.timestamp < time) { + val calc = t.iobCalc(time, profile, activePlugin.activeInsulin) + basalIobWithZeroTemp.plus(calc) + } + basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round() + val iobTotal = IobTotal.combine(bolusIob, basalIob).round() + if (time < System.currentTimeMillis()) { + iobTable.put(time, iobTotal) + } + return iobTotal } - basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round() - val iobTotal = IobTotal.combine(bolusIob, basalIob).round() - if (time < System.currentTimeMillis()) { - iobTable.put(time, iobTotal) - } - return iobTotal } override fun calculateAbsInsulinFromTreatmentsAndTemps(fromTime: Long): IobTotal { 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 d28aa3fa4f..e7c9f06407 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 @@ -144,7 +144,7 @@ class DexcomPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, calibrations, sensorStartTime)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Dexcom App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -173,7 +173,7 @@ class DexcomPlugin @Inject constructor( } } catch (e: Exception) { aapsLogger.error("Error while processing intent from Dexcom App", e) - ret = Result.failure(workDataOf("Error" to e)) + ret = Result.failure(workDataOf("Error" to e.toString())) } return ret } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index c6d0467c78..434e5eb873 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -112,7 +112,7 @@ class EversensePlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Eversense App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> @@ -142,7 +142,7 @@ class EversensePlugin @Inject constructor( )) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt index dcd6690163..36724eb4b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt @@ -70,7 +70,7 @@ class GlimpPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Glimp App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt index 41d4defeeb..728e9c12c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt @@ -88,7 +88,7 @@ class MM640gPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Eversense App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> @@ -99,7 +99,7 @@ class MM640gPlugin @Inject constructor( } } catch (e: JSONException) { aapsLogger.error("Exception: ", e) - ret = Result.failure(workDataOf("Error" to e)) + ret = Result.failure(workDataOf("Error" to e.toString())) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index 4866cc7f9e..d9c2f221e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -142,7 +142,7 @@ class NSClientSourcePlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null, !nsClientSourcePlugin.isEnabled())) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from NSClient App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> @@ -159,7 +159,7 @@ class NSClientSourcePlugin @Inject constructor( } } catch (e: Exception) { aapsLogger.error("Unhandled exception", e) - ret = Result.failure(workDataOf("Error" to e)) + ret = Result.failure(workDataOf("Error" to e.toString())) } // Objectives 0 sp.putBoolean(R.string.key_ObjectivesbgIsAvailableInNS, true) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index bcec10bd5d..17aefac5b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -81,7 +81,7 @@ class PoctechPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Poctech App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> @@ -92,7 +92,7 @@ class PoctechPlugin @Inject constructor( } } catch (e: JSONException) { aapsLogger.error("Exception: ", e) - ret = Result.failure(workDataOf("Error" to e)) + ret = Result.failure(workDataOf("Error" to e.toString())) } return ret } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index bbcc7ccc49..cf6fce3da5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -72,7 +72,7 @@ class TomatoPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Tomato App", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt index be7df833e9..622d69c284 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt @@ -91,7 +91,7 @@ class XdripPlugin @Inject constructor( repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Xdrip", it) - ret = Result.failure(workDataOf("Error" to it)) + ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { savedValues -> diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 80ffb03bad..f00d391026 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -5,7 +5,7 @@ import android.util.LongSparseArray import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.Bolus -import info.nightscout.androidaps.db.TDD +import info.nightscout.androidaps.database.entities.TotalDailyDose import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction @@ -16,6 +16,7 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.extensions.convertedToAbsolute +import info.nightscout.androidaps.extensions.toText import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject @@ -29,62 +30,62 @@ class TddCalculator @Inject constructor( private val repository: AppRepository ) { - fun calculate(days: Long): LongSparseArray { + fun calculate(days: Long): LongSparseArray { val startTime = MidnightTime.calc(dateUtil.now() - T.days(days).msecs()) val endTime = MidnightTime.calc(dateUtil.now()) - val result = LongSparseArray() + val result = LongSparseArray() repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet() .filter { it.type != Bolus.Type.PRIMING } .forEach { t -> val midnight = MidnightTime.calc(t.timestamp) - val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) - tdd.bolus += t.amount + val tdd = result[midnight] ?: TotalDailyDose(timestamp = midnight) + tdd.bolusAmount += t.amount result.put(midnight, tdd) } repository.getCarbsDataFromTimeToTimeExpanded(startTime, endTime, true).blockingGet().forEach { t -> val midnight = MidnightTime.calc(t.timestamp) - val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) + val tdd = result[midnight] ?: TotalDailyDose(timestamp = midnight) tdd.carbs += t.amount result.put(midnight, tdd) } for (t in startTime until endTime step T.mins(5).msecs()) { val midnight = MidnightTime.calc(t) - val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) + val tdd = result[midnight] ?: TotalDailyDose(timestamp = midnight) val tbr = iobCobCalculator.getTempBasalIncludingConvertedExtended(t) val profile = profileFunction.getProfile(t) ?: continue val absoluteRate = tbr?.convertedToAbsolute(t, profile) ?: profile.getBasal(t) - tdd.basal += absoluteRate / 60.0 * 5.0 + tdd.basalAmount += absoluteRate / 60.0 * 5.0 if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) { // they are not included in TBRs val eb = iobCobCalculator.getExtendedBolus(t) val absoluteEbRate = eb?.rate ?: 0.0 - tdd.bolus += absoluteEbRate / 60.0 * 5.0 + tdd.bolusAmount += absoluteEbRate / 60.0 * 5.0 } result.put(midnight, tdd) } for (i in 0 until result.size()) { val tdd = result.valueAt(i) - tdd.total = tdd.bolus + tdd.basal + tdd.totalAmount = tdd.bolusAmount + tdd.basalAmount } aapsLogger.debug(LTag.CORE, result.toString()) return result } - private fun averageTDD(tdds: LongSparseArray): TDD { - val totalTdd = TDD() + private fun averageTDD(tdds: LongSparseArray): TotalDailyDose { + val totalTdd = TotalDailyDose(timestamp = dateUtil.now()) for (i in 0 until tdds.size()) { val tdd = tdds.valueAt(i) - totalTdd.basal += tdd.basal - totalTdd.bolus += tdd.bolus - totalTdd.total += tdd.total + totalTdd.basalAmount += tdd.basalAmount + totalTdd.bolusAmount += tdd.bolusAmount + totalTdd.totalAmount += tdd.totalAmount totalTdd.carbs += tdd.carbs } - totalTdd.basal /= tdds.size().toDouble() - totalTdd.bolus /= tdds.size().toDouble() - totalTdd.total /= tdds.size().toDouble() + totalTdd.basalAmount /= tdds.size().toDouble() + totalTdd.bolusAmount /= tdds.size().toDouble() + totalTdd.totalAmount /= tdds.size().toDouble() totalTdd.carbs /= tdds.size().toDouble() return totalTdd } @@ -101,7 +102,7 @@ class TddCalculator @Inject constructor( } @Suppress("SameParameterValue") - private fun toText(tdds: LongSparseArray, includeCarbs: Boolean): String { + private fun toText(tdds: LongSparseArray, includeCarbs: Boolean): String { var t = "" for (i in 0 until tdds.size()) { t += "${tdds.valueAt(i).toText(resourceHelper, dateUtil, includeCarbs)}
" diff --git a/build.gradle b/build.gradle index 7b872f31b7..85d3954a45 100644 --- a/build.gradle +++ b/build.gradle @@ -38,23 +38,23 @@ buildscript { repositories { google() mavenCentral() - jcenter() { - content { - includeModule("org.jetbrains.trove4j", "trove4j") - } - } maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2 } dependencies { classpath 'com.android.tools.build:gradle:4.1.3' classpath 'com.google.gms:google-services:4.3.4' - classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1' + classpath 'com.google.firebase:firebase-crashlytics-gradle:2.5.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath 'com.hiya:jacoco-android:0.2' + modules { + module("org.jetbrains.trove4j:trove4j") { + replacedBy("org.jetbrains.intellij.deps:trove4j") + } + } } } @@ -62,22 +62,15 @@ allprojects { repositories { google() mavenCentral() - maven { - url "https://maven.google.com" - } + maven { url "https://maven.google.com" } + maven { url 'https://jitpack.io' } + maven { url "https://google.bintray.com/flexbox-layout" } ivy { url 'https://github.com/' patternLayout { artifact '/[organisation]/[module]/archive/[revision].[ext]' } } - maven { url 'https://jitpack.io' } - jcenter() { - content { - includeModule("com.google.android", "flexbox") - includeModule("org.jetbrains.trove4j", "trove4j") - } - } } //Support @JvmDefault tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 1f17b035cc..33d97b89d0 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -7,6 +7,7 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import info.nightscout.androidaps.extensions.PumpStateExtensionKt; + import org.joda.time.DateTime; import org.json.JSONObject; @@ -26,7 +27,6 @@ import info.nightscout.androidaps.combo.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -81,7 +81,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { private RxBusWrapper rxBus; private final CommandQueueProvider commandQueue; private final Context context; - private final DatabaseHelperInterface databaseHelper; private final PumpSync pumpSync; private final DateUtil dateUtil; @@ -156,7 +155,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { this.sp = sp; this.commandQueue = commandQueue; this.context = context; - this.databaseHelper = databaseHelper; this.pumpSync = pumpSync; this.dateUtil = dateUtil; @@ -1334,24 +1332,32 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { if (result.getSuccess()) { List tdds = pump.tddHistory; if (tdds != null) { - HashMap map = new HashMap<>(); + HashMap map = new HashMap<>(); for (int i = 0; i < tdds.size(); i++) { Tdd currTdd = tdds.get(i); if (currTdd.total < 1) continue; //cases where dummy days are introduced (e.g. Battery change with date loss) if (map.containsKey(currTdd.timestamp)) { //duplicate days on time changes - TDD existing = map.get(currTdd.timestamp); + Tdd existing = map.get(currTdd.timestamp); existing.total += currTdd.total; } else { - map.put(currTdd.timestamp, new TDD(currTdd.timestamp, 0d, 0d, currTdd.total)); + map.put(currTdd.timestamp, currTdd); } } - Collection uniqueColl = map.values(); + Collection uniqueColl = map.values(); - for (TDD currTdd : uniqueColl) { - databaseHelper.createOrUpdateTDD(currTdd); + for (Tdd currTdd : uniqueColl) { + pumpSync.createOrUpdateTotalDailyDose( + currTdd.timestamp, + 0.0, + 0.0, + currTdd.total, + null, + PumpType.ACCU_CHEK_COMBO, + serialNumber() + ); } } } diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ruffyscripter/history/Tdd.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ruffyscripter/history/Tdd.java index 35d3d31df9..c469cc9606 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ruffyscripter/history/Tdd.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ruffyscripter/history/Tdd.java @@ -1,10 +1,12 @@ package info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history; +import androidx.annotation.NonNull; + import java.util.Date; /** Total daily dosage; amount of insulin delivered over a full day. */ public class Tdd extends HistoryRecord { - public final double total; + public double total; public Tdd(long timestamp, double total) { super(timestamp); @@ -32,7 +34,7 @@ public class Tdd extends HistoryRecord { return result; } - @Override + @NonNull @Override public String toString() { return "Tdd{" + "timestamp=" + timestamp + "(" + new Date(timestamp) + ")" + diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle index 552aa32c15..6fa2e179f9 100644 --- a/core/core_dependencies.gradle +++ b/core/core_dependencies.gradle @@ -87,9 +87,7 @@ dependencies { api 'com.google.android.gms:play-services-wearable:17.0.0' api 'com.google.android.gms:play-services-location:17.1.0' - api("com.google.android:flexbox:0.3.0") { - exclude group: "com.android.support" - } + api("com.google.android:flexbox:2.0.1") api("io.socket:socket.io-client:1.0.0") { // excluding org.json which is provided by Android exclude group: "org.json", module: "json" diff --git a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt index 353f808935..85b7d1e855 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt @@ -17,12 +17,13 @@ import android.widget.TableRow import android.widget.TextView import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.databinding.ActivityTddStatsBinding -import info.nightscout.androidaps.db.TDD +import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.entities.TotalDailyDose import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.extensions.total import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -30,6 +31,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable @@ -49,7 +51,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueueProvider - @Inject lateinit var databaseHelper: DatabaseHelperInterface + @Inject lateinit var repository: AppRepository @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -59,8 +61,8 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { lateinit var tbb: String private var magicNumber = 0.0 private var decimalFormat: DecimalFormat = DecimalFormat("0.000") - private var historyList: MutableList = mutableListOf() - private var dummies: MutableList = mutableListOf() + private var historyList: MutableList = mutableListOf() + private var dummies: MutableList = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -230,7 +232,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { @SuppressLint("SetTextI18n") private fun loadDataFromDB() { historyList.clear() - historyList.addAll(databaseHelper.getTDDs()) + historyList.addAll(repository.getLastTotalDailyDoses(10, false).blockingGet()) //only use newest 10 historyList = historyList.subList(0, min(10, historyList.size)) @@ -240,18 +242,19 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { for (i in 0 until historyList.size - 1) { val elem1 = historyList[i] val elem2 = historyList[i + 1] - if (df.format(Date(elem1.date)) != df.format(Date(elem2.date + 25 * 60 * 60 * 1000))) { - val dummy = TDD() - dummy.date = elem1.date - 24 * 60 * 60 * 1000 - dummy.basal = elem1.basal / 2 - dummy.bolus = elem1.bolus / 2 + if (df.format(Date(elem1.timestamp)) != df.format(Date(elem2.timestamp + 25 * 60 * 60 * 1000))) { + val dummy = TotalDailyDose( + timestamp = elem1.timestamp - T.hours(24).msecs(), + basalAmount = elem1.basalAmount / 2.0, + bolusAmount = elem1.bolusAmount / 2.0 + ) dummies.add(dummy) - elem1.basal /= 2.0 - elem1.bolus /= 2.0 + elem1.basalAmount /= 2.0 + elem1.bolusAmount /= 2.0 } } historyList.addAll(dummies) - historyList.sortWith { lhs: TDD, rhs: TDD -> (rhs.date - lhs.date).toInt() } + historyList.sortWith { lhs: TotalDailyDose, rhs: TotalDailyDose -> (rhs.timestamp - lhs.timestamp).toInt() } runOnUiThread { cleanTable(binding.mainTable) cleanTable(binding.cumulativeTable) @@ -273,7 +276,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { //TDD table for (record in historyList) { - val tdd = record.getTotal() + val tdd = record.total // Create the table row binding.mainTable.addView( @@ -290,17 +293,17 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { // Here create the TextView dynamically tr.addView(TextView(this@TDDStatsActivity).also { labelDATE -> labelDATE.id = 200 + i - labelDATE.text = df1.format(Date(record.date)) + labelDATE.text = df1.format(Date(record.timestamp)) labelDATE.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelBASAL -> labelBASAL.id = 300 + i - labelBASAL.text = resourceHelper.gs(R.string.formatinsulinunits, record.basal) + labelBASAL.text = resourceHelper.gs(R.string.formatinsulinunits, record.basalAmount) labelBASAL.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelBOLUS -> labelBOLUS.id = 400 + i - labelBOLUS.text = resourceHelper.gs(R.string.formatinsulinunits, record.bolus) + labelBOLUS.text = resourceHelper.gs(R.string.formatinsulinunits, record.bolusAmount) labelBOLUS.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelTDD -> @@ -320,11 +323,11 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { //cumulative TDDs for (record in historyList) { - if (historyList.isNotEmpty() && df1.format(Date(record.date)) == df1.format(Date())) + if (historyList.isNotEmpty() && df1.format(Date(record.timestamp)) == df1.format(Date())) //Today should not be included continue i++ - sum += record.getTotal() + sum += record.total // Create the cumulative table row binding.cumulativeTable.addView( @@ -358,14 +361,14 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { binding.message.visibility = View.VISIBLE binding.message.text = resourceHelper.gs(R.string.olddata_Message) } else binding.mainTable.setBackgroundColor(Color.TRANSPARENT) - if (historyList.isNotEmpty() && df1.format(Date(historyList[0].date)) == df1.format(Date())) { + if (historyList.isNotEmpty() && df1.format(Date(historyList[0].timestamp)) == df1.format(Date())) { //Today should not be included historyList.removeAt(0) } historyList.reverse() i = 0 for (record in historyList) { - val tdd = record.getTotal() + val tdd = record.total if (i == 0) { weighted03 = tdd weighted05 = tdd @@ -420,10 +423,10 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { if (childCount > 1) table.removeViews(1, childCount - 1) } - private fun isOldData(historyList: List): Boolean { + private fun isOldData(historyList: List): Boolean { val type = activePlugin.activePump.pumpDescription.pumpType val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) - return historyList.size < 3 || df.format(Date(historyList[0].date)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) + return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/db/TDD.java b/core/src/main/java/info/nightscout/androidaps/db/TDD.java deleted file mode 100644 index f023c06f7f..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/TDD.java +++ /dev/null @@ -1,73 +0,0 @@ -package info.nightscout.androidaps.db; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -import java.util.Locale; - -import info.nightscout.androidaps.core.R; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; - -/** - * Created by mike on 20.09.2017. - */ - - -@DatabaseTable(tableName = "TDDs") -public class TDD { - - @DatabaseField(id = true) - public long date; - - @DatabaseField - public double bolus; - - @DatabaseField - public double basal; - - @DatabaseField - public double total; - - public double carbs; - - public double getTotal() { - return (total > 0d) ? total : (bolus + basal); - } - - - public TDD() { - } - - public TDD(long date, double bolus, double basal, double total) { - this.date = date; - this.bolus = bolus; - this.basal = basal; - this.total = total; - } - - - public String toString(DateUtil dateUtil) { - return "TDD [" + - "date=" + date + - "date(str)=" + dateUtil.dateAndTimeString(date) + - ", bolus=" + bolus + - ", basal=" + basal + - ", total=" + total + - ']'; - } - - public String toText(ResourceHelper resourceHelper, DateUtil dateUtil, boolean includeCarbs) { - if (includeCarbs) - return resourceHelper.gs(R.string.tddwithcarbsformat, dateUtil.dateStringShort(date), total, bolus, basal, basal / total * 100, carbs); - else - return resourceHelper.gs(R.string.tddformat, dateUtil.dateStringShort(date), total, bolus, basal, basal / total * 100); - } - - public String toText(ResourceHelper resourceHelper, int days, boolean includeCarbs) { - if (includeCarbs) - return resourceHelper.gs(R.string.tddwithcarbsformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolus, basal, basal / total * 100, carbs); - else - return resourceHelper.gs(R.string.tddformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolus, basal, basal / total * 100); - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt new file mode 100644 index 0000000000..bf65c784e1 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.extensions + +import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.database.entities.TotalDailyDose +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import java.util.* + +val TotalDailyDose.total + get() = if (totalAmount > 0) totalAmount else basalAmount + bolusAmount + +fun TotalDailyDose.toText(resourceHelper: ResourceHelper, dateUtil: DateUtil, includeCarbs: Boolean): String = + if (includeCarbs) resourceHelper.gs(R.string.tddwithcarbsformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalAmount / total * 100, carbs) + else resourceHelper.gs(R.string.tddformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalAmount / total * 100) + +fun TotalDailyDose.toText(resourceHelper: ResourceHelper, days: Int, includeCarbs: Boolean): String = + if (includeCarbs) resourceHelper.gs(R.string.tddwithcarbsformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100, carbs) + else resourceHelper.gs(R.string.tddformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100) 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 b8fa2b631e..a23ba8457d 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt @@ -17,7 +17,6 @@ interface DatabaseHelperInterface { fun createOrUpdate(record: OHQueueItem) fun create(record: DbRequest) fun getDanaRHistoryRecordsByType(type: Byte): List - fun getTDDs(): List fun size(table: String): Long fun deleteAllDbRequests() fun deleteDbRequest(id: String): Int @@ -26,7 +25,6 @@ interface DatabaseHelperInterface { fun deleteDbRequestbyMongoId(action: String, _id: String) fun getDbRequestIterator(): CloseableIterator fun roundDateToSec(date: Long): Long - fun createOrUpdateTDD(record: TDD) fun createOrUpdate(tempBasal: TemporaryBasal): Boolean @Deprecated("Use new DB") fun findTempBasalByPumpId(id: Long): TemporaryBasal? @@ -36,12 +34,10 @@ interface DatabaseHelperInterface { fun getProfileSwitchEventsFromTime(mills: Long, ascending: Boolean): List fun getAllOmnipodHistoryRecordsFromTimestamp(timestamp: Long, ascending: Boolean): List fun findOmnipodHistoryRecordByPumpId(pumpId: Long): OmnipodHistoryRecord? - fun getTDDsForLastXDays(days: Int): List fun getProfileSwitchData(from: Long, ascending: Boolean): List @Deprecated("Use new DB") fun getExtendedBolusByPumpId(pumpId: Long): ExtendedBolus? fun getAllProfileSwitches(): List - fun getAllTDDs(): List fun getAllOHQueueItems(maxEntries: Long): List fun resetProfileSwitch() diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt index a8fba66edc..fa20d20f61 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt @@ -55,10 +55,12 @@ interface PumpSync { * bolus is null when there is no record in database */ data class PumpState(val temporaryBasal: TemporaryBasal?, val extendedBolus: ExtendedBolus?, val bolus: Bolus?, val profile: Profile?) { + data class TemporaryBasal(val timestamp: Long, val duration: Long, val rate: Double, val isAbsolute: Boolean, val type: TemporaryBasalType, val id: Long, val pumpId: Long?) data class ExtendedBolus(val timestamp: Long, val duration: Long, val amount: Double, val rate: Double) data class Bolus(val timestamp: Long, val amount: Double) } + fun expectedPumpState(): PumpState /* @@ -171,7 +173,7 @@ interface PumpSync { * @param pumpSerial pump serial number * @return true if new record is created **/ - fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String? = null, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String) : Boolean + fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String? = null, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String): Boolean /** * Create an announcement @@ -210,7 +212,8 @@ interface PumpSync { companion object { - fun fromDbType(dbType: TemporaryBasal.Type) = values().firstOrNull { it.name == dbType.name } ?: NORMAL + fun fromDbType(dbType: TemporaryBasal.Type) = values().firstOrNull { it.name == dbType.name } + ?: NORMAL } } @@ -274,7 +277,7 @@ interface PumpSync { **/ fun syncStopTemporaryBasalWithPumpId(timestamp: Long, endPumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean - /** + /** * Invalidate of temporary basals that failed to start * EROS specific, replace by setting duration to zero ???? * @@ -336,4 +339,34 @@ interface PumpSync { * @return true if running record is found and ended by changing duration **/ fun syncStopExtendedBolusWithPumpId(timestamp: Long, endPumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean + + /* + * TOTAL DAILY DOSE + */ + + /** + * Synchronization of TDD + * + * Search for existing record following way + * 1. pumpId, pumpType, pumpSerial (only if pumpId is provided) + * 2. timestamp, pumpType, pumpSerial + * + * If record is found data is updated + * isValid field is preserved + * If db record doesn't exist, new record is created. + * + * see [info.nightscout.androidaps.database.transactions.SyncPumpTotalDailyDoseTransaction] + * + * @param timestamp timestamp of event from pump history + * @param bolusAmount bolus part + * @param basalAmount basal part + * @param totalAmount if > 0, this value is used as total. Otherwise it's calculated as basal + bolus + * @param pumpId pump id from history + * @param pumpType pump type like PumpType.ACCU_CHEK_COMBO + * @param pumpSerial pump serial number + * @return true if new record is created + **/ + + fun createOrUpdateTotalDailyDose(timestamp: Long, bolusAmount: Double, basalAmount: Double, totalAmount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean + } \ No newline at end of file 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 f51cbcedc7..ac9fa5ded0 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 @@ -5,11 +5,7 @@ import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.embedments.InterfaceIDs -import info.nightscout.androidaps.database.entities.Bolus -import info.nightscout.androidaps.database.entities.Carbs -import info.nightscout.androidaps.database.entities.ExtendedBolus -import info.nightscout.androidaps.database.entities.TemporaryBasal -import info.nightscout.androidaps.database.entities.TherapyEvent +import info.nightscout.androidaps.database.entities.* import info.nightscout.androidaps.database.transactions.* import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.PumpSync @@ -53,7 +49,7 @@ class PumpSyncImplementation @Inject constructor( * @param serialNumber serial number of of pump * @return true if data is allowed */ - private fun confirmActivePump(timestamp: Long, type: PumpType, serialNumber: String) : Boolean { + private fun confirmActivePump(timestamp: Long, type: PumpType, serialNumber: String): Boolean { val storedType = sp.getString(R.string.key_active_pump_type, "") val storedSerial = sp.getString(R.string.key_active_pump_serial_number, "") val storedTimestamp = sp.getLong(R.string.key_active_pump_change_timestamp, 0L) @@ -74,7 +70,7 @@ class PumpSyncImplementation @Inject constructor( if (type.description != storedType || serialNumber != storedSerial) rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_DATA, resourceHelper.gs(R.string.wrong_pump_data), Notification.URGENT))) - aapsLogger.error(LTag.PUMP, "Ignoring pump history record $timestamp ${type.description} $serialNumber. Registered pump: $storedType $storedSerial") + aapsLogger.error(LTag.PUMP, "Ignoring pump history record Allowed: ${dateUtil.dateAndTimeAndSecondsString(storedTimestamp)} $storedType $storedSerial Received: $timestamp ${dateUtil.dateAndTimeAndSecondsString(timestamp)}${type.description} $serialNumber") return false } @@ -323,4 +319,27 @@ class PumpSyncImplementation @Inject constructor( } } + override fun createOrUpdateTotalDailyDose(timestamp: Long, bolusAmount: Double, basalAmount: Double, totalAmount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean { + if (!confirmActivePump(timestamp, pumpType, pumpSerial)) return false + val tdd = TotalDailyDose( + timestamp = timestamp, + bolusAmount = bolusAmount, + basalAmount = basalAmount, + totalAmount = totalAmount, + interfaceIDs_backing = InterfaceIDs( + pumpId = pumpId, + pumpType = pumpType.toDbPumpType(), + pumpSerial = pumpSerial + ) + ) + repository.runTransactionForResult(SyncPumpTotalDailyDoseTransaction(tdd)) + .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving TotalDailyDose", it) } + .blockingGet() + .also { result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted TotalDailyDose $it") } + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated TotalDailyDose $it") } + return result.inserted.size > 0 + } + } + } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt index 0693b76912..aca0b7c22b 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -106,7 +106,11 @@ class DanaRSPlugin @Inject constructor( disposable.add(rxBus .toObservable(EventDanaRSDeviceChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ changePump() }, fabricPrivacy::logException) + .subscribe({ + pumpSync.connectNewPump() + changePump() + + }, fabricPrivacy::logException) ) changePump() // load device name } @@ -134,7 +138,6 @@ class DanaRSPlugin @Inject constructor( mDeviceAddress = sp.getString(R.string.key_danars_address, "") mDeviceName = sp.getString(R.string.key_danars_name, "") danaPump.reset() - pumpSync.connectNewPump() commandQueue.readStatus("DeviceChanged", null) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt index 538d9b0bf7..0ab6b0ef49 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt @@ -1,12 +1,15 @@ package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.comm.RecordTypes import info.nightscout.androidaps.db.DanaRHistoryRecord import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.interfaces.DatabaseHelperInterface +import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import org.joda.time.DateTime import java.util.* import javax.inject.Inject @@ -18,6 +21,8 @@ abstract class DanaRS_Packet_History_( @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var databaseHelper: DatabaseHelperInterface + @Inject lateinit var pumpSync: PumpSync + @Inject lateinit var danaPump: DanaPump protected var year = 0 protected var month = 0 @@ -220,6 +225,18 @@ abstract class DanaRS_Packet_History_( } } databaseHelper.createOrUpdate(danaRHistoryRecord) + //If it is a TDD, store it for stats also. + if (danaRHistoryRecord.recordCode == RecordTypes.RECORD_TYPE_DAILY) { + pumpSync.createOrUpdateTotalDailyDose( + timestamp = danaRHistoryRecord.recordDate, + bolusAmount = danaRHistoryRecord.recordDailyBolus, + basalAmount = danaRHistoryRecord.recordDailyBasal, + totalAmount = 0.0, + pumpId = null, + pumpType = PumpType.DANA_RS, + danaPump.serialNumber + ) + } rxBus.send(EventDanaRSyncStatus(dateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)) } } diff --git a/database/schemas/info.nightscout.androidaps.database.AppDatabase/15.json b/database/schemas/info.nightscout.androidaps.database.AppDatabase/15.json new file mode 100644 index 0000000000..6d50e3ec03 --- /dev/null +++ b/database/schemas/info.nightscout.androidaps.database.AppDatabase/15.json @@ -0,0 +1,2943 @@ +{ + "formatVersion": 1, + "database": { + "version": 15, + "identityHash": "ee62c3d98dff077f4f5fc44147be7a4a", + "entities": [ + { + "tableName": "apsResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `algorithm` TEXT NOT NULL, `glucoseStatusJson` TEXT NOT NULL, `currentTempJson` TEXT NOT NULL, `iobDataJson` TEXT NOT NULL, `profileJson` TEXT NOT NULL, `autosensDataJson` TEXT, `mealDataJson` TEXT NOT NULL, `isMicroBolusAllowed` INTEGER, `resultJson` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `apsResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "algorithm", + "columnName": "algorithm", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseStatusJson", + "columnName": "glucoseStatusJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentTempJson", + "columnName": "currentTempJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "iobDataJson", + "columnName": "iobDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "profileJson", + "columnName": "profileJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "autosensDataJson", + "columnName": "autosensDataJson", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mealDataJson", + "columnName": "mealDataJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isMicroBolusAllowed", + "columnName": "isMicroBolusAllowed", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "resultJson", + "columnName": "resultJson", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_apsResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_apsResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_apsResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "apsResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "boluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `amount` REAL NOT NULL, `type` TEXT NOT NULL, `isBasalInsulin` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT, `insulinEndTime` INTEGER, `peak` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `boluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isBasalInsulin", + "columnName": "isBasalInsulin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_boluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_boluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_boluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "boluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "bolusCalculatorResults", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `targetBGLow` REAL NOT NULL, `targetBGHigh` REAL NOT NULL, `isf` REAL NOT NULL, `ic` REAL NOT NULL, `bolusIOB` REAL NOT NULL, `wasBolusIOBUsed` INTEGER NOT NULL, `basalIOB` REAL NOT NULL, `wasBasalIOBUsed` INTEGER NOT NULL, `glucoseValue` REAL NOT NULL, `wasGlucoseUsed` INTEGER NOT NULL, `glucoseDifference` REAL NOT NULL, `glucoseInsulin` REAL NOT NULL, `glucoseTrend` REAL NOT NULL, `wasTrendUsed` INTEGER NOT NULL, `trendInsulin` REAL NOT NULL, `cob` REAL NOT NULL, `wasCOBUsed` INTEGER NOT NULL, `cobInsulin` REAL NOT NULL, `carbs` REAL NOT NULL, `wereCarbsUsed` INTEGER NOT NULL, `carbsInsulin` REAL NOT NULL, `otherCorrection` REAL NOT NULL, `wasSuperbolusUsed` INTEGER NOT NULL, `superbolusInsulin` REAL NOT NULL, `wasTempTargetUsed` INTEGER NOT NULL, `totalInsulin` REAL NOT NULL, `percentageCorrection` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `note` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `bolusCalculatorResults`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "targetBGLow", + "columnName": "targetBGLow", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "targetBGHigh", + "columnName": "targetBGHigh", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isf", + "columnName": "isf", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "ic", + "columnName": "ic", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bolusIOB", + "columnName": "bolusIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBolusIOBUsed", + "columnName": "wasBolusIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalIOB", + "columnName": "basalIOB", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasBasalIOBUsed", + "columnName": "wasBasalIOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseValue", + "columnName": "glucoseValue", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasGlucoseUsed", + "columnName": "wasGlucoseUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "glucoseDifference", + "columnName": "glucoseDifference", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseInsulin", + "columnName": "glucoseInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "glucoseTrend", + "columnName": "glucoseTrend", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTrendUsed", + "columnName": "wasTrendUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "trendInsulin", + "columnName": "trendInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "cob", + "columnName": "cob", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasCOBUsed", + "columnName": "wasCOBUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cobInsulin", + "columnName": "cobInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wereCarbsUsed", + "columnName": "wereCarbsUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "carbsInsulin", + "columnName": "carbsInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "otherCorrection", + "columnName": "otherCorrection", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasSuperbolusUsed", + "columnName": "wasSuperbolusUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "superbolusInsulin", + "columnName": "superbolusInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "wasTempTargetUsed", + "columnName": "wasTempTargetUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalInsulin", + "columnName": "totalInsulin", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "percentageCorrection", + "columnName": "percentageCorrection", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_bolusCalculatorResults_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_bolusCalculatorResults_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_bolusCalculatorResults_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "bolusCalculatorResults", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "carbs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `carbs`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_carbs_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_carbs_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_carbs_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "carbs", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "effectiveProfileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `basalBlocks` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `effectiveProfileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_effectiveProfileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_effectiveProfileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_effectiveProfileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "effectiveProfileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "extendedBoluses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `amount` REAL NOT NULL, `isEmulatingTempBasal` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `extendedBoluses`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "isEmulatingTempBasal", + "columnName": "isEmulatingTempBasal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_extendedBoluses_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_extendedBoluses_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_extendedBoluses_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "extendedBoluses", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "glucoseValues", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `raw` REAL, `value` REAL NOT NULL, `trendArrow` TEXT NOT NULL, `noise` REAL, `sourceSensor` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `glucoseValues`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "raw", + "columnName": "raw", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "trendArrow", + "columnName": "trendArrow", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "noise", + "columnName": "noise", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "sourceSensor", + "columnName": "sourceSensor", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_glucoseValues_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_glucoseValues_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_glucoseValues_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "glucoseValues", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "profileSwitches", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `profileName` TEXT NOT NULL, `glucoseUnit` TEXT NOT NULL, `basalBlocks` TEXT NOT NULL, `isfBlocks` TEXT NOT NULL, `icBlocks` TEXT NOT NULL, `targetBlocks` TEXT NOT NULL, `timeshift` INTEGER NOT NULL, `percentage` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, `insulinLabel` TEXT NOT NULL, `insulinEndTime` INTEGER NOT NULL, `peak` INTEGER NOT NULL, FOREIGN KEY(`referenceId`) REFERENCES `profileSwitches`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileName", + "columnName": "profileName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "basalBlocks", + "columnName": "basalBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isfBlocks", + "columnName": "isfBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "icBlocks", + "columnName": "icBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetBlocks", + "columnName": "targetBlocks", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeshift", + "columnName": "timeshift", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percentage", + "columnName": "percentage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "insulinConfiguration.insulinLabel", + "columnName": "insulinLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.insulinEndTime", + "columnName": "insulinEndTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "insulinConfiguration.peak", + "columnName": "peak", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_profileSwitches_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_profileSwitches_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_profileSwitches_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "profileSwitches", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryBasals", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `type` TEXT NOT NULL, `isAbsolute` INTEGER NOT NULL, `rate` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryBasals`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isAbsolute", + "columnName": "isAbsolute", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rate", + "columnName": "rate", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryBasals_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryBasals_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryBasals_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryBasals", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "temporaryTargets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `reason` TEXT NOT NULL, `highTarget` REAL NOT NULL, `lowTarget` REAL NOT NULL, `duration` INTEGER NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `temporaryTargets`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reason", + "columnName": "reason", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highTarget", + "columnName": "highTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "lowTarget", + "columnName": "lowTarget", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_temporaryTargets_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_temporaryTargets_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_temporaryTargets_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "temporaryTargets", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "therapyEvents", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `type` TEXT NOT NULL, `note` TEXT, `enteredBy` TEXT, `glucose` REAL, `glucoseType` TEXT, `glucoseUnit` TEXT NOT NULL, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `therapyEvents`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "utcOffset", + "columnName": "utcOffset", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "enteredBy", + "columnName": "enteredBy", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucose", + "columnName": "glucose", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "glucoseType", + "columnName": "glucoseType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "glucoseUnit", + "columnName": "glucoseUnit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_therapyEvents_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + }, + { + "name": "index_therapyEvents_timestamp", + "unique": false, + "columnNames": [ + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_therapyEvents_timestamp` ON `${TABLE_NAME}` (`timestamp`)" + } + ], + "foreignKeys": [ + { + "table": "therapyEvents", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "totalDailyDoses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `timestamp` INTEGER NOT NULL, `utcOffset` INTEGER NOT NULL, `basalAmount` REAL 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_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": [], + "foreignKeys": [] + }, + { + "tableName": "foods", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `version` INTEGER NOT NULL, `dateCreated` INTEGER NOT NULL, `isValid` INTEGER NOT NULL, `referenceId` INTEGER, `name` TEXT NOT NULL, `category` TEXT, `subCategory` TEXT, `portion` REAL NOT NULL, `carbs` INTEGER NOT NULL, `fat` INTEGER, `protein` INTEGER, `energy` INTEGER, `unit` TEXT NOT NULL, `gi` INTEGER, `nightscoutSystemId` TEXT, `nightscoutId` TEXT, `pumpType` TEXT, `pumpSerial` TEXT, `temporaryId` INTEGER, `pumpId` INTEGER, `startId` INTEGER, `endId` INTEGER, FOREIGN KEY(`referenceId`) REFERENCES `foods`(`id`) ON UPDATE NO ACTION ON DELETE NO ACTION )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateCreated", + "columnName": "dateCreated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isValid", + "columnName": "isValid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "referenceId", + "columnName": "referenceId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "category", + "columnName": "category", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "subCategory", + "columnName": "subCategory", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "portion", + "columnName": "portion", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "carbs", + "columnName": "carbs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fat", + "columnName": "fat", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "protein", + "columnName": "protein", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "energy", + "columnName": "energy", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "unit", + "columnName": "unit", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "gi", + "columnName": "gi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutSystemId", + "columnName": "nightscoutSystemId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.nightscoutId", + "columnName": "nightscoutId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpType", + "columnName": "pumpType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpSerial", + "columnName": "pumpSerial", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.temporaryId", + "columnName": "temporaryId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.pumpId", + "columnName": "pumpId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.startId", + "columnName": "startId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "interfaceIDs_backing.endId", + "columnName": "endId", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": true + }, + "indices": [ + { + "name": "index_foods_referenceId", + "unique": false, + "columnNames": [ + "referenceId" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_foods_referenceId` ON `${TABLE_NAME}` (`referenceId`)" + } + ], + "foreignKeys": [ + { + "table": "foods", + "onDelete": "NO ACTION", + "onUpdate": "NO ACTION", + "columns": [ + "referenceId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "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_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, 'ee62c3d98dff077f4f5fc44147be7a4a')" + ] + } +} \ 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 276096240d..e716102060 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 = 14 +const val DATABASE_VERSION = 15 @Database(version = DATABASE_VERSION, entities = [APSResult::class, Bolus::class, BolusCalculatorResult::class, Carbs::class, diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt index af800d028b..6f4a66b1ab 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -598,6 +598,18 @@ open class AppRepository @Inject internal constructor( fun getOldestExtendedBolusRecord(): ExtendedBolus? = database.extendedBolusDao.getOldestRecord() + // TotalDailyDose + fun getAllTotalDailyDoses(ascending: Boolean): Single> = + database.totalDailyDoseDao.getAllTotalDailyDoses() + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + fun getLastTotalDailyDoses(count: Int, ascending: Boolean): Single> = + database.totalDailyDoseDao.getLastTotalDailyDoses(count) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + } @Suppress("USELESS_CAST") 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 d34edc36d2..239081d607 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 @@ -32,10 +32,10 @@ internal interface DeviceStatusDao { fun findByNSId(nsId: String): DeviceStatus? // This query will be used with v3 to get all changed records - @Query("SELECT * FROM $TABLE_DEVICE_STATUS WHERE id > :id ORDER BY id ASC") + @Query("SELECT * FROM $TABLE_DEVICE_STATUS WHERE id > :id AND nightscoutId IS NULL ORDER BY id ASC") fun getModifiedFrom(id: Long): Single> // for WS we need 1 record only - @Query("SELECT * FROM $TABLE_DEVICE_STATUS WHERE id > :id ORDER BY id ASC limit 1") + @Query("SELECT * FROM $TABLE_DEVICE_STATUS WHERE id > :id AND nightscoutId IS NULL ORDER BY id ASC limit 1") fun getNextModifiedOrNewAfter(id: Long): Maybe } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt index 16ad4e0253..2b16339108 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.database.daos import androidx.room.Dao import androidx.room.Query import info.nightscout.androidaps.database.TABLE_TOTAL_DAILY_DOSES +import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.TotalDailyDose import io.reactivex.Single @@ -15,4 +16,17 @@ internal interface TotalDailyDoseDao : TraceableDao { @Query("DELETE FROM $TABLE_TOTAL_DAILY_DOSES") override fun deleteAllEntries() + + @Query("SELECT * FROM $TABLE_TOTAL_DAILY_DOSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") + fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): TotalDailyDose? + + @Query("SELECT * FROM $TABLE_TOTAL_DAILY_DOSES WHERE timestamp = :timestamp AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") + fun findByPumpTimestamp(timestamp: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): TotalDailyDose? + + @Query("SELECT * FROM $TABLE_TOTAL_DAILY_DOSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC") + fun getAllTotalDailyDoses(): Single> + + @Query("SELECT * FROM $TABLE_TOTAL_DAILY_DOSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY timestamp DESC LIMIT :count") + fun getLastTotalDailyDoses(count: Int): Single> + } \ No newline at end of file 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 0cd450697c..fb386312a5 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 @@ -1,30 +1,35 @@ package info.nightscout.androidaps.database.entities -import androidx.room.* +import androidx.room.Embedded +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.Index +import androidx.room.PrimaryKey import info.nightscout.androidaps.database.TABLE_TOTAL_DAILY_DOSES import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.interfaces.DBEntryWithTime import info.nightscout.androidaps.database.interfaces.TraceableDBEntry -import java.util.TimeZone +import java.util.* @Entity(tableName = TABLE_TOTAL_DAILY_DOSES, - foreignKeys = [ForeignKey( - entity = TotalDailyDose::class, - parentColumns = ["id"], - childColumns = ["referenceId"])], - indices = [Index("referenceId"), Index("timestamp")]) + foreignKeys = [ForeignKey( + entity = TotalDailyDose::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) data class TotalDailyDose( @PrimaryKey(autoGenerate = true) - override var id: Long = 0, + override var id: Long = 0, override var version: Int = 0, override var dateCreated: Long = -1, override var isValid: Boolean = true, override var referenceId: Long? = null, @Embedded - override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(), + override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(), override var timestamp: Long, override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), - var basalAmount: Double?, - var bolusAmount: Double?, - var totalAmount: Double? + var basalAmount: Double = 0.0, + var bolusAmount: Double = 0.0, + var totalAmount: Double = 0.0, // if zero it's calculated as basalAmount + bolusAmount + var carbs: Double = 0.0 ) : TraceableDBEntry, DBEntryWithTime \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpTotalDailyDoseTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpTotalDailyDoseTransaction.kt new file mode 100644 index 0000000000..805d1cabb2 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/SyncPumpTotalDailyDoseTransaction.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.TotalDailyDose + +/** + * Creates or updates the TotalDailyDose from pump synchronization + */ +class SyncPumpTotalDailyDoseTransaction(private val tdd: TotalDailyDose +) : Transaction() { + + override fun run(): TransactionResult { + tdd.interfaceIDs.pumpType ?: tdd.interfaceIDs.pumpSerial + ?: throw IllegalStateException("Some pump ID is null") + + val result = TransactionResult() + var current: TotalDailyDose? = null + // search by pumpId + if (tdd.interfaceIDs.pumpId != null) { + current = database.totalDailyDoseDao.findByPumpIds(tdd.interfaceIDs.pumpId!!, tdd.interfaceIDs.pumpType!!, tdd.interfaceIDs.pumpSerial!!) + } + // search by timestamp + if (current == null) { + current = database.totalDailyDoseDao.findByPumpTimestamp(tdd.timestamp, tdd.interfaceIDs.pumpType!!, tdd.interfaceIDs.pumpSerial!!) + } + if (current == null) { + database.totalDailyDoseDao.insertNewEntry(tdd) + result.inserted.add(tdd) + } else { + current.basalAmount = tdd.basalAmount + current.bolusAmount = tdd.bolusAmount + current.totalAmount = tdd.totalAmount + current.carbs = tdd.carbs + current.interfaceIDs.pumpId = tdd.interfaceIDs.pumpId + database.totalDailyDoseDao.updateExistingEntry(current) + result.updated.add(current) + } + + return result + } + + class TransactionResult { + + val inserted = mutableListOf() + val updated = mutableListOf() + } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 2ba8ced252..f372aca75d 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 @@ -38,7 +38,6 @@ 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.TDD; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; @@ -51,8 +50,8 @@ import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.interfaces.PumpDescription; 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; @@ -1275,12 +1274,15 @@ 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()); - TDD tdd = new TDD(); - tdd.basal = event.getBasalTotal(); - tdd.bolus = event.getBolusTotal(); - tdd.total = tdd.basal + tdd.bolus; - tdd.date = calendar.getTimeInMillis(); - databaseHelper.createOrUpdateTDD(tdd); + pumpSync.createOrUpdateTotalDailyDose( + calendar.getTimeInMillis(), + event.getBolusTotal(), + event.getBasalTotal(), + 0.0, // will be calculated automatically + null, + PumpType.ACCU_CHEK_INSIGHT, + serialNumber() + ); } private void processTubeFilledEvent(TubeFilledEvent event) { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index f4fa579e93..cebbe9cec4 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -24,7 +24,6 @@ import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.db.DbObjectBase; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.ActivePlugin; @@ -589,6 +588,21 @@ public class MedtronicHistoryData { aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, getLogPrefix() + "TDDs found: %d.\n%s", tdds.size(), gson().toJson(tdds))); + + for (PumpHistoryEntry tdd : tdds) { + DailyTotalsDTO totalsDTO = (DailyTotalsDTO) tdd.getDecodedData().get("Object"); + Boolean result = pumpSync.createOrUpdateTotalDailyDose( + totalsDTO.timestamp(), + totalsDTO.insulinBasal(), + totalsDTO.insulinBolus(), + totalsDTO.insulinTotal(), + null, + medtronicPumpStatus.pumpType, + medtronicPumpStatus.serialNumber + ); + if (result) aapsLogger.debug(LTag.PUMP, "TDD Added/Updated: " + totalsDTO); + } +/* List tddsDb = databaseHelper.getTDDsForLastXDays(3); for (PumpHistoryEntry tdd : tdds) { @@ -618,6 +632,8 @@ public class MedtronicHistoryData { } } } + + */ } @@ -1317,7 +1333,7 @@ public class MedtronicHistoryData { return tddsOut.size() == 0 ? tdds : tddsOut; } - +/* private TDD findTDD(long atechDateTime, List tddsDb) { for (TDD tdd : tddsDb) { @@ -1329,7 +1345,7 @@ public class MedtronicHistoryData { return null; } - +*/ private long tryToGetByLocalTime(long atechDateTime) { return DateTimeUtil.toMillisFromATD(atechDateTime); } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java index 697b74aa74..af12ac6962 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/DailyTotalsDTO.java @@ -8,7 +8,6 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.Locale; -import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; @@ -240,16 +239,20 @@ public class DailyTotalsDTO { .toString(); } - public void setTDD(TDD tdd) { - tdd.date = DateTimeUtil.toMillisFromATD(this.entry.atechDateTime); - tdd.basal = insulinBasal; - tdd.bolus = insulinBolus; - tdd.total = insulinTotal; + public long timestamp() { + return DateTimeUtil.toMillisFromATD(this.entry.atechDateTime); } - - public boolean doesEqual(TDD tdd) { - return tdd.total == this.insulinTotal && tdd.bolus == this.insulinBolus && tdd.basal == this.insulinBasal; + public double insulinBasal() { + return insulinBasal; } + public double insulinBolus() { + return insulinBolus; + } + public double insulinTotal() { + return insulinTotal; + } + + }