From 04f074caf92a3b284083f0d62072ee11f1055efd Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 4 Mar 2021 19:23:01 +0100 Subject: [PATCH] MainApp -> kt, the rest of DatabaseHelperInterface --- .../info/nightscout/androidaps/MainApp.java | 180 ------------------ .../info/nightscout/androidaps/MainApp.kt | 145 ++++++++++++++ .../androidaps/db/DatabaseHelper.java | 6 +- .../androidaps/db/DatabaseHelperProvider.java | 174 ++++++++++++----- .../nightscout/androidaps/db/OHQueueItem.kt | 12 -- .../plugins/general/nsclient/UploadQueue.java | 2 +- .../nsclient/services/NSClientService.java | 2 +- .../general/openhumans/OpenHumansFragment.kt | 13 +- .../general/openhumans/OpenHumansUploader.kt | 31 +-- .../general/overview/StatusLightHandler.kt | 7 +- .../general/overview/graphData/GraphData.kt | 5 +- .../general/tidepool/comm/UploadChunk.kt | 7 +- .../general/wear/ActionStringHandler.kt | 27 ++- .../sensitivity/SensitivityAAPSPlugin.kt | 9 +- .../sensitivity/SensitivityOref1Plugin.kt | 9 +- .../SensitivityWeightedAveragePlugin.kt | 9 +- .../plugins/source/EversensePlugin.kt | 7 +- .../fragments/TreatmentsCareportalFragment.kt | 15 +- .../TreatmentsExtendedBolusesFragment.kt | 13 +- .../TreatmentsProfileSwitchFragment.kt | 11 +- .../nightscout/androidaps/db/OHQueueItem.kt | 14 ++ .../interfaces/DatabaseHelperInterface.kt | 25 ++- 22 files changed, 402 insertions(+), 321 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/MainApp.java create mode 100644 app/src/main/java/info/nightscout/androidaps/MainApp.kt create mode 100644 core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java deleted file mode 100644 index 56c8b99a0a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ /dev/null @@ -1,180 +0,0 @@ -package info.nightscout.androidaps; - -import android.bluetooth.BluetoothDevice; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.ConnectivityManager; -import android.net.wifi.WifiManager; - -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import com.j256.ormlite.android.apptools.OpenHelperManager; - -import net.danlew.android.joda.JodaTimeAndroid; - -import java.util.List; - -import javax.inject.Inject; - -import dagger.android.AndroidInjector; -import dagger.android.DaggerApplication; -import info.nightscout.androidaps.database.AppRepository; -import info.nightscout.androidaps.database.transactions.VersionChangeTransaction; -import info.nightscout.androidaps.db.CompatDBHelper; -import info.nightscout.androidaps.db.DatabaseHelper; -import info.nightscout.androidaps.db.StaticInjector; -import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.PluginStore; -import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.receivers.BTReceiver; -import info.nightscout.androidaps.receivers.ChargingStateReceiver; -import info.nightscout.androidaps.receivers.DataReceiver; -import info.nightscout.androidaps.receivers.KeepAliveReceiver; -import info.nightscout.androidaps.receivers.NetworkChangeReceiver; -import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; -import info.nightscout.androidaps.services.Intents; -import info.nightscout.androidaps.utils.ActivityMonitor; -import info.nightscout.androidaps.utils.locale.LocaleHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; - -public class MainApp extends DaggerApplication { - - static DatabaseHelper sDatabaseHelper = null; - - private final CompositeDisposable disposable = new CompositeDisposable(); - - @Inject PluginStore pluginStore; - @Inject AAPSLogger aapsLogger; - @Inject ActivityMonitor activityMonitor; - @Inject VersionCheckerUtils versionCheckersUtils; - @Inject SP sp; - @Inject NSUpload nsUpload; - @Inject Config config; - - @Inject ConfigBuilderPlugin configBuilderPlugin; - @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; - @Inject List plugins; - @Inject CompatDBHelper compatDBHelper; - @Inject AppRepository repository; - - @Inject StaticInjector staticInjector; // TODO avoid , here fake only to initialize - - @Override - public void onCreate() { - super.onCreate(); - - aapsLogger.debug("onCreate"); - LocaleHelper.INSTANCE.update(this); - sDatabaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class); -/* - Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { - if (ex instanceof InternalError) { - // usually the app trying to spawn a thread while being killed - return; - } - aapsLogger.error("Uncaught exception crashing app", ex); - }); -*/ - String gitRemote = BuildConfig.REMOTE; - String commitHash = BuildConfig.HEAD; - if (gitRemote.contains("NoGitSystemAvailable")) { - gitRemote = null; - commitHash = null; - } - disposable.add(repository.runTransaction(new VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe()); - disposable.add(compatDBHelper.dbChangeDisposable()); - - registerActivityLifecycleCallbacks(activityMonitor); - - JodaTimeAndroid.init(this); - - aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME); - aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION); - aapsLogger.debug("Remote: " + BuildConfig.REMOTE); - - registerLocalBroadcastReceiver(); - - //trigger here to see the new version on app start after an update - versionCheckersUtils.triggerCheckVersion(); - - // Register all tabs in app here - pluginStore.setPlugins(plugins); - configBuilderPlugin.initialize(); - - nsUpload.uploadAppStart(); - - new Thread(() -> keepAliveManager.setAlarm(this)).start(); - doMigrations(); - } - - - private void doMigrations() { - // set values for different builds - if (!sp.contains(R.string.key_ns_alarms)) - sp.putBoolean(R.string.key_ns_alarms, config.getNSCLIENT()); - if (!sp.contains(R.string.key_ns_announcements)) - sp.putBoolean(R.string.key_ns_announcements, config.getNSCLIENT()); - if (!sp.contains(R.string.key_language)) - sp.putString(R.string.key_language, "default"); - } - - @Override - protected AndroidInjector applicationInjector() { - return DaggerAppComponent - .builder() - .application(this) - .build(); - } - - private void registerLocalBroadcastReceiver() { - IntentFilter filter = new IntentFilter(); - filter.addAction(Intents.ACTION_NEW_TREATMENT); - filter.addAction(Intents.ACTION_CHANGED_TREATMENT); - filter.addAction(Intents.ACTION_REMOVED_TREATMENT); - filter.addAction(Intents.ACTION_NEW_SGV); - filter.addAction(Intents.ACTION_NEW_PROFILE); - filter.addAction(Intents.ACTION_NEW_MBG); - filter.addAction(Intents.ACTION_NEW_CAL); - LocalBroadcastManager.getInstance(this).registerReceiver(new DataReceiver(), filter); - - filter = new IntentFilter(); - filter.addAction(Intent.ACTION_TIME_CHANGED); - filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); - registerReceiver(new TimeDateOrTZChangeReceiver(), filter); - - filter = new IntentFilter(); - filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); - filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); - filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); - registerReceiver(new NetworkChangeReceiver(), filter); - - filter = new IntentFilter(); - filter.addAction(Intent.ACTION_POWER_CONNECTED); - filter.addAction(Intent.ACTION_POWER_DISCONNECTED); - filter.addAction(Intent.ACTION_BATTERY_CHANGED); - registerReceiver(new ChargingStateReceiver(), filter); - - filter = new IntentFilter(); - filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); - filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); - registerReceiver(new BTReceiver(), filter); - } - - public static DatabaseHelper getDbHelper() { - return sDatabaseHelper; - } - - @Override - public void onTerminate() { - aapsLogger.debug(LTag.CORE, "onTerminate"); - unregisterActivityLifecycleCallbacks(activityMonitor); - keepAliveManager.cancelAlarm(this); - super.onTerminate(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt new file mode 100644 index 0000000000..da263b17de --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -0,0 +1,145 @@ +package info.nightscout.androidaps + +import android.bluetooth.BluetoothDevice +import android.content.Intent +import android.content.IntentFilter +import android.net.ConnectivityManager +import android.net.wifi.WifiManager +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import com.j256.ormlite.android.apptools.OpenHelperManager +import dagger.android.AndroidInjector +import dagger.android.DaggerApplication +import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.transactions.VersionChangeTransaction +import info.nightscout.androidaps.db.CompatDBHelper +import info.nightscout.androidaps.db.DatabaseHelper +import info.nightscout.androidaps.db.StaticInjector +import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.PluginStore +import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.receivers.BTReceiver +import info.nightscout.androidaps.receivers.ChargingStateReceiver +import info.nightscout.androidaps.receivers.DataReceiver +import info.nightscout.androidaps.receivers.KeepAliveReceiver.KeepAliveManager +import info.nightscout.androidaps.receivers.NetworkChangeReceiver +import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver +import info.nightscout.androidaps.services.Intents +import info.nightscout.androidaps.utils.ActivityMonitor +import info.nightscout.androidaps.utils.locale.LocaleHelper.update +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.disposables.CompositeDisposable +import net.danlew.android.joda.JodaTimeAndroid +import javax.inject.Inject + +class MainApp : DaggerApplication() { + + private val disposable = CompositeDisposable() + + @Inject lateinit var pluginStore: PluginStore + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var activityMonitor: ActivityMonitor + @Inject lateinit var versionCheckersUtils: VersionCheckerUtils + @Inject lateinit var sp: SP + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var config: Config + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var keepAliveManager: KeepAliveManager + @Inject lateinit var plugins: List<@JvmSuppressWildcards PluginBase> + @Inject lateinit var compatDBHelper: CompatDBHelper + @Inject lateinit var repository: AppRepository + @Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize + + override fun onCreate() { + super.onCreate() + aapsLogger.debug("onCreate") + update(this) + dbHelper = OpenHelperManager.getHelper(this, DatabaseHelper::class.java) + + var gitRemote: String? = BuildConfig.REMOTE + var commitHash: String? = BuildConfig.HEAD + if (gitRemote?.contains("NoGitSystemAvailable") == true) { + gitRemote = null + commitHash = null + } + disposable.add(repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe()) + disposable.add(compatDBHelper.dbChangeDisposable()) + registerActivityLifecycleCallbacks(activityMonitor) + JodaTimeAndroid.init(this) + aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME) + aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION) + aapsLogger.debug("Remote: " + BuildConfig.REMOTE) + registerLocalBroadcastReceiver() + + //trigger here to see the new version on app start after an update + versionCheckersUtils.triggerCheckVersion() + + // Register all tabs in app here + pluginStore.plugins = plugins + configBuilderPlugin.initialize() + nsUpload.uploadAppStart() + Thread { keepAliveManager.setAlarm(this) }.start() + doMigrations() + } + + private fun doMigrations() { + // set values for different builds + if (!sp.contains(R.string.key_ns_alarms)) sp.putBoolean(R.string.key_ns_alarms, config.NSCLIENT) + if (!sp.contains(R.string.key_ns_announcements)) sp.putBoolean(R.string.key_ns_announcements, config.NSCLIENT) + if (!sp.contains(R.string.key_language)) sp.putString(R.string.key_language, "default") + } + + override fun applicationInjector(): AndroidInjector { + return DaggerAppComponent + .builder() + .application(this) + .build() + } + + private fun registerLocalBroadcastReceiver() { + var filter = IntentFilter() + filter.addAction(Intents.ACTION_NEW_TREATMENT) + filter.addAction(Intents.ACTION_CHANGED_TREATMENT) + filter.addAction(Intents.ACTION_REMOVED_TREATMENT) + filter.addAction(Intents.ACTION_NEW_SGV) + filter.addAction(Intents.ACTION_NEW_PROFILE) + filter.addAction(Intents.ACTION_NEW_MBG) + filter.addAction(Intents.ACTION_NEW_CAL) + LocalBroadcastManager.getInstance(this).registerReceiver(DataReceiver(), filter) + filter = IntentFilter() + filter.addAction(Intent.ACTION_TIME_CHANGED) + filter.addAction(Intent.ACTION_TIMEZONE_CHANGED) + registerReceiver(TimeDateOrTZChangeReceiver(), filter) + filter = IntentFilter() + @Suppress("DEPRECATION") + filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION) + filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) + filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) + registerReceiver(NetworkChangeReceiver(), filter) + filter = IntentFilter() + filter.addAction(Intent.ACTION_POWER_CONNECTED) + filter.addAction(Intent.ACTION_POWER_DISCONNECTED) + filter.addAction(Intent.ACTION_BATTERY_CHANGED) + registerReceiver(ChargingStateReceiver(), filter) + filter = IntentFilter() + filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) + filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) + registerReceiver(BTReceiver(), filter) + } + + override fun onTerminate() { + aapsLogger.debug(LTag.CORE, "onTerminate") + unregisterActivityLifecycleCallbacks(activityMonitor) + keepAliveManager.cancelAlarm(this) + super.onTerminate() + } + + companion object { + + lateinit var dbHelper: DatabaseHelper + } +} \ No newline at end of file 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 710764a8d5..eedafc7405 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -32,7 +32,6 @@ import java.util.concurrent.TimeUnit; import javax.inject.Inject; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.dana.comm.RecordTypes; import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.Profile; @@ -44,7 +43,6 @@ import info.nightscout.androidaps.events.EventReloadProfileSwitchData; import info.nightscout.androidaps.events.EventReloadTempBasalData; 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; @@ -56,7 +54,6 @@ 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.virtual.VirtualPumpPlugin; -import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.PercentageSplitter; /** @@ -79,7 +76,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_OPEN_HUMANS_QUEUE = "OpenHumansQueue"; private static final int DATABASE_VERSION = 13; @@ -436,7 +432,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } - public CloseableIterator getDbRequestInterator() { + public CloseableIterator getDbRequestIterator() { try { return getDaoDbRequest().closeableIterator(); } 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 a86b9acdd0..f06e8ade05 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -25,174 +25,262 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface { } @Override public void createOrUpdate(@NonNull CareportalEvent careportalEvent) { - MainApp.getDbHelper().createOrUpdate(careportalEvent); + MainApp.Companion.getDbHelper().createOrUpdate(careportalEvent); } @Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) { - MainApp.getDbHelper().createOrUpdate(record); + MainApp.Companion.getDbHelper().createOrUpdate(record); } @Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) { - MainApp.getDbHelper().createOrUpdate(record); + MainApp.Companion.getDbHelper().createOrUpdate(record); } @NonNull @Override public List getDanaRHistoryRecordsByType(byte type) { - return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); + return MainApp.Companion.getDbHelper().getDanaRHistoryRecordsByType(type); } @NonNull @Override public List getTDDs() { - return MainApp.getDbHelper().getTDDs(); + return MainApp.Companion.getDbHelper().getTDDs(); } @Override public long size(@NonNull String table) { - return MainApp.getDbHelper().size(table); + return MainApp.Companion.getDbHelper().size(table); } @Override public void create(@NonNull DbRequest record) { try { - MainApp.getDbHelper().create(record); + MainApp.Companion.getDbHelper().create(record); } catch (SQLException e) { e.printStackTrace(); } } @Override public void deleteAllDbRequests() { - MainApp.getDbHelper().deleteAllDbRequests(); + MainApp.Companion.getDbHelper().deleteAllDbRequests(); } @Override public int deleteDbRequest(@NonNull String id) { - return MainApp.getDbHelper().deleteDbRequest(id); + return MainApp.Companion.getDbHelper().deleteDbRequest(id); } @Override public void deleteDbRequestbyMongoId(@NonNull String action, @NonNull String _id) { - MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); + MainApp.Companion.getDbHelper().deleteDbRequestbyMongoId(action, _id); } - @NonNull @Override public CloseableIterator getDbRequestInterator() { - return MainApp.getDbHelper().getDbRequestInterator(); + @NonNull @Override public CloseableIterator getDbRequestIterator() { + return MainApp.Companion.getDbHelper().getDbRequestIterator(); } @Override public long roundDateToSec(long date) { - return MainApp.getDbHelper().roundDateToSec(date); + return MainApp.Companion.getDbHelper().roundDateToSec(date); } @Override public void createOrUpdateTDD(@NonNull TDD record) { - MainApp.getDbHelper().createOrUpdateTDD(record); + MainApp.Companion.getDbHelper().createOrUpdateTDD(record); } @Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) { - return MainApp.getDbHelper().createOrUpdate(tempBasal); + return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal); } @NonNull @Override public TemporaryBasal findTempBasalByPumpId(long id) { - return MainApp.getDbHelper().findTempBasalByPumpId(id); + return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id); } @NonNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { - return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); + return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); } @Override public CareportalEvent getCareportalEventFromTimestamp(long timestamp) { - return MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp); + return MainApp.Companion.getDbHelper().getCareportalEventFromTimestamp(timestamp); } @NonNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { - return MainApp.getDbHelper().getAllOmnipodHistoryRecordsFromTimeStamp(timestamp, ascending); + return MainApp.Companion.getDbHelper().getAllOmnipodHistoryRecordsFromTimeStamp(timestamp, ascending); } @Nullable @Override public OmnipodHistoryRecord findOmnipodHistoryRecordByPumpId(long pumpId) { - return MainApp.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); + return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); } @NonNull @Override public List getTDDsForLastXDays(int days) { - return MainApp.getDbHelper().getTDDsForLastXDays(days); + return MainApp.Companion.getDbHelper().getTDDsForLastXDays(days); } @NonNull @Override public List getProfileSwitchData(long from, boolean ascending) { - return MainApp.getDbHelper().getProfileSwitchData(from, ascending); + return MainApp.Companion.getDbHelper().getProfileSwitchData(from, ascending); } @Override public void createOrUpdate(@NonNull InsightBolusID record) { - MainApp.getDbHelper().createOrUpdate(record); + MainApp.Companion.getDbHelper().createOrUpdate(record); } @Override public void createOrUpdate(@NonNull InsightPumpID record) { - MainApp.getDbHelper().createOrUpdate(record); + MainApp.Companion.getDbHelper().createOrUpdate(record); } @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) { - MainApp.getDbHelper().createOrUpdate(record); + MainApp.Companion.getDbHelper().createOrUpdate(record); } @Override public void delete(@NonNull ExtendedBolus extendedBolus) { - MainApp.getDbHelper().delete(extendedBolus); + MainApp.Companion.getDbHelper().delete(extendedBolus); } @Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { - return MainApp.getDbHelper().getExtendedBolusByPumpId(pumpId); + return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId); } @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) { - return MainApp.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp); + return MainApp.Companion.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp); } @Nullable @Override public InsightHistoryOffset getInsightHistoryOffset(@NonNull String pumpSerial) { - return MainApp.getDbHelper().getInsightHistoryOffset(pumpSerial); + return MainApp.Companion.getDbHelper().getInsightHistoryOffset(pumpSerial); } @Nullable @Override public InsightPumpID getPumpStoppedEvent(@NonNull String pumpSerial, long before) { - return MainApp.getDbHelper().getPumpStoppedEvent(pumpSerial, before); + return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before); } @Override public boolean createOrUpdate(@NonNull ExtendedBolus extendedBolus) { - return MainApp.getDbHelper().createOrUpdate(extendedBolus); + return MainApp.Companion.getDbHelper().createOrUpdate(extendedBolus); } @Override public void createOrUpdate(@NonNull ProfileSwitch profileSwitch) { - MainApp.getDbHelper().createOrUpdate(profileSwitch); + MainApp.Companion.getDbHelper().createOrUpdate(profileSwitch); } @Override public void delete(@NonNull TemporaryBasal tempBasal) { - MainApp.getDbHelper().delete(tempBasal); + MainApp.Companion.getDbHelper().delete(tempBasal); } @NonNull @Override public List getExtendedBolusDataFromTime(long mills, boolean ascending) { - return MainApp.getDbHelper().getExtendedBolusDataFromTime(mills, ascending); + return MainApp.Companion.getDbHelper().getExtendedBolusDataFromTime(mills, ascending); } @Override public void deleteTempBasalById(@NonNull String _id) { - MainApp.getDbHelper().deleteTempBasalById(_id); + MainApp.Companion.getDbHelper().deleteTempBasalById(_id); } @Override public void deleteExtendedBolusById(@NonNull String _id) { - MainApp.getDbHelper().deleteExtendedBolusById(_id); + MainApp.Companion.getDbHelper().deleteExtendedBolusById(_id); } @Override public void deleteCareportalEventById(@NonNull String _id) { - MainApp.getDbHelper().deleteCareportalEventById(_id); + MainApp.Companion.getDbHelper().deleteCareportalEventById(_id); } @Override public void deleteProfileSwitchById(@NonNull String _id) { - MainApp.getDbHelper().deleteProfileSwitchById(_id); + MainApp.Companion.getDbHelper().deleteProfileSwitchById(_id); } @Override public void createTempBasalFromJsonIfNotExists(@NonNull JSONObject json) { - MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json); + MainApp.Companion.getDbHelper().createTempBasalFromJsonIfNotExists(json); } @Override public void createExtendedBolusFromJsonIfNotExists(@NonNull JSONObject json) { - MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); + MainApp.Companion.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); } @Override public void createCareportalEventFromJsonIfNotExists(@NonNull JSONObject json) { - MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json); + MainApp.Companion.getDbHelper().createCareportalEventFromJsonIfNotExists(json); } @Override public void createProfileSwitchFromJsonIfNotExists(@NonNull ActivePluginProvider activePluginProvider, @NonNull NSUpload nsUpload, @NonNull JSONObject trJson) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePluginProvider, nsUpload, trJson); + MainApp.Companion.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePluginProvider, nsUpload, trJson); } @Override public void resetDatabases() { - MainApp.getDbHelper().resetDatabases(); + MainApp.Companion.getDbHelper().resetDatabases(); + } + + @Override public void createOrUpdate(@NonNull OHQueueItem record) { + MainApp.Companion.getDbHelper().createOrUpdate(record); + } + + @Override public void delete(@NonNull CareportalEvent careportalEvent) { + MainApp.Companion.getDbHelper().delete(careportalEvent); + } + + @Override public void delete(@NonNull ProfileSwitch profileSwitch) { + MainApp.Companion.getDbHelper().delete(profileSwitch); + } + + @Nullable @Override public CareportalEvent getLastCareportalEvent(@NonNull String event) { + return MainApp.Companion.getDbHelper().getLastCareportalEvent(event); + } + + @NonNull @Override public List getCareportalEventsFromTime(long mills, boolean ascending) { + return MainApp.Companion.getDbHelper().getCareportalEventsFromTime(mills, ascending); + } + + @NonNull @Override public List getCareportalEventsFromTime(long mills, @NonNull String type, boolean ascending) { + return MainApp.Companion.getDbHelper().getCareportalEventsFromTime(mills, type, ascending); + } + + @NonNull @Override public List getCareportalEvents(long start, long end, boolean ascending) { + return MainApp.Companion.getDbHelper().getCareportalEvents(start, end, ascending); + } + + @NonNull @Override public List getCareportalEvents(boolean ascending) { + return MainApp.Companion.getDbHelper().getCareportalEvents(ascending); + } + + @NonNull @Override public List getProfileSwitchEventsFromTime(long from, long to, boolean ascending) { + return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(from, to, ascending); + } + + @NonNull @Override public List getProfileSwitchEventsFromTime(long mills, boolean ascending) { + return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending); + } + + @NonNull @Override public List getAllCareportalEvents() { + return MainApp.Companion.getDbHelper().getAllCareportalEvents(); + } + + @NonNull @Override public List getAllExtendedBoluses() { + return MainApp.Companion.getDbHelper().getAllExtendedBoluses(); + } + + @NonNull @Override public List getAllProfileSwitches() { + return MainApp.Companion.getDbHelper().getAllProfileSwitches(); + } + + @NonNull @Override public List getAllTDDs() { + return MainApp.Companion.getDbHelper().getAllTDDs(); + } + + @NonNull @Override public List getAllTemporaryBasals() { + return MainApp.Companion.getDbHelper().getAllTemporaryBasals(); + } + + @NonNull @Override public List getAllOHQueueItems(long maxEntries) { + return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries); + } + + @Override public void resetCareportalEvents() { + MainApp.Companion.getDbHelper().resetCareportalEvents(); + } + + @Override public void resetProfileSwitch() { + MainApp.Companion.getDbHelper().resetProfileSwitch(); + } + + @Override public long getOHQueueSize() { + return MainApp.Companion.getDbHelper().getOHQueueSize(); + } + + @Override public void clearOpenHumansQueue() { + MainApp.Companion.getDbHelper().clearOpenHumansQueue(); + } + + @Override public long getCountOfAllRows() { + return MainApp.Companion.getDbHelper().getCountOfAllRows(); + } + + @Override public void removeAllOHQueueItemsWithIdSmallerThan(long id) { + MainApp.Companion.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(id); } } diff --git a/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt b/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt index 1a99df9a47..600a9f0823 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt +++ b/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt @@ -1,14 +1,2 @@ package info.nightscout.androidaps.db -import com.j256.ormlite.field.DatabaseField -import com.j256.ormlite.table.DatabaseTable - -@DatabaseTable(tableName = DatabaseHelper.DATABASE_OPEN_HUMANS_QUEUE) -data class OHQueueItem @JvmOverloads constructor( - @DatabaseField(generatedId = true) - val id: Long = 0, - @DatabaseField - val file: String = "", - @DatabaseField - val content: String = "" -) \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java index 08fecd9283..7ef807d698 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java @@ -124,7 +124,7 @@ public class UploadQueue implements UploadQueueInterface { String result = ""; CloseableIterator iterator; try { - iterator = databaseHelper.getDbRequestInterator(); + iterator = databaseHelper.getDbRequestIterator(); try { while (iterator.hasNext()) { DbRequest dbr = iterator.next(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 90c461b7a8..9394b2bebb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -807,7 +807,7 @@ public class NSClientService extends DaggerService { CloseableIterator iterator; int maxcount = 30; try { - iterator = databaseHelper.getDbRequestInterator(); + iterator = databaseHelper.getDbRequestIterator(); try { while (iterator.hasNext() && maxcount > 0) { DbRequest dbr = iterator.next(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt index 07bbea6753..e6d26b1bb9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt @@ -7,21 +7,19 @@ import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView -import androidx.lifecycle.Observer -import androidx.work.WorkInfo import androidx.work.WorkManager import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.Event +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import io.reactivex.rxkotlin.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.BackpressureStrategy import io.reactivex.Single import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.plusAssign import java.util.concurrent.TimeUnit import javax.inject.Inject @@ -40,10 +38,11 @@ class OpenHumansFragment : DaggerFragment() { @Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var databaseHelper: DatabaseHelperInterface override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - compositeDisposable += Single.fromCallable { MainApp.getDbHelper().ohQueueSize } + compositeDisposable += Single.fromCallable { databaseHelper.getOHQueueSize() } .subscribeOn(aapsSchedulers.io) .repeatWhen { rxBus.toObservable(UpdateViewEvent::class.java) @@ -58,7 +57,7 @@ class OpenHumansFragment : DaggerFragment() { updateGUI() }, {}) context?.applicationContext?.let { appContext -> - WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, Observer> { + WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, { val workInfo = it.lastOrNull() if (workInfo == null) { workerState?.visibility = View.GONE @@ -84,7 +83,7 @@ class OpenHumansFragment : DaggerFragment() { workerState = view.findViewById(R.id.worker_state) login!!.setOnClickListener { startActivity(Intent(context, OpenHumansLoginActivity::class.java)) } logout!!.setOnClickListener { - activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.oh_logout_confirmation), Runnable { openHumansUploader.logout() }) } + activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.oh_logout_confirmation)) { openHumansUploader.logout() } } } viewsCreated = true updateGUI() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt index b1f4639f8a..f5e1849a7a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt @@ -14,13 +14,13 @@ import androidx.core.app.NotificationManagerCompat import androidx.work.* import dagger.android.HasAndroidInjector import info.nightscout.androidaps.BuildConfig -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.db.* import info.nightscout.androidaps.events.EventPreferenceChange +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType @@ -60,6 +60,7 @@ class OpenHumansUploader @Inject constructor( private val rxBus: RxBusWrapper, private val context: Context, private val treatmentsPlugin: TreatmentsPlugin, + private val databaseHelper: DatabaseHelperInterface, val repository: AppRepository ) : PluginBase( PluginDescription() @@ -317,7 +318,7 @@ class OpenHumansUploader @Inject constructor( file = file, content = jsonObject.toString() ) - MainApp.getDbHelper().createOrUpdate(queueItem) + databaseHelper.createOrUpdate(queueItem) rxBus.send(OpenHumansFragment.UpdateQueueEvent) } catch (e: JSONException) { e.printStackTrace() @@ -347,7 +348,7 @@ class OpenHumansUploader @Inject constructor( isSetup = false oAuthTokens = null projectMemberId = null - MainApp.getDbHelper().clearOpenHumansQueue() + databaseHelper.clearOpenHumansQueue() rxBus.send(OpenHumansFragment.UpdateViewEvent) } @@ -360,8 +361,8 @@ class OpenHumansUploader @Inject constructor( //Updating the notification for every item drastically slows down the operation if (currentProgress % 1000L == 0L) showOngoingNotification(maxProgress, currentProgress) } - copyDisposable = Completable.fromCallable { MainApp.getDbHelper().clearOpenHumansQueue() } - .andThen(Single.defer { Single.just(MainApp.getDbHelper().countOfAllRows + treatmentsPlugin.service.count()) }) + copyDisposable = Completable.fromCallable { databaseHelper.clearOpenHumansQueue() } + .andThen(Single.defer { Single.just(databaseHelper.getCountOfAllRows() + treatmentsPlugin.service.count()) }) .doOnSuccess { maxProgress = it } .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } } .map { enqueueTreatment(it); increaseCounter() } @@ -369,19 +370,19 @@ class OpenHumansUploader @Inject constructor( .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) .map { enqueueBGReading(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allCareportalEvents) }) + .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllCareportalEvents()) }) .map { enqueueCareportalEvent(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allExtendedBoluses) }) + .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) }) .map { enqueueExtendedBolus(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allProfileSwitches) }) + .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) }) .map { enqueueProfileSwitch(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allTDDs) }) + .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) }) .map { enqueueTotalDailyDose(it); increaseCounter() } .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allTemporaryBasals) }) + .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) }) .map { enqueueTemporaryBasal(it); increaseCounter() } .ignoreElements() .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) }) @@ -448,7 +449,7 @@ class OpenHumansUploader @Inject constructor( fun uploadDataSegmentally(): Completable = uploadData(UPLOAD_SEGMENT_SIZE) - .repeatUntil { MainApp.getDbHelper().ohQueueSize == 0L } + .repeatUntil { databaseHelper.getOHQueueSize() == 0L } .doOnSubscribe { aapsLogger.info(LTag.OHUPLOADER, "Starting segmental upload") } @@ -460,7 +461,7 @@ class OpenHumansUploader @Inject constructor( } @Suppress("SameParameterValue") - private fun uploadData(maxEntries: Long?): Completable = gatherData(maxEntries) + private fun uploadData(maxEntries: Long): Completable = gatherData(maxEntries) .flatMap { data -> refreshAccessTokensIfNeeded().map { accessToken -> accessToken to data } } .flatMap { uploadFile(it.first, it.second).andThen(Single.just(it.second)) } .flatMapCompletable { @@ -501,8 +502,8 @@ class OpenHumansUploader @Inject constructor( } } - private fun gatherData(maxEntries: Long?) = Single.defer { - val items = MainApp.getDbHelper().getAllOHQueueItems(maxEntries) + private fun gatherData(maxEntries: Long) = Single.defer { + val items = databaseHelper.getAllOHQueueItems(maxEntries) val baos = ByteArrayOutputStream() val zos = ZipOutputStream(baos) val tags = mutableListOf() @@ -583,7 +584,7 @@ class OpenHumansUploader @Inject constructor( } private fun removeUploadedEntriesFromQueue(highestId: Long) = Completable.fromCallable { - MainApp.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(highestId) + databaseHelper.removeAllOHQueueItemsWithIdSmallerThan(highestId) } private fun handleSignOut() { 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 c414d1c5a2..adc53f239e 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 @@ -4,10 +4,10 @@ import android.graphics.Color import android.widget.TextView import androidx.annotation.StringRes import info.nightscout.androidaps.Config -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants @@ -24,7 +24,8 @@ class StatusLightHandler @Inject constructor( private val sp: SP, private val activePlugin: ActivePluginProvider, private val warnColors: WarnColors, - private val config: Config + private val config: Config, + private val databaseHelper: DatabaseHelperInterface ) { /** @@ -69,7 +70,7 @@ class StatusLightHandler @Inject constructor( private fun handleAge(view: TextView?, eventName: String, @StringRes warnSettings: Int, defaultWarnThreshold: Double, @StringRes urgentSettings: Int, defaultUrgentThreshold: Double) { val warn = sp.getDouble(warnSettings, defaultWarnThreshold) val urgent = sp.getDouble(urgentSettings, defaultUrgentThreshold) - val careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(eventName) + val careportalEvent = databaseHelper.getLastCareportalEvent(eventName) if (careportalEvent != null) { warnColors.setColorByAge(view, careportalEvent, warn, urgent) view?.text = careportalEvent.age(resourceHelper.shortTextMode(), resourceHelper) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index f5c307598c..cd1e073b4c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -10,7 +10,6 @@ import com.jjoe64.graphview.series.LineGraphSeries import com.jjoe64.graphview.series.Series import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.GlucoseValueDataPoint import info.nightscout.androidaps.data.IobTotal @@ -19,6 +18,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.LoopInterface import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.TreatmentsInterface @@ -51,6 +51,7 @@ class GraphData( @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil @@ -267,7 +268,7 @@ class GraphData( } // Careportal - MainApp.getDbHelper().getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true) + databaseHelper.getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true) .filterTimeframe(fromTime, endTime) .forEach { it.y = getNearestBg(it.x.toLong()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index 9a8c09e4dd..0635368526 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -1,13 +1,13 @@ package info.nightscout.androidaps.plugins.general.tidepool.comm import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -33,6 +33,7 @@ class UploadChunk @Inject constructor( private val profileFunction: ProfileFunction, private val treatmentsPlugin: TreatmentsPlugin, private val activePlugin: ActivePluginProvider, + private val databaseHelper: DatabaseHelperInterface, private val repository: AppRepository, private val dateUtil: DateUtil ) { @@ -127,7 +128,7 @@ class UploadChunk @Inject constructor( } private fun getBloodTests(start: Long, end: Long): List { - val readings = MainApp.getDbHelper().getCareportalEvents(start, end, true) + val readings = databaseHelper.getCareportalEvents(start, end, true) val selection = BloodGlucoseElement.fromCareportalEvents(readings) if (selection.isNotEmpty()) rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload")) @@ -169,7 +170,7 @@ class UploadChunk @Inject constructor( } private fun getProfiles(start: Long, end: Long): List { - val pss = MainApp.getDbHelper().getProfileSwitchEventsFromTime(start, end, true) + val pss = databaseHelper.getProfileSwitchEventsFromTime(start, end, true) val selection = LinkedList() for (ps in pss) { newInstanceOrNull(ps)?.let { selection.add(it) } 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 fa178dc8e8..bf4eabe017 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 @@ -5,7 +5,6 @@ import android.content.Context import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin @@ -23,13 +22,8 @@ import info.nightscout.androidaps.database.transactions.InsertTemporaryTargetAnd import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TDD -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.Constraint -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker @@ -55,6 +49,8 @@ import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.abs +import kotlin.math.min @Singleton class ActionStringHandler @Inject constructor( @@ -83,6 +79,7 @@ class ActionStringHandler @Inject constructor( private val carbsGenerator: CarbsGenerator, private val dateUtil: DateUtil, private val config: Config, + private val databaseHelper: DatabaseHelperInterface, private val repository: AppRepository, private val nsUpload: NSUpload ) { @@ -222,12 +219,12 @@ class ActionStringHandler @Inject constructor( val format = DecimalFormat("0.00") val formatInt = DecimalFormat("0") val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() - val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null + val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, tempTarget, 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) { + if (abs(bolusWizard.insulinAfterConstraints - bolusWizard.calculatedTotalInsulin) >= 0.01) { sendError("Insulin constraint violation!" + "\nCannot deliver " + format.format(bolusWizard.calculatedTotalInsulin) + "!") return @@ -365,7 +362,7 @@ class ActionStringHandler @Inject constructor( var weighted03 = 0.0 var weighted05 = 0.0 var weighted07 = 0.0 - Collections.reverse(historyList) + historyList.reverse() for (record in historyList) { val tdd = record.getTotal() if (i == 0) { @@ -384,7 +381,7 @@ class ActionStringHandler @Inject constructor( message += "0.5: " + DecimalFormatter.to2Decimal(weighted05) + "U " + (DecimalFormatter.to0Decimal(100 * weighted05 / refTDD) + "%") + "\n" message += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (DecimalFormatter.to0Decimal(100 * weighted07 / refTDD) + "%") + "\n" message += "\n" - Collections.reverse(historyList) + historyList.reverse() //add TDDs: for (record in historyList) { val tdd = record.getTotal() @@ -401,15 +398,15 @@ class ActionStringHandler @Inject constructor( } private fun getTDDList(returnDummies: MutableList): MutableList { - var historyList = MainApp.getDbHelper().tdDs - historyList = historyList.subList(0, Math.min(10, historyList.size)) + var historyList = databaseHelper.getTDDs().toMutableList() + historyList = historyList.subList(0, min(10, historyList.size)) //fill single gaps - only needed for Dana*R data val dummies: MutableList = returnDummies val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) for (i in 0 until historyList.size - 1) { val elem1 = historyList[i] val elem2 = historyList[i + 1] - if (df.format(Date(elem1!!.date)) != df.format(Date(elem2!!.date + 25 * 60 * 60 * 1000))) { + if (df.format(Date(elem1.date)) != df.format(Date(elem2.date + 25 * 60 * 60 * 1000))) { val dummy = TDD() dummy.date = elem1.date - 24 * 60 * 60 * 1000 dummy.basal = elem1.basal / 2 @@ -420,7 +417,7 @@ class ActionStringHandler @Inject constructor( } } historyList.addAll(dummies) - Collections.sort(historyList) { lhs, rhs -> (rhs.date - lhs.date).toInt() } + historyList.sortWith { lhs, rhs -> (rhs.date - lhs.date).toInt() } return historyList } 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 index 4c53d95ab7..727b7727d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -2,11 +2,11 @@ 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.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType @@ -33,7 +33,8 @@ open class SensitivityAAPSPlugin @Inject constructor( resourceHelper: ResourceHelper?, sp: SP?, private val profileFunction: ProfileFunction, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val databaseHelper: DatabaseHelperInterface ) : AbstractSensitivityPlugin(PluginDescription() .mainType(PluginType.SENSITIVITY) .pluginIcon(R.drawable.ic_generic_icon) @@ -66,8 +67,8 @@ open class SensitivityAAPSPlugin @Inject constructor( 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 siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true) val deviationsArray: MutableList = ArrayList() var pastSensitivity = "" var index = 0 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 index c04a204312..1d9a91ec49 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -2,11 +2,11 @@ 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.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType @@ -34,7 +34,8 @@ open class SensitivityOref1Plugin @Inject constructor( resourceHelper: ResourceHelper?, sp: SP?, private val profileFunction: ProfileFunction, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val databaseHelper: DatabaseHelperInterface ) : AbstractSensitivityPlugin(PluginDescription() .mainType(PluginType.SENSITIVITY) .pluginIcon(R.drawable.ic_generic_icon) @@ -67,8 +68,8 @@ open class SensitivityOref1Plugin @Inject constructor( 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 siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true) //[0] = 8 hour //[1] = 24 hour 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 index 4e742b5760..465aa86c8b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -3,11 +3,11 @@ 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.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType @@ -32,7 +32,8 @@ open class SensitivityWeightedAveragePlugin @Inject constructor( resourceHelper: ResourceHelper, sp: SP, private val profileFunction: ProfileFunction, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val databaseHelper: DatabaseHelperInterface ) : AbstractSensitivityPlugin(PluginDescription() .mainType(PluginType.SENSITIVITY) .pluginIcon(R.drawable.ic_generic_icon) @@ -65,8 +66,8 @@ open class SensitivityWeightedAveragePlugin @Inject constructor( 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) + val siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) + val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true) var pastSensitivity = "" var index = 0 val data = LongSparseArray() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index 32afcb47b8..0c5280747f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -5,13 +5,13 @@ import androidx.work.Worker import androidx.work.WorkerParameters import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.transactions.CgmSourceTransaction import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.interfaces.BgSourceInterface +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType @@ -36,7 +36,8 @@ import javax.inject.Singleton class EversensePlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val databaseHelper: DatabaseHelperInterface ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -139,7 +140,7 @@ class EversensePlugin @Inject constructor( aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers)) for (i in calibrationGlucoseLevels.indices) { try { - if (MainApp.getDbHelper().getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) { + if (eversensePlugin.databaseHelper.getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) { val data = JSONObject() data.put("enteredBy", "AndroidAPS-Eversense") data.put("created_at", DateUtil.toISOString(calibrationTimestamps[i])) 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 d3cd9363de..f19f7d6b86 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 @@ -8,12 +8,12 @@ import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.events.EventCareportalEventChange +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload @@ -45,6 +45,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var uel: UserEntryLogger private var _binding: TreatmentsCareportalFragmentBinding? = null @@ -60,12 +61,12 @@ class TreatmentsCareportalFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) binding.recyclerview.setHasFixedSize(true) binding.recyclerview.layoutManager = LinearLayoutManager(view.context) - binding.recyclerview.adapter = RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)) + binding.recyclerview.adapter = RecyclerViewAdapter(databaseHelper.getCareportalEvents(false)) binding.refreshFromNightscout.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", Runnable { uel.log("CAREPORTAL NS REFRESH") - MainApp.getDbHelper().resetCareportalEvents() + databaseHelper.resetCareportalEvents() rxBus.send(EventNSClientRestart()) }) } @@ -74,7 +75,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.careportal_removestartedevents), Runnable { uel.log("REMOVED RESTART EVENTS") - val events = MainApp.getDbHelper().getCareportalEvents(false) + val events = databaseHelper.getCareportalEvents(false) for (i in events.indices) { val careportalEvent = events[i] if (careportalEvent.json.contains(resourceHelper.gs(R.string.androidaps_start))) { @@ -82,7 +83,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else uploadQueue.removeID("dbAdd", careportalEvent._id) - MainApp.getDbHelper().delete(careportalEvent) + databaseHelper.delete(careportalEvent) } } }, null) @@ -118,7 +119,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { private fun updateGui() { if (_binding == null) return - binding.recyclerview.swapAdapter(RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)), false) + binding.recyclerview.swapAdapter(RecyclerViewAdapter(databaseHelper.getCareportalEvents(false)), false) } inner class RecyclerViewAdapter internal constructor(private var careportalEventList: List) : RecyclerView.Adapter() { @@ -159,7 +160,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else uploadQueue.removeID("dbAdd", careportalEvent._id) - MainApp.getDbHelper().delete(careportalEvent) + databaseHelper.delete(careportalEvent) }, null) } } 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 20e41bb406..3d6e3b2ae7 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 @@ -10,21 +10,21 @@ import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface 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.general.nsclient.UploadQueue -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 @@ -47,6 +47,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var uel: UserEntryLogger private var _binding: TreatmentsExtendedbolusFragmentBinding? = null @@ -123,10 +124,10 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { """.trimIndent(), { _: DialogInterface, _: Int -> uel.log("REMOVED EB") val id = extendedBolus._id - if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) - else uploadQueue.removeID("dbAdd", id) - MainApp.getDbHelper().delete(extendedBolus) - }, null) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) + databaseHelper.delete(extendedBolus) + }, null) } } binding.remove.paintFlags = binding.remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt index 1d7ba6041d..cbb2d009db 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt @@ -8,7 +8,6 @@ import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.TreatmentsProfileswitchFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsProfileswitchItemBinding @@ -16,6 +15,7 @@ import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.events.EventProfileNeedsUpdate +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload @@ -50,6 +50,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var uel: UserEntryLogger private var _binding: TreatmentsProfileswitchFragmentBinding? = null @@ -65,13 +66,13 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) binding.recyclerview.setHasFixedSize(true) binding.recyclerview.layoutManager = LinearLayoutManager(view.context) - binding.recyclerview.adapter = RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)) + binding.recyclerview.adapter = RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)) binding.refreshFromNightscout.setOnClickListener { activity?.let { activity -> uel.log("PROFILE SWITCH NS REFRESH") OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { - MainApp.getDbHelper().resetProfileSwitch() + databaseHelper.resetProfileSwitch() rxBus.send(EventNSClientRestart()) } } @@ -104,7 +105,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { fun updateGUI() { if (_binding == null) return - binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false) + binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false) } inner class RecyclerProfileViewAdapter(private var profileSwitchList: List) : RecyclerView.Adapter() { @@ -150,7 +151,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { val id = profileSwitch._id if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) else uploadQueue.removeID("dbAdd", id) - MainApp.getDbHelper().delete(profileSwitch) + databaseHelper.delete(profileSwitch) }) } } diff --git a/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt b/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt new file mode 100644 index 0000000000..5876076cbf --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.db + +import com.j256.ormlite.field.DatabaseField +import com.j256.ormlite.table.DatabaseTable + +@DatabaseTable(tableName = "OpenHumansQueue") +data class OHQueueItem @JvmOverloads constructor( + @DatabaseField(generatedId = true) + val id: Long = 0, + @DatabaseField + val file: String = "", + @DatabaseField + val content: String = "" +) \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt index c5041a2c05..186703ec33 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt @@ -17,6 +17,7 @@ interface DatabaseHelperInterface { fun createOrUpdate(record: InsightBolusID) fun createOrUpdate(record: InsightPumpID) fun createOrUpdate(record: InsightHistoryOffset) + fun createOrUpdate(record: OHQueueItem) fun create(record: DbRequest) fun getDanaRHistoryRecordsByType(type: Byte): List fun getTDDs(): List @@ -25,8 +26,10 @@ interface DatabaseHelperInterface { fun deleteDbRequest(id: String): Int fun delete(tempBasal: TemporaryBasal) fun delete(extendedBolus: ExtendedBolus) + fun delete(careportalEvent: CareportalEvent) + fun delete(profileSwitch: ProfileSwitch) fun deleteDbRequestbyMongoId(action: String, _id: String) - fun getDbRequestInterator(): CloseableIterator + fun getDbRequestIterator(): CloseableIterator fun roundDateToSec(date: Long): Long fun createOrUpdateTDD(record: TDD) fun createOrUpdate(tempBasal: TemporaryBasal): Boolean @@ -34,11 +37,26 @@ interface DatabaseHelperInterface { fun getTemporaryBasalsDataFromTime(mills: Long, ascending: Boolean): List fun getExtendedBolusDataFromTime(mills: Long, ascending: Boolean): List fun getCareportalEventFromTimestamp(timestamp: Long): CareportalEvent? + fun getLastCareportalEvent(event: String): CareportalEvent? + fun getCareportalEventsFromTime(mills: Long, ascending: Boolean): List + fun getCareportalEventsFromTime(mills: Long, type: String, ascending: Boolean): List + fun getCareportalEvents(start: Long, end: Long, ascending: Boolean): List + fun getCareportalEvents(ascending: Boolean): List + fun getProfileSwitchEventsFromTime(from: Long, to: Long, ascending: Boolean): List + fun getProfileSwitchEventsFromTime(mills: Long, ascending: Boolean): List fun getAllOmnipodHistoryRecordsFromTimestamp(timestamp: Long, ascending: Boolean): List fun findOmnipodHistoryRecordByPumpId(pumpId: Long): OmnipodHistoryRecord? fun getTDDsForLastXDays(days: Int): List fun getProfileSwitchData(from: Long, ascending: Boolean): List fun getExtendedBolusByPumpId(pumpId: Long): ExtendedBolus? + fun getAllCareportalEvents(): List + fun getAllExtendedBoluses(): List + fun getAllProfileSwitches(): List + fun getAllTDDs(): List + fun getAllTemporaryBasals(): List + fun getAllOHQueueItems(maxEntries: Long): List + fun resetCareportalEvents() + fun resetProfileSwitch() // old DB model fun deleteTempBasalById(_id: String) @@ -54,6 +72,11 @@ interface DatabaseHelperInterface { fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? fun getPumpStoppedEvent(pumpSerial: String, before: Long): InsightPumpID? + fun getOHQueueSize(): Long + fun clearOpenHumansQueue() + fun getCountOfAllRows(): Long + fun removeAllOHQueueItemsWithIdSmallerThan(id: Long) + companion object { const val DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets"