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

317 lines
12 KiB
Java
Raw Normal View History

2016-06-05 01:40:35 +02:00
package info.nightscout.androidaps.db;
import java.sql.SQLException;
2016-06-12 10:53:19 +02:00
import java.text.DecimalFormat;
2016-06-09 00:01:28 +02:00
import java.util.ArrayList;
2016-06-07 21:48:17 +02:00
import java.util.Date;
2016-06-05 01:40:35 +02:00
import java.util.List;
import android.content.Context;
import android.database.DatabaseUtils;
2016-06-05 01:40:35 +02:00
import android.database.sqlite.SQLiteDatabase;
2016-06-17 14:42:02 +02:00
import android.os.Parcel;
import android.os.Parcelable;
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;
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
2016-06-05 01:40:35 +02:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2016-06-19 13:17:16 +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;
2016-06-12 13:30:34 +02:00
import info.nightscout.androidaps.R;
2016-06-19 13:17:16 +02:00
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange;
2016-06-20 12:03:05 +02:00
import info.nightscout.utils.Round;
2016-06-07 21:48:17 +02:00
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-06-05 01:40:35 +02:00
2016-06-07 21:48:17 +02:00
private static final int DATABASE_VERSION = 1;
2016-06-05 01:40:35 +02:00
2016-06-07 21:48:17 +02:00
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
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");
TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
} catch (SQLException e) {
log.error(DatabaseHelper.class.getName(), "Can't create database", e);
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 {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempBasal.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
log.error(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
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();
}
public void cleanUpDatabases() {
// TODO: call it somewhere
log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "BgReadings"));
getWritableDatabase().delete("BgReadings", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null);
log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "BgReadings"));
log.debug("Before TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "TempBasals"));
getWritableDatabase().delete("TempBasals", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null);
log.debug("After TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "TempBasals"));
log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "Treatments"));
getWritableDatabase().delete("Treatments", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null);
log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "Treatments"));
}
2016-06-07 21:48:17 +02:00
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempBasal.class, true);
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempBasal.class);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
2016-06-19 13:17:16 +02:00
MainApp.bus().post(new EventNewBG());
MainApp.bus().post(new EventTreatmentChange());
MainApp.bus().post(new EventTempBasalChange());
2016-06-07 21:48:17 +02:00
} catch (SQLException e) {
e.printStackTrace();
}
}
public void resetTreatments() {
try {
TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
2016-06-05 01:40:35 +02:00
public Dao<TempBasal, Long> getDaoTempBasals() throws SQLException {
2016-06-07 21:48:17 +02:00
return getDao(TempBasal.class);
2016-06-05 01:40:35 +02:00
}
2016-06-07 21:48:17 +02:00
public Dao<Treatment, Long> getDaoTreatments() throws SQLException {
return getDao(Treatment.class);
}
public Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
//SQLiteDatabase db = getReadableDatabase();
//log.debug("BgReadings size: " + DatabaseUtils.queryNumEntries(db, "BgReadings"));
2016-06-07 21:48:17 +02:00
return getDao(BgReading.class);
}
/*
* Return last BgReading from database or null if db is empty
*/
2016-06-12 14:18:21 +02:00
@Nullable
2016-06-07 21:48:17 +02:00
public BgReading lastBg() {
List<BgReading> bgList = null;
try {
Dao<BgReading, Long> daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
QueryBuilder<BgReading, Long> queryBuilder = daoBgReadings.queryBuilder();
queryBuilder.orderBy("timeIndex", false);
queryBuilder.limit(1l);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) {
log.debug(e.getMessage(), e);
}
if (bgList.size() > 0)
return bgList.get(0);
else
return null;
}
2016-06-05 01:40:35 +02:00
2016-06-07 21:48:17 +02:00
/*
* Return bg reading if not old ( <9 min )
* or null if older
*/
2016-06-12 14:18:21 +02:00
@Nullable
2016-06-07 21:48:17 +02:00
public BgReading actualBg() {
BgReading lastBg = lastBg();
if (lastBg == null)
return null;
if (lastBg.timestamp > new Date().getTime() - 9 * 60 * 1000)
return lastBg;
return null;
}
2016-06-09 00:01:28 +02:00
2016-06-09 17:06:21 +02:00
public List<BgReading> getDataFromTime(long mills) {
2016-06-09 00:01:28 +02:00
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("timeIndex", false);
Where where = queryBuilder.where();
2016-06-09 17:06:21 +02:00
where.ge("timeIndex", (long) Math.ceil(mills / 60000d));
2016-06-09 00:01:28 +02:00
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<BgReading>();
}
2016-06-10 18:50:46 +02:00
/*
* Returns glucose_status for openAPS or null if no actual data available
*/
2016-06-17 14:42:02 +02:00
public static class GlucoseStatus implements Parcelable {
2016-06-10 18:50:46 +02:00
public double glucose = 0d;
public double delta = 0d;
public double avgdelta = 0d;
2016-06-12 10:53:19 +02:00
@Override
public String toString() {
2016-06-12 13:30:34 +02:00
Context context = MainApp.instance().getApplicationContext();
2016-06-12 10:53:19 +02:00
DecimalFormat formatNumber0decimalplaces = new DecimalFormat("0");
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
2016-06-12 13:30:34 +02:00
return context.getString(R.string.glucose) + " " + formatNumber0decimalplaces.format(glucose) + "\n" +
context.getString(R.string.delta) + " " + formatNumber0decimalplaces.format(delta) + "\n" +
context.getString(R.string.avgdelta) + " " + formatNumber2decimalplaces.format(avgdelta);
2016-06-12 10:53:19 +02:00
}
2016-06-17 14:42:02 +02:00
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(avgdelta);
dest.writeDouble(delta);
dest.writeDouble(glucose);
}
public final Parcelable.Creator<GlucoseStatus> CREATOR = new Parcelable.Creator<GlucoseStatus>() {
public GlucoseStatus createFromParcel(Parcel in) {
return new GlucoseStatus(in);
}
public GlucoseStatus[] newArray(int size) {
return new GlucoseStatus[size];
}
};
private GlucoseStatus(Parcel in) {
avgdelta = in.readDouble();
delta = in.readDouble();
glucose = in.readDouble();
}
public GlucoseStatus() {}
2016-06-19 13:17:16 +02:00
public GlucoseStatus(Double glucose, Double delta, Double avgdelta) {
this.glucose = glucose;
this.delta = delta;
this.avgdelta = avgdelta;
}
2016-06-20 12:03:05 +02:00
public GlucoseStatus round() {
this.glucose = Round.roundTo(this.glucose, 0.1);
this.delta = Round.roundTo(this.delta, 0.01);
this.avgdelta = Round.roundTo(this.avgdelta, 0.01);
return this;
}
2016-06-10 18:50:46 +02:00
}
2016-06-12 14:18:21 +02:00
@Nullable
2016-06-10 18:50:46 +02:00
public GlucoseStatus getGlucoseStatusData() {
GlucoseStatus result = new GlucoseStatus();
try {
Dao<BgReading, Long> daoBgreadings = null;
daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("timeIndex", false);
queryBuilder.limit(4l);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
int sizeRecords = bgReadings.size();
2016-06-19 13:17:16 +02:00
if (sizeRecords < 4 || bgReadings.get(sizeRecords - 4).timestamp < new Date().getTime() - 7 * 60 * 1000l) {
if (Config.fakeGlucoseData) {
return new GlucoseStatus(Math.random() * 400, (Math. random() - 0.5)* 18, (Math. random() - 0.5)* 18);
}
2016-06-10 18:50:46 +02:00
return null;
2016-06-19 13:17:16 +02:00
}
2016-06-10 18:50:46 +02:00
int minutes = 5;
double change;
double avg;
if (bgReadings.size() > 3) {
2016-06-11 22:46:47 +02:00
BgReading now = bgReadings.get(sizeRecords - 4);
BgReading last = bgReadings.get(sizeRecords - 3);
BgReading last1 = bgReadings.get(sizeRecords - 2);
BgReading last2 = bgReadings.get(sizeRecords - 1);
2016-06-10 18:50:46 +02:00
if (last2.value > 30) {
minutes = 3 * 5;
change = now.value - last2.value;
} else if (last1.value > 30) {
minutes = 2 * 5;
change = now.value - last1.value;
} else if (last.value > 30) {
minutes = 5;
change = now.value - last.value;
} else {
change = 0;
}
//multiply by 5 to get the same unit as delta, i.e. mg/dL/5m
avg = change / minutes * 5;
result.glucose = now.value;
2016-06-11 22:46:47 +02:00
result.delta = now.value - last.value;
2016-06-10 18:50:46 +02:00
result.avgdelta = avg;
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
2016-06-20 12:03:05 +02:00
result.round();
2016-06-10 18:50:46 +02:00
return result;
}
2016-06-05 01:40:35 +02:00
}