MainApp -> kt, the rest of DatabaseHelperInterface

This commit is contained in:
Milos Kozak 2021-03-04 19:23:01 +01:00
parent 87f348fe5a
commit 04f074caf9
22 changed files with 402 additions and 321 deletions

View file

@ -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<PluginBase> 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<? extends DaggerApplication> 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();
}
}

View file

@ -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<out DaggerApplication> {
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
}
}

View file

@ -32,7 +32,6 @@ import java.util.concurrent.TimeUnit;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.dana.comm.RecordTypes; import info.nightscout.androidaps.dana.comm.RecordTypes;
import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.NonOverlappingIntervals;
import info.nightscout.androidaps.data.Profile; 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.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.ProfileInterface; 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.general.openhumans.OpenHumansUploader;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.PercentageSplitter; 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_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_TDDS = "TDDs"; public static final String DATABASE_TDDS = "TDDs";
public static final String DATABASE_OPEN_HUMANS_QUEUE = "OpenHumansQueue";
private static final int DATABASE_VERSION = 13; private static final int DATABASE_VERSION = 13;
@ -436,7 +432,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
public CloseableIterator getDbRequestInterator() { public CloseableIterator getDbRequestIterator() {
try { try {
return getDaoDbRequest().closeableIterator(); return getDaoDbRequest().closeableIterator();
} catch (SQLException e) { } catch (SQLException e) {

View file

@ -25,174 +25,262 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
} }
@Override public void createOrUpdate(@NonNull CareportalEvent careportalEvent) { @Override public void createOrUpdate(@NonNull CareportalEvent careportalEvent) {
MainApp.getDbHelper().createOrUpdate(careportalEvent); MainApp.Companion.getDbHelper().createOrUpdate(careportalEvent);
} }
@Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) { @Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) {
MainApp.getDbHelper().createOrUpdate(record); MainApp.Companion.getDbHelper().createOrUpdate(record);
} }
@Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) { @Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) {
MainApp.getDbHelper().createOrUpdate(record); MainApp.Companion.getDbHelper().createOrUpdate(record);
} }
@NonNull @Override public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) { @NonNull @Override public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); return MainApp.Companion.getDbHelper().getDanaRHistoryRecordsByType(type);
} }
@NonNull @Override public List<TDD> getTDDs() { @NonNull @Override public List<TDD> getTDDs() {
return MainApp.getDbHelper().getTDDs(); return MainApp.Companion.getDbHelper().getTDDs();
} }
@Override public long size(@NonNull String table) { @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) { @Override public void create(@NonNull DbRequest record) {
try { try {
MainApp.getDbHelper().create(record); MainApp.Companion.getDbHelper().create(record);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override public void deleteAllDbRequests() { @Override public void deleteAllDbRequests() {
MainApp.getDbHelper().deleteAllDbRequests(); MainApp.Companion.getDbHelper().deleteAllDbRequests();
} }
@Override public int deleteDbRequest(@NonNull String id) { @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) { @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<DbRequest> getDbRequestInterator() { @NonNull @Override public CloseableIterator<DbRequest> getDbRequestIterator() {
return MainApp.getDbHelper().getDbRequestInterator(); return MainApp.Companion.getDbHelper().getDbRequestIterator();
} }
@Override public long roundDateToSec(long date) { @Override public long roundDateToSec(long date) {
return MainApp.getDbHelper().roundDateToSec(date); return MainApp.Companion.getDbHelper().roundDateToSec(date);
} }
@Override public void createOrUpdateTDD(@NonNull TDD record) { @Override public void createOrUpdateTDD(@NonNull TDD record) {
MainApp.getDbHelper().createOrUpdateTDD(record); MainApp.Companion.getDbHelper().createOrUpdateTDD(record);
} }
@Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) { @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) { @NonNull @Override public TemporaryBasal findTempBasalByPumpId(long id) {
return MainApp.getDbHelper().findTempBasalByPumpId(id); return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id);
} }
@NonNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) { @NonNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
} }
@Override public CareportalEvent getCareportalEventFromTimestamp(long timestamp) { @Override public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
return MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp); return MainApp.Companion.getDbHelper().getCareportalEventFromTimestamp(timestamp);
} }
@NonNull @Override public List<OmnipodHistoryRecord> getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { @NonNull @Override public List<OmnipodHistoryRecord> 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) { @Nullable @Override public OmnipodHistoryRecord findOmnipodHistoryRecordByPumpId(long pumpId) {
return MainApp.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId);
} }
@NonNull @Override public List<TDD> getTDDsForLastXDays(int days) { @NonNull @Override public List<TDD> getTDDsForLastXDays(int days) {
return MainApp.getDbHelper().getTDDsForLastXDays(days); return MainApp.Companion.getDbHelper().getTDDsForLastXDays(days);
} }
@NonNull @Override public List<ProfileSwitch> getProfileSwitchData(long from, boolean ascending) { @NonNull @Override public List<ProfileSwitch> 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) { @Override public void createOrUpdate(@NonNull InsightBolusID record) {
MainApp.getDbHelper().createOrUpdate(record); MainApp.Companion.getDbHelper().createOrUpdate(record);
} }
@Override public void createOrUpdate(@NonNull InsightPumpID record) { @Override public void createOrUpdate(@NonNull InsightPumpID record) {
MainApp.getDbHelper().createOrUpdate(record); MainApp.Companion.getDbHelper().createOrUpdate(record);
} }
@Override public void createOrUpdate(@NonNull InsightHistoryOffset record) { @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) {
MainApp.getDbHelper().createOrUpdate(record); MainApp.Companion.getDbHelper().createOrUpdate(record);
} }
@Override public void delete(@NonNull ExtendedBolus extendedBolus) { @Override public void delete(@NonNull ExtendedBolus extendedBolus) {
MainApp.getDbHelper().delete(extendedBolus); MainApp.Companion.getDbHelper().delete(extendedBolus);
} }
@Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { @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) { @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) { @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) { @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) { @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) { @Override public void createOrUpdate(@NonNull ProfileSwitch profileSwitch) {
MainApp.getDbHelper().createOrUpdate(profileSwitch); MainApp.Companion.getDbHelper().createOrUpdate(profileSwitch);
} }
@Override public void delete(@NonNull TemporaryBasal tempBasal) { @Override public void delete(@NonNull TemporaryBasal tempBasal) {
MainApp.getDbHelper().delete(tempBasal); MainApp.Companion.getDbHelper().delete(tempBasal);
} }
@NonNull @Override public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) { @NonNull @Override public List<ExtendedBolus> 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) { @Override public void deleteTempBasalById(@NonNull String _id) {
MainApp.getDbHelper().deleteTempBasalById(_id); MainApp.Companion.getDbHelper().deleteTempBasalById(_id);
} }
@Override public void deleteExtendedBolusById(@NonNull String _id) { @Override public void deleteExtendedBolusById(@NonNull String _id) {
MainApp.getDbHelper().deleteExtendedBolusById(_id); MainApp.Companion.getDbHelper().deleteExtendedBolusById(_id);
} }
@Override public void deleteCareportalEventById(@NonNull String _id) { @Override public void deleteCareportalEventById(@NonNull String _id) {
MainApp.getDbHelper().deleteCareportalEventById(_id); MainApp.Companion.getDbHelper().deleteCareportalEventById(_id);
} }
@Override public void deleteProfileSwitchById(@NonNull String _id) { @Override public void deleteProfileSwitchById(@NonNull String _id) {
MainApp.getDbHelper().deleteProfileSwitchById(_id); MainApp.Companion.getDbHelper().deleteProfileSwitchById(_id);
} }
@Override public void createTempBasalFromJsonIfNotExists(@NonNull JSONObject json) { @Override public void createTempBasalFromJsonIfNotExists(@NonNull JSONObject json) {
MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json); MainApp.Companion.getDbHelper().createTempBasalFromJsonIfNotExists(json);
} }
@Override public void createExtendedBolusFromJsonIfNotExists(@NonNull JSONObject json) { @Override public void createExtendedBolusFromJsonIfNotExists(@NonNull JSONObject json) {
MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); MainApp.Companion.getDbHelper().createExtendedBolusFromJsonIfNotExists(json);
} }
@Override public void createCareportalEventFromJsonIfNotExists(@NonNull JSONObject 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) { @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() { @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<CareportalEvent> getCareportalEventsFromTime(long mills, boolean ascending) {
return MainApp.Companion.getDbHelper().getCareportalEventsFromTime(mills, ascending);
}
@NonNull @Override public List<CareportalEvent> getCareportalEventsFromTime(long mills, @NonNull String type, boolean ascending) {
return MainApp.Companion.getDbHelper().getCareportalEventsFromTime(mills, type, ascending);
}
@NonNull @Override public List<CareportalEvent> getCareportalEvents(long start, long end, boolean ascending) {
return MainApp.Companion.getDbHelper().getCareportalEvents(start, end, ascending);
}
@NonNull @Override public List<CareportalEvent> getCareportalEvents(boolean ascending) {
return MainApp.Companion.getDbHelper().getCareportalEvents(ascending);
}
@NonNull @Override public List<ProfileSwitch> getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(from, to, ascending);
}
@NonNull @Override public List<ProfileSwitch> getProfileSwitchEventsFromTime(long mills, boolean ascending) {
return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending);
}
@NonNull @Override public List<CareportalEvent> getAllCareportalEvents() {
return MainApp.Companion.getDbHelper().getAllCareportalEvents();
}
@NonNull @Override public List<ExtendedBolus> getAllExtendedBoluses() {
return MainApp.Companion.getDbHelper().getAllExtendedBoluses();
}
@NonNull @Override public List<ProfileSwitch> getAllProfileSwitches() {
return MainApp.Companion.getDbHelper().getAllProfileSwitches();
}
@NonNull @Override public List<TDD> getAllTDDs() {
return MainApp.Companion.getDbHelper().getAllTDDs();
}
@NonNull @Override public List<TemporaryBasal> getAllTemporaryBasals() {
return MainApp.Companion.getDbHelper().getAllTemporaryBasals();
}
@NonNull @Override public List<OHQueueItem> 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);
} }
} }

