AndroidAPS/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java

1557 lines
65 KiB
Java
Raw Normal View History

2016-06-05 01:40:35 +02:00
package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
2016-06-05 01:40:35 +02:00
import android.database.sqlite.SQLiteDatabase;
2016-06-12 14:18:21 +02:00
import android.support.annotation.Nullable;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
2017-05-22 12:52:19 +02:00
import com.j256.ormlite.dao.CloseableIterator;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.dao.Dao;
2016-06-07 21:48:17 +02:00
import com.j256.ormlite.stmt.PreparedQuery;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.stmt.QueryBuilder;
2016-06-09 00:01:28 +02:00
import com.j256.ormlite.stmt.Where;
2016-06-05 01:40:35 +02:00
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
2016-06-07 21:48:17 +02:00
2017-05-22 12:52:19 +02:00
import org.json.JSONException;
import org.json.JSONObject;
2016-06-05 01:40:35 +02:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2016-07-11 18:07:54 +02:00
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
2016-07-11 18:07:54 +02:00
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
2016-06-07 21:48:17 +02:00
import info.nightscout.androidaps.MainApp;
2018-06-23 21:16:08 +02:00
import info.nightscout.androidaps.data.OverlappingIntervals;
2017-06-02 12:27:21 +02:00
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
2017-05-25 20:18:29 +02:00
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
2017-05-22 12:52:19 +02:00
import info.nightscout.androidaps.events.EventNewBG;
2017-06-02 12:27:21 +02:00
import info.nightscout.androidaps.events.EventProfileSwitchChange;
2017-06-16 08:37:07 +02:00
import info.nightscout.androidaps.events.EventRefreshOverview;
2017-06-12 13:11:16 +02:00
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
2017-05-23 23:56:53 +02:00
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
2018-03-19 19:49:48 +01:00
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
2018-04-19 23:18:19 +02:00
import info.nightscout.utils.JsonHelper;
2018-01-21 13:37:38 +01:00
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter;
2018-03-15 22:17:42 +01:00
import info.nightscout.utils.ToastUtils;
2016-06-07 21:48:17 +02:00
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
* data-structure (and not the DB content) should be contained in here (meaning DDL and not SQL).
* <p>
* This class can safely be called from Services, but should not call Services to avoid circular dependencies.
* One major issue with this (right now) are the scheduled events, which are put into the service. Therefor all
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/
2016-06-05 01:40:35 +02:00
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
2016-06-07 21:48:17 +02:00
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
2016-06-05 01:40:35 +02:00
2016-06-07 21:48:17 +02:00
public static final String DATABASE_NAME = "AndroidAPSDb";
2016-07-21 15:10:42 +02:00
public static final String DATABASE_BGREADINGS = "BgReadings";
2017-05-21 22:05:03 +02:00
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
2017-01-13 22:36:47 +01:00
public static final String DATABASE_TEMPTARGETS = "TempTargets";
2016-07-21 15:10:42 +02:00
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
2017-02-24 13:02:44 +01:00
public static final String DATABASE_DBREQUESTS = "DBRequests";
2017-05-25 20:18:29 +02:00
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
2017-06-02 10:25:49 +02:00
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
2018-03-14 00:57:48 +01:00
public static final String DATABASE_TDDS = "TDDs";
2016-06-05 01:40:35 +02:00
2017-08-06 12:19:25 +02:00
private static final int DATABASE_VERSION = 8;
2016-06-05 01:40:35 +02:00
2018-04-05 09:39:18 +02:00
public static Long earliestDataChange = null;
2017-05-23 20:15:14 +02:00
private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledBgPost = null;
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemBasalsPost = null;
2017-05-23 23:56:53 +02:00
private static final ScheduledExecutorService tempTargetWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemTargetPost = null;
private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledExtendedBolusPost = null;
2017-05-25 20:18:29 +02:00
private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledCareportalEventPost = null;
2017-06-02 10:25:49 +02:00
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
2018-01-07 20:24:42 +01:00
private int oldVersion = 0;
private int newVersion = 0;
2017-09-24 22:47:18 +02:00
2016-06-07 21:48:17 +02:00
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
2017-01-14 00:37:35 +01:00
onCreate(getWritableDatabase(), getConnectionSource());
2017-06-08 18:15:17 +02:00
//onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1);
2016-06-07 21:48:17 +02:00
}
2016-06-05 01:40:35 +02:00
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
2016-06-07 21:48:17 +02:00
try {
log.info("onCreate");
2017-01-13 22:36:47 +01:00
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
2016-06-07 21:48:17 +02:00
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
2016-07-21 15:10:42 +02:00
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
2017-02-24 13:02:44 +01:00
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
2017-05-22 12:52:19 +02:00
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
2017-05-25 20:18:29 +02:00
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
2017-06-02 10:25:49 +02:00
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
2018-03-14 00:57:48 +01:00
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
2017-01-14 00:37:35 +01:00
log.error("Can't create database", e);
2016-06-07 21:48:17 +02:00
throw new RuntimeException(e);
}
2016-06-05 01:40:35 +02:00
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
2016-06-07 21:48:17 +02:00
try {
2018-01-07 20:24:42 +01:00
this.oldVersion = oldVersion;
this.newVersion = newVersion;
2017-08-06 12:19:25 +02:00
if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8");
} else {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
}
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
2017-01-14 00:37:35 +01:00
log.error("Can't drop databases", e);
2016-06-07 21:48:17 +02:00
throw new RuntimeException(e);
}
2016-06-05 01:40:35 +02:00
}
2018-01-07 20:24:42 +01:00
public int getOldVersion() {
return oldVersion;
}
public int getNewVersion() {
return newVersion;
}
2016-06-05 01:40:35 +02:00
/**
2016-06-07 21:48:17 +02:00
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
}
2017-05-22 12:52:19 +02:00
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
}
// --------------------- DB resets ---------------------
2016-06-07 21:48:17 +02:00
public void resetDatabases() {
try {
2017-01-13 22:36:47 +01:00
TableUtils.dropTable(connectionSource, TempTarget.class, true);
2016-06-07 21:48:17 +02:00
TableUtils.dropTable(connectionSource, BgReading.class, true);
2016-07-21 15:10:42 +02:00
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
2017-05-22 12:52:19 +02:00
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
2017-05-25 20:18:29 +02:00
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
2017-06-02 10:25:49 +02:00
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
2018-03-14 00:57:48 +01:00
TableUtils.dropTable(connectionSource, TDD.class, true);
2017-01-13 22:36:47 +01:00
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
2016-06-07 21:48:17 +02:00
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
2016-07-21 15:10:42 +02:00
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
2017-05-22 12:52:19 +02:00
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
2017-05-25 20:18:29 +02:00
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
2017-06-02 10:25:49 +02:00
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
2018-03-14 00:57:48 +01:00
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
2017-06-01 20:52:38 +02:00
updateEarliestDataChange(0);
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2016-06-07 21:48:17 +02:00
}
VirtualPumpPlugin.setFakingStatus(true);
scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange();
scheduleExtendedBolusChange();
2017-05-23 23:56:53 +02:00
scheduleTemporaryTargetChange();
2017-05-25 20:18:29 +02:00
scheduleCareportalEventChange();
2017-06-02 10:25:49 +02:00
scheduleProfileSwitchChange();
2017-05-30 22:44:26 +02:00
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
2017-06-16 08:37:07 +02:00
MainApp.bus().post(new EventRefreshOverview("resetDatabases"));
2017-05-30 22:44:26 +02:00
}
},
3000
);
2016-06-07 21:48:17 +02:00
}
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2016-06-07 21:48:17 +02:00
}
2017-05-23 23:56:53 +02:00
scheduleTemporaryTargetChange();
2016-06-07 21:48:17 +02:00
}
2016-06-05 01:40:35 +02:00
2017-05-22 12:52:19 +02:00
public void resetTemporaryBasals() {
try {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
2017-06-01 20:52:38 +02:00
updateEarliestDataChange(0);
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
VirtualPumpPlugin.setFakingStatus(false);
scheduleTemporaryBasalChange();
2017-05-22 12:52:19 +02:00
}
public void resetExtededBoluses() {
try {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
2017-06-01 20:52:38 +02:00
updateEarliestDataChange(0);
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
scheduleExtendedBolusChange();
2017-05-22 12:52:19 +02:00
}
2017-05-29 15:26:25 +02:00
public void resetCareportalEvents() {
2017-05-25 20:18:29 +02:00
try {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-25 20:18:29 +02:00
}
scheduleCareportalEventChange();
}
2017-06-02 12:27:21 +02:00
public void resetProfileSwitch() {
2017-06-02 10:25:49 +02:00
try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-02 10:25:49 +02:00
}
scheduleProfileSwitchChange();
}
2018-03-14 00:57:48 +01:00
public void resetTDDs() {
try {
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
2017-05-22 12:52:19 +02:00
// ------------------ getDao -------------------------------------------
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
2017-01-13 22:36:47 +01:00
return getDao(TempTarget.class);
2016-06-05 01:40:35 +02:00
}
2018-04-08 22:24:04 +02:00
private Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
2016-06-07 21:48:17 +02:00
return getDao(BgReading.class);
}
2017-05-22 12:52:19 +02:00
private Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
2016-07-21 15:10:42 +02:00
return getDao(DanaRHistoryRecord.class);
2016-07-08 00:17:02 +02:00
}
2018-03-14 00:57:48 +01:00
private Dao<TDD, String> getDaoTDD() throws SQLException {
return getDao(TDD.class);
}
2017-05-22 12:52:19 +02:00
private Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
2017-02-24 13:02:44 +01:00
return getDao(DbRequest.class);
}
private Dao<TemporaryBasal, Long> getDaoTemporaryBasal() throws SQLException {
2017-05-22 12:52:19 +02:00
return getDao(TemporaryBasal.class);
}
private Dao<ExtendedBolus, Long> getDaoExtendedBolus() throws SQLException {
2017-05-22 12:52:19 +02:00
return getDao(ExtendedBolus.class);
}
2017-05-25 20:18:29 +02:00
private Dao<CareportalEvent, Long> getDaoCareportalEvents() throws SQLException {
return getDao(CareportalEvent.class);
}
2017-06-02 10:25:49 +02:00
private Dao<ProfileSwitch, Long> getDaoProfileSwitch() throws SQLException {
return getDao(ProfileSwitch.class);
}
2018-04-05 09:39:18 +02:00
public static long roundDateToSec(long date) {
2017-06-06 17:14:17 +02:00
return date - date % 1000;
}
2017-05-22 12:52:19 +02:00
// ------------------- BgReading handling -----------------------
public boolean createIfNotExists(BgReading bgReading, String from) {
2017-05-22 12:52:19 +02:00
try {
2017-06-06 17:14:17 +02:00
bgReading.date = roundDateToSec(bgReading.date);
BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) {
getDaoBgReadings().create(bgReading);
log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(bgReading);
2017-11-29 23:00:41 +01:00
return true;
2017-06-06 17:14:17 +02:00
}
if (!old.isEqual(bgReading)) {
2017-11-29 17:22:45 +01:00
log.debug("BG: Similiar found: " + old.toString());
2017-06-06 17:14:17 +02:00
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
2017-11-29 17:22:45 +01:00
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(bgReading);
2017-11-29 23:00:41 +01:00
return false;
2017-06-06 17:14:17 +02:00
}
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
2017-11-29 23:00:41 +01:00
return false;
2017-05-23 20:15:14 +02:00
}
2017-12-15 01:03:31 +01:00
public void update(BgReading bgReading) {
bgReading.date = roundDateToSec(bgReading.date);
try {
getDaoBgReadings().update(bgReading);
} catch (SQLException e) {
2018-04-08 18:15:27 +02:00
log.error("Unhandled exception", e);
2017-12-15 01:03:31 +01:00
}
}
private static void scheduleBgChange(@Nullable final BgReading bgReading) {
2017-05-23 20:15:14 +02:00
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading));
2017-05-23 20:15:14 +02:00
scheduledBgPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledBgPost != null)
scheduledBgPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledBgPost = bgWorker.schedule(task, sec, TimeUnit.SECONDS);
2017-02-24 13:02:44 +01:00
}
2017-05-22 12:52:19 +02:00
/*
2018-04-08 22:24:04 +02:00
* Return last BgReading from database or null if db is empty
*/
2017-05-22 12:52:19 +02:00
@Nullable
public static BgReading lastBg() {
List<BgReading> bgList = null;
try {
Dao<BgReading, Long> daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
QueryBuilder<BgReading, Long> queryBuilder = daoBgReadings.queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(1L);
2017-12-15 01:03:31 +01:00
queryBuilder.where().gt("value", 38).and().eq("isValid", true);
2017-05-22 12:52:19 +02:00
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) {
log.debug(e.getMessage(), e);
}
if (bgList != null && bgList.size() > 0)
return bgList.get(0);
else
return null;
}
/*
2018-04-08 22:24:04 +02:00
* Return bg reading if not old ( <9 min )
* or null if older
*/
2017-05-22 12:52:19 +02:00
@Nullable
public static BgReading actualBg() {
BgReading lastBg = lastBg();
if (lastBg == null)
return null;
2017-06-15 23:12:12 +02:00
if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000)
2017-05-22 12:52:19 +02:00
return lastBg;
return null;
}
2017-01-09 10:57:15 +01:00
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
2016-06-09 00:01:28 +02:00
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
2017-05-21 22:05:03 +02:00
queryBuilder.orderBy("date", ascending);
2016-06-09 00:01:28 +02:00
Where where = queryBuilder.where();
2017-12-15 01:03:31 +01:00
where.ge("date", mills).and().gt("value", 38).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
2016-06-09 00:01:28 +02:00
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
2016-06-09 00:01:28 +02:00
}
return new ArrayList<BgReading>();
}
2018-03-15 22:17:42 +01:00
// ------------------- TDD handling -----------------------
2018-04-08 22:24:04 +02:00
public void createOrUpdateTDD(TDD tdd) {
2018-03-14 00:57:48 +01:00
try {
2018-03-15 22:17:42 +01:00
Dao<TDD, String> dao = getDaoTDD();
dao.createOrUpdate(tdd);
2018-03-14 00:57:48 +01:00
} catch (SQLException e) {
2018-03-15 22:17:42 +01:00
ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
2018-03-14 00:57:48 +01:00
log.error("Unhandled exception", e);
}
}
public List<TDD> getTDDs() {
List<TDD> tddList;
try {
QueryBuilder<TDD, String> queryBuilder = getDaoTDD().queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(10L);
PreparedQuery<TDD> preparedQuery = queryBuilder.prepare();
tddList = getDaoTDD().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
tddList = new ArrayList<>();
}
return tddList;
}
2017-05-22 12:52:19 +02:00
// ------------- DbRequests handling -------------------
2017-02-24 13:02:44 +01:00
public void create(DbRequest dbr) {
try {
getDaoDbRequest().create(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-02-24 13:02:44 +01:00
}
}
public int delete(DbRequest dbr) {
2017-02-24 13:02:44 +01:00
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-02-24 13:02:44 +01:00
}
return 0;
}
public int deleteDbRequest(String nsClientId) {
try {
return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-02-24 13:02:44 +01:00
}
return 0;
}
2018-01-23 21:43:48 +01:00
public void deleteDbRequestbyMongoId(String action, String id) {
2017-02-24 13:02:44 +01:00
try {
QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", id).and().eq("action", action);
queryBuilder.limit(10L);
PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
2018-01-23 21:43:48 +01:00
for (DbRequest r : dbList) {
delete(r);
2017-02-24 13:02:44 +01:00
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-02-24 13:02:44 +01:00
}
}
public void deleteAllDbRequests() {
try {
TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-02-24 13:02:44 +01:00
}
}
2017-05-22 12:52:19 +02:00
public CloseableIterator getDbRequestInterator() {
try {
return getDaoDbRequest().closeableIterator();
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
return null;
}
}
// -------------------- TREATMENT HANDLING -------------------
2018-04-05 09:39:18 +02:00
public static void updateEarliestDataChange(long newDate) {
2017-06-01 20:52:38 +02:00
if (earliestDataChange == null) {
earliestDataChange = newDate;
2017-05-29 15:26:25 +02:00
return;
}
2017-06-01 20:52:38 +02:00
if (newDate < earliestDataChange) {
earliestDataChange = newDate;
2017-05-29 15:26:25 +02:00
}
}
2017-05-22 12:52:19 +02:00
// ---------------- TempTargets handling ---------------
2017-01-13 23:43:17 +01:00
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
2017-05-21 22:05:03 +02:00
queryBuilder.orderBy("date", ascending);
2017-01-13 23:43:17 +01:00
Where where = queryBuilder.where();
2017-05-21 22:05:03 +02:00
where.ge("date", mills);
2017-01-13 23:43:17 +01:00
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-01-13 23:43:17 +01:00
}
return new ArrayList<TempTarget>();
}
2017-06-08 19:34:46 +02:00
public boolean createOrUpdate(TempTarget tempTarget) {
2017-05-22 12:52:19 +02:00
try {
2017-06-08 19:34:46 +02:00
TempTarget old;
tempTarget.date = roundDateToSec(tempTarget.date);
if (tempTarget.source == Source.NIGHTSCOUT) {
old = getDaoTempTargets().queryForId(tempTarget.date);
if (old != null) {
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
return false;
}
// find by NS _id
if (tempTarget._id != null) {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempTarget._id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> trList = getDaoTempTargets().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
}
}
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
2017-06-08 19:34:46 +02:00
return false;
2017-05-22 12:52:19 +02:00
}
2016-06-17 14:42:02 +02:00
2017-05-22 12:52:19 +02:00
public void delete(TempTarget tempTarget) {
2017-01-09 10:57:15 +01:00
try {
2017-05-22 12:52:19 +02:00
getDaoTempTargets().delete(tempTarget);
2017-05-23 23:56:53 +02:00
scheduleTemporaryTargetChange();
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
}
2017-06-02 10:25:49 +02:00
private static void scheduleTemporaryTargetChange() {
2017-05-23 23:56:53 +02:00
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempTargetChange");
2017-05-23 23:56:53 +02:00
MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemTargetPost != null)
scheduledTemTargetPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemTargetPost = tempTargetWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "58795998aa86647ba4d68ce7",
"enteredBy": "",
"eventType": "Temporary Target",
"reason": "Eating Soon",
"targetTop": 80,
"targetBottom": 80,
"duration": 120,
"created_at": "2017-01-13T22:50:00.782Z",
"carbs": null,
"insulin": null
}
*/
2017-05-23 20:15:14 +02:00
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
2017-05-22 12:52:19 +02:00
try {
2018-04-19 23:18:19 +02:00
String units = JsonHelper.safeGetString(trJson, "units", MainApp.getConfigBuilder().getProfileUnits());
TempTarget tempTarget = new TempTarget()
2018-03-26 22:55:38 +02:00
.date(trJson.getLong("mills"))
.duration(trJson.getInt("duration"))
2018-04-19 23:18:19 +02:00
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
2018-03-26 22:55:38 +02:00
.reason(trJson.getString("reason"))
._id(trJson.getString("_id"))
.source(Source.NIGHTSCOUT);
createOrUpdate(tempTarget);
2017-06-08 19:34:46 +02:00
} catch (JSONException e) {
2018-07-22 21:14:42 +02:00
log.error("Unhandled exception: " + trJson.toString(), e);
2017-05-22 12:52:19 +02:00
}
}
public void deleteTempTargetById(String _id) {
2017-06-08 19:34:46 +02:00
TempTarget stored = findTempTargetById(_id);
if (stored != null) {
log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public TempTarget findTempTargetById(String _id) {
2017-05-22 12:52:19 +02:00
try {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
2017-05-22 12:52:19 +02:00
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> list = getDaoTempTargets().query(preparedQuery);
if (list.size() == 1) {
2017-06-08 19:34:46 +02:00
return list.get(0);
2017-05-22 12:52:19 +02:00
} else {
2017-06-08 19:34:46 +02:00
return null;
2017-05-22 12:52:19 +02:00
}
2017-01-09 10:57:15 +01:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-01-09 10:57:15 +01:00
}
2017-06-08 19:34:46 +02:00
return null;
2017-01-09 10:57:15 +01:00
}
2017-05-22 12:52:19 +02:00
// ----------------- DanaRHistory handling --------------------
public void createOrUpdate(DanaRHistoryRecord record) {
2017-05-22 12:52:19 +02:00
try {
getDaoDanaRHistory().createOrUpdate(record);
2018-03-19 19:49:48 +01:00
//If it is a TDD, store it for stats also.
2018-04-08 22:24:04 +02:00
if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) {
2018-03-19 19:49:48 +01:00
createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
}
2017-05-22 12:52:19 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
}
}
public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
List<DanaRHistoryRecord> historyList;
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
queryBuilder.orderBy("recordDate", false);
Where where = queryBuilder.where();
where.eq("recordCode", type);
queryBuilder.limit(200L);
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
historyList = getDaoDanaRHistory().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-22 12:52:19 +02:00
historyList = new ArrayList<>();
}
return historyList;
}
public void updateDanaRHistoryRecordId(JSONObject trJson) {
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
Where where = queryBuilder.where();
where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
if (list.size() == 0) {
// Record does not exists. Ignore
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (Config.logIncommingData)
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
} else {
// already set
}
}
2017-06-02 10:25:49 +02:00
} catch (SQLException | JSONException e) {
2018-07-22 21:14:42 +02:00
log.error("Unhandled exception: " + trJson.toString(), e);
2017-05-22 12:52:19 +02:00
}
}
// ------------ TemporaryBasal handling ---------------
2017-06-08 18:15:17 +02:00
//return true if new record was created
public boolean createOrUpdate(TemporaryBasal tempBasal) {
try {
2017-06-08 18:15:17 +02:00
TemporaryBasal old;
tempBasal.date = roundDateToSec(tempBasal.date);
if (tempBasal.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", tempBasal.pumpId);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.NIGHTSCOUT) {
old = getDaoTemporaryBasal().queryForId(tempBasal.date);
if (old != null) {
2017-08-08 15:06:31 +02:00
if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
// so far ignore, do not convert back because it may not be accurate
return false;
}
2017-06-08 18:15:17 +02:00
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
return false;
}
// find by NS _id
if (tempBasal._id != null) {
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempBasal._id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
}
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
2017-06-08 18:15:17 +02:00
return false;
}
public void delete(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().delete(tempBasal);
2017-06-01 20:52:38 +02:00
updateEarliestDataChange(tempBasal.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
2017-06-02 10:25:49 +02:00
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempBasalChange");
MainApp.bus().post(new EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange());
2017-06-01 20:52:38 +02:00
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
}
2017-05-22 22:10:56 +02:00
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
2017-05-22 22:10:56 +02:00
final int sec = 1;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "59232e1ddd032d04218dab00",
"eventType": "Temp Basal",
"duration": 60,
"percent": -50,
"created_at": "2017-05-22T18:29:57Z",
"enteredBy": "AndroidAPS",
"notes": "Basal Temp Start 50% 60.0 min",
"NSCLIENT_ID": 1495477797863,
"mills": 1495477797000,
"mgdl": 194.5,
"endmills": 1495481397000
}
*/
2017-05-23 20:15:14 +02:00
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
2017-06-08 18:15:17 +02:00
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
2017-06-08 18:15:17 +02:00
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = trJson.getInt("duration");
extendedBolus.insulin = trJson.getDouble("originalExtendedAmount");
extendedBolus._id = trJson.getString("_id");
if (!VirtualPumpPlugin.getFakingStatus()) {
VirtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
2017-06-08 18:15:17 +02:00
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
2017-06-08 18:15:17 +02:00
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
if (!VirtualPumpPlugin.getFakingStatus()) {
VirtualPumpPlugin.setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
2017-05-23 20:15:14 +02:00
} else {
TemporaryBasal tempBasal = new TemporaryBasal()
.date(trJson.getLong("mills"))
.source(Source.NIGHTSCOUT)
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
if (trJson.has("percent")) {
tempBasal.percentRate = trJson.getInt("percent") + 100;
tempBasal.isAbsolute = false;
}
if (trJson.has("absolute")) {
tempBasal.absoluteRate = trJson.getDouble("absolute");
tempBasal.isAbsolute = true;
}
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
2017-05-23 20:15:14 +02:00
}
2017-06-08 18:15:17 +02:00
} catch (JSONException e) {
2018-07-22 21:14:42 +02:00
log.error("Unhandled exception: " + trJson.toString(), e);
2017-05-23 20:15:14 +02:00
}
}
public void deleteTempBasalById(String _id) {
2017-06-08 18:15:17 +02:00
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
}
}
public TemporaryBasal findTempBasalById(String _id) {
2017-05-23 20:15:14 +02:00
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
2017-06-08 18:15:17 +02:00
if (list.size() != 1) {
return null;
2017-05-23 20:15:14 +02:00
} else {
2017-06-08 18:15:17 +02:00
return list.get(0);
2017-05-23 20:15:14 +02:00
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-23 20:15:14 +02:00
}
2017-06-08 18:15:17 +02:00
return null;
2017-05-23 20:15:14 +02:00
}
// ------------ ExtendedBolus handling ---------------
2017-06-08 18:15:17 +02:00
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try {
2017-06-08 18:15:17 +02:00
ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
return false;
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
2017-06-08 18:15:17 +02:00
return true;
}
if (extendedBolus.source == Source.NIGHTSCOUT) {
old = getDaoExtendedBolus().queryForId(extendedBolus.date);
if (old != null) {
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
2017-06-08 18:15:17 +02:00
return true;
}
return false;
}
// find by NS _id
if (extendedBolus._id != null) {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", extendedBolus._id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
2017-06-08 18:15:17 +02:00
return true;
}
}
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
2017-06-08 18:15:17 +02:00
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
2017-06-08 18:15:17 +02:00
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
2017-06-08 18:15:17 +02:00
return false;
}
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
2017-06-01 20:52:38 +02:00
updateEarliestDataChange(extendedBolus.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
2017-06-08 19:34:46 +02:00
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
2017-05-30 22:44:26 +02:00
}
}
2017-08-07 16:13:09 +02:00
2017-06-08 19:34:46 +02:00
public ExtendedBolus findExtendedBolusById(String _id) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
if (list.size() == 1) {
2017-06-08 19:34:46 +02:00
return list.get(0);
} else {
2017-06-08 19:34:46 +02:00
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
2017-06-08 19:34:46 +02:00
return null;
}
/*
{
"_id": "5924898d577eb0880e355337",
"eventType": "Combo Bolus",
"duration": 120,
"splitNow": 0,
"splitExt": 100,
"enteredinsulin": 1,
"relative": 1,
"created_at": "2017-05-23T19:12:14Z",
"enteredBy": "AndroidAPS",
"NSCLIENT_ID": 1495566734628,
"mills": 1495566734000,
"mgdl": 106
}
*/
2018-04-08 22:24:04 +02:00
public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(json);
if (extendedBolus != null)
createOrUpdate(extendedBolus);
}
2017-06-02 10:25:49 +02:00
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventExtendedBolusChange");
2017-10-04 18:04:34 +02:00
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
2017-06-01 20:52:38 +02:00
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
}
2017-05-22 22:10:56 +02:00
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
2017-05-22 22:10:56 +02:00
final int sec = 1;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
2017-05-22 12:52:19 +02:00
2017-05-25 20:18:29 +02:00
// ------------ CareportalEvent handling ---------------
public void createOrUpdate(CareportalEvent careportalEvent) {
careportalEvent.date = careportalEvent.date - careportalEvent.date % 1000;
try {
getDaoCareportalEvents().createOrUpdate(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-25 20:18:29 +02:00
}
scheduleCareportalEventChange();
}
public void delete(CareportalEvent careportalEvent) {
try {
getDaoCareportalEvents().delete(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-25 20:18:29 +02:00
}
scheduleCareportalEventChange();
}
2018-04-08 17:22:53 +02:00
public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
try {
return getDaoCareportalEvents().queryForId(timestamp);
} catch (SQLException e) {
2018-04-08 18:15:27 +02:00
log.error("Unhandled exception", e);
2018-04-08 17:22:53 +02:00
}
return null;
}
2017-05-25 20:18:29 +02:00
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", false);
Where where = queryBuilder.where();
where.eq("eventType", event);
queryBuilder.limit(1L);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
if (careportalEvents.size() == 1)
return careportalEvents.get(0);
else
return null;
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-25 20:18:29 +02:00
}
return null;
}
2017-06-06 08:21:11 +02:00
public List<CareportalEvent> getCareportalEventsFromTime(long mills, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
2018-06-23 21:16:08 +02:00
preprocessOpenAPSOfflineEvents(careportalEvents);
2017-06-06 08:21:11 +02:00
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-06 08:21:11 +02:00
}
2018-01-22 21:49:01 +01:00
return new ArrayList<>();
}
2018-06-23 21:16:08 +02:00
public void preprocessOpenAPSOfflineEvents(List<CareportalEvent> list) {
OverlappingIntervals offlineEvents = new OverlappingIntervals();
for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i);
if (!event.eventType.equals(CareportalEvent.OPENAPSOFFLINE)) continue;
offlineEvents.add(event);
}
}
2018-06-22 20:05:49 +02:00
public List<CareportalEvent> getCareportalEventsFromTime(long mills, String type, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().eq("eventType", type);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
2018-06-23 21:16:08 +02:00
preprocessOpenAPSOfflineEvents(careportalEvents);
2018-06-22 20:05:49 +02:00
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<CareportalEvent> getCareportalEvents(boolean ascending) {
2018-01-22 21:49:01 +01:00
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
2018-06-23 21:16:08 +02:00
preprocessOpenAPSOfflineEvents(careportalEvents);
2018-01-22 21:49:01 +01:00
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
2017-06-06 08:21:11 +02:00
}
2017-05-25 20:18:29 +02:00
public void deleteCareportalEventById(String _id) {
try {
2018-04-05 09:39:18 +02:00
QueryBuilder<CareportalEvent, Long> queryBuilder;
2017-05-25 20:18:29 +02:00
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
if (list.size() == 1) {
CareportalEvent record = list.get(0);
if (Config.logIncommingData)
log.debug("Removing CareportalEvent record from database: " + record.log());
2017-05-29 15:26:25 +02:00
delete(record);
2017-05-25 20:18:29 +02:00
} else {
if (Config.logIncommingData)
log.debug("CareportalEvent not found database: " + _id);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-05-25 20:18:29 +02:00
}
}
public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
try {
2018-04-05 09:39:18 +02:00
QueryBuilder<CareportalEvent, Long> queryBuilder;
2017-05-25 20:18:29 +02:00
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
CareportalEvent careportalEvent;
if (list.size() == 0) {
careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT;
if (Config.logIncommingData)
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
careportalEvent = list.get(0);
if (Config.logIncommingData)
log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
careportalEvent.date = trJson.getLong("mills");
careportalEvent.eventType = trJson.getString("eventType");
careportalEvent.json = trJson.toString();
careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent);
2017-06-02 10:25:49 +02:00
} catch (SQLException | JSONException e) {
2018-07-22 21:14:42 +02:00
log.error("Unhandled exception: " + trJson.toString(), e);
2017-05-25 20:18:29 +02:00
}
}
2017-06-02 10:25:49 +02:00
private static void scheduleCareportalEventChange() {
2017-05-25 20:18:29 +02:00
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing scheduleCareportalEventChange");
2017-05-25 20:18:29 +02:00
MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledCareportalEventPost != null)
scheduledCareportalEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledCareportalEventPost = careportalEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
2017-06-02 10:25:49 +02:00
// ---------------- ProfileSwitch handling ---------------
2017-06-02 12:27:21 +02:00
public List<ProfileSwitch> getProfileSwitchData(boolean ascending) {
2017-06-02 10:25:49 +02:00
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
2017-06-02 10:25:49 +02:00
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-02 10:25:49 +02:00
}
return new ArrayList<>();
2017-06-02 10:25:49 +02:00
}
2017-06-08 20:52:33 +02:00
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
2017-06-02 10:25:49 +02:00
try {
2017-06-08 20:52:33 +02:00
ProfileSwitch old;
profileSwitch.date = roundDateToSec(profileSwitch.date);
if (profileSwitch.source == Source.NIGHTSCOUT) {
old = getDaoProfileSwitch().queryForId(profileSwitch.date);
if (old != null) {
if (!old.isEqual(profileSwitch)) {
profileSwitch.source = old.source;
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
2017-06-08 20:52:33 +02:00
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch);
2017-06-08 20:52:33 +02:00
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
2017-06-12 13:11:16 +02:00
scheduleProfileSwitchChange();
2017-06-08 20:52:33 +02:00
return true;
}
return false;
}
// find by NS _id
if (profileSwitch._id != null) {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", profileSwitch._id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> trList = getDaoProfileSwitch().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(profileSwitch)) {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old);
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
2017-06-12 13:11:16 +02:00
scheduleProfileSwitchChange();
2017-06-08 20:52:33 +02:00
return true;
}
}
}
// look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
2017-06-08 20:52:33 +02:00
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
2017-06-12 13:11:16 +02:00
scheduleProfileSwitchChange();
2017-06-08 20:52:33 +02:00
return true;
}
if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
2017-06-12 13:11:16 +02:00
scheduleProfileSwitchChange();
2017-06-08 20:52:33 +02:00
return true;
}
2017-06-02 10:25:49 +02:00
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-02 10:25:49 +02:00
}
2017-06-08 20:52:33 +02:00
return false;
2017-06-02 10:25:49 +02:00
}
public void delete(ProfileSwitch profileSwitch) {
try {
getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-02 10:25:49 +02:00
}
}
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
2017-06-02 12:27:21 +02:00
log.debug("Firing EventProfileSwitchChange");
2017-06-12 13:11:16 +02:00
MainApp.bus().post(new EventReloadProfileSwitchData());
2017-06-02 12:27:21 +02:00
MainApp.bus().post(new EventProfileSwitchChange());
2017-06-02 10:25:49 +02:00
scheduledProfileSwitchEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledProfileSwitchEventPost != null)
scheduledProfileSwitchEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id":"592fa43ed97496a80da913d2",
"created_at":"2017-06-01T05:20:06Z",
"eventType":"Profile Switch",
"profile":"2016 +30%",
"units":"mmol",
"enteredBy":"sony",
"NSCLIENT_ID":1496294454309,
2016-06-05 01:40:35 +02:00
}
2017-06-02 10:25:49 +02:00
*/
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
2017-06-08 20:52:33 +02:00
ProfileSwitch profileSwitch = new ProfileSwitch();
2017-06-02 10:25:49 +02:00
profileSwitch.date = trJson.getLong("mills");
2017-06-02 23:59:34 +02:00
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
2017-06-02 10:25:49 +02:00
profileSwitch._id = trJson.getString("_id");
profileSwitch.profileName = trJson.getString("profile");
profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
2017-06-08 20:52:33 +02:00
profileSwitch.source = Source.NIGHTSCOUT;
2017-06-02 10:25:49 +02:00
if (trJson.has("timeshift"))
profileSwitch.timeshift = trJson.getInt("timeshift");
if (trJson.has("percentage"))
2017-06-02 12:27:21 +02:00
profileSwitch.percentage = trJson.getInt("percentage");
2017-06-02 10:25:49 +02:00
if (trJson.has("profileJson"))
2017-06-02 12:27:21 +02:00
profileSwitch.profileJson = trJson.getString("profileJson");
else {
2018-03-17 23:18:34 +01:00
ProfileStore store = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
2018-06-20 23:56:38 +02:00
if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
2018-06-20 23:56:38 +02:00
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
}
2017-06-02 10:25:49 +02:00
if (trJson.has("profilePlugin"))
2017-06-02 12:27:21 +02:00
profileSwitch.profilePlugin = trJson.getString("profilePlugin");
2017-06-02 10:25:49 +02:00
createOrUpdate(profileSwitch);
2017-06-08 20:52:33 +02:00
} catch (JSONException e) {
2018-07-22 21:14:42 +02:00
log.error("Unhandled exception: " + trJson.toString(), e);
2017-06-02 10:25:49 +02:00
}
}
public void deleteProfileSwitchById(String _id) {
2017-06-08 20:52:33 +02:00
ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) {
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public ProfileSwitch findProfileSwitchById(String _id) {
2017-06-02 10:25:49 +02:00
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
if (list.size() == 1) {
2017-06-08 20:52:33 +02:00
return list.get(0);
2017-06-02 10:25:49 +02:00
} else {
2017-06-08 20:52:33 +02:00
return null;
2017-06-02 10:25:49 +02:00
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
2017-06-02 10:25:49 +02:00
}
2017-06-08 20:52:33 +02:00
return null;
2017-06-02 10:25:49 +02:00
}
2017-09-24 22:47:18 +02:00
// ---------------- Food handling ---------------
}