diff --git a/app/build.gradle b/app/build.gradle index 959dd342da..f881b3f080 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -100,6 +100,7 @@ def allCommitted = { -> tasks.matching { it instanceof Test }.all { testLogging.events = ["failed", "skipped", "started"] + // testLogging.events = ["failed", "skipped", "started", "standard_out"] use to display stdout in travis testLogging.exceptionFormat = "full" } @@ -177,12 +178,16 @@ dependencies { wearApp project(':wear') implementation project(':core') + implementation project(':automation') + implementation project(':combo') implementation project(':database') implementation project(':dana') implementation project(':danars') implementation project(':danar') + implementation project(':insight') implementation project(':rileylink') implementation project(':medtronic') + implementation project(':omnipod-common') implementation project(':omnipod-eros') implementation project(':omnipod-dash') diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index 0a99af2948..656bdae255 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -34,7 +34,7 @@ import javax.inject.Inject @LargeTest @RunWith(AndroidJUnit4::class) class RealPumpTest { - +/* companion object { const val R_PASSWORD = 1234 const val R_SERIAL = "PBB00013LR_P" @@ -125,4 +125,5 @@ class RealPumpTest { SystemClock.sleep(1000) } } + */ } \ No newline at end of file diff --git a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt index c082e51018..e873bf5edf 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt @@ -42,7 +42,7 @@ import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class SetupWizardActivityTest { - +/* @Rule @JvmField var mActivityTestRule = ActivityTestRule(SetupWizardActivity::class.java) @@ -226,4 +226,5 @@ adb shell settings put global animator_duration_scale 0 & } } } + */ } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1abc55ecfe..18750bfda8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -140,9 +140,6 @@ android:resource="@xml/filepaths" /> - @@ -219,8 +216,6 @@ android:exported="false" /> - - - - - @@ -259,13 +240,6 @@ - - - - diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index 09505d0e18..072e621cdc 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -138,7 +138,7 @@ class MainActivity : NoSplashAppCompatActivity() { .observeOn(aapsSchedulers.main) .subscribe({ processPreferenceChange(it) }, fabricPrivacy::logException) ) - if (!sp.getBoolean(R.string.key_setupwizard_processed, false) && !isRunningRealPumpTest()) { + if (startWizard() && !isRunningRealPumpTest()) { protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, { startActivity(Intent(this, SetupWizardActivity::class.java)) }) @@ -156,6 +156,9 @@ class MainActivity : NoSplashAppCompatActivity() { if (viewPager.currentItem >= 0) pluginPreferencesMenuItem?.isEnabled = (viewPager.adapter as TabPageAdapter).getPluginAt(viewPager.currentItem).preferencesId != -1 } + private fun startWizard() : Boolean = + !sp.getBoolean(R.string.key_setupwizard_processed, false) + override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onPostCreate(savedInstanceState, persistentState) actionBarDrawerToggle.syncState() @@ -381,6 +384,7 @@ class MainActivity : NoSplashAppCompatActivity() { FirebaseCrashlytics.getInstance().setCustomKey("Remote", remote) FirebaseCrashlytics.getInstance().setCustomKey("Committed", BuildConfig.COMMITTED) FirebaseCrashlytics.getInstance().setCustomKey("Hash", hashes[0]) + FirebaseCrashlytics.getInstance().setCustomKey("Email", sp.getString(R.string.key_email_for_crash_report, "")) } } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index ae7a6e4436..9eb8a59a5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -46,6 +46,7 @@ import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.logging.AAPSLogger; @@ -54,9 +55,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; -import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.PercentageSplitter; @@ -83,9 +81,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public static final String DATABASE_DBREQUESTS = "DBRequests"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; public static final String DATABASE_TDDS = "TDDs"; - public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets"; - public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs"; - public static final String DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs"; public static final String DATABASE_OPEN_HUMANS_QUEUE = "OpenHumansQueue"; private static final int DATABASE_VERSION = 13; @@ -138,10 +133,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")"); + database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); + database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); } catch (SQLException e) { aapsLogger.error("Can't create database", e); throw new RuntimeException(e); @@ -169,13 +164,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class); TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class); TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")"); - database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + - "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")"); + database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " + + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")"); + database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")"); } else if (oldVersion < 11) { - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\""); - database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\""); + database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\""); + database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\""); } TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); } catch (SQLException e) { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java index 41f7cabdd9..a2825f000a 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -1,8 +1,9 @@ package info.nightscout.androidaps.db; +import androidx.annotation.NonNull; + import com.j256.ormlite.dao.CloseableIterator; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.SQLException; @@ -20,31 +21,31 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { @Inject DatabaseHelperProvider() { } - @Override public void createOrUpdate(@NotNull CareportalEvent careportalEvent) { + @Override public void createOrUpdate(@NonNull CareportalEvent careportalEvent) { MainApp.getDbHelper().createOrUpdate(careportalEvent); } - @Override public void createOrUpdate(@NotNull DanaRHistoryRecord record) { + @Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) { MainApp.getDbHelper().createOrUpdate(record); } - @Override public void createOrUpdate(@NotNull OmnipodHistoryRecord record) { + @Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) { MainApp.getDbHelper().createOrUpdate(record); } - @NotNull @Override public List getDanaRHistoryRecordsByType(byte type) { + @NonNull @Override public List getDanaRHistoryRecordsByType(byte type) { return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); } - @NotNull @Override public List getTDDs() { + @NonNull @Override public List getTDDs() { return MainApp.getDbHelper().getTDDs(); } - @Override public long size(@NotNull String table) { + @Override public long size(@NonNull String table) { return MainApp.getDbHelper().size(table); } - @Override public void create(@NotNull DbRequest record) { + @Override public void create(@NonNull DbRequest record) { try { MainApp.getDbHelper().create(record); } catch (SQLException e) { @@ -56,15 +57,15 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { MainApp.getDbHelper().deleteAllDbRequests(); } - @Override public int deleteDbRequest(@NotNull String id) { + @Override public int deleteDbRequest(@NonNull String id) { return MainApp.getDbHelper().deleteDbRequest(id); } - @Override public void deleteDbRequestbyMongoId(@NotNull String action, @NotNull String _id) { + @Override public void deleteDbRequestbyMongoId(@NonNull String action, @NonNull String _id) { MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); } - @NotNull @Override public CloseableIterator getDbRequestInterator() { + @NonNull @Override public CloseableIterator getDbRequestInterator() { return MainApp.getDbHelper().getDbRequestInterator(); } @@ -72,19 +73,19 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.getDbHelper().roundDateToSec(date); } - @Override public void createOrUpdateTDD(@NotNull TDD record) { + @Override public void createOrUpdateTDD(@NonNull TDD record) { MainApp.getDbHelper().createOrUpdateTDD(record); } - @Override public void createOrUpdate(@NotNull TemporaryBasal tempBasal) { + @Override public void createOrUpdate(@NonNull TemporaryBasal tempBasal) { MainApp.getDbHelper().createOrUpdate(tempBasal); } - @NotNull @Override public TemporaryBasal findTempBasalByPumpId(long id) { + @NonNull @Override public TemporaryBasal findTempBasalByPumpId(long id) { return MainApp.getDbHelper().findTempBasalByPumpId(id); } - @NotNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { + @NonNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); } @@ -92,7 +93,7 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp); } - @NotNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { + @NonNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { return MainApp.getDbHelper().getAllOmnipodHistoryRecordsFromTimeStamp(timestamp, ascending); } @@ -100,12 +101,43 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { return MainApp.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); } - @NotNull @Override public List getTDDsForLastXDays(int days) { + @NonNull @Override public List getTDDsForLastXDays(int days) { return MainApp.getDbHelper().getTDDsForLastXDays(days); } - @NotNull @Override public List getProfileSwitchData(long from, boolean ascending) { + @NonNull @Override public List getProfileSwitchData(long from, boolean ascending) { return MainApp.getDbHelper().getProfileSwitchData(from, ascending); } + @Override public void createOrUpdate(@NonNull InsightBolusID record) { + MainApp.getDbHelper().createOrUpdate(record); + } + + @Override public void createOrUpdate(@NonNull InsightPumpID record) { + MainApp.getDbHelper().createOrUpdate(record); + } + + @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) { + MainApp.getDbHelper().createOrUpdate(record); + } + + @Override public void delete(@NonNull ExtendedBolus extendedBolus) { + MainApp.getDbHelper().delete(extendedBolus); + } + + @Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { + return MainApp.getDbHelper().getExtendedBolusByPumpId(pumpId); + } + + @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) { + return MainApp.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp); + } + + @Nullable @Override public InsightHistoryOffset getInsightHistoryOffset(@NonNull String pumpSerial) { + return MainApp.getDbHelper().getInsightHistoryOffset(pumpSerial); + } + + @Nullable @Override public InsightPumpID getPumpStoppedEvent(@NonNull String pumpSerial, long before) { + return MainApp.getDbHelper().getPumpStoppedEvent(pumpSerial, before); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index 54f139f0e8..95e0888b79 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -9,12 +9,6 @@ import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSett import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansLoginActivity import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity -import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEConfigActivity -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity -import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity -import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity -import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity -import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity import info.nightscout.androidaps.setupwizard.SetupWizardActivity @Module @@ -22,17 +16,11 @@ import info.nightscout.androidaps.setupwizard.SetupWizardActivity abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity - @ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity - @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity - @ContributesAndroidInjector abstract fun contributesInsightPairingInformationActivity(): InsightPairingInformationActivity @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity - @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity - @ContributesAndroidInjector abstract fun contributesRileyLinkStatusActivity(): RileyLinkStatusActivity - @ContributesAndroidInjector abstract fun contributesRileyLinkBLEConfigActivity(): RileyLinkBLEConfigActivity @ContributesAndroidInjector abstract fun contributesSetupWizardActivity(): SetupWizardActivity @ContributesAndroidInjector abstract fun contributesSingleFragmentActivity(): SingleFragmentActivity @ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 61cb5334b0..d431be7a6c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,12 +5,16 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.automation.di.AutomationModule +import info.nightscout.androidaps.combo.di.ComboModule import info.nightscout.androidaps.core.di.CoreModule import info.nightscout.androidaps.dana.di.DanaModule import info.nightscout.androidaps.danar.di.DanaRModule import info.nightscout.androidaps.danars.di.DanaRSModule +import info.nightscout.androidaps.danars.di.InsightModule import info.nightscout.androidaps.database.DatabaseModule -import info.nightscout.androidaps.plugins.pump.common.dagger.RileyLinkModule +import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule +import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.dagger.OmnipodErosModule import javax.inject.Singleton @@ -43,6 +47,8 @@ import javax.inject.Singleton DanaModule::class, DanaRModule::class, DanaRSModule::class, + ComboModule::class, + InsightModule::class, WorkersModule::class, OHUploaderModule::class ] 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 e807a8d7f7..72c9ad308b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -10,13 +10,17 @@ import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.db.DatabaseHelperProvider import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin 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.resources.IconsProvider import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers import info.nightscout.androidaps.utils.storage.FileStorage @@ -66,5 +70,9 @@ open class AppModule { @Binds fun bindUploadQueueInterface(uploadQueue: UploadQueue): UploadQueueInterface @Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface @Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefs): ImportExportPrefsInterface + @Binds fun bindIconsProviderInterface(iconsProvider: IconsProvider): IconsProviderInterface + @Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface + @Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculatorInterface + @Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicatorInterface } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index d00f9b20fd..4acdd1f0db 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -30,13 +30,6 @@ import info.nightscout.androidaps.plugins.general.wear.WearFragment import info.nightscout.androidaps.plugins.insulin.InsulinFragment import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment -import info.nightscout.androidaps.plugins.pump.combo.ComboFragment -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment -import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic -import info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.OmnipodOverviewFragment import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpFragment import info.nightscout.androidaps.plugins.source.BGSourceFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment @@ -52,7 +45,6 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment @ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment - @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment @ContributesAndroidInjector abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment @@ -64,11 +56,8 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment @ContributesAndroidInjector abstract fun contributesOverviewFragment(): OverviewFragment - @ContributesAndroidInjector abstract fun contributesLocalInsightFragment(): LocalInsightFragment @ContributesAndroidInjector abstract fun contributesLoopFragment(): LoopFragment @ContributesAndroidInjector abstract fun contributesMaintenanceFragment(): MaintenanceFragment - @ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment - @ContributesAndroidInjector abstract fun contributesOmnipodFragment(): OmnipodOverviewFragment @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment @ContributesAndroidInjector abstract fun contributesNSClientFragment(): NSClientFragment @ContributesAndroidInjector @@ -117,11 +106,4 @@ abstract class FragmentsModule { abstract fun contributesExchangeAuthTokenDialot(): OpenHumansLoginActivity.ExchangeAuthTokenDialog @ContributesAndroidInjector abstract fun contributesPasswordCheck(): PasswordCheck - - @ContributesAndroidInjector - abstract fun contributesRileyLinkStatusGeneral(): RileyLinkStatusGeneralFragment - @ContributesAndroidInjector - abstract fun contributesRileyLinkStatusHistoryFragment(): RileyLinkStatusHistoryFragment - @ContributesAndroidInjector - abstract fun contributesRileyLinkStatusDeviceMedtronic(): RileyLinkStatusDeviceMedtronic } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt deleted file mode 100644 index cadac7d13c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.dependencyInjection - -import dagger.Module -import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager -import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask - -@Module -@Suppress("unused") -abstract class MedtronicModule { - @ContributesAndroidInjector abstract fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager - @ContributesAndroidInjector abstract fun medtronicUITaskProvider(): MedtronicUITask -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt index 50f8695bf9..04165b32a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt @@ -6,11 +6,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientServ import info.nightscout.androidaps.plugins.general.overview.notifications.DismissNotificationService import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService -import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService -import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService -import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService -import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.service.RileyLinkOmnipodService import info.nightscout.androidaps.services.AlarmSoundService import info.nightscout.androidaps.services.LocationService @@ -24,9 +19,4 @@ abstract class ServicesModule { @ContributesAndroidInjector abstract fun contributesLocationService(): LocationService @ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService @ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService - @ContributesAndroidInjector abstract fun contributesInsightAlertService(): InsightAlertService - @ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService - @ContributesAndroidInjector abstract fun contributesRileyLinkService(): RileyLinkService - @ContributesAndroidInjector abstract fun contributesRileyLinkMedtronicService(): RileyLinkMedtronicService - @ContributesAndroidInjector abstract fun contributesRileyLinkOmnipodService(): RileyLinkOmnipodService } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt index 2c105e9ce7..1405b8867f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt @@ -18,6 +18,7 @@ abstract class WizardModule { @ContributesAndroidInjector abstract fun swEditEncryptedPasswordInjector(): SWEditEncryptedPassword @ContributesAndroidInjector abstract fun swEditUrlInjector(): SWEditUrl @ContributesAndroidInjector abstract fun swFragmentInjector(): SWFragment + @ContributesAndroidInjector abstract fun swPreferenceInjector(): SWPreference @ContributesAndroidInjector abstract fun swHtmlLinkInjector(): SWHtmlLink @ContributesAndroidInjector abstract fun swInfotextInjector(): SWInfoText @ContributesAndroidInjector abstract fun swItemInjector(): SWItem diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index b6893165f0..6d86136605 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -203,7 +203,7 @@ class CarbsDialog : DialogFragmentWithDate() { } val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) if (eventTimeChanged) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index cbb30d1b0a..16a60df0dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -185,7 +185,7 @@ class CareDialog : DialogFragmentWithDate() { } val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) { - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) json.put("notes", notes) } eventTime -= eventTime % 1000 diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index 34b9b8f307..4116091eed 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -92,7 +92,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { if (!result.success) { - ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror) + ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 0af112aa29..118953e3e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -118,7 +118,7 @@ class FillDialog : DialogFragmentWithDate() { actions.add(resourceHelper.gs(R.string.record_insulin_cartridge_change).formatColor(resourceHelper, R.color.actionsConfirm)) val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) eventTime -= eventTime % 1000 if (eventTimeChanged) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index f6cc1e1428..7f25104243 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -173,7 +173,7 @@ class InsulinDialog : DialogFragmentWithDate() { val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) if (insulinAfterConstraints > 0 || eatingSoonChecked) { activity?.let { activity -> diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index cdfed0ae58..5eb2126de8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -119,7 +119,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + resourceHelper.gs(R.string.format_hours, timeShift.toDouble())) val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) if (eventTimeChanged) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) 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 543e38ddcb..fae30fc39a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy 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 c99616c7fc..8ee346247e 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.OverviewMenus import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index 74ca108a37..e02d1f5935 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.wear.events.EventWearDoAction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback @@ -58,7 +58,7 @@ import kotlin.math.abs @Singleton open class LoopPlugin @Inject constructor( injector: HasAndroidInjector, - aapsLogger: AAPSLogger?, + aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBusWrapper, private val sp: SP, @@ -85,7 +85,7 @@ open class LoopPlugin @Inject constructor( .preferencesId(R.xml.pref_loop) .enableByDefault(config.APS) .description(R.string.description_loop), - aapsLogger!!, resourceHelper, injector + aapsLogger, resourceHelper, injector ), LoopInterface { private val disposable = CompositeDisposable() @@ -147,7 +147,7 @@ open class LoopPlugin @Inject constructor( } } - fun suspendTo(endTime: Long) { + override fun suspendTo(endTime: Long) { sp.putLong("loopSuspendedTill", endTime) sp.putBoolean("isSuperBolus", false) sp.putBoolean("isDisconnected", false) @@ -178,7 +178,7 @@ open class LoopPlugin @Inject constructor( } // time exceeded - val isSuspended: Boolean + override val isSuspended: Boolean get() { val loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L) if (loopSuspendedTill == 0L) return false @@ -638,7 +638,7 @@ open class LoopPlugin @Inject constructor( createOfflineEvent(durationInMinutes) } - fun suspendLoop(durationInMinutes: Int) { + override fun suspendLoop(durationInMinutes: Int) { suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { @@ -650,7 +650,7 @@ open class LoopPlugin @Inject constructor( createOfflineEvent(durationInMinutes) } - fun createOfflineEvent(durationInMinutes: Int) { + override fun createOfflineEvent(durationInMinutes: Int) { val data = JSONObject() try { data.put("eventType", CareportalEvent.OPENAPSOFFLINE) 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 85b557b925..7ab5c30703 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 @@ -23,7 +23,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.utils.DefaultValueHelper diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/Food.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/Food.java index e30987b251..61c5f0b16f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/Food.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/Food.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.general.food; +import androidx.annotation.NonNull; + import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @@ -123,7 +125,7 @@ public class Food { gi = other.gi; } - @Override + @Override @NonNull public String toString() { StringBuilder sb = new StringBuilder(); sb.append("_id=" + _id + ";"); 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 de1b919ed1..1c15a2cd16 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 @@ -13,7 +13,7 @@ import android.text.Spanned; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.SwitchPreference; -import org.jetbrains.annotations.NotNull; +import androidx.annotation.NonNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -214,7 +214,7 @@ public class NSClientPlugin extends PluginBase { } @Override - public void preprocessPreferences(@NotNull PreferenceFragmentCompat preferenceFragment) { + public void preprocessPreferences(@NonNull PreferenceFragmentCompat preferenceFragment) { super.preprocessPreferences(preferenceFragment); if (config.getNSCLIENT()) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java index b36557c534..a5d4fcd597 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientWorker.java @@ -7,7 +7,7 @@ import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; -import org.jetbrains.annotations.NotNull; +import androidx.annotation.NonNull; import javax.inject.Inject; @@ -28,7 +28,7 @@ public class NSClientWorker extends Worker { @Inject NSClientPlugin nsClientPlugin; @Inject BundleStore bundleStore; - @NotNull + @NonNull @Override public Result doWork() { Bundle bundle = bundleStore.pickup(getInputData().getLong(DataReceiver.STORE_KEY, -1)); 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 41bef96ad5..b631374dfb 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 @@ -47,7 +47,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.general.wear.events.EventWearDoAction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.source.DexcomPlugin @@ -634,8 +634,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.infoLayout.apsModeText.visibility = View.VISIBLE } - pump.isSuspended() -> { - binding.infoLayout.apsMode.setImageResource(if (pump.pumpDescription.pumpType == PumpType.Insulet_Omnipod) { + pump.isSuspended() -> { + binding.infoLayout.apsMode.setImageResource(if (pump.model() == PumpType.Omnipod_Eros || pump.model() == PumpType.Omnipod_Dash) { // For Omnipod, indicate the pump as disconnected when it's suspended. // The only way to 'reconnect' it, is through the Omnipod tab R.drawable.ic_loop_disconnected @@ -765,7 +765,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList var cobText: String = resourceHelper.gs(R.string.value_unavailable_short) val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "Overview COB") if (cobInfo.displayCob != null) { - cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob.toInt()) + cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob!!.toInt()) if (cobInfo.futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")" } @@ -907,7 +907,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, now, useCobForScale, if (useCobForScale) 1.0 else 0.5) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, now, useDevForScale, 1.0, alignDevBgiScale) if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, now, useRatioForScale, 1.0) - if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(fromTime, endTime, useBGIForScale, if(alignDevBgiScale) 1.0 else 0.8, alignDevBgiScale) + if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(fromTime, endTime, useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8, alignDevBgiScale) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1.0) // set manual x bounds to have nice steps diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index 82362908b7..c414d1c5a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -36,11 +36,11 @@ class StatusLightHandler @Inject constructor( handleAge(careportal_cannula_age, CareportalEvent.SITECHANGE, R.string.key_statuslights_cage_warning, 48.0, R.string.key_statuslights_cage_critical, 72.0) handleAge(careportal_insulin_age, CareportalEvent.INSULINCHANGE, R.string.key_statuslights_iage_warning, 72.0, R.string.key_statuslights_iage_critical, 144.0) handleAge(careportal_sensor_age, CareportalEvent.SENSORCHANGE, R.string.key_statuslights_sage_warning, 216.0, R.string.key_statuslights_sage_critical, 240.0) - if (pump.pumpDescription.isBatteryReplaceable) { + if (pump.pumpDescription.isBatteryReplaceable || (pump is OmnipodErosPumpPlugin && pump.isUseRileyLinkBatteryLevel && pump.isBatteryChangeLoggingEnabled)) { handleAge(careportal_pb_age, CareportalEvent.PUMPBATTERYCHANGE, R.string.key_statuslights_bage_warning, 216.0, R.string.key_statuslights_bage_critical, 240.0) } if (!config.NSCLIENT) { - if (pump.model() == PumpType.Insulet_Omnipod) { + if (pump.model() == PumpType.Omnipod_Eros || pump.model() == PumpType.Omnipod_Dash) { handleOmnipodReservoirLevel(careportal_reservoir_level, R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, pump.reservoirLevel, "U") } else { handleLevel(careportal_reservoir_level, R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, pump.reservoirLevel, "U") @@ -52,8 +52,14 @@ class StatusLightHandler @Inject constructor( } if (!config.NSCLIENT) { - if (pump.model() == PumpType.Insulet_Omnipod && pump is OmnipodErosPumpPlugin) { // instance of check is needed because at startup, pump can still be VirtualPumpPlugin and that will cause a crash because of the class cast below - handleOmnipodBatteryLevel(careportal_battery_level, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble(), "%", pump.isUseRileyLinkBatteryLevel) + if (pump.model() == PumpType.Omnipod_Dash) { + // Omnipod Dash does not report its battery level + careportal_battery_level?.text = resourceHelper.gs(R.string.notavailable) + careportal_battery_level?.setTextColor(Color.WHITE) + } else if (pump.model() == PumpType.Omnipod_Eros && pump is OmnipodErosPumpPlugin) { // instance of check is needed because at startup, pump can still be VirtualPumpPlugin and that will cause a crash because of the class cast below + // The Omnipod Eros does not report its battery level. However, some RileyLink alternatives do. + // Depending on the user's configuration, we will either show the battery level reported by the RileyLink or "n/a" + handleOmnipodErosBatteryLevel(careportal_battery_level, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble(), "%", pump.isUseRileyLinkBatteryLevel) } else if (pump.model() != PumpType.AccuChekCombo) { handleLevel(careportal_battery_level, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble(), "%") } @@ -93,7 +99,7 @@ class StatusLightHandler @Inject constructor( } @Suppress("SameParameterValue") - private fun handleOmnipodBatteryLevel(view: TextView?, criticalSetting: Int, criticalDefaultValue: Double, warnSetting: Int, warnDefaultValue: Double, level: Double, units: String, useRileyLinkBatteryLevel: Boolean) { + private fun handleOmnipodErosBatteryLevel(view: TextView?, criticalSetting: Int, criticalDefaultValue: Double, warnSetting: Int, warnDefaultValue: Double, level: Double, units: String, useRileyLinkBatteryLevel: Boolean) { if (useRileyLinkBatteryLevel) { handleLevel(view, criticalSetting, criticalDefaultValue, warnSetting, warnDefaultValue, level, units) } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/AreaGraphSeries.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/AreaGraphSeries.java index 6d6cf27b51..1eef5c790c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/AreaGraphSeries.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/AreaGraphSeries.java @@ -39,7 +39,7 @@ public class AreaGraphSeries extends BaseSeries { /** * wrapped styles regarding the line */ - private final class Styles { + private static final class Styles { /** * the thickness of the line. * This option will be ignored if you are @@ -115,7 +115,7 @@ public class AreaGraphSeries extends BaseSeries { /** * creates a series without data */ - public AreaGraphSeries() { + @SuppressWarnings("unused") public AreaGraphSeries() { init(); } @@ -174,9 +174,9 @@ public class AreaGraphSeries extends BaseSeries { Iterator values = getValues(minX, maxX); // draw background - double lastEndY1 = 0; - double lastEndY2 = 0; - double lastEndX = 0; + double lastEndY1; + double lastEndY2; + double lastEndX; // draw data mPaint.setStrokeWidth(mStyles.thickness); @@ -205,8 +205,6 @@ public class AreaGraphSeries extends BaseSeries { lastEndY1 = 0; lastEndY2 = 0; lastEndX = 0; - double lastUsedEndX = 0; - float firstX = 0; int i=0; while (values.hasNext()) { E value = values.next(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/FixedLineGraphSeries.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/FixedLineGraphSeries.java index 1ccbcd85cf..4cfb27edcd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/FixedLineGraphSeries.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/FixedLineGraphSeries.java @@ -1,9 +1,5 @@ package info.nightscout.androidaps.plugins.general.overview.graphExtensions; -/** - * Created by mike on 24.04.2017. - */ - import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; @@ -25,7 +21,7 @@ public class FixedLineGraphSeries extends BaseSeri /** * wrapped styles regarding the line */ - private final class Styles { + private static final class Styles { /** * the thickness of the line. * This option will be ignored if you are @@ -100,7 +96,7 @@ public class FixedLineGraphSeries extends BaseSeri /** * creates a series without data */ - public FixedLineGraphSeries() { + @SuppressWarnings("unused") public FixedLineGraphSeries() { init(); } @@ -158,8 +154,8 @@ public class FixedLineGraphSeries extends BaseSeri Iterator values = getValues(minX, maxX); // draw background - double lastEndY = 0; - double lastEndX = 0; + double lastEndY; + double lastEndX; // draw data mPaint.setStrokeWidth(mStyles.thickness); @@ -263,8 +259,8 @@ public class FixedLineGraphSeries extends BaseSeri lastUsedEndX = endX; } else if (mStyles.drawDataPoints) { //fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above) - float first_X = (float) x + (graphLeft + 1); - float first_Y = (float) (graphTop - y) + graphHeight; + // float first_X = (float) x + (graphLeft + 1); + // float first_Y = (float) (graphTop - y) + graphHeight; //TODO canvas.drawCircle(first_X, first_Y, dataPointsRadius, mPaint); } lastEndY = orgY; @@ -289,7 +285,7 @@ public class FixedLineGraphSeries extends BaseSeri * * @return the thickness of the line */ - public int getThickness() { + @SuppressWarnings("unused") public int getThickness() { return mStyles.thickness; } @@ -312,7 +308,7 @@ public class FixedLineGraphSeries extends BaseSeri * @return whether the background will be drawn * @see #getBackgroundColor() */ - public boolean isDrawBackground() { + @SuppressWarnings("unused") public boolean isDrawBackground() { return mStyles.drawBackground; } @@ -335,7 +331,7 @@ public class FixedLineGraphSeries extends BaseSeri * @return flag whether the data points are highlighted * @see #setDataPointsRadius(float) */ - public boolean isDrawDataPoints() { + @SuppressWarnings("unused") public boolean isDrawDataPoints() { return mStyles.drawDataPoints; } @@ -346,7 +342,7 @@ public class FixedLineGraphSeries extends BaseSeri * @param drawDataPoints flag whether the data points are highlighted * @see #setDataPointsRadius(float) */ - public void setDrawDataPoints(boolean drawDataPoints) { + @SuppressWarnings("unused") public void setDrawDataPoints(boolean drawDataPoints) { mStyles.drawDataPoints = drawDataPoints; } @@ -354,7 +350,7 @@ public class FixedLineGraphSeries extends BaseSeri * @return the radius for the data points. * @see #setDrawDataPoints(boolean) */ - public float getDataPointsRadius() { + @SuppressWarnings("unused") public float getDataPointsRadius() { return mStyles.dataPointsRadius; } @@ -362,7 +358,7 @@ public class FixedLineGraphSeries extends BaseSeri * @param dataPointsRadius the radius for the data points. * @see #setDrawDataPoints(boolean) */ - public void setDataPointsRadius(float dataPointsRadius) { + @SuppressWarnings("unused") public void setDataPointsRadius(float dataPointsRadius) { mStyles.dataPointsRadius = dataPointsRadius; } @@ -371,7 +367,7 @@ public class FixedLineGraphSeries extends BaseSeri * the line. * @see #setDrawBackground(boolean) */ - public int getBackgroundColor() { + @SuppressWarnings("unused") public int getBackgroundColor() { return mStyles.backgroundColor; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt index a736e78367..2e791771f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.general.overview.notifications -import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent @@ -11,21 +10,17 @@ import android.media.RingtoneManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.widget.Button -import android.widget.TextView -import androidx.cardview.widget.CardView import androidx.core.app.NotificationCompat -import androidx.core.app.TaskStackBuilder import androidx.recyclerview.widget.RecyclerView -import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.R +import info.nightscout.androidaps.databinding.OverviewNotificationItemBinding +import info.nightscout.androidaps.interfaces.NotificationHolderInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.services.AlarmSoundServiceHelper import info.nightscout.androidaps.utils.DateUtil -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.sharedPreferences.SP @@ -42,11 +37,11 @@ class NotificationStore @Inject constructor( private val context: Context, private val iconsProvider: IconsProvider, private val alarmSoundServiceHelper: AlarmSoundServiceHelper, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val notificationHolder: NotificationHolderInterface ) { - var store: MutableList = ArrayList() - private var usesChannels = false + private var store: MutableList = ArrayList() companion object { @@ -71,20 +66,19 @@ class NotificationStore @Inject constructor( } } store.add(n) - if (sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, true) && n !is NotificationWithAction) { + if (sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, true) && n !is NotificationWithAction) raiseSystemNotification(n) - if (usesChannels && n.soundId != null && n.soundId != 0) alarmSoundServiceHelper.startAlarm(context, n.soundId) - } else { - if (n.soundId != null && n.soundId != 0) alarmSoundServiceHelper.startAlarm(context, n.soundId) - } + if (n.soundId != null && n.soundId != 0) alarmSoundServiceHelper.startAlarm(context, n.soundId) Collections.sort(store, NotificationComparator()) return true } - @Synchronized fun remove(id: Int): Boolean { + @Synchronized + fun remove(id: Int): Boolean { for (i in store.indices) { if (store[i].id == id) { if (store[i].soundId != null) alarmSoundServiceHelper.stopService(context) + aapsLogger.debug(LTag.NOTIFICATION, "Notification removed: " + store[i].text) store.removeAt(i) return true } @@ -92,11 +86,14 @@ class NotificationStore @Inject constructor( return false } - @Synchronized private fun removeExpired() { + @Synchronized + private fun removeExpired() { var i = 0 while (i < store.size) { val n = store[i] if (n.validTo != 0L && n.validTo < System.currentTimeMillis()) { + if (store[i].soundId != null) alarmSoundServiceHelper.stopService(context) + aapsLogger.debug(LTag.NOTIFICATION, "Notification expired: " + store[i].text) store.removeAt(i) i-- } @@ -116,7 +113,7 @@ class NotificationStore @Inject constructor( .setStyle(NotificationCompat.BigTextStyle().bigText(n.text)) .setPriority(NotificationCompat.PRIORITY_MAX) .setDeleteIntent(deleteIntent(n.id)) - .setContentIntent(openAppIntent(context)) + .setContentIntent(notificationHolder.openAppIntent(context)) if (n.level == Notification.URGENT) { notificationBuilder.setVibrate(longArrayOf(1000, 1000, 1000, 1000)) .setContentTitle(resourceHelper.gs(R.string.urgent_alarm)) @@ -135,20 +132,17 @@ class NotificationStore @Inject constructor( } fun createNotificationChannel() { - usesChannels = true val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - @SuppressLint("WrongConstant") val channel = NotificationChannel(CHANNEL_ID, - CHANNEL_ID, - NotificationManager.IMPORTANCE_HIGH) + val channel = NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH) mNotificationManager.createNotificationChannel(channel) } @Synchronized fun updateNotifications(notificationsView: RecyclerView) { removeExpired() -// unSnooze() - if (store.size > 0) { - val adapter = NotificationRecyclerViewAdapter(cloneStore()) + val clonedStore = ArrayList(store) + if (clonedStore.isNotEmpty()) { + val adapter = NotificationRecyclerViewAdapter(clonedStore) notificationsView.adapter = adapter notificationsView.visibility = View.VISIBLE } else { @@ -156,33 +150,24 @@ class NotificationStore @Inject constructor( } } - @Synchronized - private fun cloneStore(): List { - val clone: MutableList = ArrayList(store.size) - clone.addAll(store) - return clone - } - inner class NotificationRecyclerViewAdapter internal constructor(private val notificationsList: List) : RecyclerView.Adapter() { - override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): NotificationsViewHolder { - val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.overview_notification_item, viewGroup, false) - return NotificationsViewHolder(v) - } + override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): NotificationsViewHolder = + NotificationsViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.overview_notification_item, viewGroup, false)) override fun onBindViewHolder(holder: NotificationsViewHolder, position: Int) { val notification = notificationsList[position] - holder.dismiss.tag = notification - if (notification.buttonText != 0) holder.dismiss.setText(notification.buttonText) - else holder.dismiss.setText(R.string.snooze) + holder.binding.dismiss.tag = notification + if (notification.buttonText != 0) holder.binding.dismiss.setText(notification.buttonText) + else holder.binding.dismiss.setText(R.string.snooze) @Suppress("SetTextI18n") - holder.text.text = dateUtil.timeString(notification.date) + " " + notification.text + holder.binding.text.text = dateUtil.timeString(notification.date) + " " + notification.text when (notification.level) { - Notification.URGENT -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent)) - Notification.NORMAL -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal)) - Notification.LOW -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow)) - Notification.INFO -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo)) - Notification.ANNOUNCEMENT -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationAnnouncement)) + Notification.URGENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent)) + Notification.NORMAL -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal)) + Notification.LOW -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow)) + Notification.INFO -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo)) + Notification.ANNOUNCEMENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationAnnouncement)) } } @@ -192,12 +177,10 @@ class NotificationStore @Inject constructor( inner class NotificationsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { - var cv: CardView = itemView.findViewById(R.id.notification_cardview) - var text: TextView = itemView.findViewById(R.id.notification_text) - var dismiss: Button = itemView.findViewById(R.id.notification_dismiss) + val binding = OverviewNotificationItemBinding.bind(itemView) init { - dismiss.setOnClickListener { + binding.dismiss.setOnClickListener { val notification = it.tag as Notification rxBus.send(EventDismissNotification(notification.id)) notification.action?.run() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt index 4e85b03b5c..e254278fd4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt @@ -12,6 +12,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject +@Suppress("SpellCheckingInspection") class NotificationWithAction constructor( injector: HasAndroidInjector ) : Notification() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt index d1adfc00ed..5f52035bac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt @@ -4,9 +4,7 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection -import android.os.Build import android.os.IBinder -import androidx.annotation.RequiresApi import info.nightscout.androidaps.interfaces.NotificationHolderInterface import javax.inject.Inject import javax.inject.Singleton @@ -14,14 +12,13 @@ import javax.inject.Singleton /* This code replaces following val alarm = Intent(context, DummyService::class.java) - alarm.putExtra("soundid", n.soundId) + alarm.putExtra("soundId", n.soundId) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm) it fails randomly with error Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.DummyService} */ -@RequiresApi(Build.VERSION_CODES.O) @Singleton class DummyServiceHelper @Inject constructor( private val notificationHolder: NotificationHolderInterface 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 0d6defc736..f770689e37 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 @@ -17,11 +17,8 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus 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.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 @@ -30,7 +27,7 @@ import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import javax.inject.Singleton -@Suppress("PrivatePropertyName") +@Suppress("PrivatePropertyName", "DEPRECATION") @Singleton class PersistentNotificationPlugin @Inject constructor( injector: HasAndroidInjector, @@ -43,10 +40,9 @@ class PersistentNotificationPlugin @Inject constructor( private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val rxBus: RxBusWrapper, private val context: Context, - private val notificationHolder: NotificationHolder, + private val notificationHolder: NotificationHolderInterface, private val dummyServiceHelper: DummyServiceHelper, - private val iconsProvider: IconsProvider, - private val databaseHelper: DatabaseHelperInterface + private val iconsProvider: IconsProvider ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .neverVisible(true) @@ -216,7 +212,7 @@ class PersistentNotificationPlugin @Inject constructor( .setUnreadConversation(unreadConversationBuilder.build())) } /// End Android Auto - builder.setContentIntent(openAppIntent(context)) + builder.setContentIntent(notificationHolder.openAppIntent(context)) val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notification = builder.build() mNotificationManager.notify(notificationHolder.notificationID, notification) 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 4d81704584..82853f1437 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 @@ -81,7 +81,7 @@ class SmsCommunicatorPlugin @Inject constructor( .preferencesId(R.xml.pref_smscommunicator) .description(R.string.description_sms_communicator), aapsLogger, resourceHelper, injector -) { +), SmsCommunicatorInterface { private val disposable = CompositeDisposable() var allowedNumbers: MutableList = ArrayList() @@ -351,7 +351,7 @@ class SmsCommunicatorPlugin @Inject constructor( } }) } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopisdisabled))) + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.loopisdisabled))) receivedSms.processed = true } @@ -378,7 +378,7 @@ class SmsCommunicatorPlugin @Inject constructor( if (loopPlugin.isSuspended) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) else resourceHelper.gs(R.string.smscommunicator_loopisenabled) } else - resourceHelper.gs(R.string.smscommunicator_loopisdisabled) + resourceHelper.gs(R.string.loopisdisabled) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -1011,7 +1011,7 @@ class SmsCommunicatorPlugin @Inject constructor( } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) } - fun sendNotificationToAllNumbers(text: String): Boolean { + override fun sendNotificationToAllNumbers(text: String): Boolean { var result = true for (i in allowedNumbers.indices) { val sms = Sms(allowedNumbers[i], text) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 2fbdbe6360..51846f1270 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -204,7 +204,7 @@ class ActionStringHandler @Inject constructor( val format = DecimalFormat("0.00") val formatInt = DecimalFormat("0") val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, activePlugin.activeTreatments.tempTargetFromHistory, - carbsAfterConstraints, cobInfo.displayCob, bgReading.valueToUnits(profileFunction.getUnits()), + carbsAfterConstraints, if (cobInfo.displayCob != null) cobInfo.displayCob!! else 0.0, bgReading.valueToUnits(profileFunction.getUnits()), 0.0, percentage.toDouble(), useBG, useCOB, useBolusIOB, useBasalIOB, false, useTT, useTrend, false) if (Math.abs(bolusWizard.insulinAfterConstraints - bolusWizard.calculatedTotalInsulin) >= 0.01) { sendError("Insulin constraint violation!" + 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 84acfc5667..f3cdd7a7f2 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 @@ -16,7 +16,7 @@ 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 import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers 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 7dd387b89a..a705394f59 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 @@ -16,7 +16,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import io.reactivex.rxkotlin.plusAssign diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index de1c931ccb..1009972939 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -71,14 +71,14 @@ open class IobCobCalculatorPlugin @Inject constructor( private var absIobTable = LongSparseArray() // oldest at index 0, absolute insulin in the body private var autosensDataTable = LongSparseArray() // oldest at index 0 private var basalDataTable = LongSparseArray() // oldest at index 0 - @Volatile var bgReadings: List = listOf() // newest at index 0 + @Volatile override var bgReadings: List = listOf() // newest at index 0 @Volatile var bucketedData: MutableList? = null // we need to make sure that bucketed_data will always have the same timestamp for correct use of cached values // once referenceTime != null all bucketed data should be (x * 5min) from referenceTime var referenceTime: Long = -1 private var lastUsed5minCalculation: Boolean? = null // true if used 5min bucketed data - val dataLock = Any() + override val dataLock = Any() var stopCalculationTrigger = false private var thread: Thread? = null @@ -388,7 +388,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return getBGDataFrom } - fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal { + override fun calculateFromTreatmentsAndTempsSynchronized(time: Long, profile: Profile?): IobTotal { synchronized(dataLock) { return calculateFromTreatmentsAndTemps(time, profile) } } @@ -524,7 +524,7 @@ open class IobCobCalculatorPlugin @Inject constructor( synchronized(dataLock) { return getLastAutosensData(reason) } } - fun getCobInfo(_synchronized: Boolean, reason: String): CobInfo { + override fun getCobInfo(_synchronized: Boolean, reason: String): CobInfo { val autosensData = if (_synchronized) getLastAutosensDataSynchronized(reason) else getLastAutosensData(reason) var displayCob: Double? = null var futureCarbs = 0.0 @@ -563,7 +563,7 @@ open class IobCobCalculatorPlugin @Inject constructor( return sum / count } - fun getLastAutosensData(reason: String): AutosensData? { + override fun getLastAutosensData(reason: String): AutosensData? { if (autosensDataTable.size() < 1) { aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA null: autosensDataTable empty ($reason)") return null diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt index 5bb64109ae..f03314829d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin @@ -82,7 +82,7 @@ class IobCobOref1Thread internal constructor( rxBus.send(EventAutosensBgLoaded(cause)) } val bucketedData = iobCobCalculatorPlugin.bucketedData - val autosensDataTable = iobCobCalculatorPlugin.autosensDataTable + val autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable() if (bucketedData == null || bucketedData.size < 3) { aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from") return @@ -288,7 +288,7 @@ class IobCobOref1Thread internal constructor( } } - // add an extra negative deviation if a high temptarget is running and exercise mode is set + // add an extra negative deviation if a high temp target is running and exercise mode is set // TODO AS-FIX @Suppress("SimplifyBooleanWithConstants") if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt index 1f67032978..ed5af41c6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin @@ -83,7 +83,7 @@ class IobCobThread @Inject internal constructor( rxBus.send(EventAutosensBgLoaded(cause)) } val bucketedData = iobCobCalculatorPlugin.bucketedData - val autosensDataTable = iobCobCalculatorPlugin.autosensDataTable + val autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable() if (bucketedData == null || bucketedData.size < 3) { aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from") return diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java deleted file mode 100644 index 55e61bb5c6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java +++ /dev/null @@ -1,220 +0,0 @@ -package info.nightscout.androidaps.plugins.sensitivity; - -import androidx.annotation.NonNull; -import androidx.collection.LongSparseArray; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; -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.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; - -/** - * Created by mike on 24.06.2017. - */ - -@Singleton -public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { - - private final ProfileFunction profileFunction; - private final DateUtil dateUtil; - - @Inject - public SensitivityAAPSPlugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - ResourceHelper resourceHelper, - SP sp, - ProfileFunction profileFunction, - DateUtil dateUtil - ) { - super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginIcon(R.drawable.ic_generic_icon) - .pluginName(R.string.sensitivityaaps) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_aaps) - .description(R.string.description_sensitivity_aaps), - injector, aapsLogger, resourceHelper, sp - ); - this.profileFunction = profileFunction; - this.dateUtil = dateUtil; - } - - @NonNull @Override - public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { - LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - - String age = getSp().getString(R.string.key_age, ""); - int defaultHours = 24; - if (age.equals(getResourceHelper().gs(R.string.key_adult))) defaultHours = 24; - if (age.equals(getResourceHelper().gs(R.string.key_teenage))) defaultHours = 4; - if (age.equals(getResourceHelper().gs(R.string.key_child))) defaultHours = 4; - int hoursForDetection = getSp().getInt(R.string.key_openapsama_autosens_period, defaultHours); - - Profile profile = profileFunction.getProfile(); - - if (profile == null) { - getAapsLogger().error("No profile"); - return new AutosensResult(); - } - - if (autosensDataTable == null || autosensDataTable.size() < 4) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already - if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - - List siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true); - List profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true); - - List deviationsArray = new ArrayList<>(); - String pastSensitivity = ""; - int index = 0; - while (index < autosensDataTable.size()) { - AutosensData autosensData = autosensDataTable.valueAt(index); - - if (autosensData.time < fromTime) { - index++; - continue; - } - - if (autosensData.time > toTime) { - index++; - continue; - } - - // reset deviations after site change - if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) { - deviationsArray.clear(); - pastSensitivity += "(SITECHANGE)"; - } - - // reset deviations after profile switch - if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { - deviationsArray.clear(); - pastSensitivity += "(PROFILESWITCH)"; - } - - double deviation = autosensData.deviation; - - //set positive deviations to zero if bg < 80 - if (autosensData.bg < 80 && deviation > 0) - deviation = 0; - - if (autosensData.validDeviation) - if (autosensData.time > toTime - hoursForDetection * 60 * 60 * 1000L) - deviationsArray.add(deviation); - if (deviationsArray.size() > hoursForDetection * 60 / 5) - deviationsArray.remove(0); - - - pastSensitivity += autosensData.pastSensitivity; - int secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time); - if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { - pastSensitivity += "(" + Math.round(secondsFromMidnight / 3600d) + ")"; - } - index++; - } - - Double[] deviations = new Double[deviationsArray.size()]; - deviations = deviationsArray.toArray(deviations); - - double sens = profile.getIsfMgdl(); - - String ratioLimit = ""; - String sensResult = ""; - - getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); - - Arrays.sort(deviations); - - double percentile = IobCobCalculatorPlugin.Companion.percentile(deviations, 0.50); - double basalOff = percentile * (60.0 / 5.0) / sens; - double ratio = 1 + (basalOff / profile.getMaxDailyBasal()); - - if (percentile < 0) { // sensitive - sensResult = "Excess insulin sensitivity detected"; - } else if (percentile > 0) { // resistant - sensResult = "Excess insulin resistance detected"; - } else { - sensResult = "Sensitivity normal"; - } - - getAapsLogger().debug(LTag.AUTOSENS, sensResult); - - AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, - sensResult, deviationsArray.size()); - - getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + dateUtil.dateAndTimeString(toTime) + - " ratio: " + output.ratio - + " mealCOB: " + current.cob); - getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: deviations " + Arrays.toString(deviations)); - - return output; - } - - @NotNull @Override public SensitivityType getId() { - return SensitivityType.SENSITIVITY_AAPS; - } - - @NotNull @Override public JSONObject configuration() { - JSONObject c = new JSONObject(); - try { - c.put(getResourceHelper().gs(R.string.key_absorption_maxtime), getSp().getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_period), getSp().getInt(R.string.key_openapsama_autosens_period, 24)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_max), getSp().getDouble(R.string.key_openapsama_autosens_max, 1.2)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_min), getSp().getDouble(R.string.key_openapsama_autosens_min, 0.7)); - } catch (JSONException e) { - e.printStackTrace(); - } - return c; - } - - @Override public void applyConfiguration(@NotNull JSONObject configuration) { - try { - if (configuration.has(getResourceHelper().gs(R.string.key_absorption_maxtime))) - getSp().putDouble(R.string.key_absorption_maxtime, configuration.getDouble(getResourceHelper().gs(R.string.key_absorption_maxtime))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_period))) - getSp().putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_period))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_max))) - getSp().getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_max))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_min))) - getSp().getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_min))); - } catch (JSONException e) { - e.printStackTrace(); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt new file mode 100644 index 0000000000..4c53d95ab7 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -0,0 +1,161 @@ +package info.nightscout.androidaps.plugins.sensitivity + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.SensitivityInterface.SensitivityType +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.json.JSONException +import org.json.JSONObject +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.roundToInt + +@Singleton +open class SensitivityAAPSPlugin @Inject constructor( + injector: HasAndroidInjector?, + aapsLogger: AAPSLogger?, + resourceHelper: ResourceHelper?, + sp: SP?, + private val profileFunction: ProfileFunction, + private val dateUtil: DateUtil +) : AbstractSensitivityPlugin(PluginDescription() + .mainType(PluginType.SENSITIVITY) + .pluginIcon(R.drawable.ic_generic_icon) + .pluginName(R.string.sensitivityaaps) + .shortName(R.string.sensitivity_shortname) + .preferencesId(R.xml.pref_absorption_aaps) + .description(R.string.description_sensitivity_aaps), + injector!!, aapsLogger!!, resourceHelper!!, sp!! +) { + + override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + val autosensDataTable = plugin.getAutosensDataTable() + val age = sp.getString(R.string.key_age, "") + var defaultHours = 24 + if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 + if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 + if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 + val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) + val profile = profileFunction.getProfile() + if (profile == null) { + aapsLogger.error("No profile") + return AutosensResult() + } + if (autosensDataTable.size() < 4) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + plugin.lastDataTime()) + return AutosensResult() + } + val current = plugin.getAutosensData(toTime) // this is running inside lock already + if (current == null) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + plugin.lastDataTime()) + return AutosensResult() + } + val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) + val deviationsArray: MutableList = ArrayList() + var pastSensitivity = "" + var index = 0 + while (index < autosensDataTable.size()) { + val autosensData = autosensDataTable.valueAt(index) + if (autosensData.time < fromTime) { + index++ + continue + } + if (autosensData.time > toTime) { + index++ + continue + } + + // reset deviations after site change + if (CareportalEvent(injector).isEvent5minBack(siteChanges, autosensData.time)) { + deviationsArray.clear() + pastSensitivity += "(SITECHANGE)" + } + + // reset deviations after profile switch + if (ProfileSwitch(injector).isEvent5minBack(profileSwitches, autosensData.time, true)) { + deviationsArray.clear() + pastSensitivity += "(PROFILESWITCH)" + } + var deviation = autosensData.deviation + + //set positive deviations to zero if bg < 80 + if (autosensData.bg < 80 && deviation > 0) deviation = 0.0 + if (autosensData.validDeviation) if (autosensData.time > toTime - hoursForDetection * 60 * 60 * 1000L) deviationsArray.add(deviation) + if (deviationsArray.size > hoursForDetection * 60 / 5) deviationsArray.removeAt(0) + pastSensitivity += autosensData.pastSensitivity + val secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time) + if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { + pastSensitivity += "(" + (secondsFromMidnight / 3600.0).roundToInt() + ")" + } + index++ + } + val deviations = Array(deviationsArray.size) { i -> deviationsArray[i] } + val sens = profile.isfMgdl + val ratioLimit = "" + val sensResult: String + aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") + Arrays.sort(deviations) + val percentile = percentile(deviations, 0.50) + val basalOff = percentile * (60.0 / 5.0) / sens + val ratio = 1 + basalOff / profile.maxDailyBasal + sensResult = when { + percentile < 0 -> "Excess insulin sensitivity detected" + percentile > 0 -> "Excess insulin resistance detected" + else -> "Sensitivity normal" + + } + aapsLogger.debug(LTag.AUTOSENS, sensResult) + val output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, + sensResult, deviationsArray.size) + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity to: " + + dateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob) + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity to: deviations " + deviations.contentToString()) + return output + } + + override val id: SensitivityType + get() = SensitivityType.SENSITIVITY_AAPS + + override fun configuration(): JSONObject { + val c = JSONObject() + try { + c.put(resourceHelper.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + } catch (e: JSONException) { + e.printStackTrace() + } + return c + } + + override fun applyConfiguration(configuration: JSONObject) { + try { + if (configuration.has(resourceHelper.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_maxtime))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_period))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + } catch (e: JSONException) { + e.printStackTrace() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java deleted file mode 100644 index fbc1baa5e1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ /dev/null @@ -1,286 +0,0 @@ -package info.nightscout.androidaps.plugins.sensitivity; - -import androidx.collection.LongSparseArray; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; -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.aps.openAPSSMB.SMBDefaults; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; - - -/** - * Created by mike on 19.06.2018. - */ -@Singleton -public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { - - private final ProfileFunction profileFunction; - private final DateUtil dateUtil; - - @Inject - public SensitivityOref1Plugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - ResourceHelper resourceHelper, - SP sp, - ProfileFunction profileFunction, - DateUtil dateUtil - ) { - super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginIcon(R.drawable.ic_generic_icon) - .pluginName(R.string.sensitivityoref1) - .shortName(R.string.sensitivity_shortname) - .enableByDefault(true) - .preferencesId(R.xml.pref_absorption_oref1) - .description(R.string.description_sensitivity_oref1) - .setDefault(), - injector, aapsLogger, resourceHelper, sp - ); - this.profileFunction = profileFunction; - this.dateUtil = dateUtil; - } - - @NotNull @Override - public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { - // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular - // dependency, this should be avoided - LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - - Profile profile = profileFunction.getProfile(); - - if (profile == null) { - getAapsLogger().error("No profile"); - return new AutosensResult(); - } - - if (autosensDataTable == null || autosensDataTable.size() < 4) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - // the current - AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already - if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - List siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true); - List profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true); - - //[0] = 8 hour - //[1] = 24 hour - //Deviationshour has DeviationsArray - List> deviationsHour = Arrays.asList(new ArrayList<>(), new ArrayList<>()); - List pastSensitivityArray = Arrays.asList("", ""); - List sensResultArray = Arrays.asList("", ""); - List ratioArray = Arrays.asList(0d, 0d); - List deviationCategory = Arrays.asList(96d, 288d); - List ratioLimitArray = Arrays.asList("", ""); - List hoursDetection = Arrays.asList(8d, 24d); - - - int index = 0; - while (index < autosensDataTable.size()) { - AutosensData autosensData = autosensDataTable.valueAt(index); - - if (autosensData.time < fromTime) { - index++; - continue; - } - - if (autosensData.time > toTime) { - index++; - continue; - } - int hoursegment = 0; - //hoursegment = 0 = 8 hour - //hoursegment = 1 = 24 hour - while (hoursegment < deviationsHour.size()) { - ArrayList deviationsArray = deviationsHour.get(hoursegment); - String pastSensitivity = pastSensitivityArray.get(hoursegment); - - // reset deviations after site change - if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) { - deviationsArray.clear(); - pastSensitivity += "(SITECHANGE)"; - } - - // reset deviations after profile switch - if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { - deviationsArray.clear(); - pastSensitivity += "(PROFILESWITCH)"; - } - - double deviation = autosensData.deviation; - - //set positive deviations to zero if bg < 80 - if (autosensData.bg < 80 && deviation > 0) - deviation = 0; - - if (autosensData.validDeviation) - if (autosensData.time > toTime - hoursDetection.get(hoursegment) * 60 * 60 * 1000L) - deviationsArray.add(deviation); - - - deviationsArray.addAll(autosensData.extraDeviation); - - if (deviationsArray.size() > deviationCategory.get(hoursegment)) { - deviationsArray.remove(0); - } - - pastSensitivity += autosensData.pastSensitivity; - int secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time); - - if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { - pastSensitivity += "(" + Math.round(secondsFromMidnight / 3600d) + ")"; - } - - //Update the data back to the parent - deviationsHour.set(hoursegment, deviationsArray); - pastSensitivityArray.set(hoursegment, pastSensitivity); - hoursegment++; - } - index++; - } - - // when we have less than 8h/24 worth of deviation data, add up to 90m of zero deviations - // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely - - for (int i = 0; i < deviationsHour.size(); i++) { - ArrayList deviations = deviationsHour.get(i); - getAapsLogger().debug(LTag.AUTOSENS, "Using most recent " + deviations.size() + " deviations"); - if (deviations.size() < deviationCategory.get(i)) { - int pad = (int) Math.round((1 - (double) deviations.size() / deviationCategory.get(i)) * 18); - getAapsLogger().debug(LTag.AUTOSENS, "Adding " + pad + " more zero deviations"); - for (int d = 0; d < pad; d++) { - deviations.add(0d); - } - } - //Update the data back to the parent - deviationsHour.set(i, deviations); - - } - - int hourused = 0; - while (hourused < deviationsHour.size()) { - ArrayList deviationsArray = deviationsHour.get(hourused); - String pastSensitivity = pastSensitivityArray.get(hourused); - String sensResult = "(8 hours) "; - if (hourused == 1) sensResult = "(24 hours) "; - String ratioLimit = ""; - - Double[] deviations = new Double[deviationsArray.size()]; - deviations = (Double[]) deviationsArray.toArray(deviations); - - double sens = profile.getIsfMgdl(); - - - getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); - - Arrays.sort(deviations); - double pSensitive = IobCobCalculatorPlugin.Companion.percentile(deviations, 0.50); - double pResistant = IobCobCalculatorPlugin.Companion.percentile(deviations, 0.50); - - double basalOff = 0; - - if (pSensitive < 0) { // sensitive - basalOff = pSensitive * (60.0 / 5) / sens; - sensResult += "Excess insulin sensitivity detected"; - } else if (pResistant > 0) { // resistant - basalOff = pResistant * (60.0 / 5) / sens; - sensResult += "Excess insulin resistance detected"; - } else { - sensResult += "Sensitivity normal"; - } - - getAapsLogger().debug(LTag.AUTOSENS, sensResult); - - double ratio = 1 + (basalOff / profile.getMaxDailyBasal()); - - //Update the data back to the parent - sensResultArray.set(hourused, sensResult); - ratioArray.set(hourused, ratio); - ratioLimitArray.set(hourused, ratioLimit); - hourused++; - } - - int key = 1; - String comparison = " 8 h ratio " + ratioArray.get(0) + " vs 24h ratio " + ratioArray.get(1); - //use 24 hour ratio by default - //if the 8 hour ratio is less than the 24 hour ratio, the 8 hour ratio is used - if (ratioArray.get(0) < ratioArray.get(1)) { - key = 0; - } - //String message = hoursDetection.get(key) + " of sensitivity used"; - AutosensResult output = fillResult(ratioArray.get(key), current.cob, pastSensitivityArray.get(key), ratioLimitArray.get(key), - sensResultArray.get(key) + comparison, deviationsHour.get(key).size()); - - getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + dateUtil.dateAndTimeString(toTime) + - " ratio: " + output.ratio - + " mealCOB: " + current.cob); - - return output; - } - - @NotNull @Override public JSONObject configuration() { - JSONObject c = new JSONObject(); - try { - c.put(getResourceHelper().gs(R.string.key_openapsama_min_5m_carbimpact), getSp().getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); - c.put(getResourceHelper().gs(R.string.key_absorption_cutoff), getSp().getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_max), getSp().getDouble(R.string.key_openapsama_autosens_max, 1.2)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_min), getSp().getDouble(R.string.key_openapsama_autosens_min, 0.7)); - } catch (JSONException e) { - e.printStackTrace(); - } - return c; - } - - @Override public void applyConfiguration(@NotNull JSONObject configuration) { - try { - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_min_5m_carbimpact))) - getSp().putDouble(R.string.key_openapsama_min_5m_carbimpact, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_min_5m_carbimpact))); - if (configuration.has(getResourceHelper().gs(R.string.key_absorption_cutoff))) - getSp().putDouble(R.string.key_absorption_cutoff, configuration.getDouble(getResourceHelper().gs(R.string.key_absorption_cutoff))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_max))) - getSp().getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_max))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_min))) - getSp().getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_min))); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - @NotNull @Override public SensitivityType getId() { - return SensitivityType.SENSITIVITY_OREF1; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt new file mode 100644 index 0000000000..c04a204312 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -0,0 +1,228 @@ +package info.nightscout.androidaps.plugins.sensitivity + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.SensitivityInterface.SensitivityType +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.json.JSONException +import org.json.JSONObject +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.roundToInt + +@Singleton +open class SensitivityOref1Plugin @Inject constructor( + injector: HasAndroidInjector?, + aapsLogger: AAPSLogger?, + resourceHelper: ResourceHelper?, + sp: SP?, + private val profileFunction: ProfileFunction, + private val dateUtil: DateUtil +) : AbstractSensitivityPlugin(PluginDescription() + .mainType(PluginType.SENSITIVITY) + .pluginIcon(R.drawable.ic_generic_icon) + .pluginName(R.string.sensitivityoref1) + .shortName(R.string.sensitivity_shortname) + .enableByDefault(true) + .preferencesId(R.xml.pref_absorption_oref1) + .description(R.string.description_sensitivity_oref1) + .setDefault(), + injector!!, aapsLogger!!, resourceHelper!!, sp!! +) { + + override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular + // dependency, this should be avoided + val autosensDataTable = plugin.getAutosensDataTable() + val profile = profileFunction.getProfile() + if (profile == null) { + aapsLogger.error("No profile") + return AutosensResult() + } + if (autosensDataTable.size() < 4) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + plugin.lastDataTime()) + return AutosensResult() + } + + // the current + val current = plugin.getAutosensData(toTime) // this is running inside lock already + if (current == null) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + plugin.lastDataTime()) + return AutosensResult() + } + val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) + + //[0] = 8 hour + //[1] = 24 hour + //deviationsHour has DeviationsArray + val deviationsHour = mutableListOf(ArrayList(), ArrayList()) + val pastSensitivityArray = mutableListOf("", "") + val sensResultArray = mutableListOf("", "") + val ratioArray = mutableListOf(0.0, 0.0) + val deviationCategory = listOf(96.0, 288.0) + val ratioLimitArray = mutableListOf("", "") + val hoursDetection = listOf(8.0, 24.0) + var index = 0 + while (index < autosensDataTable.size()) { + val autosensData = autosensDataTable.valueAt(index) + if (autosensData.time < fromTime) { + index++ + continue + } + if (autosensData.time > toTime) { + index++ + continue + } + var hourSegment = 0 + //hourSegment = 0 = 8 hour + //hourSegment = 1 = 24 hour + while (hourSegment < deviationsHour.size) { + val deviationsArray = deviationsHour[hourSegment] + var pastSensitivity = pastSensitivityArray[hourSegment] + + // reset deviations after site change + if (CareportalEvent(injector).isEvent5minBack(siteChanges, autosensData.time)) { + deviationsArray.clear() + pastSensitivity += "(SITECHANGE)" + } + + // reset deviations after profile switch + if (ProfileSwitch(injector).isEvent5minBack(profileSwitches, autosensData.time, true)) { + deviationsArray.clear() + pastSensitivity += "(PROFILESWITCH)" + } + var deviation = autosensData.deviation + + //set positive deviations to zero if bg < 80 + if (autosensData.bg < 80 && deviation > 0) deviation = 0.0 + if (autosensData.validDeviation) if (autosensData.time > toTime - hoursDetection[hourSegment] * 60 * 60 * 1000L) deviationsArray.add(deviation) + deviationsArray.addAll(autosensData.extraDeviation) + if (deviationsArray.size > deviationCategory[hourSegment]) { + deviationsArray.removeAt(0) + } + pastSensitivity += autosensData.pastSensitivity + val secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time) + if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { + pastSensitivity += "(" + (secondsFromMidnight / 3600.0).roundToInt() + ")" + } + + //Update the data back to the parent + deviationsHour[hourSegment] = deviationsArray + pastSensitivityArray[hourSegment] = pastSensitivity + hourSegment++ + } + index++ + } + + // when we have less than 8h/24 worth of deviation data, add up to 90m of zero deviations + // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely + for (i in deviationsHour.indices) { + val deviations = deviationsHour[i] + aapsLogger.debug(LTag.AUTOSENS, "Using most recent " + deviations.size + " deviations") + if (deviations.size < deviationCategory[i]) { + val pad = ((1 - deviations.size.toDouble() / deviationCategory[i]) * 18).roundToInt() + aapsLogger.debug(LTag.AUTOSENS, "Adding $pad more zero deviations") + for (d in 0 until pad) { + deviations.add(0.0) + } + } + //Update the data back to the parent + deviationsHour[i] = deviations + } + var hourUsed = 0 + while (hourUsed < deviationsHour.size) { + val deviationsArray: ArrayList = deviationsHour[hourUsed] + val pastSensitivity = pastSensitivityArray[hourUsed] + var sensResult = "(8 hours) " + if (hourUsed == 1) sensResult = "(24 hours) " + val ratioLimit = "" + val deviations: Array = Array(deviationsArray.size) { i -> deviationsArray[i] } + val sens = profile.isfMgdl + aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") + Arrays.sort(deviations) + val pSensitive = percentile(deviations, 0.50) + val pResistant = percentile(deviations, 0.50) + var basalOff = 0.0 + when { + pSensitive < 0 -> { // sensitive + basalOff = pSensitive * (60.0 / 5) / sens + sensResult += "Excess insulin sensitivity detected" + } + + pResistant > 0 -> { // resistant + basalOff = pResistant * (60.0 / 5) / sens + sensResult += "Excess insulin resistance detected" + } + + else -> sensResult += "Sensitivity normal" + } + aapsLogger.debug(LTag.AUTOSENS, sensResult) + val ratio = 1 + basalOff / profile.maxDailyBasal + + //Update the data back to the parent + sensResultArray[hourUsed] = sensResult + ratioArray[hourUsed] = ratio + ratioLimitArray[hourUsed] = ratioLimit + hourUsed++ + } + var key = 1 + val comparison = " 8 h ratio " + ratioArray[0] + " vs 24h ratio " + ratioArray[1] + //use 24 hour ratio by default + //if the 8 hour ratio is less than the 24 hour ratio, the 8 hour ratio is used + if (ratioArray[0] < ratioArray[1]) { + key = 0 + } + //String message = hoursDetection.get(key) + " of sensitivity used"; + val output = fillResult(ratioArray[key], current.cob, pastSensitivityArray[key], ratioLimitArray[key], sensResultArray[key] + comparison, deviationsHour[key].size) + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity to: " + + dateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob) + return output + } + + override fun configuration(): JSONObject { + val c = JSONObject() + try { + c.put(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact), sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)) + c.put(resourceHelper.gs(R.string.key_absorption_cutoff), sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + } catch (e: JSONException) { + e.printStackTrace() + } + return c + } + + override fun applyConfiguration(configuration: JSONObject) { + try { + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact))) sp.putDouble(R.string.key_openapsama_min_5m_carbimpact, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact))) + if (configuration.has(resourceHelper.gs(R.string.key_absorption_cutoff))) sp.putDouble(R.string.key_absorption_cutoff, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_cutoff))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + } catch (e: JSONException) { + e.printStackTrace() + } + } + + override val id: SensitivityType + get() = SensitivityType.SENSITIVITY_OREF1 +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java deleted file mode 100644 index 3cc34908a5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java +++ /dev/null @@ -1,240 +0,0 @@ -package info.nightscout.androidaps.plugins.sensitivity; - -import androidx.collection.LongSparseArray; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; -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.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; - -/** - * Created by mike on 24.06.2017. - */ -@Singleton -public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { - - private final SP sp; - private final DateUtil dateUtil; - private final ProfileFunction profileFunction; - - @Inject - public SensitivityWeightedAveragePlugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - ResourceHelper resourceHelper, - SP sp, - ProfileFunction profileFunction, - DateUtil dateUtil - ) { - super(new PluginDescription() - .mainType(PluginType.SENSITIVITY) - .pluginIcon(R.drawable.ic_generic_icon) - .pluginName(R.string.sensitivityweightedaverage) - .shortName(R.string.sensitivity_shortname) - .preferencesId(R.xml.pref_absorption_aaps) - .description(R.string.description_sensitivity_weighted_average), - injector, aapsLogger, resourceHelper, sp - ); - this.sp = sp; - this.dateUtil = dateUtil; - this.profileFunction = profileFunction; - } - - @Override - public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { - LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - - String age = sp.getString(R.string.key_age, ""); - int defaultHours = 24; - if (age.equals(getResourceHelper().gs(R.string.key_adult))) defaultHours = 24; - if (age.equals(getResourceHelper().gs(R.string.key_teenage))) defaultHours = 4; - if (age.equals(getResourceHelper().gs(R.string.key_child))) defaultHours = 4; - int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); - - if (autosensDataTable == null || autosensDataTable.size() < 4) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already - if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); - return new AutosensResult(); - } - - - Profile profile = profileFunction.getProfile(); - if (profile == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No profile available"); - return new AutosensResult(); - } - - List siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true); - List profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true); - - String pastSensitivity = ""; - int index = 0; - LongSparseArray data = new LongSparseArray<>(); - - while (index < autosensDataTable.size()) { - AutosensData autosensData = autosensDataTable.valueAt(index); - - if (autosensData.time < fromTime) { - index++; - continue; - } - - if (autosensData.time > toTime) { - index++; - continue; - } - - if (autosensData.time < toTime - hoursForDetection * 60 * 60 * 1000L) { - index++; - continue; - } - - // reset deviations after site change - if (new CareportalEvent(getInjector()).isEvent5minBack(siteChanges, autosensData.time)) { - data.clear(); - pastSensitivity += "(SITECHANGE)"; - } - - // reset deviations after profile switch - if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { - data.clear(); - pastSensitivity += "(PROFILESWITCH)"; - } - - double deviation = autosensData.deviation; - - //set positive deviations to zero if bg < 80 - if (autosensData.bg < 80 && deviation > 0) - deviation = 0; - - //data.append(autosensData.time); - long reverseWeight = (toTime - autosensData.time) / (5 * 60 * 1000L); - if (autosensData.validDeviation) - data.append(reverseWeight, deviation); - //weights += reverseWeight; - //weightedsum += reverseWeight * (autosensData.validDeviation ? autosensData.deviation : 0d); - - - pastSensitivity += autosensData.pastSensitivity; - int secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time); - if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { - pastSensitivity += "(" + Math.round(secondsFromMidnight / 3600d) + ")"; - } - index++; - } - - if (data.size() == 0) { - getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)); - return new AutosensResult(); - } else { - getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)); - } - - double weightedsum = 0; - double weights = 0; - - long hightestWeight = data.keyAt(data.size() - 1); - for (int i = 0; i < data.size(); i++) { - long reversedWeigth = data.keyAt(i); - double value = data.valueAt(i); - double weight = (hightestWeight - reversedWeigth) / 2.0; - weights += weight; - weightedsum += weight * value; - } - - if (weights == 0) { - return new AutosensResult(); - } - - double sens = profile.getIsfMgdl(); - - String ratioLimit = ""; - String sensResult; - - getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); - - double average = weightedsum / weights; - double basalOff = average * (60 / 5.0) / sens; - double ratio = 1 + (basalOff / profile.getMaxDailyBasal()); - - if (average < 0) { // sensitive - sensResult = "Excess insulin sensitivity detected"; - } else if (average > 0) { // resistant - sensResult = "Excess insulin resistance detected"; - } else { - sensResult = "Sensitivity normal"; - } - - getAapsLogger().debug(LTag.AUTOSENS, sensResult); - - AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, - sensResult, data.size()); - - getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + dateUtil.dateAndTimeString(toTime) + - " ratio: " + output.ratio - + " mealCOB: " + current.cob); - - return output; - } - - @NotNull @Override public SensitivityType getId() { - return SensitivityType.SENSITIVITY_WEIGHTED; - } - - @NotNull @Override public JSONObject configuration() { - JSONObject c = new JSONObject(); - try { - c.put(getResourceHelper().gs(R.string.key_absorption_maxtime), getSp().getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_period), getSp().getInt(R.string.key_openapsama_autosens_period, 24)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_max), getSp().getDouble(R.string.key_openapsama_autosens_max, 1.2)); - c.put(getResourceHelper().gs(R.string.key_openapsama_autosens_min), getSp().getDouble(R.string.key_openapsama_autosens_min, 0.7)); - } catch (JSONException e) { - e.printStackTrace(); - } - return c; - } - - @Override public void applyConfiguration(@NotNull JSONObject configuration) { - try { - if (configuration.has(getResourceHelper().gs(R.string.key_absorption_maxtime))) - getSp().putDouble(R.string.key_absorption_maxtime, configuration.getDouble(getResourceHelper().gs(R.string.key_absorption_maxtime))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_period))) - getSp().putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_period))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_max))) - getSp().getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_max))); - if (configuration.has(getResourceHelper().gs(R.string.key_openapsama_autosens_min))) - getSp().getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(getResourceHelper().gs(R.string.key_openapsama_autosens_min))); - } catch (JSONException e) { - e.printStackTrace(); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt new file mode 100644 index 0000000000..4e742b5760 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -0,0 +1,181 @@ +package info.nightscout.androidaps.plugins.sensitivity + +import androidx.collection.LongSparseArray +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.SensitivityInterface.SensitivityType +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.json.JSONException +import org.json.JSONObject +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.roundToInt + +@Singleton +open class SensitivityWeightedAveragePlugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + sp: SP, + private val profileFunction: ProfileFunction, + private val dateUtil: DateUtil +) : AbstractSensitivityPlugin(PluginDescription() + .mainType(PluginType.SENSITIVITY) + .pluginIcon(R.drawable.ic_generic_icon) + .pluginName(R.string.sensitivityweightedaverage) + .shortName(R.string.sensitivity_shortname) + .preferencesId(R.xml.pref_absorption_aaps) + .description(R.string.description_sensitivity_weighted_average), + injector, aapsLogger, resourceHelper, sp +) { + + override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult { + val autosensDataTable = plugin.getAutosensDataTable() + val age = sp.getString(R.string.key_age, "") + var defaultHours = 24 + if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 + if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 + if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 + val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) + if (autosensDataTable.size() < 4) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + plugin.lastDataTime()) + return AutosensResult() + } + val current = plugin.getAutosensData(toTime) // this is running inside lock already + if (current == null) { + aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + plugin.lastDataTime()) + return AutosensResult() + } + val profile = profileFunction.getProfile() + if (profile == null) { + aapsLogger.debug(LTag.AUTOSENS, "No profile available") + return AutosensResult() + } + val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) + var pastSensitivity = "" + var index = 0 + val data = LongSparseArray() + while (index < autosensDataTable.size()) { + val autosensData = autosensDataTable.valueAt(index) + if (autosensData.time < fromTime) { + index++ + continue + } + if (autosensData.time > toTime) { + index++ + continue + } + if (autosensData.time < toTime - hoursForDetection * 60 * 60 * 1000L) { + index++ + continue + } + + // reset deviations after site change + if (CareportalEvent(injector).isEvent5minBack(siteChanges, autosensData.time)) { + data.clear() + pastSensitivity += "(SITECHANGE)" + } + + // reset deviations after profile switch + if (ProfileSwitch(injector).isEvent5minBack(profileSwitches, autosensData.time, true)) { + data.clear() + pastSensitivity += "(PROFILESWITCH)" + } + var deviation = autosensData.deviation + + //set positive deviations to zero if bg < 80 + if (autosensData.bg < 80 && deviation > 0) deviation = 0.0 + + //data.append(autosensData.time); + val reverseWeight = (toTime - autosensData.time) / (5 * 60 * 1000L) + if (autosensData.validDeviation) data.append(reverseWeight, deviation) + pastSensitivity += autosensData.pastSensitivity + val secondsFromMidnight = Profile.secondsFromMidnight(autosensData.time) + if (secondsFromMidnight % 3600 < 2.5 * 60 || secondsFromMidnight % 3600 > 57.5 * 60) { + pastSensitivity += "(" + (secondsFromMidnight / 3600.0).roundToInt() + ")" + } + index++ + } + if (data.size() == 0) { + aapsLogger.debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)) + return AutosensResult() + } else { + aapsLogger.debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)) + } + var weightedSum = 0.0 + var weights = 0.0 + val highestWeight = data.keyAt(data.size() - 1) + for (i in 0 until data.size()) { + val reversedWeight = data.keyAt(i) + val value = data.valueAt(i) + val weight = (highestWeight - reversedWeight) / 2.0 + weights += weight + weightedSum += weight * value + } + if (weights == 0.0) { + return AutosensResult() + } + val sens = profile.isfMgdl + val ratioLimit = "" + val sensResult: String + aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") + val average = weightedSum / weights + val basalOff = average * (60 / 5.0) / sens + val ratio = 1 + basalOff / profile.maxDailyBasal + sensResult = when { + average < 0 -> "Excess insulin sensitivity detected" + average > 0 -> "Excess insulin resistance detected" + else -> "Sensitivity normal" + } + aapsLogger.debug(LTag.AUTOSENS, sensResult) + val output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, + sensResult, data.size()) + aapsLogger.debug(LTag.AUTOSENS, "Sensitivity to: " + + dateUtil.dateAndTimeString(toTime) + + " ratio: " + output.ratio + + " mealCOB: " + current.cob) + return output + } + + override val id: SensitivityType + get() = SensitivityType.SENSITIVITY_WEIGHTED + + override fun configuration(): JSONObject { + val c = JSONObject() + try { + c.put(resourceHelper.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + } catch (e: JSONException) { + e.printStackTrace() + } + return c + } + + override fun applyConfiguration(configuration: JSONObject) { + try { + if (configuration.has(resourceHelper.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_maxtime))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_period))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + } catch (e: JSONException) { + e.printStackTrace() + } + } +} \ No newline at end of file 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 41e3673493..b9df26c318 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 @@ -8,7 +8,7 @@ import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import org.jetbrains.annotations.NotNull; +import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.List; @@ -765,7 +765,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } @Override - public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { + public void doProfileSwitch(@NonNull final ProfileStore profileStore, @NonNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { ProfileSwitch profileSwitch = profileFunction.prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); addToHistoryProfileSwitch(profileSwitch); if (percentage == 90 && duration == 10) 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 e2d5941059..07d2d2e600 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 @@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment.RecyclerViewAdapter.TreatmentsViewHolder import info.nightscout.androidaps.utils.DateUtil 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 6b87a963d8..a8f1c3d8d0 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 @@ -152,7 +152,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { val careportalEvent = v.tag as CareportalEvent activity?.let { activity -> val text = resourceHelper.gs(R.string.eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + - resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + careportalEvent.notes + "\n" + + resourceHelper.gs(R.string.notes_label) + ": " + careportalEvent.notes + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(careportalEvent.date) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { uel.log(Action.CAREPORTAL_REMOVED, careportalEvent.notes, ValueWithUnit(careportalEvent.eventType, Units.CPEvent), ValueWithUnit(careportalEvent.date, Units.Timestamp)) 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 34447354d3..efd15c3463 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 @@ -25,7 +25,7 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy 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 446cd3605f..365c5ae4c2 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 @@ -23,7 +23,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment.RecyclerViewAdapter.TempBasalsViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy diff --git a/app/src/main/java/info/nightscout/androidaps/services/Intents.java b/app/src/main/java/info/nightscout/androidaps/services/Intents.java deleted file mode 100644 index f8742bb8b6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/services/Intents.java +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.services; - -public interface Intents { - // NSClient -> App - String ACTION_NEW_TREATMENT = "info.nightscout.client.NEW_TREATMENT"; - String ACTION_CHANGED_TREATMENT = "info.nightscout.client.CHANGED_TREATMENT"; - String ACTION_REMOVED_TREATMENT = "info.nightscout.client.REMOVED_TREATMENT"; - String ACTION_NEW_PROFILE = "info.nightscout.client.NEW_PROFILE"; - String ACTION_NEW_SGV = "info.nightscout.client.NEW_SGV"; - String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG"; - String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL"; - - // xDrip -> App - String ACTION_NEW_BG_ESTIMATE = "com.eveningoutpost.dexdrip.BgEstimate"; - String EXTRA_BG_ESTIMATE = "com.eveningoutpost.dexdrip.Extras.BgEstimate"; - String EXTRA_BG_SLOPE = "com.eveningoutpost.dexdrip.Extras.BgSlope"; - String EXTRA_BG_SLOPE_NAME = "com.eveningoutpost.dexdrip.Extras.BgSlopeName"; - String EXTRA_SENSOR_BATTERY = "com.eveningoutpost.dexdrip.Extras.SensorBattery"; - String EXTRA_TIMESTAMP = "com.eveningoutpost.dexdrip.Extras.Time"; - String EXTRA_RAW = "com.eveningoutpost.dexdrip.Extras.Raw"; - String XDRIP_DATA_SOURCE_DESCRIPTION = "com.eveningoutpost.dexdrip.Extras.SourceDesc"; - - - String ACTION_NEW_BG_ESTIMATE_NO_DATA = "com.eveningoutpost.dexdrip.BgEstimateNoData"; - - String NS_EMULATOR = "com.eveningoutpost.dexdrip.NS_EMULATOR"; - - String ACTION_REMOTE_CALIBRATION = "com.eveningoutpost.dexdrip.NewCalibration"; - - String GLIMP_BG = "it.ct.glicemia.ACTION_GLUCOSE_MEASURED"; - - String DEXCOM_BG = "com.dexcom.cgm.EXTERNAL_BROADCAST"; - String EVERSENSE_BG = "com.senseonics.AndroidAPSEventSubscriber.BROADCAST"; - - String POCTECH_BG = "com.china.poctech.data"; - String TOMATO_BG = "com.fanqies.tomatofn.BgEstimate"; - - // Broadcast status - String AAPS_BROADCAST = "info.nightscout.androidaps.status"; -} diff --git a/app/src/main/java/info/nightscout/androidaps/services/Intents.kt b/app/src/main/java/info/nightscout/androidaps/services/Intents.kt new file mode 100644 index 0000000000..5e38fdb15b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/services/Intents.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.services + +@Suppress("unused") +interface Intents { + + companion object { + + // NSClient -> App + const val ACTION_NEW_TREATMENT = "info.nightscout.client.NEW_TREATMENT" + const val ACTION_CHANGED_TREATMENT = "info.nightscout.client.CHANGED_TREATMENT" + const val ACTION_REMOVED_TREATMENT = "info.nightscout.client.REMOVED_TREATMENT" + const val ACTION_NEW_PROFILE = "info.nightscout.client.NEW_PROFILE" + const val ACTION_NEW_SGV = "info.nightscout.client.NEW_SGV" + const val ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG" + const val ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL" + + // xDrip -> App + const val ACTION_NEW_BG_ESTIMATE = "com.eveningoutpost.dexdrip.BgEstimate" + const val EXTRA_BG_ESTIMATE = "com.eveningoutpost.dexdrip.Extras.BgEstimate" + const val EXTRA_BG_SLOPE = "com.eveningoutpost.dexdrip.Extras.BgSlope" + const val EXTRA_BG_SLOPE_NAME = "com.eveningoutpost.dexdrip.Extras.BgSlopeName" + const val EXTRA_SENSOR_BATTERY = "com.eveningoutpost.dexdrip.Extras.SensorBattery" + const val EXTRA_TIMESTAMP = "com.eveningoutpost.dexdrip.Extras.Time" + const val EXTRA_RAW = "com.eveningoutpost.dexdrip.Extras.Raw" + const val XDRIP_DATA_SOURCE_DESCRIPTION = "com.eveningoutpost.dexdrip.Extras.SourceDesc" + const val ACTION_NEW_BG_ESTIMATE_NO_DATA = "com.eveningoutpost.dexdrip.BgEstimateNoData" + const val NS_EMULATOR = "com.eveningoutpost.dexdrip.NS_EMULATOR" + const val ACTION_REMOTE_CALIBRATION = "com.eveningoutpost.dexdrip.NewCalibration" + const val GLIMP_BG = "it.ct.glicemia.ACTION_GLUCOSE_MEASURED" + const val DEXCOM_BG = "com.dexcom.cgm.EXTERNAL_BROADCAST" + const val EVERSENSE_BG = "com.senseonics.AndroidAPSEventSubscriber.BROADCAST" + const val POCTECH_BG = "com.china.poctech.data" + const val TOMATO_BG = "com.fanqies.tomatofn.BgEstimate" + + // Broadcast status + const val AAPS_BROADCAST = "info.nightscout.androidaps.status" + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt index 55ed268dfe..5e1dbb7cb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt @@ -27,6 +27,7 @@ import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange +import info.nightscout.androidaps.plugins.pump.omnipod.dash.OmnipodDashPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.setupwizard.elements.* import info.nightscout.androidaps.setupwizard.events.EventSWUpdate @@ -188,6 +189,13 @@ class SWDefinition @Inject constructor( .add(SWEditString(injector) .validator(SWTextValidator(String::isNotEmpty)) .preferenceId(R.string.key_patient_name)) + private val privacy = SWScreen(injector, R.string.privacy_settings) + .skippable(true) + .add(SWInfoText(injector) + .label(R.string.privacy_summary)) + .add(SWPreference(injector, this) + .option(R.xml.pref_datachoices) + ) private val screenMasterPassword = SWScreen(injector, R.string.master_password) .skippable(false) .add(SWInfoText(injector) @@ -277,14 +285,14 @@ class SWDefinition @Inject constructor( .add(SWInfoText(injector) .label(R.string.setupwizard_pump_pump_not_initialized) .visibility { !isPumpInitialized() }) - .add( // Omnipod only + .add( // Omnipod Eros only SWInfoText(injector) .label(R.string.setupwizard_pump_waiting_for_riley_link_connection) .visibility { val activePump = activePlugin.activePump activePump is OmnipodErosPumpPlugin && !activePump.isRileyLinkReady }) - .add( // Omnipod only + .add( // Omnipod Eros only SWEventListener(injector, EventRileyLinkDeviceStatusChange::class.java) .label(R.string.setupwizard_pump_riley_link_status) .visibility { activePlugin.activePump is OmnipodErosPumpPlugin }) @@ -294,18 +302,21 @@ class SWDefinition @Inject constructor( .visibility { // Hide for Omnipod, because as we don't require a Pod to be paired in the setup wizard, // Getting the status might not be possible - activePlugin.activePump !is OmnipodErosPumpPlugin + activePlugin.activePump !is OmnipodErosPumpPlugin && activePlugin.activePump !is OmnipodDashPumpPlugin }) .add(SWEventListener(injector, EventPumpStatusChanged::class.java) - .visibility { activePlugin.activePump !is OmnipodErosPumpPlugin }) + .visibility { activePlugin.activePump !is OmnipodErosPumpPlugin && activePlugin.activePump !is OmnipodDashPumpPlugin }) .validator { isPumpInitialized() } private fun isPumpInitialized(): Boolean { val activePump = activePlugin.activePump - // For Omnipod, consider the pump initialized when a RL has been configured successfully - // Users will be prompted to activate a Pod after completing the setup wizard. - return activePump.isInitialized() || (activePump is OmnipodErosPumpPlugin && activePump.isRileyLinkReady) + // For Omnipod, activating a Pod can be done after setup through the Omnipod fragment + // For the Eros model, consider the pump initialized when a RL has been configured successfully + // For Dash model, consider the pump setup without any extra conditions + return activePump.isInitialized() + || (activePump is OmnipodErosPumpPlugin && activePump.isRileyLinkReady) + || activePump is OmnipodDashPumpPlugin } private val screenAps = SWScreen(injector, R.string.configbuilder_aps) @@ -370,6 +381,7 @@ class SWDefinition @Inject constructor( .add(screenPermissionStore) .add(screenMasterPassword) .add(screenImport) + .add(privacy) .add(screenUnits) .add(displaySettings) .add(screenNsClient) diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWNumberValidator.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWNumberValidator.java index a71da1dea7..fe22e4ccd8 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWNumberValidator.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWNumberValidator.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.setupwizard; +// keep in java, it's easier public interface SWNumberValidator { boolean isValid(double value); } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWTextValidator.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWTextValidator.java index 427afbd45d..607d3a6298 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWTextValidator.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWTextValidator.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.setupwizard; +// keep in java, it's easier public interface SWTextValidator { boolean isValid(String text); } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWValidator.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWValidator.java index 3cc8d6b0c1..e7a604deef 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWValidator.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWValidator.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.setupwizard; +// keep in java, it's easier public interface SWValidator { boolean isValid(); } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt index c6cc3f9620..2a25c2ea91 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt @@ -31,8 +31,9 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { injector.androidInjector().inject(this) } + @Suppress("unused") enum class Type { - NONE, TEXT, HTML_LINK, BREAK, LISTENER, URL, STRING, NUMBER, DECIMAL_NUMBER, RADIOBUTTON, PLUGIN, BUTTON, FRAGMENT, UNIT_NUMBER + NONE, TEXT, HTML_LINK, BREAK, LISTENER, URL, STRING, NUMBER, DECIMAL_NUMBER, RADIOBUTTON, PLUGIN, BUTTON, FRAGMENT, UNIT_NUMBER, PREFERENCE } var label: Int? = null diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.kt index 76c140d708..95401bdfab 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.setupwizard.SWDefinition import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import javax.inject.Inject -class SWPlugin(injector: HasAndroidInjector, val definition: SWDefinition) : SWItem(injector, Type.PLUGIN) { +class SWPlugin(injector: HasAndroidInjector, private val definition: SWDefinition) : SWItem(injector, Type.PLUGIN) { @Inject lateinit var pluginStore: PluginStore @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPreference.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPreference.kt new file mode 100644 index 0000000000..7abafa7c82 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPreference.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.setupwizard.elements + +import android.os.Bundle +import android.widget.LinearLayout +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.activities.MyPreferenceFragment +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.PluginStore +import info.nightscout.androidaps.setupwizard.SWDefinition +import javax.inject.Inject + +class SWPreference(injector: HasAndroidInjector, private val definition: SWDefinition) : SWItem(injector, Type.PREFERENCE) { + + @Inject lateinit var pluginStore: PluginStore + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + + private var xml: Int = -1 + + fun option(xml: Int): SWPreference { + this.xml = xml + return this + } + + override fun generateDialog(layout: LinearLayout) { + addConfiguration(layout, xml) + super.generateDialog(layout) + } + + private fun addConfiguration(layout: LinearLayout, xml: Int) { + MyPreferenceFragment().also { fragment -> + fragment.arguments = Bundle().also { it.putInt("id", xml) } + definition.activity.supportFragmentManager.beginTransaction().run { + replace(layout.id, fragment) + commit() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java deleted file mode 100644 index 0bfa1cbd0d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java +++ /dev/null @@ -1,248 +0,0 @@ -package info.nightscout.androidaps.utils; -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import android.os.SystemClock; - -import org.slf4j.Logger; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; - -/** - * {@hide} - *

- * Simple SNTP client class for retrieving network time. - *

- * Sample usage: - *

SntpClient client = new SntpClient();
- * if (client.requestTime("time.foo.com")) {
- *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
- * }
- * 
- */ -@Singleton -public class SntpClient { - private final AAPSLogger aapsLogger; - private final DateUtil dateUtil; - - //private final int REFERENCE_TIME_OFFSET = 16; - private final int ORIGINATE_TIME_OFFSET = 24; - private final int RECEIVE_TIME_OFFSET = 32; - private final int TRANSMIT_TIME_OFFSET = 40; - private final int NTP_PACKET_SIZE = 48; - - private final int NTP_PORT = 123; - private final int NTP_MODE_CLIENT = 3; - private final int NTP_VERSION = 3; - - @Inject - public SntpClient( - AAPSLogger aapsLogger, - DateUtil dateUtil - ) { - this.aapsLogger = aapsLogger; - this.dateUtil = dateUtil; - } - - // Number of seconds between Jan 1, 1900 and Jan 1, 1970 - // 70 years plus 17 leap days - private final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; - - // system time computed from NTP server response - private long mNtpTime; - - // value of SystemClock.elapsedRealtime() corresponding to mNtpTime - private long mNtpTimeReference; - - // round trip time in milliseconds - private long mRoundTripTime; - - public static abstract class Callback implements Runnable { - public boolean networkConnected = false; - public boolean success = false; - public long time = 0; - } - - public synchronized void ntpTime(final Callback callback, boolean isConnected) { - callback.networkConnected = isConnected; - if (callback.networkConnected) { - new Thread(() -> doNtpTime(callback)).start(); - } else { - callback.run(); - } - } - - void doNtpTime(final Callback callback) { - aapsLogger.debug("Time detection started"); - callback.success = requestTime("time.google.com", 5000); - callback.time = getNtpTime() + SystemClock.elapsedRealtime() - getNtpTimeReference(); - aapsLogger.debug("Time detection ended: " + callback.success + " " + dateUtil.dateAndTimeString(getNtpTime())); - callback.run(); - } - - /** - * Sends an SNTP request to the given host and processes the response. - * - * @param host host name of the server. - * @param timeout network timeout in milliseconds. - * @return true if the transaction was successful. - */ - private synchronized boolean requestTime(String host, int timeout) { - try { - DatagramSocket socket = new DatagramSocket(); - socket.setSoTimeout(timeout); - InetAddress address = InetAddress.getByName(host); - byte[] buffer = new byte[NTP_PACKET_SIZE]; - DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT); - - // set mode = 3 (client) and version = 3 - // mode is in low 3 bits of first byte - // version is in bits 3-5 of first byte - buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3); - - // get current time and write it to the request packet - long requestTime = System.currentTimeMillis(); - long requestTicks = SystemClock.elapsedRealtime(); - writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime); - - socket.send(request); - - // read the response - DatagramPacket response = new DatagramPacket(buffer, buffer.length); - socket.receive(response); - long responseTicks = SystemClock.elapsedRealtime(); - long responseTime = requestTime + (responseTicks - requestTicks); - socket.close(); - - // extract the results - long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET); - long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET); - long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET); - long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime); - // receiveTime = originateTime + transit + skew - // responseTime = transmitTime + transit - skew - // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2 - // = ((originateTime + transit + skew - originateTime) + - // (transmitTime - (transmitTime + transit - skew)))/2 - // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2 - // = (transit + skew - transit + skew)/2 - // = (2 * skew)/2 = skew - long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2; - // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms"); - // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms"); - - // save our results - use the times on this side of the network latency - // (response rather than request time) - mNtpTime = responseTime + clockOffset; - mNtpTimeReference = responseTicks; - mRoundTripTime = roundTripTime; - } catch (Exception e) { - aapsLogger.debug("request time failed: " + e); - return false; - } - - return true; - } - - /** - * Returns the time computed from the NTP transaction. - * - * @return time value computed from NTP server response. - */ - private long getNtpTime() { - return mNtpTime; - } - - /** - * Returns the reference clock value (value of SystemClock.elapsedRealtime()) - * corresponding to the NTP time. - * - * @return reference clock corresponding to the NTP time. - */ - private long getNtpTimeReference() { - return mNtpTimeReference; - } - - /** - * Returns the round trip time of the NTP transaction - * - * @return round trip time in milliseconds. - */ - public long getRoundTripTime() { - return mRoundTripTime; - } - - /** - * Reads an unsigned 32 bit big endian number from the given offset in the buffer. - */ - private long read32(byte[] buffer, int offset) { - byte b0 = buffer[offset]; - byte b1 = buffer[offset + 1]; - byte b2 = buffer[offset + 2]; - byte b3 = buffer[offset + 3]; - - // convert signed bytes to unsigned values - int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0); - int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1); - int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2); - int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3); - - return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3; - } - - /** - * Reads the NTP time stamp at the given offset in the buffer and returns - * it as a system time (milliseconds since January 1, 1970). - */ - private long readTimeStamp(byte[] buffer, int offset) { - long seconds = read32(buffer, offset); - long fraction = read32(buffer, offset + 4); - return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); - } - - /** - * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp - * at the given offset in the buffer. - */ - private void writeTimeStamp(byte[] buffer, int offset, long time) { - long seconds = time / 1000L; - long milliseconds = time - seconds * 1000L; - seconds += OFFSET_1900_TO_1970; - - // write seconds in big endian format - buffer[offset++] = (byte) (seconds >> 24); - buffer[offset++] = (byte) (seconds >> 16); - buffer[offset++] = (byte) (seconds >> 8); - buffer[offset++] = (byte) (seconds >> 0); - - long fraction = milliseconds * 0x100000000L / 1000L; - // write fraction in big endian format - buffer[offset++] = (byte) (fraction >> 24); - buffer[offset++] = (byte) (fraction >> 16); - buffer[offset++] = (byte) (fraction >> 8); - // low order bits should be random data - buffer[offset++] = (byte) (Math.random() * 255.0); - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.kt b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.kt new file mode 100644 index 0000000000..3465bb8edd --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.kt @@ -0,0 +1,214 @@ +package info.nightscout.androidaps.utils + +import android.os.SystemClock +import javax.inject.Singleton +import javax.inject.Inject +import info.nightscout.androidaps.logging.AAPSLogger +import java.lang.Exception +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress + +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** + * {@hide} + * + * + * Simple SNTP client class for retrieving network time. + * + * + * Sample usage: + *
SntpClient client = new SntpClient();
+ * if (client.requestTime("time.foo.com")) {
+ * long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
+ * }
+
* + */ +@Singleton +class SntpClient @Inject constructor( + private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil +) { + + companion object { + //private final int REFERENCE_TIME_OFFSET = 16; + private const val ORIGINATE_TIME_OFFSET = 24 + private const val RECEIVE_TIME_OFFSET = 32 + private const val TRANSMIT_TIME_OFFSET = 40 + private const val NTP_PACKET_SIZE = 48 + private const val NTP_PORT = 123 + private const val NTP_MODE_CLIENT = 3 + private const val NTP_VERSION = 3 + + // Number of seconds between Jan 1, 1900 and Jan 1, 1970 + // 70 years plus 17 leap days + private const val OFFSET_1900_TO_1970 = (365L * 70L + 17L) * 24L * 60L * 60L + } + + /** + * Returns the time computed from the NTP transaction. + * + * @return time value computed from NTP server response. + */ + // system time computed from NTP server response + private var ntpTime: Long = 0 + + /** + * Returns the reference clock value (value of SystemClock.elapsedRealtime()) + * corresponding to the NTP time. + * + * @return reference clock corresponding to the NTP time. + */ + // value of SystemClock.elapsedRealtime() corresponding to mNtpTime + private var ntpTimeReference: Long = 0 + + /** + * Returns the round trip time of the NTP transaction + * + * @return round trip time in milliseconds. + */ + // round trip time in milliseconds + private var roundTripTime: Long = 0 + + abstract class Callback : Runnable { + + var networkConnected = false + var success = false + var time: Long = 0 + } + + @Synchronized fun ntpTime(callback: Callback, isConnected: Boolean) { + callback.networkConnected = isConnected + if (callback.networkConnected) { + Thread { doNtpTime(callback) }.start() + } else { + callback.run() + } + } + + fun doNtpTime(callback: Callback) { + aapsLogger.debug("Time detection started") + callback.success = requestTime("time.google.com", 5000) + callback.time = ntpTime + SystemClock.elapsedRealtime() - ntpTimeReference + aapsLogger.debug("Time detection ended: " + callback.success + " " + dateUtil.dateAndTimeString(ntpTime)) + callback.run() + } + + /** + * Sends an SNTP request to the given host and processes the response. + * + * @param host host name of the server. + * @param timeout network timeout in milliseconds. + * @return true if the transaction was successful. + */ + @Suppress("SameParameterValue") + @Synchronized private fun requestTime(host: String, timeout: Int): Boolean { + try { + val socket = DatagramSocket() + socket.soTimeout = timeout + val address = InetAddress.getByName(host) + val buffer = ByteArray(NTP_PACKET_SIZE) + val request = DatagramPacket(buffer, buffer.size, address, NTP_PORT) + + // set mode = 3 (client) and version = 3 + // mode is in low 3 bits of first byte + // version is in bits 3-5 of first byte + buffer[0] = (NTP_MODE_CLIENT or (NTP_VERSION shl 3)).toByte() + + // get current time and write it to the request packet + val requestTime = System.currentTimeMillis() + val requestTicks = SystemClock.elapsedRealtime() + writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime) + socket.send(request) + + // read the response + val response = DatagramPacket(buffer, buffer.size) + socket.receive(response) + val responseTicks = SystemClock.elapsedRealtime() + val responseTime = requestTime + (responseTicks - requestTicks) + socket.close() + + // extract the results + val originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET) + val receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET) + val transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET) + val roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime) + val clockOffset = (receiveTime - originateTime + (transmitTime - responseTime)) / 2 + + // save our results - use the times on this side of the network latency + // (response rather than request time) + ntpTime = responseTime + clockOffset + ntpTimeReference = responseTicks + this.roundTripTime = roundTripTime + } catch (e: Exception) { + aapsLogger.debug("request time failed: $e") + return false + } + return true + } + + /** + * Reads an unsigned 32 bit big endian number from the given offset in the buffer. + */ + private fun read32(buffer: ByteArray, offset: Int): Long { + val b0 = buffer[offset] + val b1 = buffer[offset + 1] + val b2 = buffer[offset + 2] + val b3 = buffer[offset + 3] + + // convert signed bytes to unsigned values + val i0 = if (b0.toInt() and 0x80 == 0x80) (b0.toInt() and 0x7F) + 0x80 else b0.toInt() + val i1 = if (b1.toInt() and 0x80 == 0x80) (b1.toInt() and 0x7F) + 0x80 else b1.toInt() + val i2 = if (b2.toInt() and 0x80 == 0x80) (b2.toInt() and 0x7F) + 0x80 else b2.toInt() + val i3 = if (b3.toInt() and 0x80 == 0x80) (b3.toInt() and 0x7F) + 0x80 else b3.toInt() + return (i0.toLong() shl 24) + (i1.toLong() shl 16) + (i2.toLong() shl 8) + i3.toLong() + } + + /** + * Reads the NTP time stamp at the given offset in the buffer and returns + * it as a system time (milliseconds since January 1, 1970). + */ + private fun readTimeStamp(buffer: ByteArray, offset: Int): Long { + val seconds = read32(buffer, offset) + val fraction = read32(buffer, offset + 4) + return (seconds - OFFSET_1900_TO_1970) * 1000 + fraction * 1000L / 0x100000000L + } + + /** + * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp + * at the given offset in the buffer. + */ + @Suppress("SameParameterValue") + private fun writeTimeStamp(buffer: ByteArray, offsetParam: Int, time: Long) { + var offset = offsetParam + var seconds = time / 1000L + val milliseconds = time - seconds * 1000L + seconds += OFFSET_1900_TO_1970 + + // write seconds in big endian format + buffer[offset++] = (seconds shr 24).toByte() + buffer[offset++] = (seconds shr 16).toByte() + buffer[offset++] = (seconds shr 8).toByte() + buffer[offset++] = (seconds shr 0).toByte() + val fraction = milliseconds * 0x100000000L / 1000L + // write fraction in big endian format + buffer[offset++] = (fraction shr 24).toByte() + buffer[offset++] = (fraction shr 16).toByte() + buffer[offset++] = (fraction shr 8).toByte() + // low order bits should be random data + buffer[offset] = (Math.random() * 255.0).toInt().toByte() + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java b/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java index fd72be7b93..af6fd3e742 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java @@ -266,7 +266,7 @@ public class TimeListEdit { } - class SpinnerAdapter extends ArrayAdapter { + static class SpinnerAdapter extends ArrayAdapter { List values; SpinnerAdapter(@NonNull Context context, int resource, final @NonNull List objects, final @NonNull List values) { @@ -371,6 +371,7 @@ public class TimeListEdit { } + @SuppressWarnings("SameParameterValue") private void addItem(int index, int timeAsSeconds, double value1, double value2) { if (itemsCount() >= 24) return; if (itemsCount() > inflatedUntil) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt index 77df9dbc69..72dbb6430f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt @@ -2,11 +2,15 @@ package info.nightscout.androidaps.utils.androidNotification import android.app.Notification import android.app.NotificationManager +import android.app.PendingIntent import android.content.Context +import android.content.Intent import androidx.core.app.NotificationCompat -import info.nightscout.androidaps.R +import androidx.core.app.TaskStackBuilder +import info.nightscout.androidaps.MainActivity +import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.interfaces.IconsProviderInterface import info.nightscout.androidaps.interfaces.NotificationHolderInterface -import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @@ -15,7 +19,7 @@ import javax.inject.Singleton class NotificationHolder @Inject constructor( resourceHelper: ResourceHelper, context: Context, - iconsProvider: IconsProvider + iconsProvider: IconsProviderInterface ) : NotificationHolderInterface { override val channelID = "AndroidAPS-Ongoing" @@ -32,4 +36,10 @@ class NotificationHolder @Inject constructor( .also { (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(notificationID, it) } + + override fun openAppIntent(context: Context): PendingIntent? = TaskStackBuilder.create(context).run { + addParentStack(MainActivity::class.java) + addNextIntent(Intent(context, MainActivity::class.java)) + getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) + } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationUtils.kt deleted file mode 100644 index 26787bd135..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationUtils.kt +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.utils.androidNotification - -import android.app.PendingIntent -import android.content.Context -import android.content.Intent -import androidx.core.app.TaskStackBuilder -import info.nightscout.androidaps.MainActivity - -fun openAppIntent(context: Context): PendingIntent? = TaskStackBuilder.create(context).run { - addParentStack(MainActivity::class.java) - addNextIntent(Intent(context, MainActivity::class.java)) - getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt index 6bdeaa73a8..beab1f4330 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt @@ -1,21 +1,22 @@ package info.nightscout.androidaps.utils.resources -import info.nightscout.androidaps.Config import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.ConfigInterface +import info.nightscout.androidaps.interfaces.IconsProviderInterface import javax.inject.Inject import javax.inject.Singleton @Singleton -class IconsProvider @Inject constructor(private val config: Config) { +class IconsProvider @Inject constructor(private val config: ConfigInterface) : IconsProviderInterface { - fun getIcon(): Int = + override fun getIcon(): Int = when { config.NSCLIENT -> R.mipmap.ic_yellowowl config.PUMPCONTROL -> R.mipmap.ic_pumpcontrol else -> R.mipmap.ic_launcher } - fun getNotificationIcon(): Int = + override fun getNotificationIcon(): Int = when { config.NSCLIENT -> R.drawable.ic_notif_nsclient config.PUMPCONTROL -> R.drawable.ic_notif_pumpcontrol diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index 39da06c1f5..4cc4047dbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -83,7 +83,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec var cob = 0.0 if (useCOB() == YES) { val cobInfo = iobCobCalculatorPlugin.getCobInfo(_synchronized, "QuickWizard COB") - if (cobInfo.displayCob != null) cob = cobInfo.displayCob + if (cobInfo.displayCob != null) cob = cobInfo.displayCob!! } // Bolus IOB var bolusIOB = false diff --git a/app/src/main/res/layout/bgsource_item.xml b/app/src/main/res/layout/bgsource_item.xml index 757afdffe4..060997d7d8 100644 --- a/app/src/main/res/layout/bgsource_item.xml +++ b/app/src/main/res/layout/bgsource_item.xml @@ -65,7 +65,7 @@ android:layout_height="wrap_content" android:paddingEnd="5dp" android:paddingStart="10dp" - android:text="@string/overview_quickwizard_item_remove_button" + android:text="@string/remove_button" android:textAlignment="viewEnd" android:textColor="@android:color/holo_orange_light" /> diff --git a/app/src/main/res/layout/dialog_wizard.xml b/app/src/main/res/layout/dialog_wizard.xml index 4e5353fc63..ce32053308 100644 --- a/app/src/main/res/layout/dialog_wizard.xml +++ b/app/src/main/res/layout/dialog_wizard.xml @@ -279,7 +279,7 @@ android:layout_gravity="center_horizontal" android:labelFor="@+id/notes" android:padding="10dp" - android:text="@string/careportal_newnstreatment_notes_label" + android:text="@string/notes_label" android:textAppearance="@style/TextAppearance.AppCompat.Small" android:textStyle="bold" /> @@ -289,7 +289,7 @@ android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" - android:autofillHints="@string/careportal_newnstreatment_notes_label" + android:autofillHints="@string/notes_label" android:gravity="start" android:inputType="text|textCapSentences" android:textAppearance="?android:attr/textAppearanceSmall" /> diff --git a/app/src/main/res/layout/dialog_wizardinfo.xml b/app/src/main/res/layout/dialog_wizardinfo.xml index 322dbfb8fd..b32e489b94 100644 --- a/app/src/main/res/layout/dialog_wizardinfo.xml +++ b/app/src/main/res/layout/dialog_wizardinfo.xml @@ -391,7 +391,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="86dp" - android:text="@string/careportal_newnstreatment_notes_label" + android:text="@string/notes_label" android:textAppearance="?android:attr/textAppearanceSmall" /> diff --git a/app/src/main/res/layout/overview_notification_item.xml b/app/src/main/res/layout/overview_notification_item.xml index 03b5688fc3..f8f1974d33 100644 --- a/app/src/main/res/layout/overview_notification_item.xml +++ b/app/src/main/res/layout/overview_notification_item.xml @@ -1,7 +1,8 @@ + android:text="Notification text. Notification text. Notification text. Notification text. Notification text. Notification text. " + tools:ignore="HardcodedText" />