View file

@ -1,14 +1,2 @@
package info.nightscout.androidaps.db 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 = ""
)

View file

@ -124,7 +124,7 @@ public class UploadQueue implements UploadQueueInterface {
String result = ""; String result = "";
CloseableIterator<DbRequest> iterator; CloseableIterator<DbRequest> iterator;
try { try {
iterator = databaseHelper.getDbRequestInterator(); iterator = databaseHelper.getDbRequestIterator();
try { try {
while (iterator.hasNext()) { while (iterator.hasNext()) {
DbRequest dbr = iterator.next(); DbRequest dbr = iterator.next();

View file

@ -807,7 +807,7 @@ public class NSClientService extends DaggerService {
CloseableIterator<DbRequest> iterator; CloseableIterator<DbRequest> iterator;
int maxcount = 30; int maxcount = 30;
try { try {
iterator = databaseHelper.getDbRequestInterator(); iterator = databaseHelper.getDbRequestIterator();
try { try {
while (iterator.hasNext() && maxcount > 0) { while (iterator.hasNext() && maxcount > 0) {
DbRequest dbr = iterator.next(); DbRequest dbr = iterator.next();

View file

@ -7,21 +7,19 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Button import android.widget.Button
import android.widget.TextView import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.work.WorkInfo
import androidx.work.WorkManager import androidx.work.WorkManager
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.Event import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import io.reactivex.rxkotlin.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.BackpressureStrategy import io.reactivex.BackpressureStrategy
import io.reactivex.Single import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
@ -40,10 +38,11 @@ class OpenHumansFragment : DaggerFragment() {
@Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var openHumansUploader: OpenHumansUploader
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var databaseHelper: DatabaseHelperInterface
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
compositeDisposable += Single.fromCallable { MainApp.getDbHelper().ohQueueSize } compositeDisposable += Single.fromCallable { databaseHelper.getOHQueueSize() }
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.repeatWhen { .repeatWhen {
rxBus.toObservable(UpdateViewEvent::class.java) rxBus.toObservable(UpdateViewEvent::class.java)
@ -58,7 +57,7 @@ class OpenHumansFragment : DaggerFragment() {
updateGUI() updateGUI()
}, {}) }, {})
context?.applicationContext?.let { appContext -> context?.applicationContext?.let { appContext ->
WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, Observer<List<WorkInfo>> { WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, {
val workInfo = it.lastOrNull() val workInfo = it.lastOrNull()
if (workInfo == null) { if (workInfo == null) {
workerState?.visibility = View.GONE workerState?.visibility = View.GONE
@ -84,7 +83,7 @@ class OpenHumansFragment : DaggerFragment() {
workerState = view.findViewById(R.id.worker_state) workerState = view.findViewById(R.id.worker_state)
login!!.setOnClickListener { startActivity(Intent(context, OpenHumansLoginActivity::class.java)) } login!!.setOnClickListener { startActivity(Intent(context, OpenHumansLoginActivity::class.java)) }
logout!!.setOnClickListener { 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 viewsCreated = true
updateGUI() updateGUI()

View file

@ -14,13 +14,13 @@ import androidx.core.app.NotificationManagerCompat
import androidx.work.* import androidx.work.*
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.db.* import info.nightscout.androidaps.db.*
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -60,6 +60,7 @@ class OpenHumansUploader @Inject constructor(
private val rxBus: RxBusWrapper, private val rxBus: RxBusWrapper,
private val context: Context, private val context: Context,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsPlugin,
private val databaseHelper: DatabaseHelperInterface,
val repository: AppRepository val repository: AppRepository
) : PluginBase( ) : PluginBase(
PluginDescription() PluginDescription()
@ -317,7 +318,7 @@ class OpenHumansUploader @Inject constructor(
file = file, file = file,
content = jsonObject.toString() content = jsonObject.toString()
) )
MainApp.getDbHelper().createOrUpdate(queueItem) databaseHelper.createOrUpdate(queueItem)
rxBus.send(OpenHumansFragment.UpdateQueueEvent) rxBus.send(OpenHumansFragment.UpdateQueueEvent)
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
@ -347,7 +348,7 @@ class OpenHumansUploader @Inject constructor(
isSetup = false isSetup = false
oAuthTokens = null oAuthTokens = null
projectMemberId = null projectMemberId = null
MainApp.getDbHelper().clearOpenHumansQueue() databaseHelper.clearOpenHumansQueue()
rxBus.send(OpenHumansFragment.UpdateViewEvent) rxBus.send(OpenHumansFragment.UpdateViewEvent)
} }
@ -360,8 +361,8 @@ class OpenHumansUploader @Inject constructor(
//Updating the notification for every item drastically slows down the operation //Updating the notification for every item drastically slows down the operation
if (currentProgress % 1000L == 0L) showOngoingNotification(maxProgress, currentProgress) if (currentProgress % 1000L == 0L) showOngoingNotification(maxProgress, currentProgress)
} }
copyDisposable = Completable.fromCallable { MainApp.getDbHelper().clearOpenHumansQueue() } copyDisposable = Completable.fromCallable { databaseHelper.clearOpenHumansQueue() }
.andThen(Single.defer { Single.just(MainApp.getDbHelper().countOfAllRows + treatmentsPlugin.service.count()) }) .andThen(Single.defer { Single.just(databaseHelper.getCountOfAllRows() + treatmentsPlugin.service.count()) })
.doOnSuccess { maxProgress = it } .doOnSuccess { maxProgress = it }
.flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } } .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } }
.map { enqueueTreatment(it); increaseCounter() } .map { enqueueTreatment(it); increaseCounter() }
@ -369,19 +370,19 @@ class OpenHumansUploader @Inject constructor(
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) })
.map { enqueueBGReading(it); increaseCounter() } .map { enqueueBGReading(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allCareportalEvents) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllCareportalEvents()) })
.map { enqueueCareportalEvent(it); increaseCounter() } .map { enqueueCareportalEvent(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allExtendedBoluses) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) })
.map { enqueueExtendedBolus(it); increaseCounter() } .map { enqueueExtendedBolus(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allProfileSwitches) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllProfileSwitches()) })
.map { enqueueProfileSwitch(it); increaseCounter() } .map { enqueueProfileSwitch(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allTDDs) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTDDs()) })
.map { enqueueTotalDailyDose(it); increaseCounter() } .map { enqueueTotalDailyDose(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(MainApp.getDbHelper().allTemporaryBasals) }) .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) })
.map { enqueueTemporaryBasal(it); increaseCounter() } .map { enqueueTemporaryBasal(it); increaseCounter() }
.ignoreElements() .ignoreElements()
.andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) }) .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) })
@ -448,7 +449,7 @@ class OpenHumansUploader @Inject constructor(
fun uploadDataSegmentally(): Completable = fun uploadDataSegmentally(): Completable =
uploadData(UPLOAD_SEGMENT_SIZE) uploadData(UPLOAD_SEGMENT_SIZE)
.repeatUntil { MainApp.getDbHelper().ohQueueSize == 0L } .repeatUntil { databaseHelper.getOHQueueSize() == 0L }
.doOnSubscribe { .doOnSubscribe {
aapsLogger.info(LTag.OHUPLOADER, "Starting segmental upload") aapsLogger.info(LTag.OHUPLOADER, "Starting segmental upload")
} }
@ -460,7 +461,7 @@ class OpenHumansUploader @Inject constructor(
} }
@Suppress("SameParameterValue") @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 { data -> refreshAccessTokensIfNeeded().map { accessToken -> accessToken to data } }
.flatMap { uploadFile(it.first, it.second).andThen(Single.just(it.second)) } .flatMap { uploadFile(it.first, it.second).andThen(Single.just(it.second)) }
.flatMapCompletable { .flatMapCompletable {
@ -501,8 +502,8 @@ class OpenHumansUploader @Inject constructor(
} }
} }
private fun gatherData(maxEntries: Long?) = Single.defer { private fun gatherData(maxEntries: Long) = Single.defer {
val items = MainApp.getDbHelper().getAllOHQueueItems(maxEntries) val items = databaseHelper.getAllOHQueueItems(maxEntries)
val baos = ByteArrayOutputStream() val baos = ByteArrayOutputStream()
val zos = ZipOutputStream(baos) val zos = ZipOutputStream(baos)
val tags = mutableListOf<String>() val tags = mutableListOf<String>()
@ -583,7 +584,7 @@ class OpenHumansUploader @Inject constructor(
} }
private fun removeUploadedEntriesFromQueue(highestId: Long) = Completable.fromCallable { private fun removeUploadedEntriesFromQueue(highestId: Long) = Completable.fromCallable {
MainApp.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(highestId) databaseHelper.removeAllOHQueueItemsWithIdSmallerThan(highestId)
} }
private fun handleSignOut() { private fun handleSignOut() {

View file

@ -4,10 +4,10 @@ import android.graphics.Color
import android.widget.TextView import android.widget.TextView
import androidx.annotation.StringRes import androidx.annotation.StringRes
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.interfaces.ActivePluginProvider 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.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants 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 sp: SP,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val warnColors: WarnColors, 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) { private fun handleAge(view: TextView?, eventName: String, @StringRes warnSettings: Int, defaultWarnThreshold: Double, @StringRes urgentSettings: Int, defaultUrgentThreshold: Double) {
val warn = sp.getDouble(warnSettings, defaultWarnThreshold) val warn = sp.getDouble(warnSettings, defaultWarnThreshold)
val urgent = sp.getDouble(urgentSettings, defaultUrgentThreshold) val urgent = sp.getDouble(urgentSettings, defaultUrgentThreshold)
val careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(eventName) val careportalEvent = databaseHelper.getLastCareportalEvent(eventName)
if (careportalEvent != null) { if (careportalEvent != null) {
warnColors.setColorByAge(view, careportalEvent, warn, urgent) warnColors.setColorByAge(view, careportalEvent, warn, urgent)
view?.text = careportalEvent.age(resourceHelper.shortTextMode(), resourceHelper) view?.text = careportalEvent.age(resourceHelper.shortTextMode(), resourceHelper)

View file

@ -10,7 +10,6 @@ import com.jjoe64.graphview.series.LineGraphSeries
import com.jjoe64.graphview.series.Series import com.jjoe64.graphview.series.Series
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.GlucoseValueDataPoint import info.nightscout.androidaps.data.GlucoseValueDataPoint
import info.nightscout.androidaps.data.IobTotal 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.ValueWrapper
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.LoopInterface import info.nightscout.androidaps.interfaces.LoopInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.interfaces.TreatmentsInterface
@ -51,6 +51,7 @@ class GraphData(
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var databaseHelper: DatabaseHelperInterface
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -267,7 +268,7 @@ class GraphData(
} }
// Careportal // Careportal
MainApp.getDbHelper().getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true) databaseHelper.getCareportalEventsFromTime(fromTime - 6 * 60 * 60 * 1000, true)
.filterTimeframe(fromTime, endTime) .filterTimeframe(fromTime, endTime)
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())

View file

@ -1,13 +1,13 @@
package info.nightscout.androidaps.plugins.general.tidepool.comm package info.nightscout.androidaps.plugins.general.tidepool.comm
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
@ -33,6 +33,7 @@ class UploadChunk @Inject constructor(
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val treatmentsPlugin: TreatmentsPlugin, private val treatmentsPlugin: TreatmentsPlugin,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val databaseHelper: DatabaseHelperInterface,
private val repository: AppRepository, private val repository: AppRepository,
private val dateUtil: DateUtil private val dateUtil: DateUtil
) { ) {
@ -127,7 +128,7 @@ class UploadChunk @Inject constructor(
} }
private fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> { private fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> {
val readings = MainApp.getDbHelper().getCareportalEvents(start, end, true) val readings = databaseHelper.getCareportalEvents(start, end, true)
val selection = BloodGlucoseElement.fromCareportalEvents(readings) val selection = BloodGlucoseElement.fromCareportalEvents(readings)
if (selection.isNotEmpty()) if (selection.isNotEmpty())
rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload")) 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<ProfileElement> { private fun getProfiles(start: Long, end: Long): List<ProfileElement> {
val pss = MainApp.getDbHelper().getProfileSwitchEventsFromTime(start, end, true) val pss = databaseHelper.getProfileSwitchEventsFromTime(start, end, true)
val selection = LinkedList<ProfileElement>() val selection = LinkedList<ProfileElement>()
for (ps in pss) { for (ps in pss) {
newInstanceOrNull(ps)?.let { selection.add(it) } newInstanceOrNull(ps)?.let { selection.add(it) }

View file

@ -5,7 +5,6 @@ import android.content.Context
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin 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.CareportalEvent
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TDD import info.nightscout.androidaps.db.TDD
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.*
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.logging.AAPSLogger 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.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
@ -55,6 +49,8 @@ import java.util.*
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.math.abs
import kotlin.math.min
@Singleton @Singleton
class ActionStringHandler @Inject constructor( class ActionStringHandler @Inject constructor(
@ -83,6 +79,7 @@ class ActionStringHandler @Inject constructor(
private val carbsGenerator: CarbsGenerator, private val carbsGenerator: CarbsGenerator,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val config: Config, private val config: Config,
private val databaseHelper: DatabaseHelperInterface,
private val repository: AppRepository, private val repository: AppRepository,
private val nsUpload: NSUpload private val nsUpload: NSUpload
) { ) {
@ -222,12 +219,12 @@ class ActionStringHandler @Inject constructor(
val format = DecimalFormat("0.00") val format = DecimalFormat("0.00")
val formatInt = DecimalFormat("0") val formatInt = DecimalFormat("0")
val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() 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, val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, tempTarget,
carbsAfterConstraints, if (cobInfo.displayCob != null) cobInfo.displayCob!! else 0.0, 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) 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!" + sendError("Insulin constraint violation!" +
"\nCannot deliver " + format.format(bolusWizard.calculatedTotalInsulin) + "!") "\nCannot deliver " + format.format(bolusWizard.calculatedTotalInsulin) + "!")
return return
@ -365,7 +362,7 @@ class ActionStringHandler @Inject constructor(
var weighted03 = 0.0 var weighted03 = 0.0
var weighted05 = 0.0 var weighted05 = 0.0
var weighted07 = 0.0 var weighted07 = 0.0
Collections.reverse(historyList) historyList.reverse()
for (record in historyList) { for (record in historyList) {
val tdd = record.getTotal() val tdd = record.getTotal()
if (i == 0) { 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.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 += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (DecimalFormatter.to0Decimal(100 * weighted07 / refTDD) + "%") + "\n"
message += "\n" message += "\n"
Collections.reverse(historyList) historyList.reverse()
//add TDDs: //add TDDs:
for (record in historyList) { for (record in historyList) {
val tdd = record.getTotal() val tdd = record.getTotal()
@ -401,15 +398,15 @@ class ActionStringHandler @Inject constructor(
} }
private fun getTDDList(returnDummies: MutableList<TDD>): MutableList<TDD> { private fun getTDDList(returnDummies: MutableList<TDD>): MutableList<TDD> {
var historyList = MainApp.getDbHelper().tdDs var historyList = databaseHelper.getTDDs().toMutableList()
historyList = historyList.subList(0, Math.min(10, historyList.size)) historyList = historyList.subList(0, min(10, historyList.size))
//fill single gaps - only needed for Dana*R data //fill single gaps - only needed for Dana*R data
val dummies: MutableList<TDD> = returnDummies val dummies: MutableList<TDD> = returnDummies
val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault())
for (i in 0 until historyList.size - 1) { for (i in 0 until historyList.size - 1) {
val elem1 = historyList[i] val elem1 = historyList[i]
val elem2 = historyList[i + 1] 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() val dummy = TDD()
dummy.date = elem1.date - 24 * 60 * 60 * 1000 dummy.date = elem1.date - 24 * 60 * 60 * 1000
dummy.basal = elem1.basal / 2 dummy.basal = elem1.basal / 2
@ -420,7 +417,7 @@ class ActionStringHandler @Inject constructor(
} }
} }
historyList.addAll(dummies) historyList.addAll(dummies)
Collections.sort(historyList) { lhs, rhs -> (rhs.date - lhs.date).toInt() } historyList.sortWith { lhs, rhs -> (rhs.date - lhs.date).toInt() }
return historyList return historyList
} }

View file

@ -2,11 +2,11 @@ package info.nightscout.androidaps.plugins.sensitivity
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -33,7 +33,8 @@ open class SensitivityAAPSPlugin @Inject constructor(
resourceHelper: ResourceHelper?, resourceHelper: ResourceHelper?,
sp: SP?, sp: SP?,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil private val dateUtil: DateUtil,
private val databaseHelper: DatabaseHelperInterface
) : AbstractSensitivityPlugin(PluginDescription() ) : AbstractSensitivityPlugin(PluginDescription()
.mainType(PluginType.SENSITIVITY) .mainType(PluginType.SENSITIVITY)
.pluginIcon(R.drawable.ic_generic_icon) .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()) aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + plugin.lastDataTime())
return AutosensResult() return AutosensResult()
} }
val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) val siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true)
val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true)
val deviationsArray: MutableList<Double> = ArrayList() val deviationsArray: MutableList<Double> = ArrayList()
var pastSensitivity = "" var pastSensitivity = ""
var index = 0 var index = 0

View file

@ -2,11 +2,11 @@ package info.nightscout.androidaps.plugins.sensitivity
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -34,7 +34,8 @@ open class SensitivityOref1Plugin @Inject constructor(
resourceHelper: ResourceHelper?, resourceHelper: ResourceHelper?,
sp: SP?, sp: SP?,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil private val dateUtil: DateUtil,
private val databaseHelper: DatabaseHelperInterface
) : AbstractSensitivityPlugin(PluginDescription() ) : AbstractSensitivityPlugin(PluginDescription()
.mainType(PluginType.SENSITIVITY) .mainType(PluginType.SENSITIVITY)
.pluginIcon(R.drawable.ic_generic_icon) .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()) aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + plugin.lastDataTime())
return AutosensResult() return AutosensResult()
} }
val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) val siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true)
val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true)
//[0] = 8 hour //[0] = 8 hour
//[1] = 24 hour //[1] = 24 hour

