diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index 1c590c2dac..100a452ede 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -6,7 +6,6 @@ import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Telephony; -import android.support.annotation.Nullable; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.stmt.PreparedQuery; @@ -33,7 +32,6 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; -import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; @@ -53,7 +51,6 @@ import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTarget import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSSgv; -import info.nightscout.utils.ToastUtils; public class DataService extends IntentService { @@ -388,7 +385,7 @@ public class DataService extends IntentService { String trstring = bundles.getString("treatment"); JSONObject trJson = new JSONObject(trstring); String _id = trJson.getString("_id"); - removeTreatmentFromDb(_id); + MainApp.getDbHelper().delete(_id); handleRemoveTempTargetRecord(trJson); } @@ -398,7 +395,7 @@ public class DataService extends IntentService { for (int i = 0; i < jsonArray.length(); i++) { JSONObject trJson = jsonArray.getJSONObject(i); String _id = trJson.getString("_id"); - removeTreatmentFromDb(_id); + MainApp.getDbHelper().delete(_id); handleRemoveTempTargetRecord(trJson); } } @@ -468,9 +465,9 @@ public class DataService extends IntentService { if (trJson.has("timeIndex")) { if (Config.logIncommingData) log.debug("ADD: timeIndex found: " + trstring); - stored = findByTimeIndex(trJson.getLong("timeIndex")); + stored = MainApp.getDbHelper().findTreatmentByTimeIndex(trJson.getLong("timeIndex")); } else { - stored = findById(_id); + stored = MainApp.getDbHelper().findTreatmentById(_id); } if (stored != null) { @@ -478,10 +475,9 @@ public class DataService extends IntentService { log.debug("ADD: Existing treatment: " + trstring); if (trJson.has("timeIndex")) { stored._id = _id; - int updated = MainApp.getDbHelper().getDaoTreatments().update(stored); + int updated = MainApp.getDbHelper().update(stored); if (Config.logIncommingData) log.debug("Records updated: " + updated); - scheduleTreatmentChange(); } } else { if (Config.logIncommingData) @@ -506,14 +502,9 @@ public class DataService extends IntentService { treatment.mealBolus = false; } treatment.setTimeIndex(treatment.getTimeIndex()); - try { - MainApp.getDbHelper().getDaoTreatments().createOrUpdate(treatment); - if (Config.logIncommingData) - log.debug("ADD: Stored treatment: " + treatment.log()); - } catch (SQLException e) { - e.printStackTrace(); - } - scheduleTreatmentChange(); + MainApp.getDbHelper().createOrUpdate(treatment); + if (Config.logIncommingData) + log.debug("ADD: Stored treatment: " + treatment.log()); } } @@ -533,15 +524,15 @@ public class DataService extends IntentService { if (trJson.has("timeIndex")) { if (Config.logIncommingData) log.debug("ADD: timeIndex found: " + trstring); - stored = findByTimeIndex(trJson.getLong("timeIndex")); + stored = MainApp.getDbHelper().findTreatmentByTimeIndex(trJson.getLong("timeIndex")); } else { - stored = findById(_id); + stored = MainApp.getDbHelper().findTreatmentById(_id); } if (stored != null) { if (Config.logIncommingData) log.debug("CHANGE: Removing old: " + trstring); - removeTreatmentFromDb(_id); + MainApp.getDbHelper().delete(_id); } if (Config.logIncommingData) @@ -567,16 +558,11 @@ public class DataService extends IntentService { treatment.mealBolus = false; } treatment.setTimeIndex(treatment.getTimeIndex()); - try { - Dao.CreateOrUpdateStatus status = MainApp.getDbHelper().getDaoTreatments().createOrUpdate(treatment); - if (Config.logIncommingData) - log.debug("Records updated: " + status.getNumLinesChanged()); - if (Config.logIncommingData) - log.debug("CHANGE: Stored treatment: " + treatment.log()); - } catch (SQLException e) { - e.printStackTrace(); - } - scheduleTreatmentChange(); + Dao.CreateOrUpdateStatus status = MainApp.getDbHelper().createOrUpdate(treatment); + if (Config.logIncommingData) + log.debug("Records updated: " + status.getNumLinesChanged()); + if (Config.logIncommingData) + log.debug("CHANGE: Stored treatment: " + treatment.log()); } public void handleDanaRHistoryRecords(JSONObject trJson) throws JSONException, SQLException { @@ -683,75 +669,10 @@ public class DataService extends IntentService { } } - @Nullable - public static Treatment findById(String _id) { - try { - Dao daoTreatments = MainApp.getDbHelper().getDaoTreatments(); - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", _id); - queryBuilder.limit(10); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = daoTreatments.query(preparedQuery); - if (trList.size() != 1) { - //log.debug("Treatment findById query size: " + trList.size()); - return null; - } else { - //log.debug("Treatment findById found: " + trList.get(0).log()); - return trList.get(0); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - @Nullable - public static Treatment findByTimeIndex(Long timeIndex) { - try { - QueryBuilder qb = null; - Dao daoTreatments = MainApp.getDbHelper().getDaoTreatments(); - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("timeIndex", timeIndex); - queryBuilder.limit(10); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = daoTreatments.query(preparedQuery); - if (trList.size() != 1) { - log.debug("Treatment findByTimeIndex query size: " + trList.size()); - return null; - } else { - log.debug("Treatment findByTimeIndex found: " + trList.get(0).log()); - return trList.get(0); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - private void removeTreatmentFromDb(String _id) throws SQLException { - Treatment stored = findById(_id); - if (stored != null) { - log.debug("REMOVE: Existing treatment (removing): " + _id); - int removed = MainApp.getDbHelper().getDaoTreatments().delete(stored); - if (Config.logIncommingData) - log.debug("Records removed: " + removed); - scheduleTreatmentChange(); - } else { - log.debug("REMOVE: Not stored treatment (ignoring): " + _id); - } - } - private void handleNewSMS(Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; MainApp.bus().post(new EventNewSMS(bundle)); } - public void scheduleTreatmentChange() { - MainApp.bus().post(new EventTreatmentChange()); - } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index abf843460e..923e29f0de 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -20,10 +20,15 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.GlucoseStatus; +import info.nightscout.androidaps.events.EventTreatmentChange; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class); @@ -37,6 +42,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final int DATABASE_VERSION = 5; + private long latestTreatmentChange = 0; + + private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); + private static ScheduledFuture scheduledPost = null; + public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); onCreate(getWritableDatabase(), getConnectionSource()); @@ -117,6 +127,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); + latestTreatmentChange = 0; } catch (SQLException e) { e.printStackTrace(); } @@ -126,6 +137,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { TableUtils.dropTable(connectionSource, Treatment.class, true); TableUtils.createTableIfNotExists(connectionSource, Treatment.class); + latestTreatmentChange = 0; } catch (SQLException e) { e.printStackTrace(); } @@ -148,7 +160,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(TempTarget.class); } - public Dao getDaoTreatments() throws SQLException { + private Dao getDaoTreatments() throws SQLException { return getDao(Treatment.class); } @@ -168,7 +180,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List bgList = null; try { - Dao daoBgReadings = MainApp.getDbHelper().getDaoBgReadings(); + Dao daoBgReadings = getDaoBgReadings(); QueryBuilder queryBuilder = daoBgReadings.queryBuilder(); queryBuilder.orderBy("timeIndex", false); queryBuilder.limit(1L); @@ -219,6 +231,131 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } + // TREATMENT HANDLING + + public boolean isDataUnchanged(long time) { + if (time >= latestTreatmentChange) return true; + else return false; + } + + public int update(Treatment treatment) { + int updated = 0; + try { + updated = getDaoTreatments().update(treatment); + latestTreatmentChange = treatment.getTimeIndex(); + } catch (SQLException e) { + e.printStackTrace(); + } + scheduleTreatmentChange(); + return updated; + } + + public Dao.CreateOrUpdateStatus createOrUpdate(Treatment treatment) { + Dao.CreateOrUpdateStatus status = null; + try { + status = getDaoTreatments().createOrUpdate(treatment); + latestTreatmentChange = treatment.getTimeIndex(); + } catch (SQLException e) { + e.printStackTrace(); + } + scheduleTreatmentChange(); + return status; + } + + public void create(Treatment treatment) { + try { + getDaoTreatments().create(treatment); + latestTreatmentChange = treatment.getTimeIndex(); + } catch (SQLException e) { + e.printStackTrace(); + } + scheduleTreatmentChange(); + } + + public int delete(String _id) { + Treatment stored = findTreatmentById(_id); + int removed = 0; + if (stored != null) { + log.debug("REMOVE: Existing treatment (removing): " + _id); + try { + removed = getDaoTreatments().delete(stored); + } catch (SQLException e) { + e.printStackTrace(); + } + if (Config.logIncommingData) + log.debug("Records removed: " + removed); + latestTreatmentChange = stored.getTimeIndex(); + scheduleTreatmentChange(); + } else { + log.debug("REMOVE: Not stored treatment (ignoring): " + _id); + } + return removed; + } + + @Nullable + public Treatment findTreatmentById(String _id) { + try { + Dao daoTreatments = getDaoTreatments(); + QueryBuilder queryBuilder = daoTreatments.queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", _id); + queryBuilder.limit(10); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = daoTreatments.query(preparedQuery); + if (trList.size() != 1) { + //log.debug("Treatment findTreatmentById query size: " + trList.size()); + return null; + } else { + //log.debug("Treatment findTreatmentById found: " + trList.get(0).log()); + return trList.get(0); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + @Nullable + public Treatment findTreatmentByTimeIndex(Long timeIndex) { + try { + QueryBuilder qb = null; + Dao daoTreatments = getDaoTreatments(); + QueryBuilder queryBuilder = daoTreatments.queryBuilder(); + Where where = queryBuilder.where(); + where.eq("timeIndex", timeIndex); + queryBuilder.limit(10); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = daoTreatments.query(preparedQuery); + if (trList.size() != 1) { + log.debug("Treatment findTreatmentByTimeIndex query size: " + trList.size()); + return null; + } else { + log.debug("Treatment findTreatmentByTimeIndex found: " + trList.get(0).log()); + return trList.get(0); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return null; + } + + static public void scheduleTreatmentChange() { + class PostRunnable implements Runnable { + public void run() { + MainApp.bus().post(new EventTreatmentChange()); + scheduledPost = null; + } + } + // prepare task for execution in 5 sec + // cancel waiting task to prevent sending multiple posts + if (scheduledPost != null) + scheduledPost.cancel(false); + Runnable task = new PostRunnable(); + final int sec = 5; + scheduledPost = worker.schedule(task, sec, TimeUnit.SECONDS); + + } + public List getTreatmentDataFromTime(long mills, boolean ascending) { try { Dao daoTreatments = getDaoTreatments(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java index 42d0ae2584..1a21fb9dd6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java @@ -16,7 +16,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; @@ -46,7 +45,6 @@ import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA; import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResultMA; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; -import info.nightscout.androidaps.plugins.Actions.dialogs.NewExtendedBolusDialog; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; @@ -82,7 +80,8 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain public ConfigBuilderPlugin() { MainApp.bus().register(this); PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ConfigBuilderPlugin");; + mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ConfigBuilderPlugin"); + ; } @Override @@ -103,7 +102,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain @Override public String getNameShort() { String name = MainApp.sResources.getString(R.string.configbuilder_shortname); - if (!name.trim().isEmpty()){ + if (!name.trim().isEmpty()) { //only if translation exists return name; } @@ -210,14 +209,14 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain public void logPluginStatus() { for (PluginBase p : pluginList) { log.debug(p.getName() + ":" + - (p.isEnabled(1) ? " GENERAL" : "") + - (p.isEnabled(2) ? " TREATMENT" : "") + - (p.isEnabled(3) ? " TEMPBASAL" : "") + - (p.isEnabled(4) ? " PROFILE" : "") + - (p.isEnabled(5) ? " APS" : "") + - (p.isEnabled(6) ? " PUMP" : "") + - (p.isEnabled(7) ? " CONSTRAINTS" : "") + - (p.isEnabled(8) ? " LOOP" : "") + + (p.isEnabled(1) ? " GENERAL" : "") + + (p.isEnabled(2) ? " TREATMENT" : "") + + (p.isEnabled(3) ? " TEMPBASAL" : "") + + (p.isEnabled(4) ? " PROFILE" : "") + + (p.isEnabled(5) ? " APS" : "") + + (p.isEnabled(6) ? " PUMP" : "") + + (p.isEnabled(7) ? " CONSTRAINTS" : "") + + (p.isEnabled(8) ? " LOOP" : "") + (p.isEnabled(9) ? " BGSOURCE" : "") ); } @@ -444,15 +443,10 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain t.carbs = (double) result.carbsDelivered; // with different carbTime record will come back from nightscout t.created_at = new Date(); t.mealBolus = result.carbsDelivered > 0; - try { - MainApp.getDbHelper().getDaoTreatments().create(t); - } catch (SQLException e) { - e.printStackTrace(); - } + MainApp.getDbHelper().create(t); t.setTimeIndex(t.getTimeIndex()); t.carbs = (double) result.carbsDelivered; uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc); - MainApp.bus().post(new EventTreatmentChange()); } mWakeLock.release(); return result; @@ -496,21 +490,15 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain t.carbs = (double) result.carbsDelivered; t.created_at = new Date(); t.mealBolus = t.carbs > 0; - try { - MainApp.getDbHelper().getDaoTreatments().create(t); - } catch (SQLException e) { - e.printStackTrace(); - } + MainApp.getDbHelper().create(t); t.setTimeIndex(t.getTimeIndex()); t.sendToNSClient(); - MainApp.bus().post(new EventTreatmentChange()); } mWakeLock.release(); return result; } - @Override public void stopBolusDelivering() { activePump.stopBolusDelivering(); @@ -819,7 +807,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain data.put("absolute", absolute); data.put("created_at", DateUtil.toISOString(new Date())); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + absolute + "u/h " + durationInMinutes +" min"); // ECOR + data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + absolute + "u/h " + durationInMinutes + " min"); // ECOR Bundle bundle = new Bundle(); bundle.putString("action", "dbAdd"); bundle.putString("collection", "treatments"); @@ -849,7 +837,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain data.put("percent", percent - 100); data.put("created_at", DateUtil.toISOString(new Date())); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + percent + "% " + durationInMinutes +" min"); // ECOR + data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + percent + "% " + durationInMinutes + " min"); // ECOR Bundle bundle = new Bundle(); bundle.putString("action", "dbAdd"); bundle.putString("collection", "treatments");