diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 4496928738..c323a475be 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -23,7 +23,6 @@ import javax.inject.Inject; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -67,15 +66,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { aapsLogger.info(LTag.DATABASE, "onCreate"); - TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); - TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); - TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); } catch (SQLException e) { aapsLogger.error("Can't create database", e); throw new RuntimeException(e); @@ -91,17 +83,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (oldVersion < 7) { aapsLogger.info(LTag.DATABASE, "onUpgrade"); onCreate(database, connectionSource); - } else if (oldVersion < 10) { - TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); - TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); - TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); - } else if (oldVersion < 11) { - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\""); - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\""); } TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); } catch (SQLException e) { @@ -152,18 +133,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // ------------------ getDao ------------------------------------------- - private Dao getDaoInsightPumpID() throws SQLException { - return getDao(InsightPumpID.class); - } - - private Dao getDaoInsightBolusID() throws SQLException { - return getDao(InsightBolusID.class); - } - - private Dao getDaoInsightHistoryOffset() throws SQLException { - return getDao(InsightHistoryOffset.class); - } - private Dao getDaoPodHistory() throws SQLException { return getDao(OmnipodHistoryRecord.class); } @@ -182,68 +151,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } - // ---------------- Insight history handling --------------- - - public void createOrUpdate(InsightHistoryOffset offset) { - try { - getDaoInsightHistoryOffset().createOrUpdate(offset); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) { - try { - return getDaoInsightHistoryOffset().queryForId(pumpSerial); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - public void createOrUpdate(InsightBolusID bolusID) { - try { - getDaoInsightBolusID().createOrUpdate(bolusID); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) { - try { - return getDaoInsightBolusID().queryBuilder() - .where().eq("pumpSerial", pumpSerial) - .and().eq("bolusID", bolusID) - .and().between("timestamp", timestamp - 259200000, timestamp + 259200000) - .queryForFirst(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - public void createOrUpdate(InsightPumpID pumpID) { - try { - getDaoInsightPumpID().createOrUpdate(pumpID); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) { - try { - return getDaoInsightPumpID().queryBuilder() - .orderBy("timestamp", false) - .where().eq("pumpSerial", pumpSerial) - .and().in("eventType", "PumpStopped", "PumpPaused") - .and().lt("timestamp", before) - .queryForFirst(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - // ---------------- Food handling --------------- // ---------------- PodHistory handling --------------- diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java index 89d892fe97..da0b2479cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -49,18 +49,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); } - @Override public void createOrUpdate(@NonNull InsightBolusID record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @Override public void createOrUpdate(@NonNull InsightPumpID record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - @Override public void delete(@NonNull ExtendedBolus extendedBolus) { // MainApp.Companion.getDbHelper().delete(extendedBolus); } @@ -70,18 +58,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return null; } - @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) { - return MainApp.Companion.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp); - } - - @Nullable @Override public InsightHistoryOffset getInsightHistoryOffset(@NonNull String pumpSerial) { - return MainApp.Companion.getDbHelper().getInsightHistoryOffset(pumpSerial); - } - - @Nullable @Override public InsightPumpID getPumpStoppedEvent(@NonNull String pumpSerial, long before) { - return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before); - } - @Override public void resetDatabases() { MainApp.Companion.getDbHelper().resetDatabases(); } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 05b5974bb5..1421d586ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -12,8 +12,9 @@ import info.nightscout.androidaps.di.CoreModule import info.nightscout.androidaps.dana.di.DanaModule import info.nightscout.androidaps.danar.di.DanaRModule import info.nightscout.androidaps.danars.di.DanaRSModule -import info.nightscout.androidaps.danars.di.InsightModule import info.nightscout.androidaps.database.DatabaseModule +import info.nightscout.androidaps.insight.di.InsightDatabaseModule +import info.nightscout.androidaps.insight.di.InsightModule import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.dagger.OmnipodErosModule @@ -51,6 +52,7 @@ import javax.inject.Singleton DanaRSModule::class, ComboModule::class, InsightModule::class, + InsightDatabaseModule::class, WorkersModule::class, OHUploaderModule::class ] diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 8ff8dac818..36df705147 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -13,6 +13,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.events.EventNewBG +import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.PumpSync @@ -39,6 +40,7 @@ class MaintenanceFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase + @Inject lateinit var insightDatabase: InsightDatabase @Inject lateinit var uel: UserEntryLogger @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var pumpSync: PumpSync @@ -70,6 +72,7 @@ class MaintenanceFragment : DaggerFragment() { fromAction { repository.clearDatabases() danaHistoryDatabase.clearAllTables() + insightDatabase.clearAllTables() dataSyncSelector.resetToNextFullSync() pumpSync.connectNewPump() } diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index f9bacb7bbd..449ea3c5e6 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -10,6 +10,8 @@ import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.insight.database.InsightDatabaseDao +import info.nightscout.androidaps.insight.database.InsightDbHelper import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin @@ -51,7 +53,7 @@ import java.util.* ConstraintChecker::class, SP::class, Context::class, OpenAPSAMAPlugin::class, OpenAPSSMBPlugin::class, TreatmentsPlugin::class, TreatmentService::class, VirtualPumpPlugin::class, DetailedBolusInfoStorage::class, TemporaryBasalStorage::class, GlimpPlugin::class, Profiler::class, - UserEntryLogger::class, LoggerUtils::class, AppRepository::class) + UserEntryLogger::class, LoggerUtils::class, AppRepository::class, InsightDatabaseDao::class) class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var activePlugin: ActivePlugin @@ -68,9 +70,10 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var repository: AppRepository @Mock lateinit var pumpSync: PumpSync + @Mock lateinit var insightDatabaseDao: InsightDatabaseDao private lateinit var danaPump: DanaPump - + private lateinit var insightDbHelper: InsightDbHelper private lateinit var constraintChecker: ConstraintChecker private lateinit var safetyPlugin: SafetyPlugin private lateinit var objectivesPlugin: ObjectivesPlugin @@ -134,14 +137,14 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) - + insightDbHelper = InsightDbHelper(insightDatabaseDao) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, ConfigImpl(), dateUtil, uel) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync, dateUtil) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) - insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, databaseHelper, pumpSync) + insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, insightDbHelper, pumpSync) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(ConfigImpl(), loggerUtils), iobCobCalculator, ConfigImpl(), dateUtil) diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt index e49f4cdf51..fe783413a0 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt @@ -7,9 +7,6 @@ interface DatabaseHelperInterface { fun resetDatabases() fun createOrUpdate(record: OmnipodHistoryRecord) - fun createOrUpdate(record: InsightBolusID) - fun createOrUpdate(record: InsightPumpID) - fun createOrUpdate(record: InsightHistoryOffset) fun createOrUpdate(record: OHQueueItem) fun delete(extendedBolus: ExtendedBolus) fun createOrUpdate(tempBasal: TemporaryBasal): Boolean @@ -24,18 +21,9 @@ interface DatabaseHelperInterface { fun getAllOHQueueItems(maxEntries: Long): List // old DB model - fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? - fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? - fun getPumpStoppedEvent(pumpSerial: String, before: Long): InsightPumpID? fun getOHQueueSize(): Long fun clearOpenHumansQueue() fun removeAllOHQueueItemsWithIdSmallerThan(id: Long) - companion object { - - const val DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets" - const val DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs" - const val DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs" - } } diff --git a/insight/build.gradle b/insight/build.gradle index 8020051b31..14391efbea 100644 --- a/insight/build.gradle +++ b/insight/build.gradle @@ -12,9 +12,21 @@ android { defaultConfig { versionCode 1 versionName "1.0" + kapt { + arguments { + arg("room.incremental", "true") + arg("room.schemaLocation", "$projectDir/schemas") + } + } } } dependencies { implementation project(':core') + + api "androidx.room:room-ktx:$room_version" + api "androidx.room:room-runtime:$room_version" + api "androidx.room:room-rxjava2:$room_version" + kapt "androidx.room:room-compiler:$room_version" + kapt "android.arch.persistence.room:compiler:$room_version" } \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt new file mode 100644 index 0000000000..76a60cd1e6 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/Converters.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.TypeConverter + +class Converters { + @TypeConverter + fun fromEventType(evenType: InsightPumpID.EventType) = evenType.name + + @TypeConverter + fun toEventType(evenType: String?) = evenType?.let { InsightPumpID.EventType.valueOf(it) } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt new file mode 100644 index 0000000000..99b6055c7f --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightBolusID.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_BOLUS_IDS, + indices = [Index("bolusID")]) +data class InsightBolusID( + var timestamp: Long, + val pumpSerial: String? = null, + val bolusID: Int? = null, + var startID: Long? = null, + var endID: Long? = null +) { + @PrimaryKey(autoGenerate = true) + var id: Long = 0 +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt new file mode 100644 index 0000000000..7be27eae76 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabase.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.insight.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters + +const val DATABASE_INSIGHT_BOLUS_IDS = "insightBolusIDs" +const val DATABASE_INSIGHT_PUMP_IDS = "insightPumpIDs" +const val DATABASE_INSIGHT_HISTORY_OFFSETS = "insightHistoryOffsets" + +@Database( + entities = [InsightBolusID::class, InsightHistoryOffset::class, InsightPumpID::class], + exportSchema = true, + version = InsightDatabase.VERSION +) +@TypeConverters(Converters::class) +abstract class InsightDatabase : RoomDatabase() { + + abstract fun insightDatabaseDao(): InsightDatabaseDao + + companion object { + + const val VERSION = 1 + + fun build(context: Context) = + Room.databaseBuilder( + context.applicationContext, + InsightDatabase::class.java, + "insight_database.db" + ) + .fallbackToDestructiveMigration() + .build() + } +} diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt new file mode 100644 index 0000000000..051f56803b --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDatabaseDao.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import info.nightscout.androidaps.insight.database.InsightPumpID.EventType + +@Dao +abstract class InsightDatabaseDao { + + @Query("SELECT * from $DATABASE_INSIGHT_BOLUS_IDS WHERE pumpSerial = :pumpSerial AND timestamp >= :timestamp - 259200000 AND timestamp <= :timestamp + 259200000 AND bolusID = :bolusID") + abstract fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightBolusID: InsightBolusID) + + @Query("SELECT * from $DATABASE_INSIGHT_HISTORY_OFFSETS WHERE pumpSerial = :pumpSerial") + abstract fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) + + @Query("SELECT * from $DATABASE_INSIGHT_PUMP_IDS WHERE pumpSerial = :pumpSerial AND (eventType = :pumpStopped OR eventType = :pumpPaused) AND timestamp < :timestamp ORDER BY timestamp DESC") + abstract fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long, pumpStopped: EventType, pumpPaused: EventType): InsightPumpID? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(insightPumpID: InsightPumpID) +} diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt new file mode 100644 index 0000000000..592acd5a73 --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightDbHelper.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.insight.database + +class InsightDbHelper (val insightDatabaseDao: InsightDatabaseDao) { + + fun getInsightBolusID(pumpSerial: String, bolusID: Int, timestamp: Long): InsightBolusID? = insightDatabaseDao.getInsightBolusID(pumpSerial, bolusID, timestamp) + + fun createOrUpdate(insightBolusID: InsightBolusID) = insightDatabaseDao.createOrUpdate(insightBolusID) + + fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? = insightDatabaseDao.getInsightHistoryOffset(pumpSerial) + + fun createOrUpdate(insightHistoryOffset: InsightHistoryOffset) = insightDatabaseDao.createOrUpdate(insightHistoryOffset) + + fun getPumpStoppedEvent(pumpSerial: String, timestamp: Long): InsightPumpID? = insightDatabaseDao.getPumpStoppedEvent(pumpSerial, timestamp, InsightPumpID.EventType.PumpStopped, InsightPumpID.EventType.PumpPaused) + + fun createOrUpdate(insightPumpID: InsightPumpID) = insightDatabaseDao.createOrUpdate(insightPumpID) + +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt new file mode 100644 index 0000000000..8c1d45111c --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightHistoryOffset.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_HISTORY_OFFSETS, + indices = [Index("pumpSerial")]) +data class InsightHistoryOffset( + @PrimaryKey val pumpSerial: String, + var offset: Long + ) diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt new file mode 100644 index 0000000000..71e5b3502e --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/database/InsightPumpID.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.insight.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = DATABASE_INSIGHT_PUMP_IDS, + indices = [Index("timestamp")]) +data class InsightPumpID( + var timestamp: Long, + var eventType: EventType = EventType.None, + val pumpSerial: String? = null, + @PrimaryKey + var eventID: Long +) { + enum class EventType { + PumpStarted, + PumpStopped, + PumpPaused, + StartOfTBR, + EndOfTBR, + None; + } +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt index 7a3024a501..b65a707469 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightActivitiesModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module import dagger.android.ContributesAndroidInjector diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt index 4aeed99770..7073ad14ae 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt new file mode 100644 index 0000000000..2e47f3891c --- /dev/null +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightDatabaseModule.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.insight.di + +import android.content.Context +import dagger.Module +import dagger.Provides +import info.nightscout.androidaps.insight.database.InsightDatabase +import info.nightscout.androidaps.insight.database.InsightDatabaseDao +import info.nightscout.androidaps.insight.database.InsightDbHelper +import javax.inject.Singleton + +@Module +class InsightDatabaseModule { + + @Provides + @Singleton + internal fun provideDatabase(context: Context): InsightDatabase = InsightDatabase.build(context) + + @Provides + @Singleton + internal fun provideInsightDatabaseDao(insightDatabase: InsightDatabase): InsightDatabaseDao = + insightDatabase.insightDatabaseDao() + + @Provides + @Singleton + internal fun provideInsightDbHelper(insightDatabaseDao: InsightDatabaseDao): InsightDbHelper = InsightDbHelper(insightDatabaseDao) + +} \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt index 59d3a3de2a..af2a086dbf 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightModule.kt @@ -1,10 +1,14 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module +import dagger.android.ContributesAndroidInjector @Module(includes = [ InsightCommModule::class, InsightActivitiesModule::class, - InsightServicesModule::class + InsightServicesModule::class, + InsightDatabaseModule::class ]) -open class InsightModule \ No newline at end of file + +@Suppress("unused") +abstract class InsightModule \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt index 3d9a4bc52e..1684d6f9de 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightServicesModule.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.danars.di +package info.nightscout.androidaps.insight.di import dagger.Module import dagger.android.ContributesAndroidInjector diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 5626f4cdb1..141f60a52a 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -33,20 +33,18 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.InsightBolusID; -import info.nightscout.androidaps.db.InsightHistoryOffset; -import info.nightscout.androidaps.db.InsightPumpID; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; +import info.nightscout.androidaps.insight.database.InsightBolusID; +import info.nightscout.androidaps.insight.database.InsightDbHelper; +import info.nightscout.androidaps.insight.database.InsightHistoryOffset; +import info.nightscout.androidaps.insight.database.InsightPumpID; +import info.nightscout.androidaps.insight.database.InsightPumpID.EventType; import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Config; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraints; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileFunction; @@ -54,7 +52,7 @@ import info.nightscout.androidaps.interfaces.Pump; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpSync; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.interfaces.PumpSync.PumpState.TemporaryBasal; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -131,6 +129,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -140,13 +139,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private final AAPSLogger aapsLogger; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; - private final TreatmentsInterface treatmentsPlugin; private final SP sp; private final CommandQueueProvider commandQueue; private final ProfileFunction profileFunction; private final Context context; private final DateUtil dateUtil; - private final DatabaseHelperInterface databaseHelper; + private final InsightDbHelper insightDbHelper; private final PumpSync pumpSync; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -199,14 +197,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai AAPSLogger aapsLogger, RxBusWrapper rxBus, ResourceHelper resourceHelper, - TreatmentsInterface treatmentsPlugin, SP sp, CommandQueueProvider commandQueue, ProfileFunction profileFunction, Context context, Config config, DateUtil dateUtil, - DatabaseHelperInterface databaseHelper, + InsightDbHelper insightDbHelper, PumpSync pumpSync ) { super(new PluginDescription() @@ -223,13 +220,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; - this.treatmentsPlugin = treatmentsPlugin; this.sp = sp; this.commandQueue = commandQueue; this.profileFunction = profileFunction; this.context = context; this.dateUtil = dateUtil; - this.databaseHelper = databaseHelper; + this.insightDbHelper = insightDbHelper; this.pumpSync = pumpSync; pumpDescription = new PumpDescription(); @@ -376,7 +372,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai calendar.set(Calendar.HOUR_OF_DAY, pumpTime.getHour()); calendar.set(Calendar.MINUTE, pumpTime.getMinute()); calendar.set(Calendar.SECOND, pumpTime.getSecond()); - if (calendar.get(Calendar.HOUR_OF_DAY) != pumpTime.getHour() || Math.abs(calendar.getTimeInMillis() - System.currentTimeMillis()) > 10000) { + if (calendar.get(Calendar.HOUR_OF_DAY) != pumpTime.getHour() || Math.abs(calendar.getTimeInMillis() - dateUtil.now()) > 10000) { calendar.setTime(new Date()); pumpTime.setYear(calendar.get(Calendar.YEAR)); pumpTime.setMonth(calendar.get(Calendar.MONTH) + 1); @@ -544,7 +540,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @Override public long lastDataTime() { - if (connectionService == null || alertService == null) return System.currentTimeMillis(); + if (connectionService == null || alertService == null) return dateUtil.now(); return connectionService.getLastDataTime(); } @@ -569,6 +565,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { + if (detailedBolusInfo.insulin == 0 || detailedBolusInfo.carbs > 0) { + throw new IllegalArgumentException(detailedBolusInfo.toString(), new Exception()); + } PumpEnactResult result = new PumpEnactResult(getInjector()); double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01; if (insulin > 0) { @@ -579,7 +578,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusMessage.setDuration(0); bolusMessage.setExtendedAmount(0); bolusMessage.setImmediateAmount(insulin); - bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? R.string.key_disable_vibration_auto : R.string.key_disable_vibration, false)); + bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB ? R.string.key_insight_disable_vibration_auto : R.string.key_insight_disable_vibration, false)); bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); bolusCancelled = false; } @@ -591,25 +590,23 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusingEvent.setPercent(0); rxBus.send(bolusingEvent); int trials = 0; - InsightBolusID insightBolusID = new InsightBolusID(); - insightBolusID.bolusID = bolusID; - insightBolusID.timestamp = System.currentTimeMillis(); - insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); - databaseHelper.createOrUpdate(insightBolusID); - detailedBolusInfo.setBolusTimestamp(insightBolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(insightBolusID.id); - if (detailedBolusInfo.carbs > 0 && detailedBolusInfo.carbTime != 0) { - DetailedBolusInfo carbInfo = new DetailedBolusInfo(); - carbInfo.carbs = detailedBolusInfo.carbs; - carbInfo.setCarbsTimestamp(detailedBolusInfo.timestamp + detailedBolusInfo.carbTime * 60L * 1000L); - carbInfo.setPumpType(PumpType.USER); - treatmentsPlugin.addToHistoryTreatment(carbInfo, false); - detailedBolusInfo.carbTime = 0; - detailedBolusInfo.carbs = 0; - } - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + Long now = dateUtil.now(); + String serial = serialNumber(); + insightDbHelper.createOrUpdate( new InsightBolusID( + now, + serial, + bolusID, + null, + null + )); + InsightBolusID insightBolusID = insightDbHelper.getInsightBolusID(serial, bolusID, now); + pumpSync.syncBolusWithPumpId( + insightBolusID.getTimestamp(), + detailedBolusInfo.insulin, + detailedBolusInfo.getBolusType(), + insightBolusID.getId(), + PumpType.ACCU_CHEK_INSIGHT, + serialNumber()); while (true) { synchronized ($bolusLock) { if (bolusCancelled) break; @@ -657,10 +654,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai aapsLogger.error("Exception while delivering bolus", e); result.comment(ExceptionTranslator.getString(context, e)); } - } else if (detailedBolusInfo.carbs > 0) { - result.success(true).enacted(true); + result.bolusDelivered(insulin); } - result.carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(insulin); return result; } @@ -701,7 +696,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (cancelTBRResult.getSuccess()) { PumpEnactResult ebResult = setExtendedBolusOnly((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes, - sp.getBoolean(R.string.key_disable_vibration_auto, false)); + sp.getBoolean(R.string.key_insight_disable_vibration_auto, false)); if (ebResult.getSuccess()) { result.success(true) .enacted(true) @@ -780,7 +775,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) { PumpEnactResult result = cancelExtendedBolusOnly(); if (result.getSuccess()) - result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_disable_vibration, false)); + result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_insight_disable_vibration, false)); try { fetchStatus(); readHistory(); @@ -804,18 +799,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusMessage.setImmediateAmount(0); bolusMessage.setVibration(disableVibration); int bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); - InsightBolusID insightBolusID = new InsightBolusID(); - insightBolusID.bolusID = bolusID; - insightBolusID.timestamp = System.currentTimeMillis(); - insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); - databaseHelper.createOrUpdate(insightBolusID); - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = insightBolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = durationInMinutes; - extendedBolus.insulin = insulin; - extendedBolus.pumpId = insightBolusID.id; - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + insightDbHelper.createOrUpdate(new InsightBolusID( + dateUtil.now(), + serialNumber(), + bolusID, + null, + null + )); result.success(true).enacted(true).comment(R.string.virtualpump_resultok); } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while delivering extended bolus: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -836,7 +826,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai PumpEnactResult cancelEBResult = null; if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly(); PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); - result.success((cancelEBResult != null && cancelEBResult.getSuccess()) && cancelTBRResult.getSuccess()); + result.success((cancelEBResult == null || (cancelEBResult != null && cancelEBResult.getSuccess())) && cancelTBRResult.getSuccess()); result.enacted((cancelEBResult != null && cancelEBResult.getEnacted()) || cancelTBRResult.getEnacted()); result.comment(cancelEBResult != null ? cancelEBResult.getComment() : cancelTBRResult.getComment()); try { @@ -906,21 +896,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai connectionService.requestMessage(cancelBolusMessage).await(); confirmAlert(AlertType.WARNING_38); alertService.ignore(null); - InsightBolusID insightBolusID = databaseHelper.getInsightBolusID(connectionService.getPumpSystemIdentification().getSerialNumber(), - activeBolus.getBolusID(), System.currentTimeMillis()); + InsightBolusID insightBolusID = insightDbHelper.getInsightBolusID(serialNumber(), activeBolus.getBolusID(), dateUtil.now()); if (insightBolusID != null) { - ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(insightBolusID.id); - if (extendedBolus != null) { - extendedBolus.durationInMinutes = (int) ((System.currentTimeMillis() - extendedBolus.date) / 60000); - if (extendedBolus.durationInMinutes <= 0) { - final String _id = extendedBolus._id; -// if (NSUpload.isIdValid(_id)) -// nsUpload.removeCareportalEntryFromNS(_id); -// else uploadQueue.removeByMongoId("dbAdd", _id); - databaseHelper.delete(extendedBolus); - } else - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - } result.enacted(true).success(true); } } @@ -941,8 +918,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void confirmAlert(AlertType alertType) { try { - long started = System.currentTimeMillis(); - while (System.currentTimeMillis() - started < 10000) { + long started = dateUtil.now(); + while (dateUtil.now() - started < 10000) { GetActiveAlertMessage activeAlertMessage = connectionService.requestMessage(new GetActiveAlertMessage()).await(); if (activeAlertMessage.getAlert() != null) { if (activeAlertMessage.getAlert().getAlertType() == alertType) { @@ -963,9 +940,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public JSONObject getJSONStatus(@NonNull Profile profile, @NonNull String profileName, @NonNull String version) { - long now = System.currentTimeMillis(); + long now = dateUtil.now(); if (connectionService == null) return new JSONObject(); - if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { + if (dateUtil.now() - connectionService.getLastConnected() > (60 * 60 * 1000)) { return new JSONObject(); } @@ -1103,7 +1080,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai public String shortStatus(boolean veryShort) { StringBuilder ret = new StringBuilder(); if (connectionService.getLastConnected() != 0) { - long agoMsec = System.currentTimeMillis() - connectionService.getLastConnected(); + long agoMsec = dateUtil.now() - connectionService.getLastConnected(); int agoMin = (int) (agoMsec / 60d / 1000d); ret.append(resourceHelper.gs(R.string.short_status_last_connected, agoMin)).append("\n"); } @@ -1130,7 +1107,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @Override public boolean isFakingTempsByExtendedBoluses() { - return sp.getBoolean("insight_enable_tbr_emulation", false); + return sp.getBoolean(R.string.key_insight_enable_tbr_emulation, false); } @NonNull @Override @@ -1141,10 +1118,10 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void readHistory() { try { PumpTime pumpTime = connectionService.requestMessage(new GetDateTimeMessage()).await().getPumpTime(); - String pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); + String serial = serialNumber(); timeOffset = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() - parseDate(pumpTime.getYear(), pumpTime.getMonth(), pumpTime.getDay(), pumpTime.getHour(), pumpTime.getMinute(), pumpTime.getSecond()); - InsightHistoryOffset historyOffset = databaseHelper.getInsightHistoryOffset(pumpSerial); + InsightHistoryOffset historyOffset = insightDbHelper.getInsightHistoryOffset(serial); try { List historyEvents = new ArrayList<>(); if (historyOffset == null) { @@ -1156,7 +1133,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } else { StartReadingHistoryMessage startMessage = new StartReadingHistoryMessage(); startMessage.setDirection(HistoryReadingDirection.FORWARD); - startMessage.setOffset(historyOffset.offset + 1); + startMessage.setOffset(historyOffset.getOffset() + 1); connectionService.requestMessage(startMessage).await(); while (true) { List newEvents = connectionService.requestMessage(new ReadHistoryEventsMessage()).await().getHistoryEvents(); @@ -1166,12 +1143,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } Collections.sort(historyEvents); Collections.reverse(historyEvents); - if (historyOffset != null) processHistoryEvents(pumpSerial, historyEvents); + if (historyOffset != null) processHistoryEvents(serial, historyEvents); if (historyEvents.size() > 0) { - historyOffset = new InsightHistoryOffset(); - historyOffset.pumpSerial = pumpSerial; - historyOffset.offset = historyEvents.get(0).getEventPosition(); - databaseHelper.createOrUpdate(historyOffset); + insightDbHelper.createOrUpdate(new InsightHistoryOffset( + serial, + historyEvents.get(0).getEventPosition()) + ); } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while reading history: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); @@ -1202,22 +1179,50 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (!processHistoryEvent(serial, temporaryBasals, pumpStartedEvents, historyEvent)) break; Collections.reverse(temporaryBasals); + for (InsightPumpID pumpID : pumpStartedEvents) { - InsightPumpID stoppedEvent = databaseHelper.getPumpStoppedEvent(pumpID.pumpSerial, pumpID.timestamp); - if (stoppedEvent == null || stoppedEvent.eventType.equals("PumpPaused")) continue; - long tbrStart = stoppedEvent.timestamp + 10000; - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = (int) ((pumpID.timestamp - tbrStart) / 60000); - temporaryBasal.date = tbrStart; - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.percentRate = 0; - temporaryBasal.isAbsolute = false; + InsightPumpID stoppedEvent = insightDbHelper.getPumpStoppedEvent(pumpID.getPumpSerial(), pumpID.getTimestamp()); + if (stoppedEvent != null && stoppedEvent.getEventType().equals(EventType.PumpStopped)) { // Search if Stop event is after 15min of Pause + InsightPumpID pauseEvent = insightDbHelper.getPumpStoppedEvent(pumpID.getPumpSerial(), stoppedEvent.getTimestamp() - T.mins(1).msecs()); + if (pauseEvent != null && pauseEvent.getEventType().equals(EventType.PumpPaused) && (stoppedEvent.getTimestamp() - pauseEvent.getTimestamp() < T.mins(16).msecs())) { + stoppedEvent = pauseEvent; + stoppedEvent.setEventType(EventType.PumpStopped); + } + } + if (stoppedEvent == null || stoppedEvent.getEventType().equals(EventType.PumpPaused) || pumpID.getTimestamp() - stoppedEvent.getTimestamp() < 10000) + continue; + long tbrStart = stoppedEvent.getTimestamp() + 10000; + TemporaryBasal temporaryBasal = new TemporaryBasal( + tbrStart, + pumpID.getTimestamp() - tbrStart, + 0, + false, + PumpSync.TemporaryBasalType.NORMAL, + pumpID.getEventID(), + pumpID.getEventID()); temporaryBasals.add(temporaryBasal); } - temporaryBasals.sort((o1, o2) -> (int) (o1.date - o2.date)); - for (TemporaryBasal temporaryBasal : temporaryBasals) - treatmentsPlugin.addToHistoryTempBasal(temporaryBasal); + temporaryBasals.sort((o1, o2) -> (int) (o1.getTimestamp() - o2.getTimestamp())); + for (TemporaryBasal temporaryBasal : temporaryBasals) { + if (temporaryBasal.getDuration() == 0L) { // for Stop TBR event duration = 0L + pumpSync.syncStopTemporaryBasalWithPumpId( + temporaryBasal.getTimestamp(), + temporaryBasal.getPumpId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); + } + if (temporaryBasal.getRate() != 100.0){ + pumpSync.syncTemporaryBasalWithPumpId( + temporaryBasal.getTimestamp(), + temporaryBasal.getRate(), + temporaryBasal.getDuration(), + temporaryBasal.isAbsolute(), + temporaryBasal.getType(), + temporaryBasal.getPumpId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); + } + } } private boolean processHistoryEvent(String serial, List temporaryBasals, List pumpStartedEvents, HistoryEvent event) { @@ -1225,13 +1230,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai else if (event instanceof DateTimeChangedEvent) processDateTimeChangedEvent((DateTimeChangedEvent) event); else if (event instanceof CannulaFilledEvent) - processCannulaFilledEvent((CannulaFilledEvent) event); + processCannulaFilledEvent(serial, (CannulaFilledEvent) event); else if (event instanceof TotalDailyDoseEvent) - processTotalDailyDoseEvent((TotalDailyDoseEvent) event); - else if (event instanceof TubeFilledEvent) processTubeFilledEvent((TubeFilledEvent) event); + processTotalDailyDoseEvent(serial, (TotalDailyDoseEvent) event); + else if (event instanceof TubeFilledEvent) processTubeFilledEvent(serial, (TubeFilledEvent) event); else if (event instanceof SniffingDoneEvent) - processSniffingDoneEvent((SniffingDoneEvent) event); - else if (event instanceof PowerUpEvent) processPowerUpEvent((PowerUpEvent) event); + processSniffingDoneEvent(serial, (SniffingDoneEvent) event); + else if (event instanceof PowerUpEvent) processPowerUpEvent(serial, (PowerUpEvent) event); else if (event instanceof OperatingModeChangedEvent) processOperatingModeChangedEvent(serial, pumpStartedEvents, (OperatingModeChangedEvent) event); else if (event instanceof StartOfTBREvent) @@ -1253,14 +1258,15 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai timeOffset -= timeAfter - timeBefore; } - private void processCannulaFilledEvent(CannulaFilledEvent event) { - if (!sp.getBoolean("insight_log_site_changes", false)) return; + private void processCannulaFilledEvent(String serial, CannulaFilledEvent event) { + if (!sp.getBoolean(R.string.key_insight_log_site_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); + if (event.getAmount() > 0.0) // Don't record event if amount is null => Fix Site Change with Insight v3 (event is always sent when Reservoir is changed) + uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE); } - private void processTotalDailyDoseEvent(TotalDailyDoseEvent event) { + private void processTotalDailyDoseEvent(String serial, TotalDailyDoseEvent event) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(0)); calendar.set(Calendar.YEAR, event.getTotalYear()); @@ -1271,28 +1277,28 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getBolusTotal(), event.getBasalTotal(), 0.0, // will be calculated automatically - null, + event.getEventPosition(), PumpType.ACCU_CHEK_INSIGHT, - serialNumber() - ); + serial); } - private void processTubeFilledEvent(TubeFilledEvent event) { - if (!sp.getBoolean("insight_log_tube_changes", false)) return; + private void processTubeFilledEvent(String serial, TubeFilledEvent event) { + if (!sp.getBoolean(R.string.key_insight_log_tube_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); + if (event.getAmount() > 0.0) // Don't record event if amount is null + logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); } - private void processSniffingDoneEvent(SniffingDoneEvent event) { - if (!sp.getBoolean("insight_log_reservoir_changes", false)) return; + private void processSniffingDoneEvent(String serial, SniffingDoneEvent event) { + if (!sp.getBoolean(R.string.key_insight_log_reservoir_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE); } - private void processPowerUpEvent(PowerUpEvent event) { - if (!sp.getBoolean("insight_log_battery_changes", false)) return; + private void processPowerUpEvent(String serial, PowerUpEvent event) { + if (!sp.getBoolean(R.string.key_insight_log_battery_changes, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE); @@ -1301,102 +1307,110 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void processOperatingModeChangedEvent(String serial, List pumpStartedEvents, OperatingModeChangedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID(); - pumpID.eventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.timestamp = timestamp; + InsightPumpID pumpID = new InsightPumpID( + timestamp, + EventType.None, + serial, + event.getEventPosition()); switch (event.getNewValue()) { case STARTED: - pumpID.eventType = "PumpStarted"; + pumpID.setEventType(EventType.PumpStarted); pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_started)); break; case STOPPED: - pumpID.eventType = "PumpStopped"; + pumpID.setEventType(EventType.PumpStopped); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); break; case PAUSED: - pumpID.eventType = "PumpPaused"; + pumpID.setEventType(EventType.PumpPaused); if (sp.getBoolean("insight_log_operating_mode_changes", false)) logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); break; } - databaseHelper.createOrUpdate(pumpID); + insightDbHelper.createOrUpdate(pumpID); } private void processStartOfTBREvent(String serial, List temporaryBasals, StartOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID(); - pumpID.eventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.timestamp = timestamp; - pumpID.eventType = "StartOfTBR"; - databaseHelper.createOrUpdate(pumpID); - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = event.getDuration(); - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.percentRate = event.getAmount(); - temporaryBasal.isAbsolute = false; - temporaryBasal.date = timestamp; - temporaryBasals.add(temporaryBasal); + insightDbHelper.createOrUpdate(new InsightPumpID( + timestamp, + EventType.StartOfTBR, + serial, + event.getEventPosition())); + temporaryBasals.add(new TemporaryBasal( + timestamp, + T.mins(event.getDuration()).msecs(), + event.getAmount(), + false, + PumpSync.TemporaryBasalType.NORMAL, + event.getEventPosition(), + event.getEventPosition())); } private void processEndOfTBREvent(String serial, List temporaryBasals, EndOfTBREvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightPumpID pumpID = new InsightPumpID(); - pumpID.eventID = event.getEventPosition(); - pumpID.pumpSerial = serial; - pumpID.eventType = "EndOfTBR"; - pumpID.timestamp = timestamp; - databaseHelper.createOrUpdate(pumpID); - TemporaryBasal temporaryBasal = new TemporaryBasal(getInjector()); - temporaryBasal.durationInMinutes = 0; - temporaryBasal.source = Source.PUMP; - temporaryBasal.pumpId = pumpID.id; - temporaryBasal.date = timestamp - 1500L; - temporaryBasals.add(temporaryBasal); + insightDbHelper.createOrUpdate(new InsightPumpID( + timestamp - 1500L, + EventType.EndOfTBR, + serial, + event.getEventPosition())); + + temporaryBasals.add(new PumpSync.PumpState.TemporaryBasal( + timestamp - 1500L, + 0L, + 100.0, + false, + PumpSync.TemporaryBasalType.NORMAL, + event.getEventPosition(), + event.getEventPosition())); } private void processBolusProgrammedEvent(String serial, BolusProgrammedEvent event) { long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; - InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID != null && bolusID.endID != null) { - bolusID.startID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); + InsightBolusID bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); + if (bolusID != null && bolusID.getEndID() != null) { + bolusID.setStartID(event.getEventPosition()); + insightDbHelper.createOrUpdate(bolusID); return; } - if (bolusID == null || bolusID.startID != null) { - bolusID = new InsightBolusID(); - bolusID.timestamp = timestamp; - bolusID.bolusID = event.getBolusID(); - bolusID.pumpSerial = serial; + if (bolusID == null || bolusID.getStartID() != null) { //In rare edge cases two boluses can share the same ID + insightDbHelper.createOrUpdate(new InsightBolusID( + timestamp, + serial, + event.getBolusID(), + event.getEventPosition(), + null + )); + bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); } - bolusID.startID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); + bolusID.setStartID(event.getEventPosition()); + insightDbHelper.createOrUpdate(bolusID); + if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.timestamp = bolusID.timestamp; - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + pumpSync.syncBolusWithPumpId( + bolusID.getTimestamp(), + event.getImmediateAmount(), + null, + bolusID.getId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); + if (profileFunction.getProfile(bolusID.getTimestamp()) != null) + pumpSync.syncExtendedBolusWithPumpId( + bolusID.getTimestamp(), + event.getExtendedAmount(), + T.mins(event.getDuration()).msecs(), + isFakingTempsByExtendedBoluses(), + bolusID.getId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } } @@ -1405,48 +1419,42 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; long startTimestamp = parseRelativeDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond(), event.getStartHour(), event.getStartMinute(), event.getStartSecond()) + timeOffset; - InsightBolusID bolusID = databaseHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); - if (bolusID == null || bolusID.endID != null) { - bolusID = new InsightBolusID(); - bolusID.timestamp = startTimestamp; - bolusID.bolusID = event.getBolusID(); - bolusID.pumpSerial = serial; + InsightBolusID bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), timestamp); + if (bolusID == null || bolusID.getEndID() != null) { // TODO() Check if test EndID is necessary + bolusID = new InsightBolusID( + startTimestamp, + serial, + event.getBolusID(), + bolusID == null ? event.getEventPosition() : bolusID.getStartID(), + event.getEventPosition()); } - bolusID.endID = event.getEventPosition(); - databaseHelper.createOrUpdate(bolusID); + bolusID.setEndID(event.getEventPosition()); + insightDbHelper.createOrUpdate(bolusID); + bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) { - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.setBolusTimestamp(bolusID.timestamp); - detailedBolusInfo.setPumpType(PumpType.ACCU_CHEK_INSIGHT); - detailedBolusInfo.setPumpSerial(serialNumber()); - detailedBolusInfo.setBolusPumpId(bolusID.id); - detailedBolusInfo.insulin = event.getImmediateAmount(); - treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); + pumpSync.syncBolusWithPumpId( + bolusID.getTimestamp(), + event.getImmediateAmount(), + null, + bolusID.getId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) { - if (event.getDuration() == 0) { - ExtendedBolus extendedBolus = databaseHelper.getExtendedBolusByPumpId(bolusID.id); - if (extendedBolus != null) { - final String _id = extendedBolus._id; -// if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id); -// else uploadQueue.removeByMongoId("dbAdd", _id); - databaseHelper.delete(extendedBolus); - } - } else { - ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); - extendedBolus.date = bolusID.timestamp; - extendedBolus.source = Source.PUMP; - extendedBolus.durationInMinutes = event.getDuration(); - extendedBolus.insulin = event.getExtendedAmount(); - extendedBolus.pumpId = bolusID.id; - if (profileFunction.getProfile(extendedBolus.date) != null) - treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); - } + if (event.getDuration() > 0 && profileFunction.getProfile(bolusID.getTimestamp()) != null) + pumpSync.syncExtendedBolusWithPumpId( + bolusID.getTimestamp(), + event.getExtendedAmount(), + T.mins(event.getDuration()).msecs(), + isFakingTempsByExtendedBoluses(), + bolusID.getId(), + PumpType.ACCU_CHEK_INSIGHT, + serial); } } private void processOccurrenceOfAlertEvent(OccurrenceOfAlertEvent event) { - if (!sp.getBoolean("insight_log_alerts", false)) return; + if (!sp.getBoolean(R.string.key_insight_log_alerts, false)) return; long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; Integer code = null; diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java index cddceb1ddd..40edeebc7b 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/connection_service/InsightConnectionService.java @@ -20,6 +20,7 @@ import java.util.List; import javax.inject.Inject; import dagger.android.DaggerService; +import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.insight.app_layer.AppLayerMessage; @@ -141,10 +142,10 @@ public class InsightConnectionService extends DaggerService implements Connectio } private void increaseRecoveryDuration() { - long maxRecoveryDuration = sp.getInt("insight_max_recovery_duration", 20); + long maxRecoveryDuration = sp.getInt(R.string.key_insight_max_recovery_duration, 20); maxRecoveryDuration = Math.min(maxRecoveryDuration, 20); maxRecoveryDuration = Math.max(maxRecoveryDuration, 0); - long minRecoveryDuration = sp.getInt("insight_min_recovery_duration", 5); + long minRecoveryDuration = sp.getInt(R.string.key_insight_min_recovery_duration, 5); minRecoveryDuration = Math.min(minRecoveryDuration, 20); minRecoveryDuration = Math.max(minRecoveryDuration, 0); recoveryDuration += 1000; @@ -295,7 +296,7 @@ public class InsightConnectionService extends DaggerService implements Connectio setState(InsightState.DISCONNECTED); cleanup(true); } else if (state != InsightState.DISCONNECTED) { - long disconnectTimeout = sp.getInt("insight_disconnect_delay", 5); + long disconnectTimeout = sp.getInt(R.string.key_insight_disconnect_delay, 5); disconnectTimeout = Math.min(disconnectTimeout, 15); disconnectTimeout = Math.max(disconnectTimeout, 0); aapsLogger.info(LTag.PUMP, "Last connection lock released, will disconnect in " + disconnectTimeout + " seconds"); diff --git a/insight/src/main/res/values/strings.xml b/insight/src/main/res/values/strings.xml index 8b235730bc..dd12e644a3 100644 --- a/insight/src/main/res/values/strings.xml +++ b/insight/src/main/res/values/strings.xml @@ -31,10 +31,20 @@ Tube changed Sight Insight Pump Alerts - insight_disable_vibration Disable vibrations on manual bolus delivery For bolus and extended bolus (only available with Insight firmware 3.x) - insight_disable_vibration_auto + insight_disable_vibration + insight_disable_vibration_auto + insight_enable_tbr_emulation + insight_log_site_changes + insight_log_tube_changes + insight_log_reservoir_changes + insight_log_battery_changes + insight_log_operating_mode_changes + insight_log_alerts + insight_min_recovery_duration + insight_max_recovery_duration + insight_disconnect_delay Disable vibrations on automated bolus delivery For SMB and Temp Basal with TBR emulation (only available with Insight firmware 3.x) Timeout during handshake - reset bluetooth diff --git a/insight/src/main/res/xml/pref_insight_local_full.xml b/insight/src/main/res/xml/pref_insight_local_full.xml index 1329db7de3..69fbec43a0 100644 --- a/insight/src/main/res/xml/pref_insight_local_full.xml +++ b/insight/src/main/res/xml/pref_insight_local_full.xml @@ -15,68 +15,68 @@ diff --git a/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml b/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml index b73c01f1f7..ca7743ec3a 100644 --- a/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml +++ b/insight/src/main/res/xml/pref_insight_local_pumpcontrol.xml @@ -15,62 +15,62 @@