View file

@ -3,11 +3,11 @@ package info.nightscout.androidaps.plugins.sensitivity
import androidx.collection.LongSparseArray import androidx.collection.LongSparseArray
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -32,7 +32,8 @@ open class SensitivityWeightedAveragePlugin @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
sp: SP, sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil private val dateUtil: DateUtil,
private val databaseHelper: DatabaseHelperInterface
) : AbstractSensitivityPlugin(PluginDescription() ) : AbstractSensitivityPlugin(PluginDescription()
.mainType(PluginType.SENSITIVITY) .mainType(PluginType.SENSITIVITY)
.pluginIcon(R.drawable.ic_generic_icon) .pluginIcon(R.drawable.ic_generic_icon)
@ -65,8 +66,8 @@ open class SensitivityWeightedAveragePlugin @Inject constructor(
aapsLogger.debug(LTag.AUTOSENS, "No profile available") aapsLogger.debug(LTag.AUTOSENS, "No profile available")
return AutosensResult() return AutosensResult()
} }
val siteChanges = MainApp.getDbHelper().getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true) val siteChanges = databaseHelper.getCareportalEventsFromTime(fromTime, CareportalEvent.SITECHANGE, true)
val profileSwitches = MainApp.getDbHelper().getProfileSwitchEventsFromTime(fromTime, true) val profileSwitches = databaseHelper.getProfileSwitchEventsFromTime(fromTime, true)
var pastSensitivity = "" var pastSensitivity = ""
var index = 0 var index = 0
val data = LongSparseArray<Double>() val data = LongSparseArray<Double>()

