From b04862f602585f7cb9052e2f7019e654ec6c46c5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 4 Feb 2021 18:22:58 +0100 Subject: [PATCH 1/2] database module --- app/build.gradle | 1 + build.gradle | 6 +- database/.gitignore | 1 + database/build.gradle | 60 ++++++++ database/consumer-rules.pro | 0 database/proguard-rules.pro | 21 +++ .../database/ExampleInstrumentedTest.kt | 25 +++ database/src/main/AndroidManifest.xml | 2 + .../androidaps/database/AppDatabase.kt | 55 +++++++ .../androidaps/database/AppRepository.kt | 118 +++++++++++++++ .../androidaps/database/Converters.kt | 142 ++++++++++++++++++ .../androidaps/database/DatabaseModule.kt | 24 +++ .../database/DelegatedAppDatabase.kt | 27 ++++ .../androidaps/database/TableNames.kt | 19 +++ .../androidaps/database/daos/APSResultDao.kt | 18 +++ .../database/daos/APSResultLinkDao.kt | 19 +++ .../database/daos/BolusCalculatorResultDao.kt | 18 +++ .../androidaps/database/daos/BolusDao.kt | 19 +++ .../androidaps/database/daos/CarbsDao.kt | 18 +++ .../daos/EffectiveProfileSwitchDao.kt | 18 +++ .../database/daos/ExtendedBolusDao.kt | 20 +++ .../database/daos/GlucoseValueDao.kt | 42 ++++++ .../androidaps/database/daos/MealLinkDao.kt | 18 +++ .../database/daos/MultiwaveBolusLinkDao.kt | 19 +++ .../database/daos/PreferenceChangeDao.kt | 16 ++ .../database/daos/ProfileSwitchDao.kt | 37 +++++ .../database/daos/TemporaryBasalDao.kt | 21 +++ .../database/daos/TemporaryTargetDao.kt | 38 +++++ .../database/daos/TherapyEventDao.kt | 24 +++ .../database/daos/TotalDailyDoseDao.kt | 18 +++ .../androidaps/database/daos/TraceableDao.kt | 60 ++++++++ .../database/daos/VersionChangeDao.kt | 19 +++ .../daos/delegated/DelegatedAPSResultDao.kt | 18 +++ .../delegated/DelegatedAPSResultLinkDao.kt | 18 +++ .../DelegatedBolusCalculatorResultDao.kt | 18 +++ .../daos/delegated/DelegatedBolusDao.kt | 18 +++ .../daos/delegated/DelegatedCarbsDao.kt | 18 +++ .../database/daos/delegated/DelegatedDao.kt | 8 + .../DelegatedEffectiveProfileSwitchDao.kt | 18 +++ .../delegated/DelegatedExtendedBolusDao.kt | 18 +++ .../delegated/DelegatedGlucoseValueDao.kt | 18 +++ .../daos/delegated/DelegatedMealLinkDao.kt | 18 +++ .../DelegatedMultiwaveBolusLinkDao.kt | 18 +++ .../delegated/DelegatedPreferenceChangeDao.kt | 14 ++ .../delegated/DelegatedProfileSwitchDao.kt | 18 +++ .../delegated/DelegatedTemporaryBasalDao.kt | 18 +++ .../delegated/DelegatedTemporaryTargetDao.kt | 18 +++ .../delegated/DelegatedTherapyEventDao.kt | 18 +++ .../delegated/DelegatedTotalDailyDoseDao.kt | 18 +++ .../delegated/DelegatedVersionChangeDao.kt | 14 ++ .../ProfileSwitchDaoWorkaround.java | 23 +++ .../workaround/TraceableDaoWorkaround.java | 31 ++++ .../daos/workaround/package-info.java | 5 + .../androidaps/database/data/Block.kt | 11 ++ .../androidaps/database/data/TargetBlock.kt | 11 ++ .../embedments/InsulinConfiguration.kt | 7 + .../database/embedments/InterfaceIDs.kt | 20 +++ .../androidaps/database/entities/APSResult.kt | 42 ++++++ .../database/entities/APSResultLink.kt | 42 ++++++ .../androidaps/database/entities/Bolus.kt | 39 +++++ .../entities/BolusCalculatorResult.kt | 53 +++++++ .../androidaps/database/entities/Carbs.kt | 29 ++++ .../entities/EffectiveProfileSwitch.kt | 30 ++++ .../database/entities/ExtendedBolus.kt | 30 ++++ .../database/entities/GlucoseValue.kt | 100 ++++++++++++ .../androidaps/database/entities/MealLink.kt | 54 +++++++ .../database/entities/MultiwaveBolusLink.kt | 37 +++++ .../database/entities/PreferenceChange.kt | 18 +++ .../database/entities/ProfileSwitch.kt | 46 ++++++ .../database/entities/TemporaryBasal.kt | 38 +++++ .../database/entities/TemporaryTarget.kt | 68 +++++++++ .../database/entities/TherapyEvent.kt | 63 ++++++++ .../database/entities/TotalDailyDose.kt | 30 ++++ .../database/entities/VersionChange.kt | 20 +++ .../androidaps/database/interfaces/DBEntry.kt | 5 + .../interfaces/DBEntryWithDuration.kt | 7 + .../database/interfaces/DBEntryWithTime.kt | 6 + .../interfaces/DBEntryWithTimeAndDuration.kt | 14 ++ .../database/interfaces/TraceableDBEntry.kt | 28 ++++ ...lCurrentTemporaryTargetIfAnyTransaction.kt | 16 ++ .../transactions/CgmSourceTransaction.kt | 74 +++++++++ .../InsertGlucoseValueTransaction.kt | 13 ++ ...poraryTargetAndCancelCurrentTransaction.kt | 21 +++ .../InvalidateGlucoseValueTransaction.kt | 15 ++ .../InvalidateTemporaryTargetTransaction.kt | 10 ++ .../database/transactions/Transaction.kt | 18 +++ .../UpdateGlucoseValueTransaction.kt | 13 ++ .../UpdateTemporaryTargetTransaction.kt | 13 ++ .../transactions/VersionChangeTransaction.kt | 30 ++++ .../nightscout/database/ExampleUnitTest.kt | 18 +++ settings.gradle | 1 + 91 files changed, 2395 insertions(+), 3 deletions(-) create mode 100644 database/.gitignore create mode 100644 database/build.gradle create mode 100644 database/consumer-rules.pro create mode 100644 database/proguard-rules.pro create mode 100644 database/src/androidTest/java/info/nightscout/database/ExampleInstrumentedTest.kt create mode 100644 database/src/main/AndroidManifest.xml create mode 100644 database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/Converters.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/DatabaseModule.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/DelegatedAppDatabase.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/TableNames.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/APSResultDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/APSResultLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/MealLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/MultiwaveBolusLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/PreferenceChangeDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/VersionChangeDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusCalculatorResultDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedCarbsDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedEffectiveProfileSwitchDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedExtendedBolusDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedGlucoseValueDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMealLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMultiwaveBolusLinkDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedPreferenceChangeDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedProfileSwitchDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryBasalDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryTargetDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTherapyEventDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTotalDailyDoseDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedVersionChangeDao.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/workaround/ProfileSwitchDaoWorkaround.java create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/workaround/TraceableDaoWorkaround.java create mode 100644 database/src/main/java/info/nightscout/androidaps/database/daos/workaround/package-info.java create mode 100644 database/src/main/java/info/nightscout/androidaps/database/data/Block.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/data/TargetBlock.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/embedments/InsulinConfiguration.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/APSResult.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/APSResultLink.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/MealLink.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/MultiwaveBolusLink.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/PreferenceChange.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/entities/VersionChange.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntry.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithDuration.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTime.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTimeAndDuration.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/interfaces/TraceableDBEntry.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/CancelCurrentTemporaryTargetIfAnyTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/InsertGlucoseValueTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/InsertTemporaryTargetAndCancelCurrentTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateGlucoseValueTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateTemporaryTargetTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/Transaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateGlucoseValueTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateTemporaryTargetTransaction.kt create mode 100644 database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt create mode 100644 database/src/test/java/info/nightscout/database/ExampleUnitTest.kt diff --git a/app/build.gradle b/app/build.gradle index 04fb0b520d..8d71d287b1 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -235,6 +235,7 @@ dependencies { wearApp project(':wear') implementation project(':core') + implementation project(':database') implementation project(':dana') implementation project(':danars') implementation project(':danar') diff --git a/build.gradle b/build.gradle index 977c6fe4ce..6f9baba6ee 100644 --- a/build.gradle +++ b/build.gradle @@ -2,12 +2,12 @@ buildscript { ext { - kotlin_version = '1.4.21' + kotlin_version = '1.4.30' coreVersion = '1.3.2' - rxjava_version = '2.2.19' + rxjava_version = '2.2.20' rxandroid_version = '2.1.1' rxkotlin_version = '2.4.0' - room_version = '2.2.5' + room_version = '2.2.6' lifecycle_version = '2.2.0' dagger_version = '2.31.2' coroutinesVersion = '1.3.7' diff --git a/database/.gitignore b/database/.gitignore new file mode 100644 index 0000000000..796b96d1c4 --- /dev/null +++ b/database/.gitignore @@ -0,0 +1 @@ +/build diff --git a/database/build.gradle b/database/build.gradle new file mode 100644 index 0000000000..5c86517f06 --- /dev/null +++ b/database/build.gradle @@ -0,0 +1,60 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' +apply plugin: 'kotlin-android-extensions' + +android { + compileSdkVersion 28 + + defaultConfig { + minSdkVersion 23 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + debug { + } + firebaseDisable { + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } +} + +dependencies { + implementation "androidx.core:core-ktx:$coreVersion" + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + + implementation "io.reactivex.rxjava2:rxjava:$rxjava_version" + implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version" + implementation("io.reactivex.rxjava2:rxkotlin:$rxkotlin_version") + + implementation "com.google.code.gson:gson:2.8.6" + + api "androidx.room:room-runtime:$room_version" + kapt "androidx.room:room-compiler:$room_version" + implementation "androidx.room:room-ktx:$room_version" + implementation "androidx.room:room-rxjava2:$room_version" + + implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" + + implementation "com.google.dagger:dagger-android:$dagger_version" + implementation "com.google.dagger:dagger-android-support:$dagger_version" + annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version" + annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version" + kapt "com.google.dagger:dagger-android-processor:$dagger_version" + kapt "com.google.dagger:dagger-compiler:$dagger_version" +} diff --git a/database/consumer-rules.pro b/database/consumer-rules.pro new file mode 100644 index 0000000000..e69de29bb2 diff --git a/database/proguard-rules.pro b/database/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/database/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/database/src/androidTest/java/info/nightscout/database/ExampleInstrumentedTest.kt b/database/src/androidTest/java/info/nightscout/database/ExampleInstrumentedTest.kt new file mode 100644 index 0000000000..d218cd479f --- /dev/null +++ b/database/src/androidTest/java/info/nightscout/database/ExampleInstrumentedTest.kt @@ -0,0 +1,25 @@ +package info.nightscout.database + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("info.nightscout.database.test", appContext.packageName) + } +} \ No newline at end of file diff --git a/database/src/main/AndroidManifest.xml b/database/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..fa796cae8a --- /dev/null +++ b/database/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt new file mode 100644 index 0000000000..ffe65a8bdc --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/AppDatabase.kt @@ -0,0 +1,55 @@ +package info.nightscout.androidaps.database + +import androidx.room.Database +import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import info.nightscout.androidaps.database.daos.* +import info.nightscout.androidaps.database.entities.* +import info.nightscout.androidaps.database.entities.APSResultLink +import info.nightscout.androidaps.database.entities.MealLink +import info.nightscout.androidaps.database.entities.MultiwaveBolusLink + +const val DATABASE_VERSION = 1 + +@Database(version = DATABASE_VERSION, entities = arrayOf(APSResult::class, Bolus::class, BolusCalculatorResult::class, Carbs::class, + EffectiveProfileSwitch::class, ExtendedBolus::class, GlucoseValue::class, ProfileSwitch::class, + TemporaryBasal::class, TemporaryTarget::class, TherapyEvent::class, TotalDailyDose::class, + APSResultLink::class, MealLink::class, MultiwaveBolusLink::class, PreferenceChange::class, VersionChange::class)) +@TypeConverters(Converters::class) +internal abstract class AppDatabase : RoomDatabase() { + + abstract val glucoseValueDao: GlucoseValueDao + + abstract val therapyEventDao: TherapyEventDao + + abstract val temporaryBasalDao: TemporaryBasalDao + + abstract val bolusDao: BolusDao + + abstract val extendedBolusDao: ExtendedBolusDao + + abstract val multiwaveBolusLinkDao: MultiwaveBolusLinkDao + + abstract val totalDailyDoseDao: TotalDailyDoseDao + + abstract val carbsDao: CarbsDao + + abstract val mealLinkDao: MealLinkDao + + abstract val temporaryTargetDao: TemporaryTargetDao + + abstract val apsResultLinkDao: APSResultLinkDao + + abstract val bolusCalculatorResultDao: BolusCalculatorResultDao + + abstract val effectiveProfileSwitchDao: EffectiveProfileSwitchDao + + abstract val profileSwitchDao: ProfileSwitchDao + + abstract val apsResultDao: APSResultDao + + abstract val versionChangeDao: VersionChangeDao + + abstract val preferenceChangeDao: PreferenceChangeDao + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt new file mode 100644 index 0000000000..0a13455b06 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -0,0 +1,118 @@ +package info.nightscout.androidaps.database + +import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.database.entities.TemporaryTarget +import info.nightscout.androidaps.database.interfaces.DBEntry +import info.nightscout.androidaps.database.transactions.Transaction +import io.reactivex.Completable +import io.reactivex.Maybe +import io.reactivex.Observable +import io.reactivex.Single +import io.reactivex.schedulers.Schedulers +import io.reactivex.subjects.PublishSubject +import java.util.concurrent.Callable +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class AppRepository @Inject internal constructor( + internal val database: AppDatabase +) { + + private val changeSubject = PublishSubject.create>() + + fun changeObservable(): Observable> = changeSubject.subscribeOn(Schedulers.io()) + + val databaseVersion = DATABASE_VERSION + + /** + * Executes a transaction ignoring its result + * Runs on IO scheduler + */ + fun runTransaction(transaction: Transaction): Completable { + val changes = mutableListOf() + return Completable.fromCallable { + database.runInTransaction { + transaction.database = DelegatedAppDatabase(changes, database) + transaction.run() + } + }.subscribeOn(Schedulers.io()).doOnComplete { + changeSubject.onNext(changes) + } + } + + /** + * Executes a transaction and returns its result + * Runs on IO scheduler + */ + fun runTransactionForResult(transaction: Transaction): Single { + val changes = mutableListOf() + return Single.fromCallable { + database.runInTransaction(Callable { + transaction.database = DelegatedAppDatabase(changes, database) + transaction.run() + }) + }.subscribeOn(Schedulers.io()).doOnSuccess { + changeSubject.onNext(changes) + } + } + + fun clearDatabases() = database.clearAllTables() + + //BG READINGS -- only valid records + fun compatGetBgReadingsDataFromTime(timestamp: Long, ascending: Boolean) = + database.glucoseValueDao.compatGetBgReadingsDataFromTime(timestamp) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + fun compatGetBgReadingsDataFromTime(start: Long, end: Long, ascending: Boolean) = + database.glucoseValueDao.compatGetBgReadingsDataFromTime(start, end) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + //BG READINGS -- including invalid/history records + fun findBgReadingByNSIdSingle(nsId: String): Single> = + database.glucoseValueDao.findByNSIdMaybe(nsId).toWrappedSingle() + + fun getModifiedBgReadingsDataFromId(lastId: Long) = + database.glucoseValueDao.getModifiedFrom(lastId) + .subscribeOn(Schedulers.io()) + + fun getBgReadingsCorrespondingLastHistoryRecord(lastId: Long) = + database.glucoseValueDao.getLastHistoryRecord(lastId) + + @Suppress("unused") // debug purpose only + fun getAllBgReadingsStartingFrom(lastId: Long) = + database.glucoseValueDao.getAllStartingFrom(lastId) + .subscribeOn(Schedulers.io()) + + // TEMP TARGETS + fun compatGetTemporaryTargetData() = + database.temporaryTargetDao.compatGetTemporaryTargetData() + + fun compatGetTemporaryTargetDataFromTime(timestamp: Long, ascending: Boolean) = + database.temporaryTargetDao.compatGetTemporaryTargetDataFromTime(timestamp) + .map { if (!ascending) it.reversed() else it } + .subscribeOn(Schedulers.io()) + + fun findTemporaryTargetByNSIdSingle(nsId: String): Single> = + database.temporaryTargetDao.findByNSIdMaybe(nsId).toWrappedSingle() + + fun getModifiedTemporaryTargetsDataFromId(lastId: Long) = + database.temporaryTargetDao.getModifiedFrom(lastId) + .subscribeOn(Schedulers.io()) + + fun getTemporaryTargetsCorrespondingLastHistoryRecord(lastId: Long) = + database.temporaryTargetDao.getLastHistoryRecord(lastId) + +} + +inline fun Maybe.toWrappedSingle(): Single> = + this.map { ValueWrapper.Existing(it) as ValueWrapper } + .switchIfEmpty(Maybe.just(ValueWrapper.Absent())) + .toSingle() + +sealed class ValueWrapper { + data class Existing(val value: T) : ValueWrapper() + class Absent : ValueWrapper() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/Converters.kt b/database/src/main/java/info/nightscout/androidaps/database/Converters.kt new file mode 100644 index 0000000000..cdac1563d5 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/Converters.kt @@ -0,0 +1,142 @@ +package info.nightscout.androidaps.database + +import androidx.room.TypeConverter +import info.nightscout.androidaps.database.data.Block +import info.nightscout.androidaps.database.data.TargetBlock +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.entities.* +import org.json.JSONArray +import org.json.JSONObject + +class Converters { + + @TypeConverter + fun fromBolusType(bolusType: Bolus.Type?) = bolusType?.name + + @TypeConverter + fun toBolusType(bolusType: String?) = bolusType?.let { Bolus.Type.valueOf(it) } + + @TypeConverter + fun fromTrendArrow(trendArrow: GlucoseValue.TrendArrow?) = trendArrow?.name + + @TypeConverter + fun toTrendArrow(trendArrow: String?) = trendArrow?.let { GlucoseValue.TrendArrow.valueOf(it) } + + @TypeConverter + fun fromSourceSensor(sourceSensor: GlucoseValue.SourceSensor?) = sourceSensor?.name + + @TypeConverter + fun toSourceSensor(sourceSensor: String?) = sourceSensor?.let { GlucoseValue.SourceSensor.valueOf(it) } + + @TypeConverter + fun fromTBRType(tbrType: TemporaryBasal.Type?) = tbrType?.name + + @TypeConverter + fun toTBRType(tbrType: String?) = tbrType?.let { TemporaryBasal.Type.valueOf(it) } + + @TypeConverter + fun fromTempTargetReason(tempTargetReason: TemporaryTarget.Reason?) = tempTargetReason?.name + + @TypeConverter + fun toTempTargetReason(tempTargetReason: String?) = tempTargetReason?.let { TemporaryTarget.Reason.valueOf(it) } + + @TypeConverter + fun fromTherapyEventType(therapyEventType: TherapyEvent.Type?) = therapyEventType?.name + + @TypeConverter + fun toTherapyEventType(therapyEventType: String?) = therapyEventType?.let { TherapyEvent.Type.valueOf(it) } + + @TypeConverter + fun fromGlucoseUnit(glucoseUnit: ProfileSwitch.GlucoseUnit?) = glucoseUnit?.name + + @TypeConverter + fun toGlucoseUnit(glucoseUnit: String?) = glucoseUnit?.let { ProfileSwitch.GlucoseUnit.valueOf(it) } + + @TypeConverter + fun fromPumpType(pumpType: InterfaceIDs.PumpType?) = pumpType?.name + + @TypeConverter + fun toPumpType(pumpType: String?) = pumpType?.let { InterfaceIDs.PumpType.valueOf(it) } + + @TypeConverter + fun fromAlgorithm(algorithm: APSResult.Algorithm?) = algorithm?.name + + @TypeConverter + fun toAlgorithm(algorithm: String?) = algorithm?.let { APSResult.Algorithm.valueOf(it) } + + @TypeConverter + fun fromListOfBlocks(blocks: List?): String? { + if (blocks == null) return null + val jsonArray = JSONArray() + blocks.forEach { + val jsonObject = JSONObject() + jsonObject.put("duration", it.duration) + jsonObject.put("amount", it.amount) + jsonArray.put(jsonObject) + } + return jsonArray.toString() + } + + @TypeConverter + fun toListOfBlocks(jsonString: String?): List? { + if (jsonString == null) return null + val jsonArray = JSONArray(jsonString) + val list = mutableListOf() + for (i in 0 until jsonArray.length()) { + val jsonObject = jsonArray.getJSONObject(i) + list.add(Block(jsonObject.getLong("duration"), jsonObject.getDouble("amount"))) + } + return list + } + + @TypeConverter + fun anyToString(value: Any?) = when (value) { + null -> null + is String -> "S$value" + is Int -> "I$value" + is Long -> "L$value" + is Boolean -> "B$value" + is Float -> "F$value" + else -> throw IllegalArgumentException("Type not supported") + } + + @TypeConverter + fun stringToAny(value: String?): Any? = when { + value == null -> null + value.startsWith("S") -> value.substring(1) + value.startsWith("I") -> value.substring(1).toInt() + value.startsWith("L") -> value.substring(1).toLong() + value.startsWith("B") -> value.substring(1).toBoolean() + value.startsWith("F") -> value.substring(1).toFloat() + else -> throw IllegalArgumentException("Type not supported") + } + + @TypeConverter + fun fromListOfTargetBlocks(blocks: List?): String? { + if (blocks == null) return null + val jsonArray = JSONArray() + blocks.forEach { + val jsonObject = JSONObject() + jsonObject.put("duration", it.duration) + jsonObject.put("lowTarget", it.lowTarget) + jsonObject.put("highTarget", it.highTarget) + jsonArray.put(jsonObject) + } + return jsonArray.toString() + } + + @TypeConverter + fun toListOfTargetBlocks(jsonString: String?): List? { + if (jsonString == null) return null + val jsonArray = JSONArray(jsonString) + val list = mutableListOf() + for (i in 0 until jsonArray.length()) { + val jsonObject = jsonArray.getJSONObject(i) + list.add(TargetBlock(jsonObject.getLong("duration"), + jsonObject.getDouble("lowTarget"), + jsonObject.getDouble("highTarget"))) + } + return list + } + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/DatabaseModule.kt b/database/src/main/java/info/nightscout/androidaps/database/DatabaseModule.kt new file mode 100644 index 0000000000..dda8cf3917 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/DatabaseModule.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.database + +import android.content.Context +import androidx.room.Room +import dagger.Module +import dagger.Provides +import javax.inject.Qualifier +import javax.inject.Singleton + +@Module +open class DatabaseModule { + + @DbFileName + @Provides + fun dbFileName() = "androidaps.db" + + @Provides + @Singleton + internal fun provideAppDatabase(context: Context, @DbFileName fileName: String) = + Room.databaseBuilder(context, AppDatabase::class.java, fileName).build() + + @Qualifier + annotation class DbFileName +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/DelegatedAppDatabase.kt b/database/src/main/java/info/nightscout/androidaps/database/DelegatedAppDatabase.kt new file mode 100644 index 0000000000..1a6e3206b0 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/DelegatedAppDatabase.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.database + +import info.nightscout.androidaps.database.daos.* +import info.nightscout.androidaps.database.daos.delegated.* +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedAppDatabase(val changes: MutableList, val database: AppDatabase) { + + val glucoseValueDao: GlucoseValueDao = DelegatedGlucoseValueDao(changes, database.glucoseValueDao) + val therapyEventDao: TherapyEventDao = DelegatedTherapyEventDao(changes, database.therapyEventDao) + val temporaryBasalDao: TemporaryBasalDao = DelegatedTemporaryBasalDao(changes, database.temporaryBasalDao) + val bolusDao: BolusDao = DelegatedBolusDao(changes, database.bolusDao) + val extendedBolusDao: ExtendedBolusDao = DelegatedExtendedExtendedBolusDao(changes, database.extendedBolusDao) + val multiwaveBolusLinkDao: MultiwaveBolusLinkDao = DelegatedMultiwaveBolusLinkDao(changes, database.multiwaveBolusLinkDao) + val totalDailyDoseDao: TotalDailyDoseDao = DelegatedTotalDailyDoseDao(changes, database.totalDailyDoseDao) + val carbsDao: CarbsDao = DelegatedCarbsDao(changes, database.carbsDao) + val mealLinkDao: MealLinkDao = DelegatedMealLinkDao(changes, database.mealLinkDao) + val temporaryTargetDao: TemporaryTargetDao = DelegatedTemporaryTargetDao(changes, database.temporaryTargetDao) + val apsResultLinkDao: APSResultLinkDao = DelegatedAPSResultLinkLinkDao(changes, database.apsResultLinkDao) + val bolusCalculatorResultDao: BolusCalculatorResultDao = DelegatedBolusCalculatorResultDao(changes, database.bolusCalculatorResultDao) + val effectiveProfileSwitchDao: EffectiveProfileSwitchDao = DelegatedEffectiveProfileSwitchDao(changes, database.effectiveProfileSwitchDao) + val profileSwitchDao: ProfileSwitchDao = DelegatedProfileSwitchDao(changes, database.profileSwitchDao) + val apsResultDao: APSResultDao = DelegatedAPSResultDao(changes, database.apsResultDao) + val versionChangeDao: VersionChangeDao = DelegatedVersionChangeDao(changes, database.versionChangeDao) + val preferenceChangeDao: PreferenceChangeDao = DelegatedPreferenceChangeDao(changes, database.preferenceChangeDao) + fun clearAllTables() = database.clearAllTables() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/TableNames.kt b/database/src/main/java/info/nightscout/androidaps/database/TableNames.kt new file mode 100644 index 0000000000..8ecb6beeff --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/TableNames.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.database + +const val TABLE_APS_RESULTS = "apsResults" +const val TABLE_APS_RESULT_LINKS = "apsResultLinks" +const val TABLE_BOLUSES = "boluses" +const val TABLE_BOLUS_CALCULATOR_RESULTS = "bolusCalculatorResults" +const val TABLE_CARBS = "carbs" +const val TABLE_EFFECTIVE_PROFILE_SWITCHES = "effectiveProfileSwitches" +const val TABLE_EXTENDED_BOLUSES = "extendedBoluses" +const val TABLE_GLUCOSE_VALUES = "glucoseValues" +const val TABLE_MEAL_LINKS = "mealLinks" +const val TABLE_MULTIWAVE_BOLUS_LINKS = "multiwaveBolusLinks" +const val TABLE_PROFILE_SWITCHES = "profileSwitches" +const val TABLE_TEMPORARY_BASALS = "temporaryBasals" +const val TABLE_TEMPORARY_TARGETS = "temporaryTargets" +const val TABLE_TOTAL_DAILY_DOSES = "totalDailyDoses" +const val TABLE_THERAPY_EVENTS = "therapyEvents" +const val TABLE_PREFERENCE_CHANGES = "preferenceChanges" +const val TABLE_VERSION_CHANGES = "versionChanges" \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultDao.kt new file mode 100644 index 0000000000..62a1608cdb --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_APS_RESULTS +import info.nightscout.androidaps.database.entities.APSResult +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface APSResultDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_APS_RESULTS WHERE id = :id") + override fun findById(id: Long): APSResult? + + @Query("DELETE FROM $TABLE_APS_RESULTS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultLinkDao.kt new file mode 100644 index 0000000000..e19a605897 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/APSResultLinkDao.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_APS_RESULTS +import info.nightscout.androidaps.database.TABLE_APS_RESULT_LINKS +import info.nightscout.androidaps.database.entities.APSResultLink +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface APSResultLinkDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_APS_RESULT_LINKS WHERE id = :id") + override fun findById(id: Long): APSResultLink? + + @Query("DELETE FROM $TABLE_APS_RESULTS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt new file mode 100644 index 0000000000..a4602a7d73 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusCalculatorResultDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_BOLUS_CALCULATOR_RESULTS +import info.nightscout.androidaps.database.entities.BolusCalculatorResult +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface BolusCalculatorResultDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_BOLUS_CALCULATOR_RESULTS WHERE id = :id") + override fun findById(id: Long): BolusCalculatorResult? + + @Query("DELETE FROM $TABLE_BOLUS_CALCULATOR_RESULTS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt new file mode 100644 index 0000000000..18e0ae0121 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_BOLUSES +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.entities.Bolus +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface BolusDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_BOLUSES WHERE id = :id") + override fun findById(id: Long): Bolus? + + @Query("DELETE FROM $TABLE_BOLUSES") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt new file mode 100644 index 0000000000..09d24908d0 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/CarbsDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_CARBS +import info.nightscout.androidaps.database.entities.Carbs +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface CarbsDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_CARBS WHERE id = :id") + override fun findById(id: Long): Carbs? + + @Query("DELETE FROM $TABLE_CARBS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt new file mode 100644 index 0000000000..8419b30e3e --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/EffectiveProfileSwitchDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_EFFECTIVE_PROFILE_SWITCHES +import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface EffectiveProfileSwitchDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_EFFECTIVE_PROFILE_SWITCHES WHERE id = :id") + override fun findById(id: Long): EffectiveProfileSwitch? + + @Query("DELETE FROM $TABLE_EFFECTIVE_PROFILE_SWITCHES") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt new file mode 100644 index 0000000000..c5e0b979bd --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt @@ -0,0 +1,20 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_EXTENDED_BOLUSES +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.entities.ExtendedBolus +import io.reactivex.Flowable +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface ExtendedBolusDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id = :id") + override fun findById(id: Long): ExtendedBolus? + + @Query("DELETE FROM $TABLE_EXTENDED_BOLUSES") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt new file mode 100644 index 0000000000..fdaefe78ad --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/GlucoseValueDao.kt @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_GLUCOSE_VALUES +import info.nightscout.androidaps.database.entities.GlucoseValue +import io.reactivex.Maybe +import io.reactivex.Single + +@Dao +internal interface GlucoseValueDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE id = :id") + override fun findById(id: Long): GlucoseValue? + + @Query("DELETE FROM $TABLE_GLUCOSE_VALUES") + override fun deleteAllEntries() + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE nightscoutId = :nsId AND referenceId IS NULL") + fun findByNSIdMaybe(nsId: String): Maybe + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE timestamp = :timestamp AND sourceSensor = :sourceSensor AND referenceId IS NULL") + fun findByTimestampAndSensor(timestamp: Long, sourceSensor: GlucoseValue.SourceSensor): GlucoseValue? + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL AND value >= 39 ORDER BY timestamp ASC") + fun compatGetBgReadingsDataFromTime(timestamp: Long): Single> + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE timestamp BETWEEN :start AND :end AND isValid = 1 AND referenceId IS NULL AND value >= 39 ORDER BY timestamp ASC") + fun compatGetBgReadingsDataFromTime(start: Long, end: Long): Single> + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE id > :lastId AND referenceId IS NULL ORDER BY timestamp ASC") + fun getDataFromId(lastId: Long): Single> + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE id >= :id") + fun getAllStartingFrom(id: Long): Single> + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE referenceId = :id ORDER BY id DESC LIMIT 1") + fun getLastHistoryRecord(id: Long): GlucoseValue? + + @Query("SELECT * FROM $TABLE_GLUCOSE_VALUES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_GLUCOSE_VALUES WHERE id > :id) ORDER BY id ASC") + fun getModifiedFrom(id: Long): Single> +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/MealLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/MealLinkDao.kt new file mode 100644 index 0000000000..86c6904e30 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/MealLinkDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_MEAL_LINKS +import info.nightscout.androidaps.database.entities.MealLink +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface MealLinkDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_MEAL_LINKS WHERE id = :id") + override fun findById(id: Long): MealLink? + + @Query("DELETE FROM $TABLE_MEAL_LINKS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/MultiwaveBolusLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/MultiwaveBolusLinkDao.kt new file mode 100644 index 0000000000..d7865779b7 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/MultiwaveBolusLinkDao.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_MEAL_LINKS +import info.nightscout.androidaps.database.TABLE_MULTIWAVE_BOLUS_LINKS +import info.nightscout.androidaps.database.entities.MultiwaveBolusLink +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface MultiwaveBolusLinkDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_MULTIWAVE_BOLUS_LINKS WHERE id = :id") + override fun findById(id: Long): MultiwaveBolusLink? + + @Query("DELETE FROM $TABLE_MEAL_LINKS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/PreferenceChangeDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/PreferenceChangeDao.kt new file mode 100644 index 0000000000..49388a6d37 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/PreferenceChangeDao.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_PREFERENCE_CHANGES +import info.nightscout.androidaps.database.entities.PreferenceChange +import io.reactivex.Single + +@Dao +interface PreferenceChangeDao { + + @Insert + fun insert(preferenceChange: PreferenceChange) + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt new file mode 100644 index 0000000000..574a9353d8 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/ProfileSwitchDao.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_PROFILE_SWITCHES +import info.nightscout.androidaps.database.data.checkSanity +import info.nightscout.androidaps.database.daos.workaround.ProfileSwitchDaoWorkaround +import info.nightscout.androidaps.database.entities.ProfileSwitch +import io.reactivex.Flowable +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface ProfileSwitchDao : ProfileSwitchDaoWorkaround { + + @Query("SELECT * FROM $TABLE_PROFILE_SWITCHES WHERE id = :id") + override fun findById(id: Long): ProfileSwitch? + + @Query("DELETE FROM $TABLE_PROFILE_SWITCHES") + override fun deleteAllEntries() +} + +internal fun ProfileSwitchDao.insertNewEntryImpl(entry: ProfileSwitch): Long { + if (!entry.basalBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for basal blocks.") + if (!entry.icBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for IC blocks.") + if (!entry.isfBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for ISF blocks.") + if (!entry.targetBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for target blocks.") + return (this as TraceableDao).insertNewEntryImpl(entry) +} + +internal fun ProfileSwitchDao.updateExistingEntryImpl(entry: ProfileSwitch): Long { + if (!entry.basalBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for basal blocks.") + if (!entry.icBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for IC blocks.") + if (!entry.isfBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for ISF blocks.") + if (!entry.targetBlocks.checkSanity()) throw IllegalArgumentException("Sanity check failed for target blocks.") + return (this as TraceableDao).updateExistingEntryImpl(entry) +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt new file mode 100644 index 0000000000..b2b88a1c7a --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_TEMPORARY_BASALS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.entities.TemporaryBasal +import io.reactivex.Flowable +import io.reactivex.Maybe +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface TemporaryBasalDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_TEMPORARY_BASALS WHERE id = :id") + override fun findById(id: Long): TemporaryBasal? + + @Query("DELETE FROM $TABLE_TEMPORARY_BASALS") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt new file mode 100644 index 0000000000..bab28cfbc1 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryTargetDao.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_TEMPORARY_TARGETS +import info.nightscout.androidaps.database.entities.TemporaryTarget +import io.reactivex.Maybe +import io.reactivex.Observable +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface TemporaryTargetDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE id = :id") + override fun findById(id: Long): TemporaryTarget? + + @Query("DELETE FROM $TABLE_TEMPORARY_TARGETS") + override fun deleteAllEntries() + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE nightscoutId = :nsId AND referenceId IS NULL") + fun findByNSIdMaybe(nsId: String): Maybe + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1") + fun getTemporaryTargetActiveAt(timestamp: Long): TemporaryTarget? + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC") + fun compatGetTemporaryTargetDataFromTime(timestamp: Long): Single> + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC") + fun compatGetTemporaryTargetData(): List + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE referenceId = :id ORDER BY id DESC LIMIT 1") + fun getLastHistoryRecord(id: Long): TemporaryTarget? + + @Query("SELECT * FROM $TABLE_TEMPORARY_TARGETS WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_TEMPORARY_TARGETS WHERE id > :id) ORDER BY id ASC") + fun getModifiedFrom(id: Long): Single> +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt new file mode 100644 index 0000000000..627b896a7c --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TherapyEventDao.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_THERAPY_EVENTS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.entities.TherapyEvent +import io.reactivex.Flowable +import io.reactivex.Maybe +import io.reactivex.Single + +@Dao +internal interface TherapyEventDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_THERAPY_EVENTS WHERE id = :id") + override fun findById(id: Long): TherapyEvent? + + @Query("DELETE FROM $TABLE_THERAPY_EVENTS") + override fun deleteAllEntries() + + @Query("SELECT * FROM $TABLE_THERAPY_EVENTS WHERE type = :type AND timestamp = :timestamp AND referenceId IS NULL") + fun findByTimestamp(type: TherapyEvent.Type, timestamp: Long): TherapyEvent? + +} \ 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 new file mode 100644 index 0000000000..16ad4e0253 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TotalDailyDoseDao.kt @@ -0,0 +1,18 @@ +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.entities.TotalDailyDose +import io.reactivex.Single + +@Suppress("FunctionName") +@Dao +internal interface TotalDailyDoseDao : TraceableDao { + + @Query("SELECT * FROM $TABLE_TOTAL_DAILY_DOSES WHERE id = :id") + override fun findById(id: Long): TotalDailyDose? + + @Query("DELETE FROM $TABLE_TOTAL_DAILY_DOSES") + override fun deleteAllEntries() +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt new file mode 100644 index 0000000000..7eed5e5528 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Insert +import androidx.room.Update +import info.nightscout.androidaps.database.daos.workaround.TraceableDaoWorkaround +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import io.reactivex.Single + +internal interface TraceableDao : TraceableDaoWorkaround { + + fun findById(id: Long): T? + + fun deleteAllEntries() + + //fun getAllStartingFrom(id: Long): Single> + + @Insert + fun insert(entry: T): Long + + @Update + fun update(entry: T) +} + +/** + * Inserts a new entry + * @return The ID of the newly generated entry + */ +//@Transaction +internal fun TraceableDao.insertNewEntryImpl(entry: T): Long { + if (entry.id != 0L) throw IllegalArgumentException("ID must be 0.") + if (entry.version != 0) throw IllegalArgumentException("Version must be 0.") + if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.") + if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).") + val lastModified = System.currentTimeMillis() + entry.dateCreated = lastModified + val id = insert(entry) + entry.id = id + return id +} + +/** + * Updates an existing entry + * @return The ID of the newly generated HISTORIC entry + */ +//@Transaction +internal fun TraceableDao.updateExistingEntryImpl(entry: T): Long { + if (entry.id == 0L) throw IllegalArgumentException("ID must not be 0.") + if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.") + if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).") + val lastModified = System.currentTimeMillis() + entry.dateCreated = lastModified + val current = findById(entry.id) + ?: throw IllegalArgumentException("The entry with the specified ID does not exist.") + if (current.referenceId != null) throw IllegalArgumentException("The entry with the specified ID is historic and cannot be updated.") + entry.version = current.version + 1 + update(entry) + current.referenceId = entry.id + current.id = 0 + return insert(current) +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/VersionChangeDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/VersionChangeDao.kt new file mode 100644 index 0000000000..fabbead4fa --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/VersionChangeDao.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.database.daos + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import info.nightscout.androidaps.database.TABLE_VERSION_CHANGES +import info.nightscout.androidaps.database.entities.VersionChange +import io.reactivex.Single + +@Dao +interface VersionChangeDao { + + @Insert + fun insert(versionChange: VersionChange) + + @Query("SELECT * FROM $TABLE_VERSION_CHANGES ORDER BY id DESC LIMIT 1") + fun getMostRecentVersionChange(): VersionChange? + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultDao.kt new file mode 100644 index 0000000000..ffe6180770 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.APSResultDao +import info.nightscout.androidaps.database.entities.APSResult +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedAPSResultDao(changes: MutableList, private val dao: APSResultDao) : DelegatedDao(changes), APSResultDao by dao { + + override fun insertNewEntry(entry: APSResult): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: APSResult): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultLinkDao.kt new file mode 100644 index 0000000000..2152d3f9f0 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedAPSResultLinkDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.APSResultLinkDao +import info.nightscout.androidaps.database.entities.APSResultLink +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedAPSResultLinkLinkDao(changes: MutableList, private val dao: APSResultLinkDao) : DelegatedDao(changes), APSResultLinkDao by dao { + + override fun insertNewEntry(entry: APSResultLink): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: APSResultLink): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusCalculatorResultDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusCalculatorResultDao.kt new file mode 100644 index 0000000000..40e92dcb04 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusCalculatorResultDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.BolusCalculatorResultDao +import info.nightscout.androidaps.database.entities.BolusCalculatorResult +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedBolusCalculatorResultDao(changes: MutableList, private val dao: BolusCalculatorResultDao) : DelegatedDao(changes), BolusCalculatorResultDao by dao { + + override fun insertNewEntry(entry: BolusCalculatorResult): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: BolusCalculatorResult): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusDao.kt new file mode 100644 index 0000000000..67afec9e18 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedBolusDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.BolusDao +import info.nightscout.androidaps.database.entities.Bolus +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedBolusDao(changes: MutableList, private val dao: BolusDao) : DelegatedDao(changes), BolusDao by dao { + + override fun insertNewEntry(entry: Bolus): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: Bolus): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedCarbsDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedCarbsDao.kt new file mode 100644 index 0000000000..0a2da34a05 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedCarbsDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.CarbsDao +import info.nightscout.androidaps.database.entities.Carbs +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedCarbsDao(changes: MutableList, private val dao: CarbsDao) : DelegatedDao(changes), CarbsDao by dao { + + override fun insertNewEntry(entry: Carbs): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: Carbs): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedDao.kt new file mode 100644 index 0000000000..ff5fe9ba64 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedDao.kt @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.interfaces.DBEntry + +/** + * A DAO that adds updated or inserted entries to a list + */ +internal abstract class DelegatedDao(protected val changes: MutableList) \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedEffectiveProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedEffectiveProfileSwitchDao.kt new file mode 100644 index 0000000000..6516ffbc6c --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedEffectiveProfileSwitchDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.EffectiveProfileSwitchDao +import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedEffectiveProfileSwitchDao(changes: MutableList, private val dao: EffectiveProfileSwitchDao) : DelegatedDao(changes), EffectiveProfileSwitchDao by dao { + + override fun insertNewEntry(entry: EffectiveProfileSwitch): Long { + changes.add(entry) + return super.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: EffectiveProfileSwitch): Long { + changes.add(entry) + return super.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedExtendedBolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedExtendedBolusDao.kt new file mode 100644 index 0000000000..fa3a6369fd --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedExtendedBolusDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.ExtendedBolusDao +import info.nightscout.androidaps.database.entities.ExtendedBolus +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedExtendedExtendedBolusDao(changes: MutableList, private val dao: ExtendedBolusDao) : DelegatedDao(changes), ExtendedBolusDao by dao { + + override fun insertNewEntry(entry: ExtendedBolus): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: ExtendedBolus): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedGlucoseValueDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedGlucoseValueDao.kt new file mode 100644 index 0000000000..d16e84ebc5 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedGlucoseValueDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.GlucoseValueDao +import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedGlucoseValueDao(changes: MutableList, private val dao: GlucoseValueDao) : DelegatedDao(changes), GlucoseValueDao by dao { + + override fun insertNewEntry(entry: GlucoseValue): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: GlucoseValue): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMealLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMealLinkDao.kt new file mode 100644 index 0000000000..a568dd5aed --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMealLinkDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.MealLinkDao +import info.nightscout.androidaps.database.entities.MealLink +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedMealLinkDao(changes: MutableList, private val dao: MealLinkDao) : DelegatedDao(changes), MealLinkDao by dao { + + override fun insertNewEntry(entry: MealLink): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: MealLink): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMultiwaveBolusLinkDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMultiwaveBolusLinkDao.kt new file mode 100644 index 0000000000..fd6079a146 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedMultiwaveBolusLinkDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.MultiwaveBolusLinkDao +import info.nightscout.androidaps.database.entities.MultiwaveBolusLink +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedMultiwaveBolusLinkDao(changes: MutableList, private val dao: MultiwaveBolusLinkDao) : DelegatedDao(changes), MultiwaveBolusLinkDao by dao { + + override fun insertNewEntry(entry: MultiwaveBolusLink): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: MultiwaveBolusLink): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedPreferenceChangeDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedPreferenceChangeDao.kt new file mode 100644 index 0000000000..97ba761423 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedPreferenceChangeDao.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.PreferenceChangeDao +import info.nightscout.androidaps.database.entities.PreferenceChange +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedPreferenceChangeDao(changes: MutableList, private val dao: PreferenceChangeDao) : DelegatedDao(changes), PreferenceChangeDao by dao { + + override fun insert(preferenceChange: PreferenceChange) { + changes.add(preferenceChange) + return dao.insert(preferenceChange) + } + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedProfileSwitchDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedProfileSwitchDao.kt new file mode 100644 index 0000000000..11ded9ccdc --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedProfileSwitchDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.ProfileSwitchDao +import info.nightscout.androidaps.database.entities.ProfileSwitch +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedProfileSwitchDao(changes: MutableList, private val dao: ProfileSwitchDao) : DelegatedDao(changes), ProfileSwitchDao by dao { + + override fun insertNewEntry(entry: ProfileSwitch): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: ProfileSwitch): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryBasalDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryBasalDao.kt new file mode 100644 index 0000000000..c48ca004cb --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryBasalDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.TemporaryBasalDao +import info.nightscout.androidaps.database.entities.TemporaryBasal +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedTemporaryBasalDao(changes: MutableList, private val dao: TemporaryBasalDao) : DelegatedDao(changes), TemporaryBasalDao by dao { + + override fun insertNewEntry(entry: TemporaryBasal): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: TemporaryBasal): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryTargetDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryTargetDao.kt new file mode 100644 index 0000000000..a3cba800f5 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTemporaryTargetDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.TemporaryTargetDao +import info.nightscout.androidaps.database.entities.TemporaryTarget +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedTemporaryTargetDao(changes: MutableList, private val dao: TemporaryTargetDao) : DelegatedDao(changes), TemporaryTargetDao by dao { + + override fun insertNewEntry(entry: TemporaryTarget): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: TemporaryTarget): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTherapyEventDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTherapyEventDao.kt new file mode 100644 index 0000000000..767edd50a9 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTherapyEventDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.TherapyEventDao +import info.nightscout.androidaps.database.entities.TherapyEvent +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedTherapyEventDao(changes: MutableList, private val dao: TherapyEventDao) : DelegatedDao(changes), TherapyEventDao by dao { + + override fun insertNewEntry(entry: TherapyEvent): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: TherapyEvent): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTotalDailyDoseDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTotalDailyDoseDao.kt new file mode 100644 index 0000000000..95bc5ab108 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedTotalDailyDoseDao.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.TotalDailyDoseDao +import info.nightscout.androidaps.database.entities.TotalDailyDose +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedTotalDailyDoseDao(changes: MutableList, private val dao: TotalDailyDoseDao) : DelegatedDao(changes), TotalDailyDoseDao by dao { + + override fun insertNewEntry(entry: TotalDailyDose): Long { + changes.add(entry) + return dao.insertNewEntry(entry) + } + + override fun updateExistingEntry(entry: TotalDailyDose): Long { + changes.add(entry) + return dao.updateExistingEntry(entry) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedVersionChangeDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedVersionChangeDao.kt new file mode 100644 index 0000000000..81a5ecb799 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/delegated/DelegatedVersionChangeDao.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.database.daos.delegated + +import info.nightscout.androidaps.database.daos.VersionChangeDao +import info.nightscout.androidaps.database.entities.VersionChange +import info.nightscout.androidaps.database.interfaces.DBEntry + +internal class DelegatedVersionChangeDao(changes: MutableList, private val dao: VersionChangeDao) : DelegatedDao(changes), VersionChangeDao by dao { + + override fun insert(versionChange: VersionChange) { + changes.add(versionChange) + return dao.insert(versionChange) + } + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/ProfileSwitchDaoWorkaround.java b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/ProfileSwitchDaoWorkaround.java new file mode 100644 index 0000000000..9a817ff215 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/ProfileSwitchDaoWorkaround.java @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.database.daos.workaround; + +import androidx.room.Transaction; + +import info.nightscout.androidaps.database.daos.ProfileSwitchDao; +import info.nightscout.androidaps.database.daos.ProfileSwitchDaoKt; +import info.nightscout.androidaps.database.daos.TraceableDao; +import info.nightscout.androidaps.database.entities.ProfileSwitch; + +public interface ProfileSwitchDaoWorkaround extends TraceableDao { + + @Override + @Transaction + default long insertNewEntry(ProfileSwitch entry) { + return ProfileSwitchDaoKt.insertNewEntryImpl((ProfileSwitchDao) this, entry); + } + + @Override + @Transaction + default long updateExistingEntry(ProfileSwitch entry) { + return ProfileSwitchDaoKt.updateExistingEntryImpl((ProfileSwitchDao) this, entry); + } +} diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/TraceableDaoWorkaround.java b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/TraceableDaoWorkaround.java new file mode 100644 index 0000000000..ddeb1d0d80 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/TraceableDaoWorkaround.java @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.database.daos.workaround; + +import androidx.room.Transaction; + +import info.nightscout.androidaps.database.daos.TraceableDao; +import info.nightscout.androidaps.database.daos.TraceableDaoKt; +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry; + +public interface TraceableDaoWorkaround { + + /** + * Inserts a new entry + * + * @return The ID of the newly generated entry + */ + @Transaction + default long insertNewEntry(T entry) { + return TraceableDaoKt.insertNewEntryImpl((TraceableDao) this, entry); + } + + /** + * Updates an existing entry + * + * @return The ID of the newly generated HISTORIC entry + */ + @Transaction + default long updateExistingEntry(T entry) { + return TraceableDaoKt.updateExistingEntryImpl((TraceableDao) this, entry); + } + +} diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/package-info.java b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/package-info.java new file mode 100644 index 0000000000..089581be3b --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/workaround/package-info.java @@ -0,0 +1,5 @@ +/** + * Workarounds until Kotlin is able to properly translate interface default methods while annotation processing. + * See https://youtrack.jetbrains.com/issue/KT-25960 + */ +package info.nightscout.androidaps.database.daos.workaround; \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/data/Block.kt b/database/src/main/java/info/nightscout/androidaps/database/data/Block.kt new file mode 100644 index 0000000000..0b4a98b5c1 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/data/Block.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.database.data + +import java.util.concurrent.TimeUnit + +data class Block(var duration: Long, var amount: Double) + +fun List.checkSanity(): Boolean { + var sum = 0L + forEach { sum += it.duration } + return sum == TimeUnit.DAYS.toMillis(1) +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/data/TargetBlock.kt b/database/src/main/java/info/nightscout/androidaps/database/data/TargetBlock.kt new file mode 100644 index 0000000000..4c95fba75f --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/data/TargetBlock.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.database.data + +import java.util.concurrent.TimeUnit + +data class TargetBlock(var duration: Long, var lowTarget: Double, var highTarget: Double) + +fun List.checkSanity(): Boolean { + var sum = 0L + forEach { sum += it.duration } + return sum == TimeUnit.DAYS.toMillis(1) +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/embedments/InsulinConfiguration.kt b/database/src/main/java/info/nightscout/androidaps/database/embedments/InsulinConfiguration.kt new file mode 100644 index 0000000000..50450ae52d --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/embedments/InsulinConfiguration.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.database.embedments + +data class InsulinConfiguration( + var insulinLabel: String, + var insulinEndTime: Long, + var peak: Long +) \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt new file mode 100644 index 0000000000..86873d9915 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt @@ -0,0 +1,20 @@ +package info.nightscout.androidaps.database.embedments + +data class InterfaceIDs( + var nightscoutSystemId: String? = null, + var nightscoutId: String? = null, + var pumpType: PumpType? = null, + var pumpSerial: String? = null, + var pumpId: Long? = null, + var startId: Long? = null, + var endId: Long? = null +) { + enum class PumpType { + ACCU_CHEK_INSIGHT, + ACCU_CHEK_COMBO, + DANA_R, + DANA_RS, + MEDTRONIC, + OMNIPOD + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/APSResult.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/APSResult.kt new file mode 100644 index 0000000000..42ef8e7dac --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/APSResult.kt @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_APS_RESULTS +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 + +@Entity(tableName = TABLE_APS_RESULTS, + foreignKeys = [ForeignKey( + entity = APSResult::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class APSResult( + @PrimaryKey(autoGenerate = true) + 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? = null, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var algorithm: Algorithm, + var glucoseStatusJson: String, + var currentTempJson: String, + var iobDataJson: String, + var profileJson: String, + var autosensDataJson: String?, + var mealDataJson: String, + var isMicroBolusAllowed: Boolean?, + var resultJson: String +) : TraceableDBEntry, DBEntryWithTime { + enum class Algorithm { + MA, + AMA, + SMB + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/APSResultLink.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/APSResultLink.kt new file mode 100644 index 0000000000..8fed1f9578 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/APSResultLink.kt @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_APS_RESULT_LINKS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry + +@Entity(tableName = TABLE_APS_RESULT_LINKS, + foreignKeys = [ForeignKey( + entity = APSResult::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("apsResultId")), ForeignKey( + + entity = Bolus::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("smbId")), ForeignKey( + + entity = TemporaryBasal::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("tbrId")), ForeignKey( + + entity = APSResultLink::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("referenceId"))], + indices = [Index("referenceId"), Index("apsResultId"), + Index("smbId"), Index("tbrId")]) +data class APSResultLink( + @PrimaryKey(autoGenerate = true) + 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? = null, + var apsResultId: Long, + var smbId: Long? = null, + var tbrId: Long? = null +) : TraceableDBEntry { + override val foreignKeysValid: Boolean + get() = super.foreignKeysValid && apsResultId != 0L && smbId != 0L && tbrId != 0L +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt new file mode 100644 index 0000000000..a683ca31f3 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt @@ -0,0 +1,39 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_BOLUSES +import info.nightscout.androidaps.database.embedments.InsulinConfiguration +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 + +@Entity(tableName = TABLE_BOLUSES, + foreignKeys = [ForeignKey( + entity = Bolus::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class Bolus( + @PrimaryKey(autoGenerate = true) + 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? = null, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var amount: Double, + var type: Type, + var isBasalInsulin: Boolean, + @Embedded + var insulinConfiguration: InsulinConfiguration? = null +) : TraceableDBEntry, DBEntryWithTime { + enum class Type { + NORMAL, + SMB, + PRIMING + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt new file mode 100644 index 0000000000..056d1fd363 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/BolusCalculatorResult.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_BOLUS_CALCULATOR_RESULTS +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 + +@Entity(tableName = TABLE_BOLUS_CALCULATOR_RESULTS, + foreignKeys = [ForeignKey( + entity = BolusCalculatorResult::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class BolusCalculatorResult( + @PrimaryKey(autoGenerate = true) + 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? = null, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var targetBGLow: Double, + var targetBGHigh: Double, + var isf: Double, + var ic: Double, + var bolusIOB: Double, + var wasBolusIOBUsed: Boolean, + var basalIOB: Double, + var wasBasalIOBUsed: Boolean, + var glucoseValue: Double, + var wasGlucoseUsed: Boolean, + var glucoseDifference: Double, + var glucoseInsulin: Double, + var glucoseTrend: Double, + var wasTrendUsed: Boolean, + var trendInsulin: Double, + var cob: Double, + var wasCOBUsed: Boolean, + var cobInsulin: Double, + var carbs: Double, + var wereCarbsUsed: Boolean, + var carbsInsulin: Double, + var otherCorrection: Double, + var wasSuperbolusUsed: Boolean, + var superbolusInsulin: Double, + var wasTempTargetUsed: Boolean, + var totalInsulin: Double +) : TraceableDBEntry, DBEntryWithTime \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt new file mode 100644 index 0000000000..5694d1041a --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/Carbs.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_CARBS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_CARBS, + foreignKeys = [ForeignKey( + entity = Carbs::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class Carbs( + @PrimaryKey(autoGenerate = true) + 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? = null, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + override var duration: Long, + var amount: Double +) : TraceableDBEntry, DBEntryWithTimeAndDuration \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt new file mode 100644 index 0000000000..273634e25a --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/EffectiveProfileSwitch.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.data.Block +import info.nightscout.androidaps.database.TABLE_EFFECTIVE_PROFILE_SWITCHES +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_EFFECTIVE_PROFILE_SWITCHES, + foreignKeys = [ForeignKey( + entity = EffectiveProfileSwitch::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class EffectiveProfileSwitch( + @PrimaryKey(autoGenerate = true) + 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? = null, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + override var duration: Long, + var basalBlocks: List +) : TraceableDBEntry, DBEntryWithTimeAndDuration \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt new file mode 100644 index 0000000000..40792c11c7 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/ExtendedBolus.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_EXTENDED_BOLUSES +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_EXTENDED_BOLUSES, + foreignKeys = [ForeignKey( + entity = ExtendedBolus::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class ExtendedBolus( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + override var duration: Long, + var amount: Double, + var isEmulatingTempBasal: Boolean +) : TraceableDBEntry, DBEntryWithTimeAndDuration \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt new file mode 100644 index 0000000000..55716ba4ac --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/GlucoseValue.kt @@ -0,0 +1,100 @@ +package info.nightscout.androidaps.database.entities + +import com.google.gson.annotations.SerializedName +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_GLUCOSE_VALUES +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 + +@Entity(tableName = TABLE_GLUCOSE_VALUES, + foreignKeys = [ForeignKey( + entity = GlucoseValue::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class GlucoseValue( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var raw: Double?, + var value: Double, + var trendArrow: TrendArrow, + var noise: Double?, + var sourceSensor: SourceSensor +) : TraceableDBEntry, DBEntryWithTime { + + fun contentEqualsTo(other: GlucoseValue): Boolean = + timestamp == other.timestamp && + utcOffset == other.utcOffset && + raw == other.raw && + value == other.value && + trendArrow == other.trendArrow && + noise == other.noise && + sourceSensor == other.sourceSensor && + isValid == other.isValid + + fun isRecordDeleted(other: GlucoseValue): Boolean = + isValid && !other.isValid + + enum class TrendArrow (val text:String, val symbol:String){ + @SerializedName("NONE") NONE("NONE", "??"), + @SerializedName("TripleUp")TRIPLE_UP("TripleUp", "X"), + @SerializedName("DoubleUp")DOUBLE_UP("DoubleUp", "\u21c8"), + @SerializedName("SingleUp")SINGLE_UP("SingleUp", "\u2191"), + @SerializedName("FortyFiveUp")FORTY_FIVE_UP("FortyFiveUp", "\u2197"), + @SerializedName("Flat")FLAT("Flat", "\u2192"), + @SerializedName("FortyFiveDown")FORTY_FIVE_DOWN("FortyFiveDown", "\u2198"), + @SerializedName("SingleDown")SINGLE_DOWN("SingleDown", "\u2193"), + @SerializedName("DoubleDown")DOUBLE_DOWN("DoubleDown", "\u21ca"), + @SerializedName("TripleDown")TRIPLE_DOWN("TripleDown", "X") + ; + + companion object { + fun fromString(direction : String?) = values().firstOrNull {it.text == direction} ?: NONE + } + } + + enum class SourceSensor(val text : String) { + @SerializedName("AndroidAPS-Dexcom") DEXCOM_NATIVE_UNKNOWN("AndroidAPS-Dexcom"), + @SerializedName("AndroidAPS-DexcomG6") DEXCOM_G6_NATIVE("AndroidAPS-DexcomG6"), + @SerializedName("AndroidAPS-DexcomG5") DEXCOM_G5_NATIVE("AndroidAPS-DexcomG5"), + @SerializedName("Bluetooth Wixel") DEXCOM_G4_WIXEL("Bluetooth Wixel"), + @SerializedName("xBridge Wixel") DEXCOM_G4_XBRIDGE("xBridge Wixel"), + @SerializedName("G4 Share Receiver") DEXCOM_G4_NATIVE("G4 Share Receiver"), + @SerializedName("Medtrum A6") MEDTRUM_A6("Medtrum A6"), + @SerializedName("Network G4") DEXCOM_G4_NET("Network G4"), + @SerializedName("Network G4 and xBridge") DEXCOM_G4_NET_XBRIDGE("Network G4 and xBridge"), + @SerializedName("Network G4 and Classic xDrip") DEXCOM_G4_NET_CLASSIC("Network G4 and Classic xDrip"), + @SerializedName("DexcomG5") DEXCOM_G5_XDRIP("DexcomG5"), + @SerializedName("G6 Native") DEXCOM_G6_NATIVE_XDRIP("G6 Native"), + @SerializedName("G5 Native") DEXCOM_G5_NATIVE_XDRIP("G5 Native"), + @SerializedName("Network libre") LIBRE_1_NET("Network libre"), + @SerializedName("BlueReader") LIBRE_1_BLUE("BlueReader"), + @SerializedName("Transmiter PL") LIBRE_1_PL("Transmiter PL"), + @SerializedName("Blucon") LIBRE_1_BLUCON("Blucon"), + @SerializedName("Tomato") LIBRE_1_TOMATO("Tomato"), + @SerializedName("Rfduino") LIBRE_1_RF("Rfduino"), + @SerializedName("LimiTTer") LIBRE_1_LIMITTER("LimiTTer"), + @SerializedName("Glimp") GLIMP("Glimp"), + @SerializedName("Libre2") LIBRE_2_NATIVE("Libre2"), + @SerializedName("Poctech") POCTECH_NATIVE("Poctech"), + @SerializedName("MM600Series") MM_600_SERIES("MM600Series"), + @SerializedName("Eversense") EVERSENSE("Eversense"), + @SerializedName("Random") RANDOM("Random"), + @SerializedName("Unknown") UNKNOWN("Unknown") + ; + + companion object { + fun fromString(source : String?) = values().firstOrNull {it.text == source} ?: UNKNOWN + } + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/MealLink.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/MealLink.kt new file mode 100644 index 0000000000..4c6a3c5f32 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/MealLink.kt @@ -0,0 +1,54 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_MEAL_LINKS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry + +@Entity(tableName = TABLE_MEAL_LINKS, + foreignKeys = [ForeignKey( + entity = Bolus::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("bolusId")), ForeignKey( + + entity = Carbs::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("carbsId")), ForeignKey( + + entity = BolusCalculatorResult::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("bolusCalcResultId")), ForeignKey( + + entity = TemporaryBasal::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("superbolusTempBasalId")), ForeignKey( + + entity = TherapyEvent::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("noteId")), ForeignKey( + + entity = MealLink::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("bolusId"), + Index("carbsId"), Index("bolusCalcResultId"), + Index("superbolusTempBasalId"), Index("noteId")]) +data class MealLink( + @PrimaryKey(autoGenerate = true) + 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? = null, + var bolusId: Long? = null, + var carbsId: Long? = null, + var bolusCalcResultId: Long? = null, + var superbolusTempBasalId: Long? = null, + var noteId: Long? = null +) : TraceableDBEntry { + override val foreignKeysValid: Boolean + get() = super.foreignKeysValid && bolusId != 0L && carbsId != 0L && + bolusCalcResultId != 0L && superbolusTempBasalId != 0L && noteId != 0L +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/MultiwaveBolusLink.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/MultiwaveBolusLink.kt new file mode 100644 index 0000000000..e8fbf135e0 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/MultiwaveBolusLink.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_MULTIWAVE_BOLUS_LINKS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry + +@Entity(tableName = TABLE_MULTIWAVE_BOLUS_LINKS, + foreignKeys = [ForeignKey( + entity = Bolus::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("bolusId")), ForeignKey( + + entity = ExtendedBolus::class, + parentColumns = arrayOf("id"), + childColumns = arrayOf("extendedBolusId")), ForeignKey( + + entity = MultiwaveBolusLink::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("bolusId"), + Index("extendedBolusId")]) +data class MultiwaveBolusLink( + @PrimaryKey(autoGenerate = true) + 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? = null, + var bolusId: Long, + var extendedBolusId: Long +) : TraceableDBEntry { + override val foreignKeysValid: Boolean + get() = super.foreignKeysValid && bolusId != 0L && bolusId != 0L && extendedBolusId != 0L +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/PreferenceChange.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/PreferenceChange.kt new file mode 100644 index 0000000000..8ff67ccb71 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/PreferenceChange.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.Entity +import androidx.room.PrimaryKey +import info.nightscout.androidaps.database.TABLE_PREFERENCE_CHANGES +import info.nightscout.androidaps.database.interfaces.DBEntry +import info.nightscout.androidaps.database.interfaces.DBEntryWithTime +import java.util.TimeZone + +@Entity(tableName = TABLE_PREFERENCE_CHANGES) +data class PreferenceChange( + @PrimaryKey(autoGenerate = true) + override var id: Long = 0L, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var key: String, + var value: Any? +) : DBEntry, DBEntryWithTime \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt new file mode 100644 index 0000000000..aa845fb8db --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/ProfileSwitch.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.data.Block +import info.nightscout.androidaps.database.TABLE_PROFILE_SWITCHES +import info.nightscout.androidaps.database.data.TargetBlock +import info.nightscout.androidaps.database.embedments.InsulinConfiguration +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_PROFILE_SWITCHES, + foreignKeys = [ForeignKey( + entity = ProfileSwitch::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class ProfileSwitch( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var profileName: String, + var glucoseUnit: GlucoseUnit, + var basalBlocks: List, + var isfBlocks: List, + var icBlocks: List, + var targetBlocks: List, + @Embedded + var insulinConfiguration: InsulinConfiguration, + var timeshift: Int, + var percentage: Int, + override var duration: Long +) : TraceableDBEntry, DBEntryWithTimeAndDuration { + enum class GlucoseUnit { + MGDL, + MMOL + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt new file mode 100644 index 0000000000..01f034ae86 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryBasal.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_TEMPORARY_BASALS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_TEMPORARY_BASALS, + foreignKeys = [ForeignKey( + entity = TemporaryBasal::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class TemporaryBasal( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var type: Type, + var isAbsolute: Boolean, + var rate: Double, + override var duration: Long +) : TraceableDBEntry, DBEntryWithTimeAndDuration { + enum class Type { + NORMAL, + EMULATED_PUMP_SUSPEND, + PUMP_SUSPEND, + SUPERBOLUS + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt new file mode 100644 index 0000000000..96bde2e864 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TemporaryTarget.kt @@ -0,0 +1,68 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.Embedded +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.Index +import androidx.room.PrimaryKey +import com.google.gson.annotations.SerializedName +import info.nightscout.androidaps.database.TABLE_TEMPORARY_TARGETS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.* + +@Entity(tableName = TABLE_TEMPORARY_TARGETS, + foreignKeys = [ForeignKey( + entity = TemporaryTarget::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class TemporaryTarget( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var reason: Reason, + var highTarget: Double, // in mgdl + var lowTarget: Double, // in mgdl + override var duration: Long // in millis +) : TraceableDBEntry, DBEntryWithTimeAndDuration { + + fun contentEqualsTo(other: TemporaryTarget): Boolean = + timestamp == other.timestamp && + utcOffset == other.utcOffset && + reason == other.reason && + highTarget == other.highTarget && + lowTarget == other.lowTarget && + duration == other.duration && + isValid == other.isValid + + fun isRecordDeleted(other: TemporaryTarget): Boolean = + isValid && !other.isValid + + enum class Reason(val text: String) { + @SerializedName("Custom") + CUSTOM("Custom"), + @SerializedName("Hypo") + HYPOGLYCEMIA("Hypo"), + @SerializedName("Activity") + ACTIVITY("Activity"), + @SerializedName("Eating Soon") + EATING_SOON("Eating Soon"), + @SerializedName("Automation") + AUTOMATION("Automation") + ; + + companion object { + fun fromString(direction: String?) = values().firstOrNull { it.text == direction } + ?: CUSTOM + } + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt new file mode 100644 index 0000000000..2225fed98f --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt @@ -0,0 +1,63 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +import info.nightscout.androidaps.database.TABLE_THERAPY_EVENTS +import info.nightscout.androidaps.database.embedments.InterfaceIDs +import info.nightscout.androidaps.database.interfaces.DBEntryWithTimeAndDuration +import info.nightscout.androidaps.database.interfaces.TraceableDBEntry +import java.util.TimeZone + +@Entity(tableName = TABLE_THERAPY_EVENTS, + foreignKeys = [ForeignKey( + entity = TherapyEvent::class, + parentColumns = ["id"], + childColumns = ["referenceId"])], + indices = [Index("referenceId"), Index("timestamp")]) +data class TherapyEvent( + @PrimaryKey(autoGenerate = true) + 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + override var duration: Long = 0, + var type: Type, + var note: String? = null, + var amount: Double? = null +) : TraceableDBEntry, DBEntryWithTimeAndDuration { + enum class Type { + CANNULA_CHANGED, + TUBE_CHANGED, + RESERVOIR_CHANGED, + BATTERY_CHANGED, + LEAKING_INFUSION_SET, + SENSOR_INSERTED, + SENSOR_STARTED, + SENSOR_STOPPED, + FINGER_STICK_BG_VALUE, + ACTIVITY, + FALLING_ASLEEP, + WAKING_UP, + SICKNESS, + STRESS, + PRE_PERIOD, + ALCOHOL, + CORTISON, + FEELING_LOW, + FEELING_HIGH, + ANNOUNCEMENT, + QUESTION, + NOTE, + APS_OFFLINE, + BATTERY_EMPTY, + RESERVOIR_EMPTY, + OCCLUSION, + PUMP_STOPPED, + PUMP_STARTED, + PUMP_PAUSED + } +} \ 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 new file mode 100644 index 0000000000..0cd450697c --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TotalDailyDose.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.* +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 + +@Entity(tableName = TABLE_TOTAL_DAILY_DOSES, + 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 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 timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var basalAmount: Double?, + var bolusAmount: Double?, + var totalAmount: Double? +) : TraceableDBEntry, DBEntryWithTime \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/VersionChange.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/VersionChange.kt new file mode 100644 index 0000000000..83ca1ccc40 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/VersionChange.kt @@ -0,0 +1,20 @@ +package info.nightscout.androidaps.database.entities + +import androidx.room.Entity +import androidx.room.PrimaryKey +import info.nightscout.androidaps.database.TABLE_VERSION_CHANGES +import info.nightscout.androidaps.database.interfaces.DBEntry +import info.nightscout.androidaps.database.interfaces.DBEntryWithTime +import java.util.TimeZone + +@Entity(tableName = TABLE_VERSION_CHANGES) +data class VersionChange( + @PrimaryKey(autoGenerate = true) + override var id: Long = 0L, + override var timestamp: Long, + override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(), + var versionCode: Int, + var versionName: String, + var gitRemote: String?, + var commitHash: String? +) : DBEntry, DBEntryWithTime \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntry.kt b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntry.kt new file mode 100644 index 0000000000..f6c01287a6 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntry.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.database.interfaces + +interface DBEntry { + var id: Long +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithDuration.kt b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithDuration.kt new file mode 100644 index 0000000000..469ec17d6d --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithDuration.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.database.interfaces + +interface DBEntryWithDuration { + var duration: Long + + val durationUnknown get() = duration == Long.MAX_VALUE +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTime.kt b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTime.kt new file mode 100644 index 0000000000..103942fcf0 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTime.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.database.interfaces + +interface DBEntryWithTime { + var timestamp: Long + var utcOffset: Long +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTimeAndDuration.kt b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTimeAndDuration.kt new file mode 100644 index 0000000000..b4f3f0bbbf --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/interfaces/DBEntryWithTimeAndDuration.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.database.interfaces + +import kotlin.math.min + +interface DBEntryWithTimeAndDuration : DBEntryWithTime, DBEntryWithDuration + +var DBEntryWithTimeAndDuration.end + get() = timestamp + duration + set(value) { + duration = value - timestamp + } + +@JvmOverloads +fun DBEntryWithTimeAndDuration.getRemainingDuration(current: Long = System.currentTimeMillis()) = min(0L, end - current) \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/interfaces/TraceableDBEntry.kt b/database/src/main/java/info/nightscout/androidaps/database/interfaces/TraceableDBEntry.kt new file mode 100644 index 0000000000..7ab0ce0984 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/interfaces/TraceableDBEntry.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.database.interfaces + +import info.nightscout.androidaps.database.embedments.InterfaceIDs + +interface TraceableDBEntry: DBEntry { + var version: Int + var dateCreated: Long + var isValid: Boolean + var referenceId: Long? + var interfaceIDs_backing: InterfaceIDs? + + val historic: Boolean get() = referenceId != null + + val foreignKeysValid: Boolean get() = referenceId != 0L + + var interfaceIDs: InterfaceIDs + get() { + var value = this.interfaceIDs_backing + if (value == null) { + value = InterfaceIDs() + interfaceIDs_backing = value + } + return value + } + set(value) { + interfaceIDs_backing = value + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/CancelCurrentTemporaryTargetIfAnyTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/CancelCurrentTemporaryTargetIfAnyTransaction.kt new file mode 100644 index 0000000000..206e9c1d1c --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/CancelCurrentTemporaryTargetIfAnyTransaction.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.TemporaryTarget +import info.nightscout.androidaps.database.interfaces.end + +class CancelCurrentTemporaryTargetIfAnyTransaction( + val timestamp: Long +) : Transaction() { + override fun run() { + val current = database.temporaryTargetDao.getTemporaryTargetActiveAt(timestamp) + if (current != null) { + current.end = timestamp + database.temporaryTargetDao.updateExistingEntry(current) + } + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt new file mode 100644 index 0000000000..7a9a5a2dda --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/CgmSourceTransaction.kt @@ -0,0 +1,74 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.database.entities.TherapyEvent + +/** + * Inserts data from a CGM source into the database + */ +class CgmSourceTransaction( + private val glucoseValues: List, + private val calibrations: List, + private val sensorInsertionTime: Long? +) : Transaction>() { + + override fun run(): List { + val insertedGlucoseValues = mutableListOf() + glucoseValues.forEach { + val current = database.glucoseValueDao.findByTimestampAndSensor(it.timestamp, it.sourceSensor) + val glucoseValue = GlucoseValue( + timestamp = it.timestamp, + raw = it.raw, + value = it.value, + noise = it.noise, + trendArrow = it.trendArrow, + sourceSensor = it.sourceSensor + ) + glucoseValue.interfaceIDs.nightscoutId = it.nightscoutId + when { + current == null -> { + database.glucoseValueDao.insertNewEntry(glucoseValue) + insertedGlucoseValues.add(glucoseValue) + } + + !current.contentEqualsTo(glucoseValue) -> { + glucoseValue.id = current.id + database.glucoseValueDao.updateExistingEntry(glucoseValue) + } + } + } + calibrations.forEach { + if (database.therapyEventDao.findByTimestamp(TherapyEvent.Type.FINGER_STICK_BG_VALUE, it.timestamp) == null) { + database.therapyEventDao.insertNewEntry(TherapyEvent( + timestamp = it.timestamp, + type = TherapyEvent.Type.FINGER_STICK_BG_VALUE, + amount = it.value + )) + } + } + sensorInsertionTime?.let { + if (database.therapyEventDao.findByTimestamp(TherapyEvent.Type.SENSOR_INSERTED, it) == null) { + database.therapyEventDao.insertNewEntry(TherapyEvent( + timestamp = it, + type = TherapyEvent.Type.SENSOR_INSERTED + )) + } + } + return insertedGlucoseValues + } + + data class TransactionGlucoseValue( + val timestamp: Long, + val value: Double, + val raw: Double?, + val noise: Double?, + val trendArrow: GlucoseValue.TrendArrow, + val nightscoutId: String? = null, + val sourceSensor: GlucoseValue.SourceSensor + ) + + data class Calibration( + val timestamp: Long, + val value: Double + ) +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertGlucoseValueTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertGlucoseValueTransaction.kt new file mode 100644 index 0000000000..b75c4a3928 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertGlucoseValueTransaction.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.GlucoseValue + +/** + * Creates the GlucoseValue + */ +class InsertGlucoseValueTransaction(val glucoseValue: GlucoseValue) : Transaction() { + + override fun run() { + database.glucoseValueDao.insert(glucoseValue) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertTemporaryTargetAndCancelCurrentTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertTemporaryTargetAndCancelCurrentTransaction.kt new file mode 100644 index 0000000000..c3d42b3e52 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InsertTemporaryTargetAndCancelCurrentTransaction.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.TemporaryTarget +import info.nightscout.androidaps.database.interfaces.end + +class InsertTemporaryTargetAndCancelCurrentTransaction( + private val temporaryTarget: TemporaryTarget +) : Transaction() { + + constructor(timestamp: Long, duration: Long, reason: TemporaryTarget.Reason, lowTarget: Double, highTarget: Double) : + this(TemporaryTarget(timestamp = timestamp, reason = reason, lowTarget = lowTarget, highTarget = highTarget, duration = duration)) + + override fun run() { + val current = database.temporaryTargetDao.getTemporaryTargetActiveAt(temporaryTarget.timestamp) + if (current != null) { + current.end = temporaryTarget.timestamp + database.temporaryTargetDao.updateExistingEntry(current) + } + database.temporaryTargetDao.insertNewEntry(temporaryTarget) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateGlucoseValueTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateGlucoseValueTransaction.kt new file mode 100644 index 0000000000..69895ed8bd --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateGlucoseValueTransaction.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.transactions.Transaction + +/** + * Invalidates the GlucoseValue with the specified id + */ +class InvalidateGlucoseValueTransaction(val id: Long) : Transaction() { + override fun run() { + val glucoseValue = database.glucoseValueDao.findById(id) + ?: throw IllegalArgumentException("There is no such GlucoseValue with the specified ID.") + glucoseValue.isValid = false + database.glucoseValueDao.updateExistingEntry(glucoseValue) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateTemporaryTargetTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateTemporaryTargetTransaction.kt new file mode 100644 index 0000000000..7109fbf672 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/InvalidateTemporaryTargetTransaction.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.database.transactions + +class InvalidateTemporaryTargetTransaction(val id: Long) : Transaction() { + override fun run() { + val temporaryTarget = database.temporaryTargetDao.findById(id) + ?: throw IllegalArgumentException("There is no such TemporaryTarget with the specified ID.") + temporaryTarget.isValid = false + database.temporaryTargetDao.updateExistingEntry(temporaryTarget) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/Transaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/Transaction.kt new file mode 100644 index 0000000000..36d07a9926 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/Transaction.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.DelegatedAppDatabase + +/** + * Base class for database transactions + * @param T The return type of the Transaction + */ +abstract class Transaction { + + /** + * Executes the Transaction + */ + internal abstract fun run(): T + + internal lateinit var database: DelegatedAppDatabase + +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateGlucoseValueTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateGlucoseValueTransaction.kt new file mode 100644 index 0000000000..8d6ce188be --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateGlucoseValueTransaction.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.GlucoseValue + +/** + * Updates the GlucoseValue + */ +class UpdateGlucoseValueTransaction(val glucoseValue: GlucoseValue) : Transaction() { + + override fun run() { + database.glucoseValueDao.updateExistingEntry(glucoseValue) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateTemporaryTargetTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateTemporaryTargetTransaction.kt new file mode 100644 index 0000000000..0a9f140c20 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateTemporaryTargetTransaction.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.TemporaryTarget + +/** + * Updates the TemporaryTarget + */ +class UpdateTemporaryTargetTransaction(private val temporaryTarget: TemporaryTarget) : Transaction() { + + override fun run() { + database.temporaryTargetDao.updateExistingEntry(temporaryTarget) + } +} \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt new file mode 100644 index 0000000000..d828e279b3 --- /dev/null +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.database.transactions + +import info.nightscout.androidaps.database.entities.VersionChange +import java.util.* + +class VersionChangeTransaction( + private val versionName: String, + private val versionCode: Int, + private val gitRemote: String?, + private val commitHash: String?) : Transaction() { + + override fun run() { + val current = database.versionChangeDao.getMostRecentVersionChange() + if (current == null + || current.versionName != versionName + || current.versionCode != versionCode + || current.gitRemote != gitRemote + || current.commitHash != commitHash) { + val currentTime = System.currentTimeMillis() + database.versionChangeDao.insert(VersionChange( + timestamp = System.currentTimeMillis(), + versionCode = versionCode, + versionName = versionName, + gitRemote = gitRemote, + commitHash = commitHash + )) + } + } + +} \ No newline at end of file diff --git a/database/src/test/java/info/nightscout/database/ExampleUnitTest.kt b/database/src/test/java/info/nightscout/database/ExampleUnitTest.kt new file mode 100644 index 0000000000..a0b6e3a55e --- /dev/null +++ b/database/src/test/java/info/nightscout/database/ExampleUnitTest.kt @@ -0,0 +1,18 @@ +package info.nightscout.database + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 4fb6743f5f..163be2365a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,3 @@ +include ':database' include ':app', ':wear', ':core', ':dana', ':danar', ':danars', ':rileylink', ':medtronic', ':omnipod' From cfe23cef96c3ad4176ad22749782375ea3a9fecb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 4 Feb 2021 20:54:09 +0100 Subject: [PATCH 2/2] AapsSchedulers --- app/jacoco.exec | Bin 79946 -> 161640 bytes .../nightscout/androidaps/MainActivity.kt | 7 +- .../dependencyInjection/AppModule.kt | 6 ++ .../androidaps/dialogs/WizardDialog.kt | 7 +- .../historyBrowser/HistoryBrowseActivity.kt | 13 ++-- .../IobCobCalculatorPluginHistory.kt | 4 +- .../historyBrowser/TreatmentsPluginHistory.kt | 4 +- .../plugins/aps/loop/LoopFragment.kt | 12 ++-- .../plugins/aps/loop/LoopPlugin.java | 9 ++- .../aps/openAPSAMA/OpenAPSAMAFragment.kt | 11 ++-- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 12 ++-- .../configBuilder/ConfigBuilderFragment.kt | 7 +- .../objectives/ObjectivesFragment.kt | 8 +-- .../general/actions/ActionsFragment.kt | 15 +++-- .../general/automation/AutomationFragment.kt | 11 ++-- .../general/automation/AutomationPlugin.kt | 17 ++--- .../automation/dialogs/EditEventDialog.kt | 19 +++--- .../automation/dialogs/EditTriggerDialog.kt | 21 +++--- .../dataBroadcaster/DataBroadcastPlugin.kt | 31 ++++----- .../plugins/general/food/FoodFragment.kt | 7 +- .../plugins/general/food/FoodService.java | 5 +- .../general/nsclient/NSClientFragment.java | 6 +- .../general/nsclient/NSClientPlugin.java | 19 +++--- .../nsclient/services/NSClientService.java | 17 ++--- .../general/openhumans/OpenHumansFragment.kt | 31 ++++----- .../openhumans/OpenHumansLoginActivity.kt | 8 +-- .../general/openhumans/OpenHumansUploader.kt | 14 ++-- .../general/overview/OverviewFragment.kt | 60 +++++++++--------- .../general/overview/OverviewPlugin.kt | 12 ++-- .../activities/QuickWizardListActivity.kt | 7 +- .../persistentNotification/DummyService.kt | 5 +- .../PersistentNotificationPlugin.kt | 37 ++++++----- .../SmsCommunicatorFragment.kt | 7 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 7 +- .../general/tidepool/TidepoolFragment.kt | 9 +-- .../general/tidepool/TidepoolPlugin.kt | 39 +++++------- .../plugins/general/wear/WearPlugin.kt | 49 +++++++------- .../xdripStatusline/StatusLinePlugin.kt | 38 +++++------ .../IobCobCalculatorPlugin.java | 23 ++++--- .../profile/local/LocalProfileFragment.kt | 8 +-- .../plugins/profile/ns/NSProfileFragment.kt | 7 +- .../plugins/pump/combo/ComboFragment.java | 8 +-- .../pump/insight/LocalInsightFragment.java | 5 +- .../pump/virtual/VirtualPumpFragment.kt | 15 +++-- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 10 +-- .../plugins/source/BGSourceFragment.kt | 11 ++-- .../plugins/treatments/TreatmentService.java | 5 +- .../plugins/treatments/TreatmentsFragment.kt | 5 +- .../plugins/treatments/TreatmentsPlugin.java | 13 ++-- .../fragments/TreatmentsBolusFragment.kt | 11 ++-- .../fragments/TreatmentsCareportalFragment.kt | 5 +- .../TreatmentsExtendedBolusesFragment.kt | 11 ++-- .../TreatmentsProfileSwitchFragment.kt | 5 +- .../fragments/TreatmentsTempTargetFragment.kt | 5 +- .../TreatmentsTemporaryBasalsFragment.kt | 7 +- .../androidaps/queue/CommandQueue.kt | 32 +++++----- .../androidaps/services/LocationService.kt | 7 +- .../androidaps/setupwizard/SWEventListener.kt | 7 +- .../setupwizard/SetupWizardActivity.kt | 27 ++++---- .../androidaps/utils/stats/TddCalculator.kt | 14 ++-- .../info/nightscout/androidaps/TestBase.kt | 3 + .../androidaps/TestBaseWithProfile.kt | 6 +- ...S_Packet_Bolus_Set_Step_Bolus_StartTest.kt | 3 +- ...Packet_Notify_Delivery_Rate_DisplayTest.kt | 2 +- .../interfaces/ConstraintsCheckerTest.kt | 4 +- .../plugins/aps/loop/LoopPluginTest.kt | 4 +- .../configBuilder/ConfigBuilderPluginTest.kt | 4 +- .../dstHelper/DstHelperPluginTest.kt | 5 +- .../SignatureVerifierPluginTest.kt | 4 +- .../storage/StorageConstraintPluginTest.kt | 13 ++-- .../VersionCheckerUtilsKtTest.kt | 2 +- .../general/automation/AutomationEventTest.kt | 3 +- .../automation/triggers/TriggerTestBase.kt | 2 +- .../nsclient/NsClientReceiverDelegateTest.kt | 2 +- .../SmsCommunicatorPluginTest.kt | 2 +- .../IobCobCalculatorPluginTest.kt | 4 +- .../plugins/pump/combo/ComboPluginTest.kt | 2 +- .../plugins/pump/danaR/DanaRPluginTest.kt | 2 +- .../plugins/pump/danaR/comm/DanaRTestBase.kt | 2 +- .../pump/danaRKorean/DanaRKoreanPluginTest.kt | 2 +- .../plugins/pump/danaRS/DanaRSPluginTest.kt | 2 +- .../plugins/pump/danaRv2/DanaRv2PluginTest.kt | 2 +- .../pump/virtual/VirtualPumpPluginUTest.kt | 7 +- .../plugins/source/NSClientPluginTest.kt | 4 +- .../treatments/TreatmentsPluginTest.kt | 2 +- .../androidaps/queue/CommandQueueTest.kt | 7 +- .../utils/wizard/BolusWizardTest.kt | 2 +- .../activities/TDDStatsActivity.java | 6 +- .../androidaps/dialogs/BolusProgressDialog.kt | 15 +++-- .../androidaps/dialogs/NtpProgressDialog.kt | 4 +- .../androidaps/plugins/bus/RxBusWrapper.kt | 8 ++- .../pump/common/PumpPluginAbstract.java | 8 ++- .../androidaps/utils/rx/AapsSchedulers.kt | 27 ++++++++ .../androidaps/utils/rx/RxExtensions.kt | 43 +++++++++++++ .../androidaps/dana/DanaFragment.kt | 28 ++++---- .../dana/activities/DanaHistoryActivity.kt | 11 ++-- .../activities/DanaUserOptionsActivity.kt | 7 +- .../danaRKorean/DanaRKoreanPlugin.java | 9 +-- .../androidaps/danaRv2/DanaRv2Plugin.java | 7 +- .../androidaps/danar/AbstractDanaRPlugin.java | 11 ++-- .../androidaps/danar/DanaRPlugin.java | 9 +-- .../AbstractDanaRExecutionService.java | 7 +- .../androidaps/danars/DanaRSPlugin.kt | 15 +++-- .../danars/activities/EnterPinActivity.kt | 10 +-- .../danars/dialogs/PairingProgressDialog.java | 9 +-- .../danars/services/DanaRSService.kt | 23 ++++--- database/build.gradle | 1 - .../transactions/VersionChangeTransaction.kt | 1 - .../pump/medtronic/MedtronicFragment.kt | 35 +++++----- .../pump/medtronic/MedtronicPumpPlugin.java | 8 ++- .../pump/omnipod/OmnipodPumpPlugin.java | 19 +++--- .../driver/manager/OmnipodManager.java | 13 ++-- .../omnipod/manager/AapsOmnipodManager.java | 6 +- .../omnipod/ui/OmnipodOverviewFragment.kt | 18 +++--- .../pump/omnipod/ui/PodManagementActivity.kt | 14 ++-- 115 files changed, 734 insertions(+), 567 deletions(-) create mode 100644 core/src/main/java/info/nightscout/androidaps/utils/rx/AapsSchedulers.kt create mode 100644 core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt diff --git a/app/jacoco.exec b/app/jacoco.exec index aef5037acf47867bdaf0bdc64ec90bf0fd9e08d2..97d8cc2389170a0c67c5b221bb980367f2a03daa 100644 GIT binary patch delta 18021 zcmb_k2Ut^A-_Iq4oZKvKn4$<#1Z9T3WVYzC2G&A0G(0=bZolxBkb|b=JQ>lazf= z^oZ~zDl2WpwgN@rq{-QNei@lLp_(vFjzB<6%v(}FfPG!MWd&51`AZL5QTHb~m1b3V z^@YRMiKOt*qNCHU2y+FQ@JC1->>t}sR)0`Q4PCtR_X*ebY^LMe5gK$)knXf_Yrj}p zi-<5-d^{S45C{$2d9S2m`7sy#K5E$Bn}j;T89f`CeED*DbbmNJG;r}uu~ZfbAO*_fES#Rx5ryP?Wg>rrXD(;Z?gE?zD5HV8{G$D3~S#4U(Z# z;-ls3H|W;U31T7|F7HY~w|9to{P1MtEC>|)(`Bv%f`v9x`a2cT5f%xhsG&stc6;IP z!y(Yq6^7f(pd`Z%{cC_ve8`3%FZ|XKpm7z!_Sx1IYm{hq|01g?yKMGBMeA7fEHQJ{ z+rldvSUaFQdEwuZMRu88<_fyOINuoPI8H_?sTsvy{tI^v-N`;~xo;41E*p?X6yBHy z6`R7KQfUoAZ3kLu1)%W_M{ECF+-}Z;^a?tSB*Ni{Z!G;-PDCMLU~Mfu@lhFEIwYkHO({&W#i#ks9++4K3OMh_h;s;>uiRuIIO_5DjDdF&EQHWT1Y}#wpt_wf} zr;%=lg1C5yP^%{d(r9%yK1%?8>hmOfb{I5@d?_3qCS}; zv$KlFW)~KTOXwZ$M3St!R6woo@|E@Sil=#ydNduCo_clUr{zy;!F`4+T^B}Bbe#{O zlsy&tF^*-}UNPL{5Y$jQ_OX6Hm0&Sz)+`TYJBHS5~cT|=j&yTQ1Z z?CL!H#2zA5&ZvpQh!$!4?Y@>YUcbxVR(xkR^U0yc3&B%ICz6 zmZ)&C7SsqSqXW{#>W~0-T!|rC(yk6fBwV1JAWgNEyXj>5kh7kpX*xnMkgcp?VBVmWrAgC$xla3>)vbM_#K3;Qa zCsaHdAU5hGXw<5;DbeNfGB|wF6;jhgux1SjV;nkhS^{)+?2IN{+%vv9S7if4UN|Vn z+dz4YHTdUB6gfE(9l_}fbf$_(K{F5Ar%E1L`#?fiEU^w!&Nz@_ic`KHEKWon+R(e} zpp%z@s_tZ?KKn+eBiKsq`SNj%@QXotxC`k|FU)UAH5O!PKq$l|*uWu|K=SRy1JgH; zt>`7_g*P;s=^{{CC|Bhdc+ab^+H^@saq1FQwCqo2l`6m4yL9ayL0?!K7Z2t09j)3Z zpspn#t#n=b&2=BoptVkfD->8c+jPp$%SJlbA?wvau5aWanvB5AtWbS@2p;QS_pG5l zYjyN=&ymLu2s%{+wuJ4syk)`EvWpAXE*BP$6Lf;Zu5os$h1oepE-eHCK~t?9)w!K) zxH&p=ImP1XHQj}jnJ`h5xY8$uEq0QF$sGRT|AM#iK zZ9vonfo3f-@8bUwjab%DpMDAVnr=wsxzB$`i*ygX?g@~bFBj{Cc&h{gAa(>u2?vT( z_%qZ^6uw!7f1r5>bDK9)>IysNS6eJ>NNXR*so}*lMRNQDGP6RBpesqj$+TL_!kB9P z>_Xc8PPa?c_+YeyGB1ByZ$YbuS9JuZjG>oL7j*DVHTmHB%tE|2OjB+T2QwwgO6DV4 zQS^^rWqV(plL}flKdAF^hVveF$gK7+J<2_|RraD7qfV5gwrEsl2^K6-8&21O5dPBP)=g(fgTqM-J5)8&w(HpjT z$ryA;NVzpVVS&S5+|rm2-9go7ymowX5sA-Ik1rOiPTrE+6%M(MBOmyL?j0X`=8OOn zBwSQ0T=94N^+16q?|zgd-!u{e!(E|#j*r5vK}p>W_pJCiA=L?&G-e@WpW>o|?7S?A zQUGpr43q|};SvF!W+U}hP`~#HI)Q}QoOrVv(UJ)aubay+j~SN-KYcGlI!P6PbL|_wJj+7AQqhu=U(}CU)$9u z@uPKs>Rz@cReX1K6sKsdBu8O+_gp0JvS$r_t;<}tMdnYX;Bhx4vWeog0c-cnk~pDLoWO3D0uo^n8@Xd@G|NoNxyS zhKtEOMQv2MQAp)f7xU-pAFt3v5D_cWVYISPuQ2USEEmkPTEXPBmhdYx4*k9aVn|P5inIQY9UT{^FWAXai@JVsWNLZJl#NR}Uc!sS^wL*@RGb24 zwbQN(iMnl@J8Z;fI|6LSOTe`d!N+|`W7QM@5Bqz-^uhR7SW-^^VY#Ay9X9T&y)v&D zs}xoOQy3l!$IEm|ju=P3Ek1jDv`hN`LS21=)UAOs64TL$BbQgs-+5$MZ^IpoJ zgt6MfTn3}C3TBG0DP+8JXg{gjSpO#k_HS*{T+of%mCOkMNNE4zj zQR|iZ*Yg2XNyodNX?98kEU}M+gE@}KT#EXl!AnjAt$y8&>0o_HGY(D$n=ow?Zr#e1 zJ^S!^9uldbhT>7MEl||)8G`<9c0aKO$)sftGC^51#Y4B9KvQUgP8NCG+;H_@*#^%; z0^t)WbmWJIs9)|5EyTr$S;lO47&gKk@!+LM`b>!^vDr zgyfaVjvsrd1cK@7_?XRVD z!$L}H!mUa28p<5K1WB%&J1QeKQ}vYf*+OCHa(k;v0;>HI;Pf~WwYfU|mBQD*fL+;Ekq*{nn>R%< z+*f8xjktMk(n^=3=P{4g{~iRZ7j$SsqO*rfNJ*&^u|Kr!Qo_=GrUb;Gk_iN24oxO+ zwC|eS`Qi^}@KflOzN>LxNk?tJ?)GHTlo{Uvh0U8a2@+7|kPPuv>E2WmZ>!@dGyHbt zdZ^@_VESZKkXwQv4g!y9;Nl7q=vGRVab?v6CNmC4uO%98PW@}Zc=m_g zC;LLpRKD33SEfP6t~<)SxP3tRpKbTBM_V?h z1!|eRFR48Bmlf}E6p|N6%)R*zsD50+{*Ou~7eH;u07Ju67!&wD7R@ygHrH@*UD_1} zpU!gOqvKL5K`Ti134sA~?9kx1&lc&nEF>7lvZR!dl9*!Ox^~z7U3XVQ?RY@jF)HNW z@0+URLYbf4YV24EMkW)n96(wS%J|&_*N4K*d83gT&F?nqgEYSdYgT6mW@H3~YJ&A- zfxxhaLzSh!gmC%237NljVM|cSe1}54YEE59p&3@QJHP#O;c2!3vL-pitfr7Ab63wz zH5ZSu{&;n{80=Tt@>tp?*x%wG8P|#Z?(bL@7t$2l`DqFJP^k;Wu;HB}msjn&q_vJ3Q>9#-YlBixMdD>j4vUDG{<1r28av8MtnRDYMKdPyLD&8)b`>9JQRthx1Z%$Lk5+00IvC#-Zmc)*kuR z>%J4VHlvyiwE((q?x1 z=Ip;)9DHx&E9p8hp`=$6gaq;1SUfOpVvdWE$fy`k&%HNX(cFOd}$cIQiP^IFK~4g>I$*SX3RG+T^C45 z=++KI1k|l^LW3L!4;VRZ$`Urda_^)9-xxRKbn3va1Ak2o!0Yb2q>_-!ymUH>8%Hu~ zI@XJz;](8$POdjg40m3V#k{9)As{ogWg`R!r{R9Utu=u*biQl?z}nQ%{PXcA_D zmBY_Vub%oO9QPXiiF9C^jT7p4&Q|qxw_|?qTM)cEpdd@A=H`xUaE+s<%TE)ph^nr( zWlVPZwl|KTIiSiDKq-;;h|ZG^wwbT{`#D?PBF*5IN-e}@7?!P+kp%C=CeB=oD)lQT zB$#(O{>B53Ki?lT2e?@;L#5uf=Wd22%kYQup_N{QjIL{kTkO(ntA@L_`!a=DyN=Q_ zF=Ya*^1s27=o|%szF~+jk&?>lZb2AC1)c58>>ZdO1?BKA_Kuw@wPT=)bJ+$2(V{8IP8LQrp zK#?dhfjZOCfEd=H;-2-ID8~=j!6KLttI*d&lesLfHLj-BBYF{=5S+;>JP3R<;Lh24a1^DOiEHKx5B ze`GFYlo%)@HlwhlR0)Eu48D?yuykQZFZ4-oIM-V;1Sb941Z8DKgh%SFqb0A^`ck=b z+B}NIJo%ub>gkOYbOuxMuHe2&{ehB+w$;t8PHJ8AhO$~RXu#=ZL>1imHsOO66S>z= zF|Qvtk)T>gJ=-v;XWOXUqz%gO(JX!pkCnojbP_(ezxs{gecjFdV>W&@D?%gP7eiJ~*Qcuj8Qi%Z z1Xeo&xen2s&0L3wGc>~oUP{S7D$XQX?Fa$Yf8FrJv&$noL*=U0P$?9_mhJ6O+XwEm z|FX~Q*|=^YLTgSP8(T@qR`@8ZUvz=uoq=4!+cYwohCuU+Y8Rp9InGb3s z*B5-eu{(A;H1fSdLA~yzek~i|(m78!`w+1pY0P$+Tu3;wDon=YLfegUA%{Zv;)Tbu zFEIacrEA;>Y-<@!V6oY+S!0Nj1|IEJYd6V|CB@3%#5Q|VhAWkozEx77I&$<-uZ0cl zQWiXSmEsfF*jFkxMVU^3umsoOQj=>xAGl)&-S@zuWb5 z@Wi2wTOEwI+8EKpi8$P-dj8#w*r-YgcYccj*x#SqnfTJ)C+ zWlE1gYl1TKvs|n&xp%)euVWljWri=q6ro}GBq$^#I6E*<-|4Ik9q(a-S;zB5ALw^% zBFxMSX6;doJh10@KDM9RL1m3U1Y9GzM4A+w7O(raV2c)~>y&ppxbbTw`bRx6>JHlz z6BO(tSx%Jscm#(-G{(#^N_Iem*A#P*msIUia=IgYcO{n3XKw+mFN@jU$K@3>u0?_F zTBwO}g;|7g1B2I9Qn-7a)3yA;^J+WBz*3eo;kkg~WLM2()+}{MlIac+W;V7mNn4na zKXOu5p>{k&jG4Y8F`g08Q;7~-Dq(?co7i0rvij;e%901pbf>Q3w=sn_@7f=M?M|Nf zti&1fjd*0-m8|v(A+0I^F1m=ItV)F2Q7F{jcHuGsOO)%o?VhTmslV{tWQ@kSHLHbfi@mOmri2qIWw_-31 zo^m>yQa{^fX3>jWj_Y*7##qi+)pG-KJngpsw`^{=!8~ZKIx9RZA}l8)Oy3eJyXs$G zoaT_prnnB`w^WeyrI>4O<4uf!cqb`ba3NvUq3(!(q`*Am#&cz|N@`K>*BzcMX;q8| zXVM;dc1Rr22OCS7+1>NTXBXyZGqXK9W#?#%$ByrwTQIf=cW{%@PWlf!BEqqyp)2Y; zNh6TpxgomJnqY=~O@eH84v0%c@bE5YCJ=3vCsT{uXD?tdfOZccZ0UKyghCl7sMAds z8!HDta6arMHZ{^t95gY~IBKGqMbD1$c9OQ^=!HH3+!^wmkO*x?P+*XLk9Ym3f343m z?*MAtrB0 zyTYPVHsEpAR?&JMlOfKYRJKE0TRck7sTZA6bLp|!fiXQA6nWjmk~2(^S{yn;-|s!2 zwz_pN3)gs*oPK6YP>eNaLz#CGK1)C%)xF>wBsM0~3|z3NV0OODDRHQ2nKJ~&#Mxm+ z(Ply< zzd7Ff(&V~A+~IL9`ZCMKtyr8pa0XgU4puCjc_8H-W|NSWR5YCZ>9c3W@r=zy$A=S2 z=zHJJc=-b0-0vQU*CeA9I^myqKRGaN?hJpTD{Zdy(APP=%89U5hvr0tg=gm&7VYO= zY&p{+za~x7UPCst-Sl*jo!&aDdtvW@r&jP#yJBt!5}hC zKAiiE992*-DsM#hyqtU~o+2|J>^JpK$yt7zo;Zxs?!yU@y50|7y=?v7Qngn43(9n2 z0cGs0O0lbcOO<=X0HG7st? zz|p|}FFR)Lc~>eRy?i_dS||A1W`=BZqa zkD@Q^`m4Pez?da9rgdyF1N{e4&7gKQ)eSvU6s#M}?7^!yb`~NVZYlG7xyFvI1%@Fd zL)?7-cZqVF#@r#?&T z@lzKrZ7^*t7OpKA%x!F+nL1@c?37^(qZj50eVjvbwAn#fnHl=?cjKb|{E>ESa-=n3 zs606lDK8b2*mDmYy+cC8nVqNTE;6Q657EOIhD-%*l~ z+Gp5=AQCIEUZEXTcGf~Gy|CZ~7rArkMIA?$z~@vn{Z@vvG#;kNd)E-tya>8RfjPJ_ z!x3U+peZF$Y>Wi~w7rb@zyvJ((K1mgX?|wM-W8+)b7pmxCNd;6JThCqId@(4nc%E?gNbIaI`@~l*!zf-1x1Eu$>?{EL~FCHVk9I}{2gKYWsyRE$AEvwDk)yJuf%MB z_)%Ec0^|;!A)t-M)J}3#@$kbJ>Y!uHfWUVxB$m-?~ZENzW^@ zBZ9&sHDQM7_h*arTWeQJnNMK!5E3Nf&FG!ED9<5`CR^VmH>azGgavYrFPkwpHR<0( zycJZQdU9~cPQRAS^c7RC6dj8gq4fWe_?#7gV{N+PrhU&Mq59qE-VQTunj}>>so1qS zIiV2|!CHNl)u!vW!r>wZf>FpHZBtN=Kc45rH(u*r$mq?^1iprhLqV+#w;t=?WPAM5 zdetoUY6eqf)^vj_A;WBz*>`(KvR`g_|& znVL4@!VUx3%QN_ZAZ9H*`4f1RWq~b|+$5;Ptv-?=v+OSFa{&DoP_#`;!UdAgb3EPv z20KkE*7W=|g_{r5nHic$O-8r@7hhsIgQwSM=g}tOt@-0ItfVs?ZnHJeCw+M5^O$R>c)o)njl6BkNhatYL77YenF>w*=^wL8tQH4<)?HupdUwx0*Bc?2 zq*wb8t|n-NMJTV~>A)o)dpz+W=QTx~ECw7+Pfj#*-pFF_ZN8YbFlK?w16gxKWM&e% z(8n)udH$UZc4Uzwe2t9MPR#Ax5=--oh@U=D^o>wLj*RCRanSo-7+bj1Ynv(lM&p4(2 N-yx`HE;tgx{{v<9CA|Ou delta 11 ScmaFyj`P$9mWC~iUKRi*w*^%I diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index 8466a0c2f1..09505d0e18 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -57,10 +57,10 @@ import info.nightscout.androidaps.utils.extensions.isRunningRealPumpTest import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.IconsProvider +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.tabs.TabPageAdapter import info.nightscout.androidaps.utils.ui.UIRunnable -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject @@ -71,6 +71,7 @@ class MainActivity : NoSplashAppCompatActivity() { private val disposable = CompositeDisposable() @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var androidPermission: AndroidPermission @Inject lateinit var sp: SP @@ -125,7 +126,7 @@ class MainActivity : NoSplashAppCompatActivity() { setupViews() disposable.add(rxBus .toObservable(EventRebuildTabs::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ if (it.recreate) recreate() else setupViews() @@ -134,7 +135,7 @@ class MainActivity : NoSplashAppCompatActivity() { ) disposable.add(rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ processPreferenceChange(it) }, fabricPrivacy::logException) ) if (!sp.getBoolean(R.string.key_setupwizard_processed, false) && !isRunningRealPumpTest()) { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 3acf9d9297..e807a8d7f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -17,6 +17,8 @@ import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.utils.androidNotification.NotificationHolder +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.Storage import javax.inject.Singleton @@ -46,6 +48,10 @@ open class AppModule { return FileStorage() } + @Provides + @Singleton + internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers() + @Module interface AppBindings { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 63102ed9ae..dc3d1d47e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -36,9 +36,9 @@ import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.wizard.BolusWizard -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import java.text.DecimalFormat import java.util.* @@ -48,6 +48,7 @@ import kotlin.math.abs class WizardDialog : DaggerDialogFragment() { @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var mainApp: MainApp @Inject lateinit var sp: SP @@ -188,10 +189,10 @@ class WizardDialog : DaggerDialogFragment() { // bus disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ activity?.runOnUiThread { calculateInsulin() } - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) ) } diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt index 0c3db46994..22cfa8f5ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt @@ -32,10 +32,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.toVisibility +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -46,6 +45,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @@ -173,7 +173,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { super.onResume() disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ // catch only events from iobCobCalculatorPluginHistory if (it.cause is EventCustomCalculationFinished) { @@ -183,7 +183,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { ) disposable.add(rxBus .toObservable(EventAutosensBgLoaded::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ // catch only events from iobCobCalculatorPluginHistory if (it.cause is EventCustomCalculationFinished) { @@ -193,12 +193,12 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { ) disposable.add(rxBus .toObservable(EventIobCalculationProgress::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ binding.overviewIobcalculationprogess.text = it.progress }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventRefreshOverview::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ if (it.now) { updateGUI("EventRefreshOverview", bgOnly = false) @@ -308,7 +308,6 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { // **** BG **** graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null) - // add target line graphData.addTargetLine(fromTime, toTime, profile, null) diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt index bf7401036a..14d2da5ac1 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt @@ -12,6 +12,7 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAverage import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @@ -20,6 +21,7 @@ import javax.inject.Singleton class IobCobCalculatorPluginHistory @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, + aapsSchedulers: AapsSchedulers, rxBus: RxBusWrapper, sp: SP, resourceHelper: ResourceHelper, @@ -31,7 +33,7 @@ class IobCobCalculatorPluginHistory @Inject constructor( sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin, fabricPrivacy: FabricPrivacy, dateUtil: DateUtil -) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction, +) : IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPluginHistory, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) { override fun onStart() { // do not attach to rxbus diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt index f9d0a4019b..c38c5845bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt @@ -13,6 +13,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @@ -21,6 +22,7 @@ import javax.inject.Singleton class TreatmentsPluginHistory @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, + aapsSchedulers: AapsSchedulers, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, context: Context, @@ -31,7 +33,7 @@ class TreatmentsPluginHistory @Inject constructor( fabricPrivacy: FabricPrivacy, dateUtil: DateUtil, uploadQueue: UploadQueue -) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue) { +) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue) { init { onStart() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index 5abcb3cf1c..864f56a1d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt @@ -17,13 +17,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class LoopFragment : DaggerFragment() { + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @@ -59,18 +61,18 @@ class LoopFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventLoopUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventLoopSetLastRunGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ clearGUI() binding.lastrun.text = it.text - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateGUI() sp.putBoolean(R.string.key_objectiveuseloop, true) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index c8cd892ce5..5cd3ded85e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -72,15 +72,16 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class LoopPlugin extends PluginBase implements LoopInterface { private final HasAndroidInjector injector; private final SP sp; private final RxBusWrapper rxBus; + private final AapsSchedulers aapsSchedulers; private final ConstraintChecker constraintChecker; private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; @@ -123,6 +124,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface { public LoopPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, SP sp, Config config, @@ -153,6 +155,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface { aapsLogger, resourceHelper, injector ); this.injector = injector; + this.aapsSchedulers = aapsSchedulers; this.sp = sp; this.rxBus = rxBus; this.constraintChecker = constraintChecker; @@ -181,7 +184,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface { super.onStart(); disposable.add(rxBus .toObservable(EventTempTargetChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> invoke("EventTempTargetChange", true), fabricPrivacy::logException) ); /* @@ -193,7 +196,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface { */ disposable.add(rxBus .toObservable(EventAutosensCalculationFinished.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { // Autosens calculation not triggered by a new BG if (!(event.getCause() instanceof EventNewBG)) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt index ddb429d9fa..a9a171b46a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.JSONFormatter import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import org.json.JSONArray import org.json.JSONException @@ -29,6 +29,7 @@ class OpenAPSAMAFragment : DaggerFragment() { private var disposable: CompositeDisposable = CompositeDisposable() @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -61,16 +62,16 @@ class OpenAPSAMAFragment : DaggerFragment() { disposable += rxBus .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventOpenAPSUpdateResultGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateResultGUI(it.text) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index c617424762..b27c9fd1c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -19,16 +19,18 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.JSONFormatter import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import org.json.JSONArray import org.json.JSONException import javax.inject.Inject class OpenAPSSMBFragment : DaggerFragment() { + private var disposable: CompositeDisposable = CompositeDisposable() @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -60,16 +62,16 @@ class OpenAPSSMBFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventOpenAPSUpdateResultGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateResultGUI(it.text) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 52ec1fd95f..5bd7e72a60 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -22,13 +22,14 @@ import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject class ConfigBuilderFragment : DaggerFragment() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @@ -77,10 +78,10 @@ class ConfigBuilderFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventConfigBuilderUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ for (pluginViewHolder in pluginViewHolders) pluginViewHolder.update() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index ea11c69e26..f12c4b5b93 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -35,8 +35,8 @@ import info.nightscout.androidaps.utils.SntpClient import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -44,6 +44,7 @@ class ObjectivesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -92,11 +93,10 @@ class ObjectivesFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventObjectivesUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ binding.recyclerview.adapter?.notifyDataSetChanged() - }, { fabricPrivacy.logException(it) } - ) + }, fabricPrivacy::logException) } @Synchronized diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index f86acfab3e..8eeb10429a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -36,10 +36,10 @@ import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.SingleClickButton import info.nightscout.androidaps.utils.ui.UIRunnable -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject @@ -47,6 +47,7 @@ import javax.inject.Inject class ActionsFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @@ -223,27 +224,27 @@ class ActionsFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventInitializationChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventRefreshOverview::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventCustomActionsChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventCareportalEventChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt index 8ff11d49f7..e599fe8797 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt @@ -35,13 +35,14 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject class AutomationFragment : DaggerFragment(), OnStartDragListener { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -93,16 +94,16 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { super.onResume() disposable += rxBus .toObservable(EventAutomationUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutomationDataChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ eventListAdapter.notifyDataSetChanged() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index 825fb75659..e67906b101 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -32,9 +32,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.json.JSONArray import org.json.JSONException import org.json.JSONObject @@ -54,6 +54,7 @@ class AutomationPlugin @Inject constructor( private val rxBus: RxBusWrapper, private val constraintChecker: ConstraintChecker, aapsLogger: AAPSLogger, + private val aapsSchedulers: AapsSchedulers, private val config: Config, private val locationServiceHelper: LocationServiceHelper, private val dateUtil: DateUtil @@ -103,7 +104,7 @@ class AutomationPlugin @Inject constructor( disposable += rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ e -> if (e.isChanged(resourceHelper, R.string.key_location)) { locationServiceHelper.stopService(context) @@ -112,11 +113,11 @@ class AutomationPlugin @Inject constructor( }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutomationDataChanged::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ storeToSP() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventLocationChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ e -> e?.let { aapsLogger.debug(LTag.AUTOMATION, "Grabbed location: $it.location.latitude $it.location.longitude Provider: $it.location.provider") @@ -125,19 +126,19 @@ class AutomationPlugin @Inject constructor( }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventChargingState::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ processActions() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNetworkChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ processActions() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ processActions() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventBTChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ aapsLogger.debug(LTag.AUTOMATION, "Grabbed new BT event: $it") btConnects.add(it) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt index 10084a9110..2ce260102f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt @@ -9,7 +9,7 @@ import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.AutomationDialogEventBinding import info.nightscout.androidaps.dialogs.DialogFragmentWithDate @@ -27,14 +27,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class EditEventDialog : DialogFragmentWithDate() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var mainApp: MainApp + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var automationPlugin: AutomationPlugin @@ -52,11 +53,11 @@ class EditEventDialog : DialogFragmentWithDate() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { - event = AutomationEvent(mainApp) + event = AutomationEvent(injector) // load data from bundle (savedInstanceState ?: arguments)?.let { bundle -> position = bundle.getInt("position", -1) - bundle.getString("event")?.let { event = AutomationEvent(mainApp).fromJSON(it) } + bundle.getString("event")?.let { event = AutomationEvent(injector).fromJSON(it) } } onCreateViewGeneral() @@ -94,28 +95,28 @@ class EditEventDialog : DialogFragmentWithDate() { disposable += rxBus .toObservable(EventAutomationUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ actionListAdapter?.notifyDataSetChanged() showPreconditions() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutomationAddAction::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ event.addAction(it.action) actionListAdapter?.notifyDataSetChanged() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutomationUpdateTrigger::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ event.trigger = it.trigger binding.triggerDescription.text = event.trigger.friendlyDescription() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventAutomationUpdateAction::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ event.actions[it.position] = it.action actionListAdapter?.notifyDataSetChanged() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditTriggerDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditTriggerDialog.kt index 4e79780e9e..2a73b4bc24 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditTriggerDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditTriggerDialog.kt @@ -4,7 +4,7 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import info.nightscout.androidaps.MainApp +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.databinding.AutomationDialogEditTriggerBinding import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.plugins.bus.RxBusWrapper @@ -17,15 +17,16 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerCon import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDummy import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import org.json.JSONObject import javax.inject.Inject class EditTriggerDialog : DialogFragmentWithDate() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var mainApp: MainApp + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var fabricPrivacy: FabricPrivacy private var disposable: CompositeDisposable = CompositeDisposable() @@ -42,7 +43,7 @@ class EditTriggerDialog : DialogFragmentWithDate() { savedInstanceState: Bundle?): View { // load data from bundle (savedInstanceState ?: arguments)?.let { bundle -> - bundle.getString("trigger")?.let { triggers = TriggerDummy(mainApp).instantiate(JSONObject(it)) } + bundle.getString("trigger")?.let { triggers = TriggerDummy(injector).instantiate(JSONObject(it)) } } onCreateViewGeneral() @@ -55,28 +56,28 @@ class EditTriggerDialog : DialogFragmentWithDate() { disposable += rxBus .toObservable(EventTriggerChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ binding.layoutTrigger.removeAllViews() triggers?.generateDialog(binding.layoutTrigger) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTriggerRemove::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ findParent(triggers, it.trigger)?.list?.remove(it.trigger) binding.layoutTrigger.removeAllViews() triggers?.generateDialog(binding.layoutTrigger) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTriggerClone::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ findParent(triggers, it.trigger)?.list?.add(it.trigger.duplicate()) binding.layoutTrigger.removeAllViews() triggers?.generateDialog(binding.layoutTrigger) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) // display root trigger triggers?.generateDialog(binding.layoutTrigger) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 28d2b378b5..ac2a5f2392 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -30,8 +30,8 @@ import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @@ -40,6 +40,7 @@ class DataBroadcastPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBusWrapper, @@ -67,32 +68,32 @@ class DataBroadcastPlugin @Inject constructor( super.onStart() disposable.add(rxBus .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTreatmentChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventNewBasalProfile::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventOverviewBolusProgress::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendData(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendData(it) }, fabricPrivacy::logException)) } override fun onStop() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt index 58b7fdb779..b9acd8aaf2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject @@ -32,6 +32,7 @@ import kotlin.collections.ArrayList class FoodFragment : DaggerFragment() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -106,8 +107,8 @@ class FoodFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventFoodDatabaseChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java index fd8329cc4a..ceb72727a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java @@ -36,8 +36,8 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; /** * Created by mike on 24.09.2017. @@ -47,6 +47,7 @@ public class FoodService extends OrmLiteBaseService { @Inject AAPSLogger aapsLogger; @Inject RxBusWrapper rxBus; @Inject FabricPrivacy fabricPrivacy; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -59,7 +60,7 @@ public class FoodService extends OrmLiteBaseService { dbInitialize(); disposable.add(rxBus .toObservable(EventNsFood.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { int mode = event.getMode(); JSONArray array = event.getFoods(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java index 3f4e24490c..37de04a623 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.nsclient; import android.graphics.Paint; import android.os.Bundle; -import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; import android.view.View; @@ -25,8 +24,8 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.alertDialogs.OKDialog; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; public class NSClientFragment extends DaggerFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { @@ -36,6 +35,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList @Inject RxBusWrapper rxBus; @Inject UploadQueue uploadQueue; @Inject FabricPrivacy fabricPrivacy; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -93,7 +93,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList super.onResume(); disposable.add(rxBus .toObservable(EventNSClientUpdateGUI.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> updateGui(), fabricPrivacy::logException) ); updateGui(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index ef0ad789f9..de1b919ed1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -59,9 +59,9 @@ import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.buildHelper.BuildHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class NSClientPlugin extends PluginBase { @@ -71,6 +71,7 @@ public class NSClientPlugin extends PluginBase { private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final Context context; + private final AapsSchedulers aapsSchedulers; private final FabricPrivacy fabricPrivacy; private final SP sp; private final Config config; @@ -96,6 +97,7 @@ public class NSClientPlugin extends PluginBase { public NSClientPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, ResourceHelper resourceHelper, Context context, @@ -119,6 +121,7 @@ public class NSClientPlugin extends PluginBase { ); this.aapsLogger = aapsLogger; + this.aapsSchedulers = aapsSchedulers; this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.context = context; @@ -158,7 +161,7 @@ public class NSClientPlugin extends PluginBase { nsClientReceiverDelegate.grabReceiversState(); disposable.add(rxBus .toObservable(EventNSClientStatus.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { status = event.getStatus(resourceHelper); rxBus.send(new EventNSClientUpdateGUI()); @@ -166,17 +169,17 @@ public class NSClientPlugin extends PluginBase { ); disposable.add(rxBus .toObservable(EventNetworkChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (nsClientService != null) { context.unbindService(mConnection); @@ -185,7 +188,7 @@ public class NSClientPlugin extends PluginBase { ); disposable.add(rxBus .toObservable(EventNSClientNewLog.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { addToLog(event); aapsLogger.debug(LTag.NSCLIENT, event.getAction() + " " + event.getLogText()); @@ -193,12 +196,12 @@ public class NSClientPlugin extends PluginBase { ); disposable.add(rxBus .toObservable(EventChargingState.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientResend.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> resend(event.getReason()), fabricPrivacy::logException) ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 43950c67ca..90c461b7a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -68,9 +68,9 @@ import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.buildHelper.BuildHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; @@ -78,6 +78,7 @@ import io.socket.emitter.Emitter; public class NSClientService extends DaggerService { @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; + @Inject AapsSchedulers aapsSchedulers; @Inject NSSettingsStatus nsSettingsStatus; @Inject NSDeviceStatus nsDeviceStatus; @Inject DatabaseHelperInterface databaseHelper; @@ -147,7 +148,7 @@ public class NSClientService extends DaggerService { disposable.add(rxBus .toObservable(EventConfigBuilderChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (nsEnabled != nsClientPlugin.isEnabled(PluginType.GENERAL)) { latestDateInReceivedData = 0; @@ -158,7 +159,7 @@ public class NSClientService extends DaggerService { ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event.isChanged(resourceHelper, R.string.key_nsclientinternal_url) || event.isChanged(resourceHelper, R.string.key_nsclientinternal_api_secret) || @@ -172,7 +173,7 @@ public class NSClientService extends DaggerService { ); disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received"); destroy(); @@ -181,7 +182,7 @@ public class NSClientService extends DaggerService { ); disposable.add(rxBus .toObservable(EventNSClientRestart.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { latestDateInReceivedData = 0; restart(); @@ -189,17 +190,17 @@ public class NSClientService extends DaggerService { ); disposable.add(rxBus .toObservable(NSAuthAck.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(this::processAuthAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSUpdateAck.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(this::processUpdateAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSAddAck.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(this::processAddAck, fabricPrivacy::logException) ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt index e22130d998..fb8faa1bcb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt @@ -18,11 +18,10 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.BackpressureStrategy import io.reactivex.Single -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject @@ -37,25 +36,23 @@ class OpenHumansFragment : DaggerFragment() { private var queueSizeValue = 0L private val compositeDisposable = CompositeDisposable() - @Inject - lateinit var rxBus: RxBusWrapper - - @Inject - lateinit var openHumansUploader: OpenHumansUploader - - @Inject - lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var openHumansUploader: OpenHumansUploader + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var aapsSchedulers: AapsSchedulers override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) compositeDisposable += Single.fromCallable { MainApp.getDbHelper().ohQueueSize } - .subscribeOn(Schedulers.io()) - .repeatWhen { rxBus.toObservable(UpdateViewEvent::class.java) - .cast(Any::class.java) - .mergeWith(rxBus.toObservable(UpdateQueueEvent::class.java) - .throttleLatest(5, TimeUnit.SECONDS)) - .toFlowable(BackpressureStrategy.LATEST) } - .observeOn(AndroidSchedulers.mainThread()) + .subscribeOn(aapsSchedulers.io) + .repeatWhen { + rxBus.toObservable(UpdateViewEvent::class.java) + .cast(Any::class.java) + .mergeWith(rxBus.toObservable(UpdateQueueEvent::class.java) + .throttleLatest(5, TimeUnit.SECONDS)) + .toFlowable(BackpressureStrategy.LATEST) + } + .observeOn(aapsSchedulers.main) .subscribe({ queueSizeValue = it updateGUI() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansLoginActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansLoginActivity.kt index b9395f5416..ecb110d6dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansLoginActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansLoginActivity.kt @@ -14,8 +14,8 @@ import androidx.fragment.app.FragmentActivity import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.NoSplashAppCompatActivity +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.Disposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject class OpenHumansLoginActivity : NoSplashAppCompatActivity() { @@ -45,8 +45,8 @@ class OpenHumansLoginActivity : NoSplashAppCompatActivity() { class ExchangeAuthTokenDialog : DaggerDialogFragment() { - @Inject - lateinit var openHumansUploader: OpenHumansUploader + @Inject lateinit var openHumansUploader: OpenHumansUploader + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: Disposable? = null @@ -63,7 +63,7 @@ class OpenHumansLoginActivity : NoSplashAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - disposable = openHumansUploader.login(arguments?.getString("authToken")!!).subscribeOn(Schedulers.io()).subscribe({ + disposable = openHumansUploader.login(arguments?.getString("authToken")!!).subscribeOn(aapsSchedulers.io).subscribe({ dismiss() SetupDoneDialog().show(parentFragmentManager, "SetupDoneDialog") }, { 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 eefaa2963e..373d3fb327 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 @@ -27,13 +27,13 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable -import io.reactivex.schedulers.Schedulers import org.json.JSONArray import org.json.JSONException import org.json.JSONObject @@ -52,10 +52,11 @@ class OpenHumansUploader @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - val sp: SP, - val rxBus: RxBusWrapper, - val context: Context, - val treatmentsPlugin: TreatmentsPlugin + private val aapsSchedulers: AapsSchedulers, + private val sp: SP, + private val rxBus: RxBusWrapper, + private val context: Context, + private val treatmentsPlugin: TreatmentsPlugin ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) @@ -85,6 +86,7 @@ class OpenHumansUploader @Inject constructor( } private val openHumansAPI = OpenHumansAPI(OPEN_HUMANS_URL, CLIENT_ID, CLIENT_SECRET, REDIRECT_URL) + @Suppress("PrivatePropertyName") private val FILE_NAME_DATE_FORMAT = SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") } @@ -401,7 +403,7 @@ class OpenHumansUploader @Inject constructor( wakeLock.release() } .onErrorComplete() - .subscribeOn(Schedulers.io()) + .subscribeOn(aapsSchedulers.io) .subscribe() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index a06fe3fdd0..a9d1c0348a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -59,12 +59,11 @@ import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.androidaps.utils.wizard.QuickWizard -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -80,6 +79,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -209,63 +209,63 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList super.onResume() disposable.add(rxBus .toObservable(EventRefreshOverview::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ if (it.now) updateGUI(it.from) else scheduleUpdateGUI(it.from) - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventExtendedBolusChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventExtendedBolusChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventTempBasalChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventTempBasalChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTreatmentChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventTreatmentChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventTreatmentChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTempTargetChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventTempTargetChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventTempTargetChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventAcceptOpenLoopChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventCareportalEventChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventCareportalEventChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventCareportalEventChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventInitializationChanged::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventInitializationChanged") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventInitializationChanged") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventAutosensCalculationFinished") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventAutosensCalculationFinished") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventProfileNeedsUpdate") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventProfileNeedsUpdate") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventPreferenceChange") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventPreferenceChange") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventNewOpenLoopNotification::class.java) - .observeOn(Schedulers.io()) - .subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updatePumpStatus(it) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updatePumpStatus(it) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventIobCalculationProgress::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ binding.graphsLayout.iobCalculationProgress.text = it.progress }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ binding.graphsLayout.iobCalculationProgress.text = it.progress }, fabricPrivacy::logException)) refreshLoop = Runnable { scheduleUpdateGUI("refreshLoop") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 7f82ccbd09..d010dea773 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -16,12 +16,11 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNo import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.* import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.json.JSONObject import javax.inject.Inject import javax.inject.Singleton @@ -34,6 +33,7 @@ class OverviewPlugin @Inject constructor( private val rxBus: RxBusWrapper, private val sp: SP, aapsLogger: AAPSLogger, + private val aapsSchedulers: AapsSchedulers, resourceHelper: ResourceHelper, private val config: Config ) : PluginBase(PluginDescription() @@ -56,18 +56,18 @@ class OverviewPlugin @Inject constructor( notificationStore.createNotificationChannel() disposable += rxBus .toObservable(EventNewNotification::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ n -> if (notificationStore.add(n.notification)) rxBus.send(EventRefreshOverview("EventNewNotification")) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventDismissNotification::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ n -> if (notificationStore.remove(n.id)) rxBus.send(EventRefreshOverview("EventDismissNotification")) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) } override fun onStop() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt index b8923981fd..0256647221 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt @@ -18,13 +18,14 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWiza import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.wizard.QuickWizard -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class QuickWizardListActivity : NoSplashAppCompatActivity() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var quickWizard: QuickWizard @@ -95,11 +96,11 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() { super.onResume() disposable += rxBus .toObservable(EventQuickWizardChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ val adapter = RecyclerViewAdapter(supportFragmentManager) binding.recyclerview.swapAdapter(adapter, false) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) } override fun onPause() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt index 6d45fcd721..3534146fe0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt @@ -12,8 +12,8 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.androidNotification.NotificationHolder +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject /** @@ -21,6 +21,7 @@ import javax.inject.Inject */ class DummyService : DaggerService() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -47,7 +48,7 @@ class DummyService : DaggerService() { } disposable.add(rxBus .toObservable(EventAppExit::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ aapsLogger.debug(LTag.CORE, "EventAppExit received") stopSelf() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index b26b84cfed..96fbefbc65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -7,10 +7,8 @@ import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.app.RemoteInput -import androidx.core.app.TaskStackBuilder import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* @@ -26,8 +24,8 @@ import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.androidNotification.openAppIntent import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @@ -37,6 +35,7 @@ class PersistentNotificationPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val profileFunction: ProfileFunction, private val fabricPrivacy: FabricPrivacy, private val activePlugins: ActivePluginProvider, @@ -74,36 +73,36 @@ class PersistentNotificationPlugin @Inject constructor( createNotificationChannel() // make sure channels exist before triggering updates through the bus disposable.add(rxBus .toObservable(EventRefreshOverview::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTreatmentChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventInitializationChanged::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventNewBasalProfile::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ triggerNotificationUpdate() }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) triggerNotificationUpdate() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt index 092f67aa38..0f61f217f2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.extensions.plusAssign -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject @@ -20,6 +20,7 @@ import kotlin.math.max class SmsCommunicatorFragment : DaggerFragment() { + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @@ -45,8 +46,8 @@ class SmsCommunicatorFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventSmsCommunicatorUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index b83b56ea8e..7bf5fb22c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -38,10 +38,10 @@ import info.nightscout.androidaps.receivers.BundleStore import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.apache.commons.lang3.StringUtils import java.text.Normalizer import java.util.* @@ -55,6 +55,7 @@ class SmsCommunicatorPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val sp: SP, private val constraintChecker: ConstraintChecker, private val rxBus: RxBusWrapper, @@ -107,8 +108,8 @@ class SmsCommunicatorPlugin @Inject constructor( super.onStart() disposable += rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ event: EventPreferenceChange? -> processSettings(event) }, fabricPrivacy::logException) } override fun onStop() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolFragment.kt index 760ecc61b3..3da7ec902b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolFragment.kt @@ -15,17 +15,19 @@ import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolR import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolUpdateGUI import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class TidepoolFragment : DaggerFragment() { + @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var tidepoolPlugin: TidepoolPlugin @Inject lateinit var tidepoolUploader: TidepoolUploader @Inject lateinit var sp: SP @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: CompositeDisposable = CompositeDisposable() @@ -53,7 +55,7 @@ class TidepoolFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventTidepoolUpdateGUI::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ if (_binding == null) return@subscribe tidepoolPlugin.updateLog() @@ -61,7 +63,7 @@ class TidepoolFragment : DaggerFragment() { binding.status.text = tidepoolUploader.connectionStatus.name binding.log.text = tidepoolPlugin.textLog binding.logscrollview.fullScroll(ScrollView.FOCUS_DOWN) - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) } @Synchronized @@ -76,5 +78,4 @@ class TidepoolFragment : DaggerFragment() { _binding = null } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt index 701221e361..5492f801a5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt @@ -32,9 +32,9 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -44,6 +44,7 @@ class TidepoolPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBusWrapper, private val context: Context, private val fabricPrivacy: FabricPrivacy, @@ -71,11 +72,11 @@ class TidepoolPlugin @Inject constructor( super.onStart() disposable += rxBus .toObservable(EventTidepoolDoUpload::class.java) - .observeOn(Schedulers.io()) - .subscribe({ doUpload() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ doUpload() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTidepoolResetData::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ if (tidepoolUploader.connectionStatus != CONNECTED) { aapsLogger.debug(LTag.TIDEPOOL, "Not connected for delete Dataset") @@ -84,18 +85,14 @@ class TidepoolPlugin @Inject constructor( sp.putLong(R.string.key_tidepool_last_end, 0) tidepoolUploader.doLogin() } - }, { - fabricPrivacy.logException(it) - }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTidepoolStatus::class.java) - .observeOn(Schedulers.io()) - .subscribe({ event -> addToLog(event) }, { - fabricPrivacy.logException(it) - }) + .observeOn(aapsSchedulers.io) + .subscribe({ event -> addToLog(event) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNewBG::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .filter { it.bgReading != null } // better would be optional in API level >24 .map { it.bgReading } .subscribe({ bgReading -> @@ -106,27 +103,21 @@ class TidepoolPlugin @Inject constructor( && (!sp.getBoolean(R.string.key_tidepool_only_while_unmetered, false) || receiverStatusStore.isWifiConnected) && rateLimit.rateLimit("tidepool-new-data-upload", T.mins(4).secs().toInt())) doUpload() - }, { - fabricPrivacy.logException(it) - }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ event -> if (event.isChanged(resourceHelper, R.string.key_tidepool_dev_servers) || event.isChanged(resourceHelper, R.string.key_tidepool_username) || event.isChanged(resourceHelper, R.string.key_tidepool_password) ) tidepoolUploader.resetInstance() - }, { - fabricPrivacy.logException(it) - }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventNetworkChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({}, { - fabricPrivacy.logException(it) - }) // TODO start upload on wifi connect + .observeOn(aapsSchedulers.io) + .subscribe({}, fabricPrivacy::logException) // TODO start upload on wifi connect } @@ -150,7 +141,7 @@ class TidepoolPlugin @Inject constructor( private fun doUpload() = when (tidepoolUploader.connectionStatus) { DISCONNECTED -> tidepoolUploader.doLogin(true) - CONNECTED -> tidepoolUploader.doUpload() + CONNECTED -> tidepoolUploader.doUpload() else -> { } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index 3325e48ca1..84acfc5667 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -10,8 +10,8 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress @@ -19,9 +19,9 @@ import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpda import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @@ -30,6 +30,7 @@ class WearPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val sp: SP, private val mainApp: MainApp, private val fabricPrivacy: FabricPrivacy, @@ -52,57 +53,57 @@ class WearPlugin @Inject constructor( super.onStart() disposable.add(rxBus .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventTreatmentChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventNewBasalProfile::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }) { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.io) + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ // possibly new high or low mark resendDataToWatch() // status may be formatted differently sendDataToWatch(status = true, basals = false, bgValue = false) - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventRefreshOverview::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ if (WatchUpdaterService.shouldReportLoopStatus(loopPlugin.get().isEnabled(PluginType.LOOP))) sendDataToWatch(status = true, basals = false, bgValue = false) - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventBolusRequested::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ event: EventBolusRequested -> val status = String.format(resourceHelper.gs(R.string.bolusrequested), event.amount) val intent = Intent(mainApp, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) intent.putExtra("progresspercent", 0) intent.putExtra("progressstatus", status) mainApp.startService(intent) - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventDismissBolusProgressIfRunning::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ event: EventDismissBolusProgressIfRunning -> if (event.result == null) return@subscribe val status: String = if (event.result!!.success) { @@ -114,10 +115,10 @@ class WearPlugin @Inject constructor( intent.putExtra("progresspercent", 100) intent.putExtra("progressstatus", status) mainApp.startService(intent) - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventOverviewBolusProgress::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ event: EventOverviewBolusProgress -> if (!event.isSMB() || sp.getBoolean("wear_notifySMB", true)) { val intent = Intent(mainApp, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) @@ -125,7 +126,7 @@ class WearPlugin @Inject constructor( intent.putExtra("progressstatus", event.status) mainApp.startService(intent) } - }) { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException)) } override fun onStop() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index f5285334f1..63ada549fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -11,19 +11,19 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @@ -33,6 +33,7 @@ class StatusLinePlugin @Inject constructor( private val sp: SP, private val profileFunction: ProfileFunction, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val activePlugin: ActivePluginProvider, @@ -56,6 +57,7 @@ class StatusLinePlugin @Inject constructor( private var lastLoopStatus = false companion object { + //broadcast related constants @Suppress("SpellCheckingInspection") private const val EXTRA_STATUSLINE = "com.eveningoutpost.dexdrip.Extras.Statusline" @@ -70,29 +72,29 @@ class StatusLinePlugin @Inject constructor( override fun onStart() { super.onStart() disposable += rxBus.toObservable(EventRefreshOverview::class.java) - .observeOn(Schedulers.io()) - .subscribe({ if (lastLoopStatus != loopPlugin.isEnabled(PluginType.LOOP)) sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ if (lastLoopStatus != loopPlugin.isEnabled(PluginType.LOOP)) sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventExtendedBolusChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventTempBasalChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventTreatmentChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventConfigBuilderChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventAppInitialized::class.java) - .observeOn(Schedulers.io()) - .subscribe({ sendStatus() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ sendStatus() }, fabricPrivacy::logException) } override fun onStop() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index a9f29b6151..e8f4ab6249 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventConfigBuilderChange; @@ -34,32 +35,32 @@ import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryBgData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; @Singleton public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculatorInterface { private final HasAndroidInjector injector; + private final AapsSchedulers aapsSchedulers; private final SP sp; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; @@ -96,6 +97,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat public IobCobCalculatorPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, SP sp, ResourceHelper resourceHelper, @@ -117,6 +119,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat aapsLogger, resourceHelper, injector ); this.injector = injector; + this.aapsSchedulers = aapsSchedulers; this.sp = sp; this.rxBus = rxBus; this.resourceHelper = resourceHelper; @@ -136,7 +139,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat // EventConfigBuilderChange disposable.add(rxBus .toObservable(EventConfigBuilderChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { stopCalculation("onEventConfigBuilderChange"); synchronized (dataLock) { @@ -149,7 +152,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat // EventNewBasalProfile disposable.add(rxBus .toObservable(EventNewBasalProfile.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event == null) { // on init no need of reset return; @@ -165,7 +168,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat // EventNewBG .... cannot be used for invalidating because only event with last BG is fired disposable.add(rxBus .toObservable(EventNewBG.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { stopCalculation("onEventNewBG"); runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, event); @@ -174,7 +177,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat // EventPreferenceChange disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event.isChanged(resourceHelper, R.string.key_openapsama_autosens_period) || event.isChanged(resourceHelper, R.string.key_age) || @@ -197,19 +200,19 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat // EventAppInitialized disposable.add(rxBus .toObservable(EventAppInitialized.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, event), fabricPrivacy::logException) ); // EventNewHistoryData disposable.add(rxBus .toObservable(EventNewHistoryData.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> newHistoryData(event, false), fabricPrivacy::logException) ); // EventNewHistoryBgData disposable.add(rxBus .toObservable(EventNewHistoryBgData.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> newHistoryData(new EventNewHistoryData(event.getTimestamp()), true), fabricPrivacy::logException) ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index e7f5b7b639..88a623a091 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -22,7 +22,7 @@ import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.text.DecimalFormat import javax.inject.Inject @@ -37,6 +37,7 @@ class LocalProfileFragment : DaggerFragment() { @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var hardLimits: HardLimits @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: CompositeDisposable = CompositeDisposable() @@ -213,9 +214,8 @@ class LocalProfileFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventLocalProfileChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ build() }, { fabricPrivacy.logException(it) } - ) + .observeOn(aapsSchedulers.main) + .subscribe({ build() },fabricPrivacy::logException) build() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index 67470b3df9..b3c8a98dd8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -31,6 +31,7 @@ class NSProfileFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var nsProfilePlugin: NSProfilePlugin + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: CompositeDisposable = CompositeDisposable() @@ -117,8 +118,8 @@ class NSProfileFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventNSProfileUpdateGUI::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index 80df605acf..fd76ef6ae9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.combo; -import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; @@ -28,8 +27,8 @@ import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; public class ComboFragment extends DaggerFragment implements View.OnClickListener { @@ -39,6 +38,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene @Inject RxBusWrapper rxBus; @Inject SP sp; @Inject FabricPrivacy fabricPrivacy; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -81,12 +81,12 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene super.onResume(); disposable.add(rxBus .toObservable(EventComboPumpUpdateGUI.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> updateGui(), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventQueueChanged.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> updateGui(), fabricPrivacy::logException) ); updateGui(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 0de43b35f7..82523c20dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -35,7 +35,7 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.resources.ResourceHelper; -import io.reactivex.android.schedulers.AndroidSchedulers; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.disposables.CompositeDisposable; public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener { @@ -45,6 +45,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick @Inject ResourceHelper resourceHelper; @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -80,7 +81,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick super.onResume(); disposable.add(rxBus .toObservable(EventLocalInsightUpdateGUI.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> updateGUI(), fabricPrivacy::logException) ); updateGUI(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt index 88a81e27f5..b6f92b6c79 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -28,6 +28,7 @@ class VirtualPumpFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -57,16 +58,16 @@ class VirtualPumpFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventVirtualPumpUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index d5eab6b5d0..b9af60afcf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -20,22 +20,22 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType -import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.InstanceId.instanceId import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.json.JSONException import org.json.JSONObject import javax.inject.Inject @@ -49,6 +49,7 @@ class VirtualPumpPlugin @Inject constructor( private val rxBus: RxBusWrapper, private var fabricPrivacy: FabricPrivacy, resourceHelper: ResourceHelper, + private val aapsSchedulers: AapsSchedulers, private val sp: SP, private val profileFunction: ProfileFunction, private val treatmentsPlugin: TreatmentsPlugin, @@ -67,7 +68,6 @@ class VirtualPumpPlugin @Inject constructor( injector, aapsLogger, resourceHelper, commandQueue ), PumpInterface { - private val disposable = CompositeDisposable() var batteryPercent = 50 var reservoirInUnits = 50 @@ -112,8 +112,8 @@ class VirtualPumpPlugin @Inject constructor( super.onStart() disposable += rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ event: EventPreferenceChange -> if (event.isChanged(resourceHelper, R.string.key_virtualpump_type)) refreshConfiguration() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ event: EventPreferenceChange -> if (event.isChanged(resourceHelper, R.string.key_virtualpump_type)) refreshConfiguration() }, fabricPrivacy::logException) refreshConfiguration() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt index a9489a0a55..3c9f8ffef7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -41,6 +41,7 @@ class BGSourceFragment : DaggerFragment() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @Inject lateinit var databaseHelper: DatabaseHelperInterface + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() private val millsToThePast = T.hours(12).msecs() @@ -68,13 +69,13 @@ class BGSourceFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventNewBG::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventNewHistoryBgData::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) ) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 12c17d6c7e..49d1070b7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -49,8 +49,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryDa import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.JsonHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; /** @@ -65,6 +65,7 @@ public class TreatmentService extends OrmLiteBaseService { @Inject MedtronicPumpPlugin medtronicPumpPlugin; @Inject DatabaseHelperInterface databaseHelper; @Inject OpenHumansUploader openHumansUploader; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -77,7 +78,7 @@ public class TreatmentService extends OrmLiteBaseService { dbInitialize(); disposable.add(rxBus .toObservable(EventNsTreatment.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { int mode = event.getMode(); JSONObject payload = event.getPayload(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt index af9b1aa8cb..b3e48679cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -28,6 +28,7 @@ class TreatmentsFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -76,7 +77,7 @@ class TreatmentsFragment : DaggerFragment() { super.onResume() disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index cf7a11dcd3..b1a02ce819 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -62,14 +62,15 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { private final Context context; + private final AapsSchedulers aapsSchedulers; private final SP sp; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; @@ -98,6 +99,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface HasAndroidInjector injector, AAPSLogger aapsLogger, RxBusWrapper rxBus, + AapsSchedulers aapsSchedulers, ResourceHelper resourceHelper, Context context, SP sp, @@ -122,6 +124,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface this.resourceHelper = resourceHelper; this.context = context; this.rxBus = rxBus; + this.aapsSchedulers = aapsSchedulers; this.sp = sp; this.profileFunction = profileFunction; this.activePlugin = activePlugin; @@ -138,7 +141,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface super.onStart(); disposable.add(rxBus .toObservable(EventReloadTreatmentData.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTreatmentData"); initializeTreatmentData(range()); @@ -150,19 +153,19 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface )); disposable.add(rxBus .toObservable(EventReloadProfileSwitchData.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> initializeProfileSwitchData(range()), fabricPrivacy::logException )); disposable.add(rxBus .toObservable(EventTempTargetChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> initializeTempTargetData(range()), fabricPrivacy::logException )); disposable.add(rxBus .toObservable(EventReloadTempBasalData.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { getAapsLogger().debug(LTag.DATATREATMENTS, "EventReloadTempBasalData"); initializeTempBasalData(range()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt index 447a2206c6..7c7c6dd579 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt @@ -28,8 +28,8 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -47,6 +47,7 @@ class TreatmentsBolusFragment : DaggerFragment() { @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper + @Inject lateinit var aapsSchedulers: AapsSchedulers private var _binding: TreatmentsBolusFragmentBinding? = null @@ -94,13 +95,13 @@ class TreatmentsBolusFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventTreatmentChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index f3b0a28ae0..54fc2f592d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -25,8 +25,8 @@ import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -43,6 +43,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper + @Inject lateinit var aapsSchedulers: AapsSchedulers private var _binding: TreatmentsCareportalFragmentBinding? = null @@ -93,7 +94,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventCareportalEventChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt index e519665853..f3a47b88ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -45,6 +45,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers private var _binding: TreatmentsExtendedbolusFragmentBinding? = null @@ -135,13 +136,13 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGui() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt index e4a43027d8..2ab82a8a36 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt @@ -30,8 +30,8 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -48,6 +48,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper + @Inject lateinit var aapsSchedulers: AapsSchedulers private var _binding: TreatmentsProfileswitchFragmentBinding? = null @@ -80,7 +81,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) ) updateGUI() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt index 52c97eb0aa..9b41d72243 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt @@ -30,8 +30,8 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -47,6 +47,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -80,7 +81,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventTempTargetChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt index 45abbff111..82c500db21 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -27,7 +27,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -41,6 +41,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers private var _binding: TreatmentsTempbasalsFragmentBinding? = null @@ -63,12 +64,12 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { super.onResume() disposable.add(rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) ) updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index b2d141b0f2..a94806bd5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -25,7 +25,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification @@ -36,9 +35,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -87,16 +86,17 @@ import javax.inject.Singleton @Singleton class CommandQueue @Inject constructor( private val injector: HasAndroidInjector, - val aapsLogger: AAPSLogger, - val rxBus: RxBusWrapper, - val resourceHelper: ResourceHelper, - val constraintChecker: ConstraintChecker, - val profileFunction: ProfileFunction, - val activePlugin: Lazy, - val context: Context, - val sp: SP, + private val aapsLogger: AAPSLogger, + private val rxBus: RxBusWrapper, + private val aapsSchedulers: AapsSchedulers, + private val resourceHelper: ResourceHelper, + private val constraintChecker: ConstraintChecker, + private val profileFunction: ProfileFunction, + private val activePlugin: Lazy, + private val context: Context, + private val sp: SP, private val buildHelper: BuildHelper, - val fabricPrivacy: FabricPrivacy + private val fabricPrivacy: FabricPrivacy ) : CommandQueueProvider { private val disposable = CompositeDisposable() @@ -109,7 +109,7 @@ class CommandQueue @Inject constructor( init { disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ aapsLogger.debug(LTag.PROFILE, "onProfileSwitch") profileFunction.getProfile()?.let { @@ -127,7 +127,7 @@ class CommandQueue @Inject constructor( } }) } - }) { exception: Throwable -> fabricPrivacy.logException(exception) } + }, fabricPrivacy::logException) ) } @@ -208,7 +208,7 @@ class CommandQueue @Inject constructor( override fun independentConnect(reason: String, callback: Callback?) { aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") - val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, fabricPrivacy) + val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, fabricPrivacy) tempCommandQueue.readStatus(reason, callback) } @@ -292,7 +292,7 @@ class CommandQueue @Inject constructor( } removeAll(CommandType.BOLUS) removeAll(CommandType.SMB_BOLUS) - Thread(Runnable { activePlugin.get().activePump.stopBolusDelivering() }).run() + Thread { activePlugin.get().activePump.stopBolusDelivering() }.run() } // returns true if command is queued @@ -500,7 +500,7 @@ class CommandQueue @Inject constructor( @Synchronized override fun isCustomCommandInQueue(customCommandType: Class): Boolean { - if(isCustomCommandRunning(customCommandType)) { + if (isCustomCommandRunning(customCommandType)) { return true } synchronized(queue) { diff --git a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt index fe2d02ba66..ae116f03df 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt +++ b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt @@ -25,9 +25,9 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.androidNotification.NotificationHolder +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import javax.inject.Inject class LocationService : DaggerService() { @@ -35,6 +35,7 @@ class LocationService : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var notificationHolder: NotificationHolder @Inject lateinit var lastLocationDataContainer: LastLocationDataContainer @@ -137,11 +138,11 @@ class LocationService : DaggerService() { } disposable.add(rxBus .toObservable(EventAppExit::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe({ aapsLogger.debug(LTag.LOCATION, "EventAppExit received") stopSelf() - }) { fabricPrivacy.logException(it) } + }, fabricPrivacy::logException) ) } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt index 5a7806b9a7..e0326133f1 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt @@ -7,8 +7,9 @@ import android.widget.TextView import dagger.android.HasAndroidInjector import info.nightscout.androidaps.events.EventStatus import info.nightscout.androidaps.setupwizard.elements.SWItem -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable +import javax.inject.Inject class SWEventListener constructor( injector: HasAndroidInjector, @@ -21,11 +22,13 @@ class SWEventListener constructor( private var textView: TextView? = null private var visibilityValidator: SWValidator? = null + @Inject lateinit var aapsSchedulers: AapsSchedulers + // TODO: Adrian how to clear disposable in this case? init { disposable.add(rxBus .toObservable(clazz) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe { event: Any -> status = (event as EventStatus).getStatus(resourceHelper) @SuppressLint("SetTextI18n") diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt index 8bbde70d06..0313207d37 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt @@ -21,8 +21,8 @@ import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.locale.LocaleHelper.update +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import kotlin.math.max @@ -36,6 +36,7 @@ class SetupWizardActivity : NoSplashAppCompatActivity() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() private lateinit var screens: List @@ -77,36 +78,36 @@ class SetupWizardActivity : NoSplashAppCompatActivity() { swDefinition.activity = this disposable.add(rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateButtons() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateButtons() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventRileyLinkDeviceStatusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateButtons() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateButtons() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventNSClientStatus::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateButtons() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateButtons() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventProfileNeedsUpdate::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateButtons() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateButtons() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventProfileStoreChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateButtons() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ updateButtons() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventSWUpdate::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ event: EventSWUpdate -> if (event.redraw) generateLayout() updateButtons() - }) { fabricPrivacy.logException(it) } + }, fabricPrivacy::logException) ) updateButtons() } 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 b4d1d6ac81..12c2496796 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 @@ -1,9 +1,9 @@ package info.nightscout.androidaps.utils.stats +import android.content.Context import android.text.Spanned import android.util.LongSparseArray import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.interfaces.ActivePluginProvider @@ -21,6 +21,7 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject @@ -29,15 +30,16 @@ class TddCalculator @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, resourceHelper: ResourceHelper, - val mainApp: MainApp, - val sp: SP, - val activePlugin: ActivePluginProvider, - val profileFunction: ProfileFunction, + context: Context, + private val aapsSchedulers: AapsSchedulers, + private val sp: SP, + private val activePlugin: ActivePluginProvider, + private val profileFunction: ProfileFunction, fabricPrivacy: FabricPrivacy, nsUpload: NSUpload, private val dateUtil: DateUtil, uploadQueue: UploadQueue -) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue) { +) : TreatmentsPlugin(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil, uploadQueue) { init { service = TreatmentService(injector) // plugin is not started diff --git a/app/src/test/java/info/nightscout/androidaps/TestBase.kt b/app/src/test/java/info/nightscout/androidaps/TestBase.kt index 60022c99dd..ff88739ba2 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBase.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps import info.nightscout.androidaps.logging.AAPSLoggerTest +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import org.junit.Before import org.junit.Rule import org.mockito.Mockito @@ -11,6 +13,7 @@ import java.util.* open class TestBase { val aapsLogger = AAPSLoggerTest() + val aapsSchedulers: AapsSchedulers = TestAapsSchedulers() // Add a JUnit rule that will setup the @Mock annotated vars and log. // Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method. diff --git a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 7542f104e7..990a4f5b0a 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -14,6 +14,8 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import org.json.JSONObject import org.junit.Before import org.mockito.Mock @@ -29,7 +31,7 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var defaultValueHelper: DefaultValueHelper @Mock lateinit var dateUtil: DateUtil - val rxBus = RxBusWrapper() + val rxBus = RxBusWrapper(aapsSchedulers) val profileInjector = HasAndroidInjector { AndroidInjector { @@ -57,7 +59,7 @@ open class TestBaseWithProfile : TestBase() { } } - lateinit var validProfileJSON: String + private lateinit var validProfileJSON: String lateinit var validProfile: Profile val TESTPROFILENAME = "someProfile" diff --git a/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt b/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt index 0247ff9da5..e97af48150 100644 --- a/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.danars.comm import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.Config import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint @@ -55,7 +54,7 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_StartTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin({ AndroidInjector { } }, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt b/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt index 66ac024330..104ba1d13a 100644 --- a/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.kt @@ -68,7 +68,7 @@ class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) danaPump.bolusingTreatment = Treatment(packetInjector) } } \ No newline at end of file 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 c3e4ddbca5..a1a9fa796e 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -117,8 +117,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config()) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context) - danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) - danaRSPlugin = DanaRSPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) + danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) + danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsPlugin, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy, sp) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, treatmentsPlugin, iobCobCalculatorPlugin, hardLimits, profiler, fabricPrivacy) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index 1b93fed0cf..39658bf320 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -39,7 +39,7 @@ import org.powermock.modules.junit4.PowerMockRunner class LoopPluginTest : TestBase() { @Mock lateinit var sp: SP - private val rxBus: RxBusWrapper = RxBusWrapper() + private val rxBus: RxBusWrapper = RxBusWrapper(aapsSchedulers) @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @@ -62,7 +62,7 @@ class LoopPluginTest : TestBase() { @Before fun prepareMock() { hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, nsUpload) - loopPlugin = LoopPlugin(injector, aapsLogger, rxBus, sp, Config(), constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, treatmentsPlugin, virtualPumpPlugin, actionStringHandler, iobCobCalculatorPlugin, receiverStatusStore, fabricPrivacy, nsUpload, hardLimits) + loopPlugin = LoopPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, Config(), constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, treatmentsPlugin, virtualPumpPlugin, actionStringHandler, iobCobCalculatorPlugin, receiverStatusStore, fabricPrivacy, nsUpload, hardLimits) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(context.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt index c340f6b35b..4e7fc5e9cc 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt @@ -28,7 +28,7 @@ class ConfigBuilderPluginTest : TestBase() { @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var activePlugin: ActivePluginProvider - lateinit var configBuilderPlugin: ConfigBuilderPlugin + private lateinit var configBuilderPlugin: ConfigBuilderPlugin val injector = HasAndroidInjector { AndroidInjector { @@ -43,6 +43,6 @@ class ConfigBuilderPluginTest : TestBase() { @Before fun prepareMock() { - configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, resourceHelper, sp, RxBusWrapper(), activePlugin) + configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, resourceHelper, sp, RxBusWrapper(aapsSchedulers), activePlugin) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt index d1f147d691..16acf0592e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt @@ -4,7 +4,6 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -27,13 +26,13 @@ class DstHelperPluginTest : TestBase() { @Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var loopPlugin: LoopPlugin - lateinit var plugin: DstHelperPlugin + private lateinit var plugin: DstHelperPlugin val injector = HasAndroidInjector { AndroidInjector { } } @Before fun mock() { - plugin = DstHelperPlugin(injector, aapsLogger, RxBusWrapper(), resourceHelper, sp, activePlugin, loopPlugin) + plugin = DstHelperPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, sp, activePlugin, loopPlugin) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt index 706c663802..b54fd71efd 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt @@ -4,7 +4,6 @@ import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -13,10 +12,11 @@ import org.junit.Test import org.mockito.Mock class SignatureVerifierPluginTest : TestBase() { + @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var context: Context - private val rxBus = RxBusWrapper() + private val rxBus = RxBusWrapper(aapsSchedulers) val injector = HasAndroidInjector { AndroidInjector { } } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt index 31a960bcc3..90c1199dac 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.constraints.storage -import android.os.Environment -import android.os.StatFs import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase @@ -14,26 +12,25 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock -import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class StorageConstraintPluginTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper - private val rxBusWrapper = RxBusWrapper() + private val rxBusWrapper = RxBusWrapper(aapsSchedulers) - lateinit var storageConstraintPlugin: StorageConstraintPlugin + private lateinit var storageConstraintPlugin: StorageConstraintPlugin @Before fun prepareMock() { - storageConstraintPlugin = StorageConstraintPlugin(HasAndroidInjector { AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) + storageConstraintPlugin = StorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) } class MockedStorageConstraintPlugin constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, - private val rxBus: RxBusWrapper + rxBus: RxBusWrapper ) : StorageConstraintPlugin(injector, aapsLogger, resourceHelper, rxBus) { var memSize = 150L @@ -41,7 +38,7 @@ class StorageConstraintPluginTest : TestBase() { } @Test fun isLoopInvocationAllowedTest() { - val mocked = MockedStorageConstraintPlugin(HasAndroidInjector { AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) + val mocked = MockedStorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) // Set free space under 200(Mb) to disable loop mocked.memSize = 150L Assert.assertEquals(false, mocked.isClosedLoopAllowed(Constraint(true)).value()) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt index 8d85f1e340..b9d2db18da 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt @@ -21,7 +21,7 @@ class VersionCheckerUtilsKtTest : TestBase() { @Mock lateinit var context: Context val config = Config() - val rxBus = RxBusWrapper() + private val rxBus = RxBusWrapper(aapsSchedulers) @Before fun setup() { versionCheckerUtils = VersionCheckerUtils(aapsLogger, sp, resourceHelper, rxBus, config, context) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt index 75a3b202e3..9ac5cb8d07 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin @@ -36,7 +35,7 @@ class AutomationEventTest : TestBase() { it.loopPlugin = loopPlugin it.resourceHelper = resourceHelper it.configBuilderPlugin = configBuilderPlugin - it.rxBus = RxBusWrapper() + it.rxBus = RxBusWrapper(aapsSchedulers) } } } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt index bda0b5c532..b610dd3188 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt @@ -42,7 +42,7 @@ open class TriggerTestBase : TestBaseWithProfile() { AndroidInjector { if (it is Trigger) { it.aapsLogger = aapsLogger - it.rxBus = RxBusWrapper() + it.rxBus = RxBusWrapper(aapsSchedulers) it.resourceHelper = resourceHelper it.profileFunction = profileFunction it.sp = sp diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt index b3a275d255..671178dfd9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt @@ -33,7 +33,7 @@ class NsClientReceiverDelegateTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper lateinit var receiverStatusStore: ReceiverStatusStore - val rxBus: RxBusWrapper = RxBusWrapper() + val rxBus = RxBusWrapper(aapsSchedulers) private var sut: NsClientReceiverDelegate? = null diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index e21fc77cc7..5c5c79f016 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -114,7 +114,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { `when`(SmsManager.getDefault()).thenReturn(smsManager) `when`(sp.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678") - smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculatorPlugin, xdripCalibrations, otp, Config(), DateUtil(context, resourceHelper)) + smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculatorPlugin, xdripCalibrations, otp, Config(), DateUtil(context, resourceHelper)) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) Mockito.doAnswer { invocation: InvocationOnMock -> val callback = invocation.getArgument(1) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt index 9bb58a0738..1c13d8acfa 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt @@ -31,7 +31,7 @@ import java.util.* class IobCobCalculatorPluginTest : TestBase() { @Mock lateinit var sp: SP - private val rxBus: RxBusWrapper = RxBusWrapper() + private val rxBus = RxBusWrapper(aapsSchedulers) @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var activePlugin: ActivePluginProvider @@ -59,7 +59,7 @@ class IobCobCalculatorPluginTest : TestBase() { @Before fun mock() { - iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) + iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt index 46951f8730..bf455dd0bc 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt @@ -51,7 +51,7 @@ class ComboPluginTest : TestBase() { @Before fun prepareMocks() { `when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") - comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(), resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context) + comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, profileFunction, treatmentsPlugin, sp, commandQueue, context) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt index 7c46aa7f41..d450ef2687 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt @@ -46,7 +46,7 @@ class DanaRPluginTest : TestBaseWithProfile() { `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = info.nightscout.androidaps.dana.DanaPump(aapsLogger, sp, injector) - danaRPlugin = DanaRPlugin(injector, aapsLogger, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) + danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy) } @Test @Throws(Exception::class) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt index 602274a128..279076df49 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt @@ -55,7 +55,7 @@ open class DanaRTestBase : TestBase() { it.danaRPlugin = danaRPlugin it.danaRKoreanPlugin = danaRKoreanPlugin it.danaRv2Plugin = danaRv2Plugin - it.rxBus = RxBusWrapper() + it.rxBus = RxBusWrapper(aapsSchedulers) it.resourceHelper = resourceHelper it.activePlugin = activePluginProvider it.configBuilder = configBuilder diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt index f5e463523a..31b968ef12 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -46,7 +46,7 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, injector) - danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, rxBus, danaPump, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, dateUtil, fabricPrivacy) + danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, aapsSchedulers, rxBus, danaPump, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, dateUtil, fabricPrivacy) } @Test @Throws(Exception::class) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt index d1619600d5..eee474f841 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.kt @@ -65,6 +65,6 @@ class DanaRSPluginTest : DanaRSTestBase() { Mockito.`when`(resourceHelper.gs(eq(R.string.limitingbasalratio), anyObject(), anyObject())).thenReturn("limitingbasalratio") Mockito.`when`(resourceHelper.gs(eq(R.string.limitingpercentrate), anyObject(), anyObject())).thenReturn("limitingpercentrate") - danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin(HasAndroidInjector { AndroidInjector { Unit } }, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, activePluginProvider, sp, commandQueue, danaPump, detailedBolusInfoStorage, fabricPrivacy, dateUtil) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt index ec4bee9761..980779da3b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt @@ -46,7 +46,7 @@ class DanaRv2PluginTest : TestBaseWithProfile() { `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, injector) - danaRv2Plugin = DanaRv2Plugin(injector, aapsLogger, rxBus, context, danaPump, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, detailedBolusInfoStorage, dateUtil, fabricPrivacy) + danaRv2Plugin = DanaRv2Plugin(injector, aapsLogger, aapsSchedulers, rxBus, context, danaPump, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, detailedBolusInfoStorage, dateUtil, fabricPrivacy) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt index cdafb560a6..1d3db18e1c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt @@ -1,13 +1,12 @@ package info.nightscout.androidaps.plugins.pump.virtual import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil @@ -27,7 +26,7 @@ import org.powermock.modules.junit4.PowerMockRunner @PrepareForTest(FabricPrivacy::class) class VirtualPumpPluginUTest : TestBase() { - val rxBus = RxBusWrapper() + private val rxBus = RxBusWrapper(aapsSchedulers) @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var sp: SP @@ -40,7 +39,7 @@ class VirtualPumpPluginUTest : TestBase() { @Before fun prepareMocks() { - virtualPumpPlugin = VirtualPumpPlugin(HasAndroidInjector { AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, sp, profileFunction, treatmentsPlugin, commandQueue, Config(), dateUtil) + virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, treatmentsPlugin, commandQueue, Config(), dateUtil) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt index 1f2da4c70d..3b068ea810 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt @@ -1,10 +1,8 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert @@ -24,7 +22,7 @@ class NSClientPluginTest : TestBase() { @Before fun setup() { - nsClientSourcePlugin = NSClientSourcePlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger, sp, Config()) + nsClientSourcePlugin = NSClientSourcePlugin({ AndroidInjector { } }, resourceHelper, aapsLogger, Config()) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt index a8e1af60e9..5d742554e0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt @@ -60,7 +60,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() { `when`(profileFunction.getProfile(ArgumentMatchers.anyLong())).thenReturn(validProfile) `when`(activePluginProvider.activeInsulin).thenReturn(insulinOrefRapidActingPlugin) - sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, resourceHelper, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, uploadQueue) + sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, uploadQueue) sot.service = treatmentService } diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt index 505a823937..bccde087ea 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt @@ -11,10 +11,10 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.commands.Command +import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.buildHelper.BuildHelper @@ -55,7 +55,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Before fun prepare() { - commandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, buildHelper, fabricPrivacy) + commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, lazyActivePlugin, context, sp, buildHelper, fabricPrivacy) val pumpDescription = PumpDescription() pumpDescription.basalMinimumRate = 0.1 @@ -268,16 +268,19 @@ class CommandQueueTest : TestBaseWithProfile() { } private class CustomCommand1 : CustomCommand { + override val statusDescription: String get() = "CUSTOM COMMAND 1" } private class CustomCommand2 : CustomCommand { + override val statusDescription: String get() = "CUSTOM COMMAND 2" } private class CustomCommand3 : CustomCommand { + override val statusDescription: String get() = "CUSTOM COMMAND 3" } diff --git a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt index 5fb9bb1e77..5034861a23 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt @@ -52,7 +52,7 @@ class BolusWizardTest : TestBase() { if (it is BolusWizard) { it.aapsLogger = aapsLogger it.resourceHelper = resourceHelper - it.rxBus = RxBusWrapper() + it.rxBus = RxBusWrapper(aapsSchedulers) it.profileFunction = profileFunction it.constraintChecker = constraintChecker it.activePlugin = activePlugin diff --git a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index 2065e31b63..b9cc88fc28 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -45,6 +45,7 @@ import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; @@ -59,6 +60,7 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { @Inject CommandQueueProvider commandQueue; @Inject DatabaseHelperInterface databaseHelper; @Inject FabricPrivacy fabricPrivacy; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -83,12 +85,12 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity { super.onResume(); disposable.add(rxBus .toObservable(EventPumpStatusChanged.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> statusView.setText(event.getStatus(resourceHelper)), exception -> fabricPrivacy.logException(exception)) ); disposable.add(rxBus .toObservable(EventDanaRSyncStatus.class) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.getMain()) .subscribe(event -> { aapsLogger.debug("EventDanaRSyncStatus: " + event.getMessage()); statusView.setText(event.getMessage()); diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt index 22e5e0467f..6273d544f5 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBo import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -31,6 +31,7 @@ class BolusProgressDialog : DaggerDialogFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -111,17 +112,17 @@ class BolusProgressDialog : DaggerDialogFragment() { disposable.add(rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ binding.status.text = it.getStatus(resourceHelper) }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ binding.status.text = it.getStatus(resourceHelper) }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventDismissBolusProgressIfRunning::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ if (running) dismiss() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ if (running) dismiss() }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventOverviewBolusProgress::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ aapsLogger.debug(LTag.UI, "Status: ${it.status} Percent: ${it.percent}") binding.status.text = it.status @@ -131,7 +132,7 @@ class BolusProgressDialog : DaggerDialogFragment() { scheduleDismiss() } state = it.status - }) { fabricPrivacy.logException(it) } + }, fabricPrivacy::logException) ) } diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt index 927d8cf70c..7f01141dc1 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt @@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -25,6 +26,7 @@ class NtpProgressDialog : DaggerDialogFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -71,7 +73,7 @@ class NtpProgressDialog : DaggerDialogFragment() { disposable += rxBus .toObservable(EventNtpStatus::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ event: EventNtpStatus -> if (_binding != null) { aapsLogger.debug(LTag.UI, "Status: " + event.status + " Percent: " + event.percent) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt b/core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt index cb1bc903fa..a1444e296d 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt @@ -1,14 +1,16 @@ package info.nightscout.androidaps.plugins.bus import info.nightscout.androidaps.events.Event +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.Observable -import io.reactivex.schedulers.Schedulers import io.reactivex.subjects.PublishSubject import javax.inject.Inject import javax.inject.Singleton @Singleton -open class RxBusWrapper @Inject constructor() { +open class RxBusWrapper @Inject constructor( + val aapsSchedulers: AapsSchedulers +) { private val publisher = PublishSubject.create() @@ -20,6 +22,6 @@ open class RxBusWrapper @Inject constructor() { // Using ofType we filter only events that match that class type fun toObservable(eventType: Class): Observable = publisher - .subscribeOn(Schedulers.io()) + .subscribeOn(aapsSchedulers.io) .ofType(eventType) } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index f80f6fc04d..6d41ad4db0 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -41,6 +41,7 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @@ -70,6 +71,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI protected PumpDriverState pumpState = PumpDriverState.NotInitialized; protected boolean displayConnectionMessages = false; protected PumpType pumpType; + protected AapsSchedulers aapsSchedulers; protected PumpPluginAbstract( @@ -84,7 +86,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI SP sp, Context context, FabricPrivacy fabricPrivacy, - DateUtil dateUtil + DateUtil dateUtil, + AapsSchedulers aapsSchedulers ) { super(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue); @@ -100,6 +103,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI pumpDescription.setPumpDescription(pumpType); this.pumpType = pumpType; this.dateUtil = dateUtil; + this.aapsSchedulers = aapsSchedulers; } @@ -119,7 +123,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> context.unbindService(serviceConnection), fabricPrivacy::logException) ); onStartCustomActions(); diff --git a/core/src/main/java/info/nightscout/androidaps/utils/rx/AapsSchedulers.kt b/core/src/main/java/info/nightscout/androidaps/utils/rx/AapsSchedulers.kt new file mode 100644 index 0000000000..e05bbf975d --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/utils/rx/AapsSchedulers.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.utils.rx + +import io.reactivex.Scheduler +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.schedulers.Schedulers + +/** + * Created by adrian on 12.04.20. + */ + +interface AapsSchedulers { + val main: Scheduler + val io: Scheduler + val cpu: Scheduler +} + +class DefaultAapsSchedulers : AapsSchedulers { + override val main: Scheduler = AndroidSchedulers.mainThread() + override val io: Scheduler = Schedulers.io() + override val cpu: Scheduler = Schedulers.computation() +} + +class TestAapsSchedulers : AapsSchedulers { + override val main: Scheduler = Schedulers.trampoline() + override val io: Scheduler = Schedulers.trampoline() + override val cpu: Scheduler = Schedulers.trampoline() +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt b/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt new file mode 100644 index 0000000000..78e2db0e7a --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt @@ -0,0 +1,43 @@ +package info.nightscout.androidaps.utils.rx + +import io.reactivex.Completable +import io.reactivex.Flowable +import io.reactivex.Single +import java.util.concurrent.TimeUnit +import kotlin.math.pow + +/** + * Created by adrian on 12.04.20. + */ + +inline fun Single.retryExponentialBackoff(retries: Int, time: Long, timeUnit: TimeUnit): Single = + this.retryWhen { throwables: Flowable -> + throwables.zipWith( + Flowable.range(0, retries), + { throwable: Throwable, retryCount: Int -> + if (retryCount >= retries) { + throw throwable + } else { + retryCount + } + } + ).flatMap { retryCount: Int -> + Flowable.timer(time * 2.toDouble().pow(retryCount.toDouble()).toLong(), timeUnit) + } + } + +fun Completable.retryExponentialBackoff(retries: Int, time: Long, timeUnit: TimeUnit): Completable = + this.retryWhen { throwables: Flowable -> + throwables.zipWith( + Flowable.range(0, retries), + { throwable: Throwable, retryCount: Int -> + if (retryCount >= retries) { + throw throwable + } else { + retryCount + } + } + ).flatMap { retryCount: Int -> + Flowable.timer(time * 2.toDouble().pow(retryCount.toDouble()).toLong(), timeUnit) + } + } \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt index 6d9c93146f..7bd63eab06 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.dana +import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.Handler @@ -30,8 +31,8 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -47,6 +48,7 @@ class DanaFragment : DaggerFragment() { @Inject lateinit var sp: SP @Inject lateinit var warnColors: WarnColors @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: CompositeDisposable = CompositeDisposable() @@ -118,38 +120,39 @@ class DanaFragment : DaggerFragment() { loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) disposable += rxBus .toObservable(EventInitializationChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(info.nightscout.androidaps.dana.events.EventDanaRNewStatus::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventQueueChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ - when { - it.status == EventPumpStatusChanged.Status.CONNECTING -> + when (it.status) { + EventPumpStatusChanged.Status.CONNECTING -> @Suppress("SetTextI18n") binding.btconnection.text = "{fa-bluetooth-b spin} ${it.secondsElapsed}s" - it.status == EventPumpStatusChanged.Status.CONNECTED -> + EventPumpStatusChanged.Status.CONNECTED -> @Suppress("SetTextI18n") binding.btconnection.text = "{fa-bluetooth}" - it.status == EventPumpStatusChanged.Status.DISCONNECTED -> + EventPumpStatusChanged.Status.DISCONNECTED -> @Suppress("SetTextI18n") binding.btconnection.text = "{fa-bluetooth-b}" + else -> {} } if (it.getStatus(resourceHelper) != "") { binding.danaPumpstatus.text = it.getStatus(resourceHelper) @@ -174,6 +177,7 @@ class DanaFragment : DaggerFragment() { _binding = null } + @SuppressLint("SetTextI18n") @Synchronized fun updateGUI() { if (_binding == null) return @@ -199,7 +203,7 @@ class DanaFragment : DaggerFragment() { warnColors.setColor(binding.dailyunits, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75, pump.maxDailyTotalUnits * 0.9) binding.basabasalrate.text = "( " + (pump.activeProfile + 1) + " ) " + resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) // DanaRPlugin, DanaRKoreanPlugin - if (activePlugin.activePump.isFakingTempsByExtendedBoluses == true) { + if (activePlugin.activePump.isFakingTempsByExtendedBoluses) { binding.tempbasal.text = activePlugin.activeTreatments.getRealTempBasalFromHistory(System.currentTimeMillis())?.toStringFull() ?: "" } else { diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt index 9f9fd0e1a7..770f468536 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.util.* import javax.inject.Inject @@ -46,6 +46,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -63,15 +64,15 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { super.onResume() disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ binding.status.text = it.getStatus(resourceHelper) }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ binding.status.text = it.getStatus(resourceHelper) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventDanaRSyncStatus::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ aapsLogger.debug(LTag.PUMP, "EventDanaRSyncStatus: " + it.message) binding.status.text = it.message - }) { fabricPrivacy.logException(it) } + }, fabricPrivacy::logException) } override fun onPause() { diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt index 70ff917df7..0bf692cf40 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt @@ -19,7 +19,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.extensions.plusAssign -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import java.text.DecimalFormat import javax.inject.Inject @@ -35,6 +35,7 @@ class DanaUserOptionsActivity : NoSplashAppCompatActivity() { @Inject lateinit var danaPump: DanaPump @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -52,8 +53,8 @@ class DanaUserOptionsActivity : NoSplashAppCompatActivity() { super.onResume() disposable += rxBus .toObservable(EventInitializationChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ setData() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ setData() }, fabricPrivacy::logException) } @Synchronized diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java index 9439694815..bc73b69c61 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java @@ -37,9 +37,9 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class DanaRKoreanPlugin extends AbstractDanaRPlugin { @@ -55,6 +55,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { public DanaRKoreanPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, DanaPump danaPump, Context context, @@ -66,7 +67,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { DateUtil dateUtil, FabricPrivacy fabricPrivacy ) { - super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, activePlugin, sp, dateUtil); + super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; @@ -84,7 +85,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (isEnabled(PluginType.PUMP)) { boolean previousValue = useExtendedBoluses; @@ -98,7 +99,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { ); disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> context.unbindService(mConnection), fabricPrivacy::logException) ); super.onStart(); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index 30da4bd9d8..e9f3f15da6 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -36,9 +36,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class DanaRv2Plugin extends AbstractDanaRPlugin { @@ -58,6 +58,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public DanaRv2Plugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, Context context, DanaPump danaPump, @@ -70,7 +71,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { DateUtil dateUtil, FabricPrivacy fabricPrivacy ) { - super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, activePlugin, sp, dateUtil); + super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; @@ -90,7 +91,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> context.unbindService(mConnection), fabricPrivacy::logException) ); super.onStart(); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index 22c206ede5..dd34a34460 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -38,18 +38,18 @@ import info.nightscout.androidaps.plugins.common.ManufacturerType; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; -import info.nightscout.androidaps.queue.commands.CustomCommand; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; +import info.nightscout.androidaps.queue.commands.CustomCommand; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.TimeChangeType; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; /** * Created by mike on 28.01.2018. @@ -69,6 +69,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected ActivePluginProvider activePlugin; protected SP sp; protected DateUtil dateUtil; + protected AapsSchedulers aapsSchedulers; protected AbstractDanaRPlugin( HasAndroidInjector injector, @@ -76,6 +77,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump ResourceHelper resourceHelper, ConstraintChecker constraintChecker, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, CommandQueueProvider commandQueue, RxBusWrapper rxBus, ActivePluginProvider activePlugin, @@ -98,18 +100,19 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump this.activePlugin = activePlugin; this.sp = sp; this.dateUtil = dateUtil; + this.aapsSchedulers = aapsSchedulers; } @Override protected void onStart() { super.onStart(); disposable.add(rxBus .toObservable(EventConfigBuilderChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> danaPump.reset()) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event.isChanged(getResourceHelper(), R.string.key_danar_bt_name)) { danaPump.reset(); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index 6e145737cb..277c09d0c2 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -35,9 +35,9 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; @Singleton public class DanaRPlugin extends AbstractDanaRPlugin { @@ -53,6 +53,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { public DanaRPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, Context context, ResourceHelper resourceHelper, @@ -64,7 +65,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { DateUtil dateUtil, FabricPrivacy fabricPrivacy ) { - super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, activePlugin, sp, dateUtil); + super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; @@ -81,7 +82,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); disposable.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (isEnabled(PluginType.PUMP)) { boolean previousValue = useExtendedBoluses; @@ -95,7 +96,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { ); disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> context.unbindService(mConnection), fabricPrivacy::logException) ); super.onStart(); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java index bb02e4e136..1dc1853665 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java @@ -47,9 +47,9 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; /** * Created by mike on 28.01.2018. @@ -66,6 +66,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; @Inject DatabaseHelperInterface databaseHelper; + @Inject AapsSchedulers aapsSchedulers; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -114,7 +115,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { super.onCreate(); disposable.add(rxBus .toObservable(EventBTChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event.getState() == EventBTChange.Change.DISCONNECT) { aapsLogger.debug(LTag.PUMP, "Device was disconnected " + event.getDeviceName());//Device was disconnected @@ -129,7 +130,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { ); disposable.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { aapsLogger.debug(LTag.PUMP, "EventAppExit received"); if (mSerialIOThread != null) 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 a5f2758c17..a0803d2a15 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -26,17 +26,17 @@ import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType -import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.json.JSONException import org.json.JSONObject import javax.inject.Inject @@ -48,6 +48,7 @@ import kotlin.math.max class DanaRSPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, + private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBusWrapper, private val context: Context, resourceHelper: ResourceHelper, @@ -93,18 +94,18 @@ class DanaRSPlugin @Inject constructor( context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE) disposable.add(rxBus .toObservable(EventAppExit::class.java) - .observeOn(Schedulers.io()) - .subscribe({ context.unbindService(mConnection) }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ context.unbindService(mConnection) }, fabricPrivacy::logException) ) disposable.add(rxBus .toObservable(EventConfigBuilderChange::class.java) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.io) .subscribe { danaPump.reset() } ) disposable.add(rxBus .toObservable(EventDanaRSDeviceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ changePump() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ changePump() }, fabricPrivacy::logException) ) changePump() // load device name } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt b/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt index a61c5e330a..41c952e6c5 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt @@ -12,10 +12,10 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.textValidator.DefaultEditTextValidator import info.nightscout.androidaps.utils.textValidator.EditTextValidator -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import kotlin.experimental.xor @@ -27,6 +27,7 @@ class EnterPinActivity : NoSplashAppCompatActivity() { @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var sp: SP @Inject lateinit var bleComm: BLEComm + @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -55,8 +56,7 @@ class EnterPinActivity : NoSplashAppCompatActivity() { if (result) { bleComm.finishV3Pairing() finish() - } - else OKDialog.show(this, resourceHelper.gs(R.string.error), resourceHelper.gs(R.string.invalidinput)) + } else OKDialog.show(this, resourceHelper.gs(R.string.error), resourceHelper.gs(R.string.invalidinput)) } } binding.okcancel.cancel.setOnClickListener { finish() } @@ -66,8 +66,8 @@ class EnterPinActivity : NoSplashAppCompatActivity() { super.onResume() disposable.add(rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ if (it.status == EventPumpStatusChanged.Status.DISCONNECTED) finish() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.main) + .subscribe({ if (it.status == EventPumpStatusChanged.Status.DISCONNECTED) finish() }, fabricPrivacy::logException) ) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java index 1fd8464446..a3e6e2362d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java +++ b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java @@ -16,18 +16,19 @@ import javax.inject.Inject; import dagger.android.support.DaggerDialogFragment; import info.nightscout.androidaps.danars.R; -import info.nightscout.androidaps.danars.databinding.DanarsPairingProgressDialogBinding; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.danars.activities.PairingHelperActivity; +import info.nightscout.androidaps.danars.databinding.DanarsPairingProgressDialogBinding; import info.nightscout.androidaps.danars.events.EventDanaRSPairingSuccess; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; public class PairingProgressDialog extends DaggerDialogFragment { + @Inject AapsSchedulers aapsSchedulers; @Inject ResourceHelper resourceHelper; @Inject RxBusWrapper rxBus; @Inject FabricPrivacy fabricPrivacy; @@ -114,7 +115,7 @@ public class PairingProgressDialog extends DaggerDialogFragment { super.onResume(); disposable.add(rxBus .toObservable(EventDanaRSPairingSuccess.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> pairingEnded = true, fabricPrivacy::logException) ); if (pairingEnded) dismiss(); diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index b396c07234..c6f795efeb 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -42,9 +42,9 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable -import io.reactivex.schedulers.Schedulers import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.util.concurrent.TimeUnit @@ -53,8 +53,10 @@ import kotlin.math.abs import kotlin.math.min class DanaRSService : DaggerService() { + @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @@ -81,8 +83,8 @@ class DanaRSService : DaggerService() { super.onCreate() disposable.add(rxBus .toObservable(EventAppExit::class.java) - .observeOn(Schedulers.io()) - .subscribe({ stopSelf() }) { fabricPrivacy.logException(it) } + .observeOn(aapsSchedulers.io) + .subscribe({ stopSelf() }, fabricPrivacy::logException) ) } @@ -409,7 +411,7 @@ class DanaRSService : DaggerService() { sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) - return msgStop.success() + return msgStop.success() } fun updateBasalsInPump(profile: Profile): Boolean { @@ -437,12 +439,12 @@ class DanaRSService : DaggerService() { RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRS_Packet_History_Alarm(injector) RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRS_Packet_History_Prime(injector) RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRS_Packet_History_Basal(injector) - RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRS_Packet_History_Bolus(injector) - RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRS_Packet_History_Carbohydrate(injector) - RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRS_Packet_History_Daily(injector) - RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRS_Packet_History_Blood_Glucose(injector) - RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRS_Packet_History_Refill(injector) - RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRS_Packet_History_Suspend(injector) + RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRS_Packet_History_Bolus(injector) + RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRS_Packet_History_Carbohydrate(injector) + RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRS_Packet_History_Daily(injector) + RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRS_Packet_History_Blood_Glucose(injector) + RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRS_Packet_History_Refill(injector) + RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRS_Packet_History_Suspend(injector) } if (msg != null) { sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 1)) @@ -459,6 +461,7 @@ class DanaRSService : DaggerService() { } inner class LocalBinder : Binder() { + val serviceInstance: DanaRSService get() = this@DanaRSService } diff --git a/database/build.gradle b/database/build.gradle index 5c86517f06..f7aaee21f6 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -1,7 +1,6 @@ apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' -apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt index d828e279b3..ade887647f 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/VersionChangeTransaction.kt @@ -16,7 +16,6 @@ class VersionChangeTransaction( || current.versionCode != versionCode || current.gitRemote != gitRemote || current.commitHash != commitHash) { - val currentTime = System.currentTimeMillis() database.versionChangeDao.insert(VersionChange( timestamp = System.currentTimeMillis(), versionCode = versionCode, diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 8dc971ff0d..888af39085 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -42,7 +42,7 @@ import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject @@ -60,6 +60,7 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var medtronicUtil: MedtronicUtil @Inject lateinit var medtronicPumpStatus: MedtronicPumpStatus @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposable: CompositeDisposable = CompositeDisposable() @@ -130,43 +131,43 @@ class MedtronicFragment : DaggerFragment() { loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) disposable += rxBus .toObservable(EventRefreshButtonState::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ binding.refresh.isEnabled = it.newState }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ binding.refresh.isEnabled = it.newState }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventRileyLinkDeviceStatusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ aapsLogger.debug(LTag.PUMP, "onStatusEvent(EventRileyLinkDeviceStatusChange): $it") setDeviceStatus() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventMedtronicPumpValuesChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventMedtronicPumpConfigurationChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ aapsLogger.debug(LTag.PUMP, "EventMedtronicPumpConfigurationChanged triggered") medtronicPumpPlugin.rileyLinkService?.verifyConfiguration() updateGUI() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventQueueChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGUI() }, fabricPrivacy::logException) updateGUI() } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index b962bedb9b..34280bdca4 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -90,6 +90,7 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.TimeChangeType; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -140,7 +141,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter MedtronicHistoryData medtronicHistoryData, RileyLinkServiceData rileyLinkServiceData, ServiceTaskExecutor serviceTaskExecutor, - DateUtil dateUtil + DateUtil dateUtil, + AapsSchedulers aapsSchedulers ) { super(new PluginDescription() // @@ -152,7 +154,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later - injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil + injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers ); this.rileyLinkUtil = rileyLinkUtil; @@ -559,7 +561,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private boolean initializePump(boolean realInit) { - if (rileyLinkMedtronicService==null) + if (rileyLinkMedtronicService == null) return false; aapsLogger.info(LTag.PUMP, getLogPrefix() + "initializePump - start"); diff --git a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java index 1f7f334bf5..bd91e28573 100644 --- a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java +++ b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java @@ -103,9 +103,9 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.TimeChangeType; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.plugins.pump.omnipod.driver.definition.OmnipodConstants.BASAL_STEP_DURATION; @@ -129,6 +129,7 @@ public class OmnipodPumpPlugin extends PumpPluginBase implements PumpInterface, private final OmnipodAlertUtil omnipodAlertUtil; private final ProfileFunction profileFunction; private final AAPSLogger aapsLogger; + private final AapsSchedulers aapsSchedulers; private final RxBusWrapper rxBus; private final ActivePluginProvider activePlugin; private final Context context; @@ -160,6 +161,7 @@ public class OmnipodPumpPlugin extends PumpPluginBase implements PumpInterface, public OmnipodPumpPlugin( HasAndroidInjector injector, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, Context context, ResourceHelper resourceHelper, @@ -188,6 +190,7 @@ public class OmnipodPumpPlugin extends PumpPluginBase implements PumpInterface, .description(R.string.omnipod_pump_description), // injector, aapsLogger, resourceHelper, commandQueue); this.aapsLogger = aapsLogger; + this.aapsSchedulers = aapsSchedulers; this.rxBus = rxBus; this.activePlugin = activePlugin; this.context = context; @@ -284,32 +287,32 @@ public class OmnipodPumpPlugin extends PumpPluginBase implements PumpInterface, disposables.add(rxBus .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> context.unbindService(serviceConnection), fabricPrivacy::logException) ); disposables.add(rxBus .toObservable(EventOmnipodTbrChanged.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> handleCancelledTbr(), fabricPrivacy::logException) ); disposables.add(rxBus .toObservable(EventOmnipodUncertainTbrRecovered.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> handleUncertainTbrRecovery(), fabricPrivacy::logException) ); disposables.add(rxBus .toObservable(EventOmnipodActiveAlertsChanged.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> handleActivePodAlerts(), fabricPrivacy::logException) ); disposables.add(rxBus .toObservable(EventOmnipodFaultEventChanged.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> handlePodFaultEvent(), fabricPrivacy::logException) ); disposables.add(rxBus .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { if (event.isChanged(getResourceHelper(), OmnipodStorageKeys.Preferences.BASAL_BEEPS_ENABLED) || event.isChanged(getResourceHelper(), OmnipodStorageKeys.Preferences.BOLUS_BEEPS_ENABLED) || @@ -338,7 +341,7 @@ public class OmnipodPumpPlugin extends PumpPluginBase implements PumpInterface, ); disposables.add(rxBus .toObservable(EventAppInitialized.class) - .observeOn(Schedulers.io()) + .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { // See if a bolus was active before the app previously exited // If so, add it to history diff --git a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/manager/OmnipodManager.java b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/manager/OmnipodManager.java index 084c5aa524..9338668177 100644 --- a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/manager/OmnipodManager.java +++ b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/manager/OmnipodManager.java @@ -52,11 +52,11 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.exception.PodFault import info.nightscout.androidaps.plugins.pump.omnipod.driver.exception.PodProgressStatusVerificationFailedException; import info.nightscout.androidaps.plugins.pump.omnipod.driver.exception.PrecedingCommandFailedUncertainlyException; import info.nightscout.androidaps.plugins.pump.omnipod.rileylink.manager.OmnipodRileyLinkCommunicationManager; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Single; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.SingleSubject; public class OmnipodManager { @@ -71,8 +71,10 @@ public class OmnipodManager { private final Object bolusDataMutex = new Object(); private final AAPSLogger aapsLogger; + private final AapsSchedulers aapsSchedulers; public OmnipodManager(AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, OmnipodRileyLinkCommunicationManager communicationService, PodStateManager podStateManager) { if (communicationService == null) { @@ -82,6 +84,7 @@ public class OmnipodManager { throw new IllegalArgumentException("Pod State Manager can not be null"); } this.aapsLogger = aapsLogger; + this.aapsSchedulers = aapsSchedulers; this.communicationService = communicationService; this.podStateManager = podStateManager; @@ -111,7 +114,7 @@ public class OmnipodManager { return Single.timer(delayInMillis, TimeUnit.MILLISECONDS) // .map(o -> verifyPodProgressStatus(PodProgressStatus.PRIMING_COMPLETED, ActivationProgress.PRIMING_COMPLETED)) // - .subscribeOn(Schedulers.io()); + .subscribeOn(aapsSchedulers.getIo()); } public synchronized Single insertCannula( @@ -135,7 +138,7 @@ public class OmnipodManager { return Single.timer(delayInMillis, TimeUnit.MILLISECONDS) // .map(o -> verifyPodProgressStatus(PodProgressStatus.ABOVE_FIFTY_UNITS, ActivationProgress.COMPLETED)) // - .subscribeOn(Schedulers.io()); + .subscribeOn(aapsSchedulers.getIo()); } public synchronized StatusResponse getPodStatus() { @@ -366,7 +369,7 @@ public class OmnipodManager { long progressReportInterval = estimatedRemainingBolusDuration.getMillis() / numberOfProgressReports; disposables.add(Flowable.intervalRange(0, numberOfProgressReports + 1, 0, progressReportInterval, TimeUnit.MILLISECONDS) // - .subscribeOn(Schedulers.io()) // + .subscribeOn(aapsSchedulers.getIo()) // .subscribe(count -> { int percentage = (int) ((double) count / numberOfProgressReports * 100); double estimatedUnitsDelivered = activeBolusData == null ? 0 : activeBolusData.estimateUnitsDelivered(); @@ -387,7 +390,7 @@ public class OmnipodManager { disposables.add(Completable.complete() // .delay(estimatedRemainingBolusDuration.getMillis(), TimeUnit.MILLISECONDS) // - .subscribeOn(Schedulers.io()) // + .subscribeOn(aapsSchedulers.getIo()) // .doOnComplete(() -> { synchronized (bolusDataMutex) { double bolusNotDelivered = 0.0d; diff --git a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/manager/AapsOmnipodManager.java b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/manager/AapsOmnipodManager.java index e60147b94b..db17adff1e 100644 --- a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/manager/AapsOmnipodManager.java +++ b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/manager/AapsOmnipodManager.java @@ -88,6 +88,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.util.AapsOmnipodUtil; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodAlertUtil; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.sharedPreferences.SP; import io.reactivex.subjects.SingleSubject; @@ -97,6 +98,7 @@ public class AapsOmnipodManager { private final PodStateManager podStateManager; private final AapsOmnipodUtil aapsOmnipodUtil; private final AAPSLogger aapsLogger; + private final AapsSchedulers aapsSchedulers; private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final HasAndroidInjector injector; @@ -129,6 +131,7 @@ public class AapsOmnipodManager { PodStateManager podStateManager, AapsOmnipodUtil aapsOmnipodUtil, AAPSLogger aapsLogger, + AapsSchedulers aapsSchedulers, RxBusWrapper rxBus, SP sp, ResourceHelper resourceHelper, @@ -143,6 +146,7 @@ public class AapsOmnipodManager { this.podStateManager = podStateManager; this.aapsOmnipodUtil = aapsOmnipodUtil; this.aapsLogger = aapsLogger; + this.aapsSchedulers = aapsSchedulers; this.rxBus = rxBus; this.sp = sp; this.resourceHelper = resourceHelper; @@ -154,7 +158,7 @@ public class AapsOmnipodManager { this.profileFunction = profileFunction; this.context = context; - delegate = new OmnipodManager(aapsLogger, communicationService, podStateManager); + delegate = new OmnipodManager(aapsLogger, aapsSchedulers, communicationService, podStateManager); reloadSettings(); } diff --git a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/OmnipodOverviewFragment.kt b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/OmnipodOverviewFragment.kt index 15582f7e6b..0c074e3fd9 100644 --- a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/OmnipodOverviewFragment.kt +++ b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/OmnipodOverviewFragment.kt @@ -47,6 +47,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.android.schedulers.AndroidSchedulers @@ -79,6 +80,7 @@ class OmnipodOverviewFragment : DaggerFragment() { @Inject lateinit var dateUtil: DateUtil @Inject lateinit var omnipodManager: AapsOmnipodManager @Inject lateinit var protectionCheck: ProtectionCheck + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposables: CompositeDisposable = CompositeDisposable() @@ -159,31 +161,31 @@ class OmnipodOverviewFragment : DaggerFragment() { loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) disposables += rxBus .toObservable(EventRileyLinkDeviceStatusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateRileyLinkStatus() updatePodActionButtons() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposables += rxBus .toObservable(EventOmnipodPumpValuesChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateOmnipodStatus() updatePodActionButtons() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposables += rxBus .toObservable(EventQueueChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updateQueueStatus() updatePodActionButtons() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) disposables += rxBus .toObservable(EventPreferenceChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) + .observeOn(aapsSchedulers.main) .subscribe({ updatePodActionButtons() - }, { fabricPrivacy.logException(it) }) + }, fabricPrivacy::logException) updateUi() } diff --git a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/PodManagementActivity.kt b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/PodManagementActivity.kt index 1f83fe832a..bf87dd8e59 100644 --- a/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/PodManagementActivity.kt +++ b/omnipod/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/ui/PodManagementActivity.kt @@ -31,6 +31,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.toVisibility +import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable @@ -51,6 +52,7 @@ class PodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var context: Context @Inject lateinit var omnipodPumpPlugin: OmnipodPumpPlugin @Inject lateinit var serviceTaskExecutor: ServiceTaskExecutor + @Inject lateinit var aapsSchedulers: AapsSchedulers private var disposables: CompositeDisposable = CompositeDisposable() @@ -124,16 +126,16 @@ class PodManagementActivity : NoSplashAppCompatActivity() { super.onResume() disposables += rxBus .toObservable(EventRileyLinkDeviceStatusChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ refreshButtons() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ refreshButtons() }, fabricPrivacy::logException) disposables += rxBus .toObservable(EventOmnipodPumpValuesChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ refreshButtons() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ refreshButtons() }, fabricPrivacy::logException) disposables += rxBus .toObservable(EventQueueChanged::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ refreshButtons() }, { fabricPrivacy.logException(it) }) + .observeOn(aapsSchedulers.main) + .subscribe({ refreshButtons() }, fabricPrivacy::logException) refreshButtons() }