View file

@ -5,13 +5,13 @@ import androidx.work.Worker
import androidx.work.WorkerParameters import androidx.work.WorkerParameters
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.interfaces.BgSourceInterface import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
@ -36,7 +36,8 @@ import javax.inject.Singleton
class EversensePlugin @Inject constructor( class EversensePlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
aapsLogger: AAPSLogger aapsLogger: AAPSLogger,
private val databaseHelper: DatabaseHelperInterface
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.BGSOURCE) .mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment::class.java.name) .fragmentClass(BGSourceFragment::class.java.name)
@ -139,7 +140,7 @@ class EversensePlugin @Inject constructor(
aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers)) aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers))
for (i in calibrationGlucoseLevels.indices) { for (i in calibrationGlucoseLevels.indices) {
try { try {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) { if (eversensePlugin.databaseHelper.getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) {
val data = JSONObject() val data = JSONObject()
data.put("enteredBy", "AndroidAPS-Eversense") data.put("enteredBy", "AndroidAPS-Eversense")
data.put("created_at", DateUtil.toISOString(calibrationTimestamps[i])) data.put("created_at", DateUtil.toISOString(calibrationTimestamps[i]))

View file

@ -8,12 +8,12 @@ import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.events.EventCareportalEventChange import info.nightscout.androidaps.events.EventCareportalEventChange
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
@ -45,6 +45,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var databaseHelper: DatabaseHelperInterface
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
private var _binding: TreatmentsCareportalFragmentBinding? = null private var _binding: TreatmentsCareportalFragmentBinding? = null
@ -60,12 +61,12 @@ class TreatmentsCareportalFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.recyclerview.setHasFixedSize(true) binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.recyclerview.adapter = RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)) binding.recyclerview.adapter = RecyclerViewAdapter(databaseHelper.getCareportalEvents(false))
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", Runnable {
uel.log("CAREPORTAL NS REFRESH") uel.log("CAREPORTAL NS REFRESH")
MainApp.getDbHelper().resetCareportalEvents() databaseHelper.resetCareportalEvents()
rxBus.send(EventNSClientRestart()) rxBus.send(EventNSClientRestart())
}) })
} }
@ -74,7 +75,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.careportal_removestartedevents), Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.careportal_removestartedevents), Runnable {
uel.log("REMOVED RESTART EVENTS") uel.log("REMOVED RESTART EVENTS")
val events = MainApp.getDbHelper().getCareportalEvents(false) val events = databaseHelper.getCareportalEvents(false)
for (i in events.indices) { for (i in events.indices) {
val careportalEvent = events[i] val careportalEvent = events[i]
if (careportalEvent.json.contains(resourceHelper.gs(R.string.androidaps_start))) { if (careportalEvent.json.contains(resourceHelper.gs(R.string.androidaps_start))) {
@ -82,7 +83,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
nsUpload.removeCareportalEntryFromNS(careportalEvent._id) nsUpload.removeCareportalEntryFromNS(careportalEvent._id)
else else
uploadQueue.removeID("dbAdd", careportalEvent._id) uploadQueue.removeID("dbAdd", careportalEvent._id)
MainApp.getDbHelper().delete(careportalEvent) databaseHelper.delete(careportalEvent)
} }
} }
}, null) }, null)
@ -118,7 +119,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
private fun updateGui() { private fun updateGui() {
if (_binding == null) return 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<CareportalEvent>) : RecyclerView.Adapter<CareportalEventsViewHolder>() { inner class RecyclerViewAdapter internal constructor(private var careportalEventList: List<CareportalEvent>) : RecyclerView.Adapter<CareportalEventsViewHolder>() {
@ -159,7 +160,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
nsUpload.removeCareportalEntryFromNS(careportalEvent._id) nsUpload.removeCareportalEntryFromNS(careportalEvent._id)
else else
uploadQueue.removeID("dbAdd", careportalEvent._id) uploadQueue.removeID("dbAdd", careportalEvent._id)
MainApp.getDbHelper().delete(careportalEvent) databaseHelper.delete(careportalEvent)
}, null) }, null)
} }
} }

View file

@ -10,21 +10,21 @@ import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Intervals import info.nightscout.androidaps.data.Intervals
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding
import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue 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.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
@ -47,6 +47,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var databaseHelper: DatabaseHelperInterface
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
private var _binding: TreatmentsExtendedbolusFragmentBinding? = null private var _binding: TreatmentsExtendedbolusFragmentBinding? = null
@ -123,10 +124,10 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
""".trimIndent(), { _: DialogInterface, _: Int -> """.trimIndent(), { _: DialogInterface, _: Int ->
uel.log("REMOVED EB") uel.log("REMOVED EB")
val id = extendedBolus._id val id = extendedBolus._id
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", id) else uploadQueue.removeID("dbAdd", id)
MainApp.getDbHelper().delete(extendedBolus) databaseHelper.delete(extendedBolus)
}, null) }, null)
} }
} }
binding.remove.paintFlags = binding.remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.remove.paintFlags = binding.remove.paintFlags or Paint.UNDERLINE_TEXT_FLAG

View file

@ -8,7 +8,6 @@ import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.TreatmentsProfileswitchFragmentBinding import info.nightscout.androidaps.databinding.TreatmentsProfileswitchFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsProfileswitchItemBinding 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.db.Source
import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.events.EventProfileNeedsUpdate
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
@ -50,6 +50,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var databaseHelper: DatabaseHelperInterface
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
private var _binding: TreatmentsProfileswitchFragmentBinding? = null private var _binding: TreatmentsProfileswitchFragmentBinding? = null
@ -65,13 +66,13 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.recyclerview.setHasFixedSize(true) binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) 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 { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
uel.log("PROFILE SWITCH NS REFRESH") uel.log("PROFILE SWITCH NS REFRESH")
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") {
MainApp.getDbHelper().resetProfileSwitch() databaseHelper.resetProfileSwitch()
rxBus.send(EventNSClientRestart()) rxBus.send(EventNSClientRestart())
} }
} }
@ -104,7 +105,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
fun updateGUI() { fun updateGUI() {
if (_binding == null) return 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<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() { inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() {
@ -150,7 +151,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
val id = profileSwitch._id val id = profileSwitch._id
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeID("dbAdd", id) else uploadQueue.removeID("dbAdd", id)
MainApp.getDbHelper().delete(profileSwitch) databaseHelper.delete(profileSwitch)
}) })
} }
} }

View file

@ -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 = ""
)

View file

@ -17,6 +17,7 @@ interface DatabaseHelperInterface {
fun createOrUpdate(record: InsightBolusID) fun createOrUpdate(record: InsightBolusID)
fun createOrUpdate(record: InsightPumpID) fun createOrUpdate(record: InsightPumpID)
fun createOrUpdate(record: InsightHistoryOffset) fun createOrUpdate(record: InsightHistoryOffset)
fun createOrUpdate(record: OHQueueItem)
fun create(record: DbRequest) fun create(record: DbRequest)
fun getDanaRHistoryRecordsByType(type: Byte): List<DanaRHistoryRecord> fun getDanaRHistoryRecordsByType(type: Byte): List<DanaRHistoryRecord>
fun getTDDs(): List<TDD> fun getTDDs(): List<TDD>
@ -25,8 +26,10 @@ interface DatabaseHelperInterface {
fun deleteDbRequest(id: String): Int fun deleteDbRequest(id: String): Int
fun delete(tempBasal: TemporaryBasal) fun delete(tempBasal: TemporaryBasal)
fun delete(extendedBolus: ExtendedBolus) fun delete(extendedBolus: ExtendedBolus)
fun delete(careportalEvent: CareportalEvent)
fun delete(profileSwitch: ProfileSwitch)
fun deleteDbRequestbyMongoId(action: String, _id: String) fun deleteDbRequestbyMongoId(action: String, _id: String)
fun getDbRequestInterator(): CloseableIterator<DbRequest> fun getDbRequestIterator(): CloseableIterator<DbRequest>
fun roundDateToSec(date: Long): Long fun roundDateToSec(date: Long): Long
fun createOrUpdateTDD(record: TDD) fun createOrUpdateTDD(record: TDD)
fun createOrUpdate(tempBasal: TemporaryBasal): Boolean fun createOrUpdate(tempBasal: TemporaryBasal): Boolean
@ -34,11 +37,26 @@ interface DatabaseHelperInterface {
fun getTemporaryBasalsDataFromTime(mills: Long, ascending: Boolean): List<TemporaryBasal> fun getTemporaryBasalsDataFromTime(mills: Long, ascending: Boolean): List<TemporaryBasal>
fun getExtendedBolusDataFromTime(mills: Long, ascending: Boolean): List<ExtendedBolus> fun getExtendedBolusDataFromTime(mills: Long, ascending: Boolean): List<ExtendedBolus>
fun getCareportalEventFromTimestamp(timestamp: Long): CareportalEvent? fun getCareportalEventFromTimestamp(timestamp: Long): CareportalEvent?
fun getLastCareportalEvent(event: String): CareportalEvent?
fun getCareportalEventsFromTime(mills: Long, ascending: Boolean): List<CareportalEvent>
fun getCareportalEventsFromTime(mills: Long, type: String, ascending: Boolean): List<CareportalEvent>
fun getCareportalEvents(start: Long, end: Long, ascending: Boolean): List<CareportalEvent>
fun getCareportalEvents(ascending: Boolean): List<CareportalEvent>
fun getProfileSwitchEventsFromTime(from: Long, to: Long, ascending: Boolean): List<ProfileSwitch>
fun getProfileSwitchEventsFromTime(mills: Long, ascending: Boolean): List<ProfileSwitch>
fun getAllOmnipodHistoryRecordsFromTimestamp(timestamp: Long, ascending: Boolean): List<OmnipodHistoryRecord> fun getAllOmnipodHistoryRecordsFromTimestamp(timestamp: Long, ascending: Boolean): List<OmnipodHistoryRecord>
fun findOmnipodHistoryRecordByPumpId(pumpId: Long): OmnipodHistoryRecord? fun findOmnipodHistoryRecordByPumpId(pumpId: Long): OmnipodHistoryRecord?
fun getTDDsForLastXDays(days: Int): List<TDD> fun getTDDsForLastXDays(days: Int): List<TDD>
fun getProfileSwitchData(from: Long, ascending: Boolean): List<ProfileSwitch> fun getProfileSwitchData(from: Long, ascending: Boolean): List<ProfileSwitch>
fun getExtendedBolusByPumpId(pumpId: Long): ExtendedBolus? fun getExtendedBolusByPumpId(pumpId: Long): ExtendedBolus?
fun getAllCareportalEvents(): List<CareportalEvent>
fun getAllExtendedBoluses(): List<ExtendedBolus>
fun getAllProfileSwitches(): List<ProfileSwitch>
fun getAllTDDs(): List<TDD>
fun getAllTemporaryBasals(): List<TemporaryBasal>
fun getAllOHQueueItems(maxEntries: Long): List<OHQueueItem>
fun resetCareportalEvents()
fun resetProfileSwitch()
// old DB model // old DB model
fun deleteTempBasalById(_id: String) fun deleteTempBasalById(_id: String)
@ -54,6 +72,11 @@ interface DatabaseHelperInterface {
fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset? fun getInsightHistoryOffset(pumpSerial: String): InsightHistoryOffset?
fun getPumpStoppedEvent(pumpSerial: String, before: Long): InsightPumpID? fun getPumpStoppedEvent(pumpSerial: String, before: Long): InsightPumpID?
fun getOHQueueSize(): Long
fun clearOpenHumansQueue()
fun getCountOfAllRows(): Long
fun removeAllOHQueueItemsWithIdSmallerThan(id: Long)
companion object { companion object {
const val DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets" const val DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets"