From f6cd1201e3f85bf035dcbfeceeb6f087998341c9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 5 Apr 2018 09:39:18 +0200 Subject: [PATCH 1/6] Treatments refactor --- .../nightscout/androidaps/MainActivity.java | 4 +- .../androidaps/Services/DataService.java | 144 +++--- .../androidaps/db/DatabaseHelper.java | 286 +----------- .../androidaps/db/ExtendedBolus.java | 4 +- .../androidaps/db/TemporaryBasal.java | 2 +- .../androidaps/events/EventNsTreatment.java | 36 ++ .../events/EventTreatmentChange.java | 2 +- .../interfaces/InsulinInterface.java | 5 +- .../interfaces/TreatmentsInterface.java | 2 +- .../androidaps/plugins/Food/Food.java | 8 +- .../androidaps/plugins/Food/FoodService.java | 1 + .../plugins/Insulin/ActivityGraph.java | 2 +- .../Insulin/InsulinOrefBasePlugin.java | 2 +- .../IobCobCalculator/AutosensData.java | 3 +- .../IobCobCalculator/IobCobThread.java | 2 +- .../events/EventOverviewBolusProgress.java | 3 +- .../plugins/Overview/graphData/GraphData.java | 2 +- .../plugins/PumpCombo/ComboPlugin.java | 2 +- .../plugins/PumpDanaR/DanaRPlugin.java | 2 +- .../PumpDanaR/comm/MsgBolusProgress.java | 6 +- .../plugins/PumpDanaR/comm/MsgBolusStop.java | 4 +- .../AbstractDanaRExecutionService.java | 3 +- .../services/DanaRExecutionService.java | 2 +- .../PumpDanaRKorean/DanaRKoreanPlugin.java | 2 +- .../services/DanaRKoreanExecutionService.java | 2 +- .../plugins/PumpDanaRS/DanaRSPlugin.java | 2 +- ...naRS_Packet_Bolus_Set_Step_Bolus_Stop.java | 2 +- ...anaRS_Packet_Notify_Delivery_Complete.java | 2 +- ...S_Packet_Notify_Delivery_Rate_Display.java | 2 +- .../PumpDanaRS/services/DanaRSService.java | 2 +- .../plugins/PumpDanaRv2/DanaRv2Plugin.java | 2 +- .../services/DanaRv2ExecutionService.java | 2 +- .../plugins/PumpInsight/InsightPlugin.java | 2 +- .../SmsCommunicatorPlugin.java | 2 +- .../{db => plugins/Treatments}/Treatment.java | 43 +- .../plugins/Treatments/TreatmentService.java | 426 ++++++++++++++++++ .../plugins/Treatments/TreatmentsPlugin.java | 38 +- .../fragments/TreatmentsBolusFragment.java | 8 +- .../wearintegration/WatchUpdaterService.java | 2 +- .../java/info/nightscout/utils/DateUtil.java | 4 + .../info/nightscout/utils/JsonHelper.java | 54 ++- .../Insulin/InsulinOrefBasePluginTest.java | 2 +- .../nightscout/utils/BolusWizardTest.java | 1 - 43 files changed, 676 insertions(+), 451 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java rename app/src/main/java/info/nightscout/androidaps/{db => plugins/Treatments}/Treatment.java (75%) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 0ae1e48775..188cbf393d 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -48,6 +48,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Food.FoodPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock; +import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.tabs.SlidingTabLayout; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.utils.ImportExportPrefs; @@ -378,7 +379,8 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe MainApp.getDbHelper().resetDatabases(); // should be handled by Plugin-Interface and // additional service interface and plugin registry - MainApp.getSpecificPlugin(FoodPlugin.class).getService().resetFood(); + FoodPlugin.getPlugin().getService().resetFood(); + TreatmentsPlugin.getPlugin().getService().resetTreatments(); } }) .create() 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 7a0193d65c..6a771fc4a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventNsFood; +import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; @@ -40,6 +41,7 @@ import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin; import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.utils.BundleLogger; +import info.nightscout.utils.JsonHelper; import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; @@ -382,19 +384,18 @@ public class DataService extends IntentService { if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { try { if (bundles.containsKey("treatment")) { - String trstring = bundles.getString("treatment"); - handleAddChangeDataFromNS(trstring); + JSONObject json = new JSONObject(bundles.getString("treatment")); + handleTreatmentFromNS(json, intent); } if (bundles.containsKey("treatments")) { String trstring = bundles.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { - JSONObject trJson = jsonArray.getJSONObject(i); - String trstr = trJson.toString(); - handleAddChangeDataFromNS(trstr); + JSONObject json = jsonArray.getJSONObject(i); + handleTreatmentFromNS(json, intent); } } - } catch (Exception e) { + } catch (JSONException e) { log.error("Unhandled exception", e); } } @@ -403,21 +404,19 @@ public class DataService extends IntentService { try { if (bundles.containsKey("treatment")) { String trstring = bundles.getString("treatment"); - JSONObject trJson = new JSONObject(trstring); - String _id = trJson.getString("_id"); - handleRemovedRecordFromNS(_id); + JSONObject json = new JSONObject(trstring); + handleTreatmentFromNS(json); } if (bundles.containsKey("treatments")) { String trstring = bundles.getString("treatments"); JSONArray jsonArray = new JSONArray(trstring); for (int i = 0; i < jsonArray.length(); i++) { - JSONObject trJson = jsonArray.getJSONObject(i); - String _id = trJson.getString("_id"); - handleRemovedRecordFromNS(_id); + JSONObject json = jsonArray.getJSONObject(i); + handleTreatmentFromNS(json); } } - } catch (Exception e) { + } catch (JSONException e) { log.error("Unhandled exception", e); } } @@ -489,8 +488,12 @@ public class DataService extends IntentService { } } - private void handleRemovedRecordFromNS(String _id) { - MainApp.getDbHelper().deleteTreatmentById(_id); + private void handleTreatmentFromNS(JSONObject json) { + // new DB model + EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json); + MainApp.bus().post(evtTreatment); + // old DB model + String _id = JsonHelper.safeGetString(json, "_id"); MainApp.getDbHelper().deleteTempTargetById(_id); MainApp.getDbHelper().deleteTempBasalById(_id); MainApp.getDbHelper().deleteExtendedBolusById(_id); @@ -498,86 +501,53 @@ public class DataService extends IntentService { MainApp.getDbHelper().deleteProfileSwitchById(_id); } - private void handleAddChangeDataFromNS(String trstring) throws JSONException { - JSONObject trJson = new JSONObject(trstring); - handleDanaRHistoryRecords(trJson); // update record _id in history - handleAddChangeTempTargetRecord(trJson); - handleAddChangeTempBasalRecord(trJson); - handleAddChangeExtendedBolusRecord(trJson); - handleAddChangeCareportalEventRecord(trJson); - handleAddChangeTreatmentRecord(trJson); - handleAddChangeProfileSwitchRecord(trJson); - } - - public void handleDanaRHistoryRecords(JSONObject trJson) { - if (trJson.has(DanaRNSHistorySync.DANARSIGNATURE)) { - MainApp.getDbHelper().updateDanaRHistoryRecordId(trJson); - } - } - - public void handleAddChangeTreatmentRecord(JSONObject trJson) throws JSONException { - if (trJson.has("insulin") || trJson.has("carbs")) { - MainApp.getDbHelper().createTreatmentFromJsonIfNotExists(trJson); - return; - } - } - - public void handleAddChangeTempTargetRecord(JSONObject trJson) throws JSONException { - if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPORARYTARGET)) { - MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(trJson); - } - } - - public void handleAddChangeTempBasalRecord(JSONObject trJson) throws JSONException { - if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPBASAL)) { - MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(trJson); - } - } - - public void handleAddChangeExtendedBolusRecord(JSONObject trJson) throws JSONException { - if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.COMBOBOLUS)) { - MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(trJson); - } - } - - public void handleAddChangeCareportalEventRecord(JSONObject trJson) throws JSONException { - if (trJson.has("insulin") && trJson.getDouble("insulin") > 0) - return; - if (trJson.has("carbs") && trJson.getDouble("carbs") > 0) - return; - if (trJson.has("eventType") && ( - trJson.getString("eventType").equals(CareportalEvent.SITECHANGE) || - trJson.getString("eventType").equals(CareportalEvent.INSULINCHANGE) || - trJson.getString("eventType").equals(CareportalEvent.SENSORCHANGE) || - trJson.getString("eventType").equals(CareportalEvent.BGCHECK) || - trJson.getString("eventType").equals(CareportalEvent.NOTE) || - trJson.getString("eventType").equals(CareportalEvent.NONE) || - trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT) || - trJson.getString("eventType").equals(CareportalEvent.QUESTION) || - trJson.getString("eventType").equals(CareportalEvent.EXERCISE) || - trJson.getString("eventType").equals(CareportalEvent.OPENAPSOFFLINE) || - trJson.getString("eventType").equals(CareportalEvent.PUMPBATTERYCHANGE) - )) { - MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(trJson); + private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException { + // new DB model + int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; + double insulin = JsonHelper.safeGetDouble(json, "insulin"); + double carbs = JsonHelper.safeGetDouble(json, "carbs"); + String eventType = JsonHelper.safeGetString(json, "eventType"); + if (insulin > 0 || carbs > 0) { + EventNsTreatment evtTreatment = new EventNsTreatment(mode, json); + MainApp.bus().post(evtTreatment); + } else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) { + // old DB model + MainApp.getDbHelper().updateDanaRHistoryRecordId(json); + } else if (eventType.equals(CareportalEvent.TEMPORARYTARGET)) { + MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.TEMPBASAL)) { + MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { + MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { + MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.SITECHANGE) || + eventType.equals(CareportalEvent.INSULINCHANGE) || + eventType.equals(CareportalEvent.SENSORCHANGE) || + eventType.equals(CareportalEvent.BGCHECK) || + eventType.equals(CareportalEvent.NOTE) || + eventType.equals(CareportalEvent.NONE) || + eventType.equals(CareportalEvent.ANNOUNCEMENT) || + eventType.equals(CareportalEvent.QUESTION) || + eventType.equals(CareportalEvent.EXERCISE) || + eventType.equals(CareportalEvent.OPENAPSOFFLINE) || + eventType.equals(CareportalEvent.PUMPBATTERYCHANGE)) { + MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json); } - if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.ANNOUNCEMENT)) { - long date = trJson.getLong("mills"); + if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) { + long date = JsonHelper.safeGetLong(json,"mills"); long now = System.currentTimeMillis(); - if (date > now - 15 * 60 * 1000L && trJson.has("notes") - && !(trJson.has("enteredBy") && trJson.getString("enteredBy").equals(SP.getString("careportal_enteredby", "AndroidAPS")))) { - Notification announcement = new Notification(Notification.NSANNOUNCEMENT, trJson.getString("notes"), Notification.ANNOUNCEMENT, 60); + String enteredBy = JsonHelper.safeGetString(json, "enteredBy", ""); + String notes = JsonHelper.safeGetString(json, "notes", ""); + if (date > now - 15 * 60 * 1000L && !notes.isEmpty() + && !enteredBy.equals(SP.getString("careportal_enteredby", "AndroidAPS"))) { + Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); MainApp.bus().post(new EventNewNotification(announcement)); } } } - public void handleAddChangeProfileSwitchRecord(JSONObject trJson) throws JSONException { - if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.PROFILESWITCH)) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson); - } - } - private void handleNewSMS(Intent intent) { Bundle bundle = intent.getExtras(); if (bundle == null) return; 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 b1349e1761..7c7b373414 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -28,9 +28,7 @@ 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.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventCareportalEventChange; @@ -43,15 +41,10 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; -import info.nightscout.androidaps.events.EventTreatmentChange; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; -import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; -import info.nightscout.utils.DateUtil; import info.nightscout.utils.NSUpload; import info.nightscout.utils.PercentageSplitter; import info.nightscout.utils.ToastUtils; @@ -72,7 +65,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals"; public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses"; public static final String DATABASE_TEMPTARGETS = "TempTargets"; - public static final String DATABASE_TREATMENTS = "Treatments"; public static final String DATABASE_DANARHISTORY = "DanaRHistory"; public static final String DATABASE_DBREQUESTS = "DBRequests"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; @@ -81,14 +73,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final int DATABASE_VERSION = 8; - private static Long earliestDataChange = null; + public static Long earliestDataChange = null; private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledBgPost = null; - private static final ScheduledExecutorService treatmentsWorker = Executors.newSingleThreadScheduledExecutor(); - private static ScheduledFuture scheduledTratmentPost = null; - private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTemBasalsPost = null; @@ -118,7 +107,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { log.info("onCreate"); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); - TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DbRequest.class); @@ -141,12 +129,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (oldVersion == 7 && newVersion == 8) { log.debug("Upgrading database from v7 to v8"); - TableUtils.dropTable(connectionSource, Treatment.class, true); - TableUtils.createTableIfNotExists(connectionSource, Treatment.class); } else { log.info(DatabaseHelper.class.getName(), "onUpgrade"); TableUtils.dropTable(connectionSource, TempTarget.class, true); - TableUtils.dropTable(connectionSource, Treatment.class, true); TableUtils.dropTable(connectionSource, BgReading.class, true); TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); TableUtils.dropTable(connectionSource, DbRequest.class, true); @@ -178,40 +163,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { super.close(); } - public void cleanUpDatabases() { - // TODO: call it somewhere - log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS)); - getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null); - log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS)); - - log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS)); - getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null); - log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS)); - - log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS)); - getWritableDatabase().delete(DATABASE_TREATMENTS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null); - log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS)); - - log.debug("Before History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY)); - getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null); - log.debug("After History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY)); - - log.debug("Before TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS)); - getWritableDatabase().delete(DATABASE_TEMPORARYBASALS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null); - log.debug("After TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS)); - - log.debug("Before ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES)); - getWritableDatabase().delete(DATABASE_EXTENDEDBOLUSES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null); - log.debug("After ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES)); - - log.debug("Before CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS)); - getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null); - log.debug("After CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS)); - - log.debug("Before ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES)); - getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null); - log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES)); - } public long size(String database) { return DatabaseUtils.queryNumEntries(getReadableDatabase(), database); @@ -222,7 +173,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void resetDatabases() { try { TableUtils.dropTable(connectionSource, TempTarget.class, true); - TableUtils.dropTable(connectionSource, Treatment.class, true); TableUtils.dropTable(connectionSource, BgReading.class, true); TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); TableUtils.dropTable(connectionSource, DbRequest.class, true); @@ -232,7 +182,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.dropTable(connectionSource, TDD.class, true); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); - TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DbRequest.class); @@ -248,7 +197,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { VirtualPumpPlugin.setFakingStatus(true); scheduleBgChange(null); // trigger refresh scheduleTemporaryBasalChange(); - scheduleTreatmentChange(null); scheduleExtendedBolusChange(); scheduleTemporaryTargetChange(); scheduleCareportalEventChange(); @@ -264,17 +212,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { ); } - public void resetTreatments() { - try { - TableUtils.dropTable(connectionSource, Treatment.class, true); - TableUtils.createTableIfNotExists(connectionSource, Treatment.class); - updateEarliestDataChange(0); - } catch (SQLException e) { - log.error("Unhandled exception", e); - } - scheduleTreatmentChange(null); - } - public void resetTempTargets() { try { TableUtils.dropTable(connectionSource, TempTarget.class, true); @@ -343,11 +280,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(TempTarget.class); } - private Dao getDaoTreatments() throws SQLException { - return getDao(Treatment.class); - } - - private Dao getDaoBgReadings() throws SQLException { + private Dao getDaoBgReadings() throws SQLException { return getDao(BgReading.class); } @@ -379,7 +312,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(ProfileSwitch.class); } - public long roundDateToSec(long date) { + public static long roundDateToSec(long date) { return date - date % 1000; } // ------------------- BgReading handling ----------------------- @@ -604,147 +537,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // -------------------- TREATMENT HANDLING ------------------- - // return true if new record is created - public boolean createOrUpdate(Treatment treatment) { - try { - Treatment old; - treatment.date = roundDateToSec(treatment.date); - - if (treatment.source == Source.PUMP) { - // check for changed from pump change in NS - QueryBuilder queryBuilder = getDaoTreatments().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("pumpId", treatment.pumpId); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = getDaoTreatments().query(preparedQuery); - if (trList.size() > 0) { - // do nothing, pump history record cannot be changed - log.debug("TREATMENT: Pump record already found in database: " + treatment.toString()); - return false; - } - getDaoTreatments().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); - return true; - } - if (treatment.source == Source.NIGHTSCOUT) { - old = getDaoTreatments().queryForId(treatment.date); - if (old != null) { - if (!old.isEqual(treatment)) { - boolean historyChange = old.isDataChanging(treatment); - long oldDate = old.date; - getDaoTreatments().delete(old); // need to delete/create because date may change too - old.copyFrom(treatment); - getDaoTreatments().create(old); - log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); - if (historyChange) { - updateEarliestDataChange(oldDate); - updateEarliestDataChange(old.date); - } - scheduleTreatmentChange(treatment); - return true; - } - return false; - } - // find by NS _id - if (treatment._id != null) { - QueryBuilder queryBuilder = getDaoTreatments().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", treatment._id); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = getDaoTreatments().query(preparedQuery); - if (trList.size() > 0) { - old = trList.get(0); - if (!old.isEqual(treatment)) { - boolean historyChange = old.isDataChanging(treatment); - long oldDate = old.date; - getDaoTreatments().delete(old); // need to delete/create because date may change too - old.copyFrom(treatment); - getDaoTreatments().create(old); - log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); - if (historyChange) { - updateEarliestDataChange(oldDate); - updateEarliestDataChange(old.date); - } - scheduleTreatmentChange(treatment); - return true; - } - } - } - getDaoTreatments().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); - return true; - } - if (treatment.source == Source.USER) { - getDaoTreatments().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment); - return true; - } - } catch (SQLException e) { - log.error("Unhandled exception", e); - } - return false; - } - - public void delete(Treatment treatment) { - try { - getDaoTreatments().delete(treatment); - updateEarliestDataChange(treatment.date); - } catch (SQLException e) { - log.error("Unhandled exception", e); - } - scheduleTreatmentChange(treatment); - } - - public void update(Treatment treatment) { - try { - getDaoTreatments().update(treatment); - updateEarliestDataChange(treatment.date); - } catch (SQLException e) { - log.error("Unhandled exception", e); - } - scheduleTreatmentChange(treatment); - } - - public void deleteTreatmentById(String _id) { - Treatment stored = findTreatmentById(_id); - if (stored != null) { - log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString()); - delete(stored); - updateEarliestDataChange(stored.date); - scheduleTreatmentChange(null); - } - } - - @Nullable - private Treatment findTreatmentById(String _id) { - try { - Dao daoTreatments = getDaoTreatments(); - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", _id); - queryBuilder.limit(10L); - 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) { - log.error("Unhandled exception", e); - } - return null; - } - - private void updateEarliestDataChange(long newDate) { + public static void updateEarliestDataChange(long newDate) { if (earliestDataChange == null) { earliestDataChange = newDate; return; @@ -754,73 +547,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } - private static void scheduleTreatmentChange(@Nullable final Treatment treatment) { - class PostRunnable implements Runnable { - public void run() { - log.debug("Firing EventTreatmentChange"); - MainApp.bus().post(new EventReloadTreatmentData(new EventTreatmentChange(treatment))); - if (earliestDataChange != null) - MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); - earliestDataChange = null; - scheduledTratmentPost = null; - } - } - // prepare task for execution in 1 sec - // cancel waiting task to prevent sending multiple posts - if (scheduledTratmentPost != null) - scheduledTratmentPost.cancel(false); - Runnable task = new PostRunnable(); - final int sec = 1; - scheduledTratmentPost = treatmentsWorker.schedule(task, sec, TimeUnit.SECONDS); - - } - - public List getTreatmentDataFromTime(long mills, boolean ascending) { - try { - Dao daoTreatments = getDaoTreatments(); - List treatments; - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - queryBuilder.orderBy("date", ascending); - Where where = queryBuilder.where(); - where.ge("date", mills); - PreparedQuery preparedQuery = queryBuilder.prepare(); - treatments = daoTreatments.query(preparedQuery); - return treatments; - } catch (SQLException e) { - log.error("Unhandled exception", e); - } - return new ArrayList(); - } - - public void createTreatmentFromJsonIfNotExists(JSONObject trJson) { - try { - Treatment treatment = new Treatment(); - treatment.source = Source.NIGHTSCOUT; - treatment.date = roundDateToSec(trJson.getLong("mills")); - treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0; - treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d; - treatment.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; - treatment._id = trJson.getString("_id"); - if (trJson.has("isSMB")) - treatment.isSMB = trJson.getBoolean("isSMB"); - if (trJson.has("eventType")) { - treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus"); - double carbs = treatment.carbs; - if (trJson.has("boluscalc")) { - JSONObject boluscalc = trJson.getJSONObject("boluscalc"); - if (boluscalc.has("carbs")) { - carbs = Math.max(boluscalc.getDouble("carbs"), carbs); - } - } - if (carbs <= 0) - treatment.mealBolus = false; - } - createOrUpdate(treatment); - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - // ---------------- TempTargets handling --------------- public List getTemptargetsDataFromTime(long mills, boolean ascending) { @@ -1557,7 +1283,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteCareportalEventById(String _id) { try { - QueryBuilder queryBuilder = null; + QueryBuilder queryBuilder; queryBuilder = getDaoCareportalEvents().queryBuilder(); Where where = queryBuilder.where(); where.eq("_id", _id); @@ -1580,7 +1306,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) { try { - QueryBuilder queryBuilder = null; + QueryBuilder queryBuilder; queryBuilder = getDaoCareportalEvents().queryBuilder(); Where where = queryBuilder.where(); where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java index 7bd60fe496..8e7022b609 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -12,19 +12,17 @@ import com.j256.ormlite.table.DatabaseTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; import java.util.Objects; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java index e2303bac53..0747669538 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -6,7 +6,6 @@ import com.j256.ormlite.table.DatabaseTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; import java.util.Objects; import info.nightscout.androidaps.MainApp; @@ -17,6 +16,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.SP; diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java new file mode 100644 index 0000000000..2c5ba6c9c0 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.events; + +import org.json.JSONObject; + + +/** + * Event which is published with data fetched from NightScout specific for the + * Treatment-class. + *

+ * Payload is the from NS retrieved JSON-String which should be handled by all + * subscriber. + */ + +public class EventNsTreatment extends Event { + + public static final int ADD = 0; + public static final int UPDATE = 1; + public static final int REMOVE = 2; + + private final int mode; + + private final JSONObject payload; + + public EventNsTreatment(int mode, JSONObject payload) { + this.mode = mode; + this.payload = payload; + } + + public int getMode() { + return mode; + } + + public JSONObject getPayload() { + return payload; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java index 2a3581f9bf..989b24b7f9 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.events; import android.support.annotation.Nullable; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; /** * Created by mike on 04.06.2016. diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java index f7be6883e9..a123554ae8 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java @@ -1,10 +1,7 @@ package info.nightscout.androidaps.interfaces; -import java.util.Date; - import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; /** * Created by mike on 17.04.2017. diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index 129e54b50b..f93dbdf5fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -9,7 +9,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.ProfileIntervals; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Food/Food.java b/app/src/main/java/info/nightscout/androidaps/plugins/Food/Food.java index 5506d32471..49da1d6ac5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Food/Food.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Food/Food.java @@ -5,8 +5,6 @@ import com.j256.ormlite.table.DatabaseTable; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Objects; @@ -18,9 +16,7 @@ import info.nightscout.utils.JsonHelper; @DatabaseTable(tableName = Food.TABLE_FOODS) public class Food { - private static Logger log = LoggerFactory.getLogger(Food.class); - - public static final String TABLE_FOODS = "Foods"; + static final String TABLE_FOODS = "Foods"; @DatabaseField(id = true) public long key; @@ -65,7 +61,7 @@ public class Food { @DatabaseField public int gi; // not used yet - public Food() { + private Food() { key = System.currentTimeMillis(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java index c3028461ec..44b96850ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java @@ -347,6 +347,7 @@ public class FoodService extends OrmLiteBaseService { * @param _id * @return */ + @Nullable public Food findByNSId(String _id) { try { List list = this.getDao().queryForEq("_id", _id); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/ActivityGraph.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/ActivityGraph.java index 5a0d7fcce9..8bbd1d3e7f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/ActivityGraph.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/ActivityGraph.java @@ -12,7 +12,7 @@ import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java index cf56452bcc..672c5cfeb6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java @@ -5,7 +5,7 @@ import com.squareup.otto.Bus; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java index 42a2b35490..397656306b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java @@ -10,8 +10,7 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java index da7d0fbbbd..0a9fbb75e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java @@ -20,7 +20,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java index 18c3ff1e27..6f9526369e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java @@ -3,8 +3,7 @@ package info.nightscout.androidaps.plugins.Overview.events; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.Event; public class EventOverviewBolusProgress extends Event { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java index 7d1cd07b69..a017f31209 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.BasalData; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index 43d855dab1..b25e6d3b4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -28,7 +28,7 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java index ee0f33b281..df8dea6178 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.Constraint; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java index b200ccc5c1..79358526fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java @@ -1,16 +1,12 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; -import com.squareup.otto.Bus; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; - import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class MsgBolusProgress extends MessageBase { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java index 7040b84183..6718d76194 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java @@ -1,13 +1,11 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; -import com.squareup.otto.Bus; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class MsgBolusStop extends MessageBase { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/AbstractDanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/AbstractDanaRExecutionService.java index 4727e2650f..5524cf5c5c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/AbstractDanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/AbstractDanaRExecutionService.java @@ -21,10 +21,9 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import info.nightscout.androidaps.plugins.PumpDanaR.SerialIOThread; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStop; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgHistoryAlarm; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java index 4bf080f3fb..eabf4fc94a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java index 212eb95dcd..61851561ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.Constraint; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java index 12d7590a59..c136666d5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java index 17bc4671ce..a8e460c078 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java @@ -26,7 +26,7 @@ import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java index 5383fca413..83e84e28cc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java @@ -9,7 +9,7 @@ import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java index 0139b12197..fb5793995c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java @@ -9,7 +9,7 @@ import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java index 26c12c27af..5354836375 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java @@ -7,7 +7,7 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java index 489864ebd1..dd7f22b0b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java @@ -19,7 +19,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java index 5d7eae2091..765ef865cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java @@ -17,7 +17,7 @@ import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpDescription; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java index 1eb73a500a..27b1275047 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java @@ -18,7 +18,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventPreferenceChange; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java index 4ad70cfc31..f94ff4d3ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java @@ -21,7 +21,7 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginBase; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index b6c8ebca33..8308a2eb92 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -315,7 +315,7 @@ public class SmsCommunicatorPlugin extends PluginBase { switch (splited[1].toUpperCase()) { case "REFRESH": Intent restartNSClient = new Intent(Intents.ACTION_RESTART); - MainApp.getDbHelper().resetTreatments(); + TreatmentsPlugin.getPlugin().getService().resetTreatments(); MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); reply = "TERATMENTS REFRESH " + q.size() + " receivers"; diff --git a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java similarity index 75% rename from app/src/main/java/info/nightscout/androidaps/db/Treatment.java rename to app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java index 31df191387..31d44a3e30 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java @@ -1,10 +1,12 @@ -package info.nightscout.androidaps.db; +package info.nightscout.androidaps.plugins.Treatments; import android.graphics.Color; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; +import org.json.JSONException; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,6 +16,8 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; +import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; @@ -21,11 +25,14 @@ import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWith import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.JsonHelper; -@DatabaseTable(tableName = DatabaseHelper.DATABASE_TREATMENTS) +@DatabaseTable(tableName = Treatment.TABLE_TREATMENTS) public class Treatment implements DataPointWithLabelInterface { private static Logger log = LoggerFactory.getLogger(Treatment.class); + public static final String TABLE_TREATMENTS = "Treatments"; + @DatabaseField(id = true) public long date; @@ -57,6 +64,32 @@ public class Treatment implements DataPointWithLabelInterface { public Treatment() { } + public static Treatment createFromJson(JSONObject json) throws JSONException { + Treatment treatment = new Treatment(); + treatment.source = Source.NIGHTSCOUT; + treatment.date = DateUtil.roundDateToSec(JsonHelper.safeGetLong(json, "mills")); + if (treatment.date == 0L) + return null; + treatment.carbs = JsonHelper.safeGetDouble(json,"carbs"); + treatment.insulin = JsonHelper.safeGetDouble(json,"insulin"); + treatment.pumpId = JsonHelper.safeGetLong(json, "pumpId"); + treatment._id = json.getString("_id"); + treatment.isSMB = JsonHelper.safeGetBoolean(json,"isSMB"); + if (json.has("eventType")) { + treatment.mealBolus = !json.get("eventType").equals("Correction Bolus"); + double carbs = treatment.carbs; + if (json.has("boluscalc")) { + JSONObject boluscalc = json.getJSONObject("boluscalc"); + if (boluscalc.has("carbs")) { + carbs = Math.max(boluscalc.getDouble("carbs"), carbs); + } + } + if (carbs <= 0) + treatment.mealBolus = false; + } + return treatment; + } + public String toString() { return "Treatment{" + "date= " + date + @@ -72,9 +105,8 @@ public class Treatment implements DataPointWithLabelInterface { } public boolean isDataChanging(Treatment other) { - if (date != other.date) { + if (date != other.date) return true; - } if (insulin != other.insulin) return true; if (carbs != other.carbs) @@ -83,9 +115,8 @@ public class Treatment implements DataPointWithLabelInterface { } public boolean isEqual(Treatment other) { - if (date != other.date) { + if (date != other.date) return false; - } if (insulin != other.insulin) return false; if (carbs != other.carbs) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java new file mode 100644 index 0000000000..2a5b798018 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java @@ -0,0 +1,426 @@ +package info.nightscout.androidaps.plugins.Treatments; + +import android.content.Intent; +import android.os.IBinder; +import android.support.annotation.Nullable; + +import com.j256.ormlite.android.apptools.OpenHelperManager; +import com.j256.ormlite.android.apptools.OrmLiteBaseService; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.stmt.PreparedQuery; +import com.j256.ormlite.stmt.QueryBuilder; +import com.j256.ormlite.stmt.Where; +import com.j256.ormlite.support.ConnectionSource; +import com.j256.ormlite.table.TableUtils; +import com.squareup.otto.Subscribe; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.ICallback; +import info.nightscout.androidaps.db.Source; +import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.events.EventNsTreatment; +import info.nightscout.androidaps.events.EventReloadTreatmentData; +import info.nightscout.androidaps.events.EventTreatmentChange; +import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; +import info.nightscout.utils.JsonHelper; + + +/** + * Created by mike on 24.09.2017. + */ + +public class TreatmentService extends OrmLiteBaseService { + private static Logger log = LoggerFactory.getLogger(TreatmentService.class); + + private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); + private static ScheduledFuture scheduledTreatmentEventPost = null; + + public TreatmentService() { + onCreate(); + dbInitialize(); + MainApp.bus().register(this); + } + + /** + * This method is a simple re-implementation of the database create and up/downgrade functionality + * in SQLiteOpenHelper#getDatabaseLocked method. + *

+ * It is implemented to be able to late initialize separate plugins of the application. + */ + protected void dbInitialize() { + DatabaseHelper helper = OpenHelperManager.getHelper(this, DatabaseHelper.class); + int newVersion = helper.getNewVersion(); + int oldVersion = helper.getOldVersion(); + + if (oldVersion > newVersion) { + onDowngrade(this.getConnectionSource(), oldVersion, newVersion); + } else { + onUpgrade(this.getConnectionSource(), oldVersion, newVersion); + } + } + + public Dao getDao() { + try { + return DaoManager.createDao(this.getConnectionSource(), Treatment.class); + } catch (SQLException e) { + log.error("Cannot create Dao for Treatment.class"); + } + + return null; + } + + @Subscribe + @SuppressWarnings("unused") + public void handleNsEvent(EventNsTreatment event) { + int mode = event.getMode(); + JSONObject payload = event.getPayload(); + + if (mode == EventNsTreatment.ADD || mode == EventNsTreatment.UPDATE) { + this.createTreatmentFromJsonIfNotExists(payload); + } else { // EventNsTreatment.REMOVE + this.deleteNS(payload); + } + } + + @Override + public void onCreate() { + super.onCreate(); + try { + log.info("onCreate"); + TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); + } catch (SQLException e) { + log.error("Can't create database", e); + throw new RuntimeException(e); + } + } + + public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { + if (oldVersion == 7 && newVersion == 8) { + log.debug("Upgrading database from v7 to v8"); + try { + TableUtils.dropTable(connectionSource, Treatment.class, true); + TableUtils.createTableIfNotExists(connectionSource, Treatment.class); + } catch (SQLException e) { + log.error("Can't create database", e); + throw new RuntimeException(e); + } + } else { + log.info("onUpgrade"); +// this.resetFood(); + } + } + + public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { + // this method is not supported right now + } + + public void resetTreatments() { + try { + TableUtils.dropTable(this.getConnectionSource(), Treatment.class, true); + TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); + DatabaseHelper.updateEarliestDataChange(0); + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + scheduleTreatmentChange(null); + } + + + /** + * A place to centrally register events to be posted, if any data changed. + * This should be implemented in an abstract service-class. + *

+ * We do need to make sure, that ICallback is extended to be able to handle multiple + * events, or handle a list of events. + *

+ * on some methods the earliestDataChange event is handled separatly, in that it is checked if it is + * set to null by another event already (eg. scheduleExtendedBolusChange). + * + * @param event + * @param eventWorker + * @param callback + */ + private void scheduleEvent(final Event event, ScheduledExecutorService eventWorker, + final ICallback callback) { + + class PostRunnable implements Runnable { + public void run() { + log.debug("Firing EventFoodChange"); + MainApp.bus().post(event); + if (DatabaseHelper.earliestDataChange != null) + MainApp.bus().post(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); + DatabaseHelper.earliestDataChange = null; + callback.setPost(null); + } + } + // prepare task for execution in 1 sec + // cancel waiting task to prevent sending multiple posts + if (callback.getPost() != null) + callback.getPost().cancel(false); + Runnable task = new PostRunnable(); + final int sec = 1; + callback.setPost(eventWorker.schedule(task, sec, TimeUnit.SECONDS)); + } + + /** + * Schedule a foodChange Event. + */ + public void scheduleTreatmentChange(@Nullable final Treatment treatment) { + this.scheduleEvent(new EventReloadTreatmentData(new EventTreatmentChange(treatment)), treatmentEventWorker, new ICallback() { + @Override + public void setPost(ScheduledFuture post) { + scheduledTreatmentEventPost = post; + } + + @Override + public ScheduledFuture getPost() { + return scheduledTreatmentEventPost; + } + }); + } + + public List getTreatmentData() { + try { + return this.getDao().queryForAll(); + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + + return new ArrayList<>(); + } + + /* + { + "_id": "551ee3ad368e06e80856e6a9", + "type": "food", + "category": "Zakladni", + "subcategory": "Napoje", + "name": "Mleko", + "portion": 250, + "carbs": 12, + "gi": 1, + "created_at": "2015-04-14T06:59:16.500Z", + "unit": "ml" + } + */ + public void createTreatmentFromJsonIfNotExists(JSONObject json) { + try { + Treatment treatment = Treatment.createFromJson(json); + if (treatment != null) + createOrUpdate(treatment); + } catch (JSONException e) { + log.error("Unhandled exception", e); + } + } + + public void createFoodFromJsonIfNotExists(JSONArray array) { + try { + for (int n = 0; n < array.length(); n++) { + JSONObject json = array.getJSONObject(n); + createTreatmentFromJsonIfNotExists(json); + } + } catch (JSONException e) { + log.error("Unhandled exception", e); + } + } + + // return true if new record is created + public boolean createOrUpdate(Treatment treatment) { + try { + Treatment old; + treatment.date = DatabaseHelper.roundDateToSec(treatment.date); + + if (treatment.source == Source.PUMP) { + // check for changed from pump change in NS + QueryBuilder queryBuilder = getDao().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("pumpId", treatment.pumpId); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDao().query(preparedQuery); + if (trList.size() > 0) { + // do nothing, pump history record cannot be changed + log.debug("TREATMENT: Pump record already found in database: " + treatment.toString()); + return false; + } + getDao().create(treatment); + log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + DatabaseHelper.updateEarliestDataChange(treatment.date); + scheduleTreatmentChange(treatment); + return true; + } + if (treatment.source == Source.NIGHTSCOUT) { + old = getDao().queryForId(treatment.date); + if (old != null) { + if (!old.isEqual(treatment)) { + boolean historyChange = old.isDataChanging(treatment); + long oldDate = old.date; + getDao().delete(old); // need to delete/create because date may change too + old.copyFrom(treatment); + getDao().create(old); + log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); + if (historyChange) { + DatabaseHelper.updateEarliestDataChange(oldDate); + DatabaseHelper.updateEarliestDataChange(old.date); + } + scheduleTreatmentChange(treatment); + return true; + } + return false; + } + // find by NS _id + if (treatment._id != null) { + old = findByNSId(treatment._id); + if (old != null) { + if (!old.isEqual(treatment)) { + boolean historyChange = old.isDataChanging(treatment); + long oldDate = old.date; + getDao().delete(old); // need to delete/create because date may change too + old.copyFrom(treatment); + getDao().create(old); + log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); + if (historyChange) { + DatabaseHelper.updateEarliestDataChange(oldDate); + DatabaseHelper.updateEarliestDataChange(old.date); + } + scheduleTreatmentChange(treatment); + return true; + } + } + } + getDao().create(treatment); + log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + DatabaseHelper.updateEarliestDataChange(treatment.date); + scheduleTreatmentChange(treatment); + return true; + } + if (treatment.source == Source.USER) { + getDao().create(treatment); + log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + DatabaseHelper.updateEarliestDataChange(treatment.date); + scheduleTreatmentChange(treatment); + return true; + } + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return false; + } + + public void deleteNS(JSONObject json) { + String _id = JsonHelper.safeGetString(json, "_id"); + if (_id != null && !_id.isEmpty()) + this.deleteByNSId(_id); + } + + /** + * deletes an entry by its NS Id. + *

+ * Basically a convenience method for findByNSId and delete. + * + * @param _id + */ + private void deleteByNSId(String _id) { + Treatment stored = findByNSId(_id); + if (stored != null) { + log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString()); + delete(stored); + DatabaseHelper.updateEarliestDataChange(stored.date); + scheduleTreatmentChange(null); + } + } + + /** + * deletes the treatment and sends the treatmentChange Event + *

+ * should be moved ot a Service + * + * @param treatment + */ + public void delete(Treatment treatment) { + try { + getDao().delete(treatment); + DatabaseHelper.updateEarliestDataChange(treatment.date); + this.scheduleTreatmentChange(treatment); + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + } + + public void update(Treatment treatment) { + try { + getDao().update(treatment); + DatabaseHelper.updateEarliestDataChange(treatment.date); + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + scheduleTreatmentChange(treatment); + } + + /** + * finds treatment by its NS Id. + * + * @param _id + * @return + */ + @Nullable + public Treatment findByNSId(String _id) { + try { + Dao daoTreatments = getDao(); + QueryBuilder queryBuilder = daoTreatments.queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", _id); + queryBuilder.limit(10L); + 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) { + log.error("Unhandled exception", e); + } + return null; + } + + public List getTreatmentDataFromTime(long mills, boolean ascending) { + try { + Dao daoTreatments = getDao(); + List treatments; + QueryBuilder queryBuilder = daoTreatments.queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.ge("date", mills); + PreparedQuery preparedQuery = queryBuilder.prepare(); + treatments = daoTreatments.query(preparedQuery); + return treatments; + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return new ArrayList<>(); + } + + @Nullable + @Override + public IBinder onBind(Intent intent) { + return null; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java index 55195928fc..722ce0539a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsPlugin.java @@ -27,7 +27,6 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventReloadProfileSwitchData; import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; @@ -43,6 +42,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotificati import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; +import info.nightscout.utils.T; /** * Created by mike on 05.08.2016. @@ -58,14 +58,16 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return treatmentsPlugin; } + private TreatmentService service; + private IobTotal lastTreatmentCalculation; private IobTotal lastTempBasalsCalculation; - private final static ArrayList treatments = new ArrayList<>(); - private final static Intervals tempBasals = new NonOverlappingIntervals<>(); - private final static Intervals extendedBoluses = new NonOverlappingIntervals<>(); - private final static Intervals tempTargets = new OverlappingIntervals<>(); - private final static ProfileIntervals profiles = new ProfileIntervals<>(); + private final ArrayList treatments = new ArrayList<>(); + private final Intervals tempBasals = new NonOverlappingIntervals<>(); + private final Intervals extendedBoluses = new NonOverlappingIntervals<>(); + private final Intervals tempTargets = new OverlappingIntervals<>(); + private final ProfileIntervals profiles = new ProfileIntervals<>(); public TreatmentsPlugin() { super(new PluginDescription() @@ -76,6 +78,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .preferencesId(R.xml.pref_absorption_oref0) .alwaysEnabled(true) ); + this.service = new TreatmentService(); } @Override @@ -94,18 +97,22 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface MainApp.bus().register(this); } - private static void initializeTreatmentData() { + public TreatmentService getService() { + return this.service; + } + + private void initializeTreatmentData() { double dia = Constants.defaultDIA; if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) dia = MainApp.getConfigBuilder().getProfile().getDia(); long fromMills = (long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)); synchronized (treatments) { treatments.clear(); - treatments.addAll(MainApp.getDbHelper().getTreatmentDataFromTime(fromMills, false)); + treatments.addAll(getService().getTreatmentDataFromTime(fromMills, false)); } } - private static void initializeTempBasalData() { + private void initializeTempBasalData() { double dia = Constants.defaultDIA; if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) dia = MainApp.getConfigBuilder().getProfile().getDia(); @@ -117,7 +124,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } - private static void initializeExtendedBolusData() { + private void initializeExtendedBolusData() { double dia = Constants.defaultDIA; if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) dia = MainApp.getConfigBuilder().getProfile().getDia(); @@ -203,7 +210,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (profile == null) return result; long now = System.currentTimeMillis(); - long dia_ago = now - (Double.valueOf(1.5d * profile.getDia() * 60 * 60 * 1000l)).longValue(); + long dia_ago = now - (Double.valueOf(1.5d * profile.getDia() * T.hours(1).msecs())).longValue(); synchronized (treatments) { for (Treatment treatment : treatments) { @@ -235,7 +242,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public List getTreatmentsFromHistory() { synchronized (treatments) { - return (List) treatments.clone(); + return new ArrayList<>(treatments); } } @@ -300,6 +307,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } @Subscribe + @SuppressWarnings("unused") public void onStatusEvent(final EventReloadTempBasalData ev) { log.debug("EventReloadTempBasalData"); initializeTempBasalData(); @@ -442,7 +450,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface treatment.carbs = detailedBolusInfo.carbs; treatment.source = detailedBolusInfo.source; treatment.mealBolus = treatment.carbs > 0; - boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(treatment); + boolean newRecordCreated = getService().createOrUpdate(treatment); //log.debug("Adding new Treatment record" + treatment.toString()); if (detailedBolusInfo.carbTime != 0) { Treatment carbsTreatment = new Treatment(); @@ -451,7 +459,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface carbsTreatment.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records carbsTreatment.carbs = detailedBolusInfo.carbs; carbsTreatment.source = detailedBolusInfo.source; - MainApp.getDbHelper().createOrUpdate(carbsTreatment); + getService().createOrUpdate(carbsTreatment); //log.debug("Adding new Treatment record" + carbsTreatment); } if (newRecordCreated && detailedBolusInfo.isValid) @@ -480,6 +488,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface // TempTargets @Subscribe + @SuppressWarnings("unused") public void onStatusEvent(final EventTempTargetChange ev) { initializeTempTargetData(); } @@ -509,6 +518,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface // Profile Switch @Subscribe + @SuppressWarnings("unused") public void onStatusEvent(final EventReloadProfileSwitchData ev) { initializeProfileSwitchData(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java index 6831ee33f9..87626ed4cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java @@ -31,7 +31,7 @@ import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; @@ -145,14 +145,14 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. final String _id = treatment._id; if (treatment.source == Source.PUMP) { treatment.isValid = false; - MainApp.getDbHelper().update(treatment); + TreatmentsPlugin.getPlugin().getService().update(treatment); } else { if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); } else { UploadQueue.removeID("dbAdd", _id); } - MainApp.getDbHelper().delete(treatment); + TreatmentsPlugin.getPlugin().getService().delete(treatment); } updateGUI(); FabricPrivacy.getInstance().logCustom(new CustomEvent("RemoveTreatment")); @@ -204,7 +204,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. builder.setMessage(this.getContext().getString(R.string.refresheventsfromnightscout) + "?"); builder.setPositiveButton(this.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { - MainApp.getDbHelper().resetTreatments(); + TreatmentsPlugin.getPlugin().getService().resetTreatments(); Intent restartNSClient = new Intent(Intents.ACTION_RESTART); MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index 90a1262a6b..bde197b45f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -37,7 +37,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; diff --git a/app/src/main/java/info/nightscout/utils/DateUtil.java b/app/src/main/java/info/nightscout/utils/DateUtil.java index cb0081f941..fd88ec2f9a 100644 --- a/app/src/main/java/info/nightscout/utils/DateUtil.java +++ b/app/src/main/java/info/nightscout/utils/DateUtil.java @@ -167,4 +167,8 @@ public class DateUtil { return System.currentTimeMillis(); } + public static long roundDateToSec(long date) { + return date - date % 1000; + } + } diff --git a/app/src/main/java/info/nightscout/utils/JsonHelper.java b/app/src/main/java/info/nightscout/utils/JsonHelper.java index 3cc9a3c8a0..ead68132af 100644 --- a/app/src/main/java/info/nightscout/utils/JsonHelper.java +++ b/app/src/main/java/info/nightscout/utils/JsonHelper.java @@ -17,41 +17,79 @@ public class JsonHelper { private JsonHelper() {}; - public static String safeGetString(JSONObject json, String fieldName) throws JSONException { + public static String safeGetString(JSONObject json, String fieldName) { String result = null; if (json.has(fieldName)) { - result = json.getString(fieldName); + try { + result = json.getString(fieldName); + } catch (JSONException ignored) { + } } return result; } - public static String safeGetString(JSONObject json, String fieldName, String defaultValue) throws JSONException { + public static String safeGetString(JSONObject json, String fieldName, String defaultValue) { String result = defaultValue; if (json.has(fieldName)) { - result = json.getString(fieldName); + try { + result = json.getString(fieldName); + } catch (JSONException ignored) { + } } return result; } - public static double safeGetDouble(JSONObject json, String fieldName) throws JSONException { + public static double safeGetDouble(JSONObject json, String fieldName) { double result = 0d; if (json.has(fieldName)) { - result = json.getDouble(fieldName); + try { + result = json.getDouble(fieldName); + } catch (JSONException ignored) { + } } return result; } - public static int safeGetInt(JSONObject json, String fieldName) throws JSONException { + public static int safeGetInt(JSONObject json, String fieldName) { int result = 0; if (json.has(fieldName)) { - result = json.getInt(fieldName); + try { + result = json.getInt(fieldName); + } catch (JSONException ignored) { + } + } + + return result; + } + + public static long safeGetLong(JSONObject json, String fieldName) { + long result = 0; + + if (json.has(fieldName)) { + try { + result = json.getLong(fieldName); + } catch (JSONException e) { + } + } + + return result; + } + + public static boolean safeGetBoolean(JSONObject json, String fieldName) { + boolean result = false; + + if (json.has(fieldName)) { + try { + result = json.getBoolean(fieldName); + } catch (JSONException e) { + } } return result; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePluginTest.java index d362937b82..c98dd07959 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePluginTest.java @@ -4,7 +4,7 @@ import org.junit.Before; import org.junit.Test; import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/app/src/test/java/info/nightscout/utils/BolusWizardTest.java b/app/src/test/java/info/nightscout/utils/BolusWizardTest.java index 4dfd87f870..be386e5eba 100644 --- a/app/src/test/java/info/nightscout/utils/BolusWizardTest.java +++ b/app/src/test/java/info/nightscout/utils/BolusWizardTest.java @@ -11,7 +11,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin; From a615553047a25834a8a23bf4cf4628173019b2c9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 5 Apr 2018 10:02:57 +0200 Subject: [PATCH 2/6] check for profile already set before notification --- .../nightscout/androidaps/queue/CommandQueue.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index 141d064682..8b7b2f8fbe 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -299,6 +299,13 @@ public class CommandQueue { // returns true if command is queued public boolean setProfile(Profile profile, Callback callback) { + if (isThisProfileSet(profile)) { + log.debug("QUEUE: Correct profile already set"); + if (callback != null) + callback.result(new PumpEnactResult().success(true).enacted(false)).run(); + return false; + } + if (isRunning(Command.CommandType.BASALPROFILE)) { if (callback != null) callback.result(executingNowError()).run(); @@ -329,13 +336,6 @@ public class CommandQueue { MainApp.bus().post(new EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM)); - if (isThisProfileSet(profile)) { - log.debug("QUEUE: Correct profile already set"); - if (callback != null) - callback.result(new PumpEnactResult().success(true).enacted(false)).run(); - return false; - } - // remove all unfinished removeAll(Command.CommandType.BASALPROFILE); From ba7d0aebaaced1f221d0009bb3ea08fed5a0e3c4 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 5 Apr 2018 10:46:23 +0200 Subject: [PATCH 3/6] show message ragarding closed loop mode only if closed mode is enabled in preferences --- .../java/info/nightscout/androidaps/MainApp.java | 5 ----- .../plugins/ConstraintsSafety/SafetyPlugin.java | 14 +++++++++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index d925330484..b5a1878160 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -212,11 +212,6 @@ public class MainApp extends Application { startKeepAliveService(); }).start(); } - - if (!isEngineeringModeOrRelease()) { - Notification n = new Notification(Notification.TOAST_ALARM, gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); - bus().post(new EventNewNotification(n)); - } } private void registerLocalBroadcastReceiver() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java index a3e27e1662..219236263c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPlugin.java @@ -14,6 +14,8 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; +import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.HardLimits; import info.nightscout.utils.Round; @@ -55,12 +57,18 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @Override public Constraint isClosedLoopAllowed(Constraint value) { - if (!MainApp.isEngineeringModeOrRelease()) - value.set(false, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), this); - String mode = SP.getString("aps_mode", "open"); if (!mode.equals("closed")) value.set(false, MainApp.gs(R.string.closedmodedisabledinpreferences), this); + + if (!MainApp.isEngineeringModeOrRelease()) { + if (value.value()) { + Notification n = new Notification(Notification.TOAST_ALARM, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL); + MainApp.bus().post(new EventNewNotification(n)); + } + value.set(false, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), this); + } + return value; } From ee133f87ae03981b7c69c97c38ea53cbec66c44b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 5 Apr 2018 10:56:55 +0200 Subject: [PATCH 4/6] fix test --- .../androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java index bfe430ccf5..0bd35e49ff 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/ConstraintsSafety/SafetyPluginTest.java @@ -230,6 +230,7 @@ public class SafetyPluginTest { AAPSMocker.mockConstraintsChecker(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); + AAPSMocker.mockBus(); when(MainApp.getConfigBuilder().getActivePump()).thenReturn(pump); From a5a0a27db6d42d630c29f0e50f5c36213a94cd9b Mon Sep 17 00:00:00 2001 From: "Markus M. May" Date: Thu, 5 Apr 2018 20:38:49 +0200 Subject: [PATCH 5/6] Xchange activity and eating soon temp target mgdl --- app/src/main/java/info/nightscout/androidaps/Constants.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index cd645abd9a..aeb4977584 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -41,10 +41,10 @@ public class Constants { // Temp targets public static final int defaultActivityTTDuration = 90; // min - public static final double defaultActivityTTmgdl = 90d; + public static final double defaultActivityTTmgdl = 140d; public static final double defaultActivityTTmmol = 8d; public static final int defaultEatingSoonTTDuration = 45; // min - public static final double defaultEatingSoonTTmgdl = 140d; + public static final double defaultEatingSoonTTmgdl = 90d; public static final double defaultEatingSoonTTmmol = 5d; public static final int defaultHypoTTDuration = 30; // min public static final double defaultHypoTTmgdl = 120d; From f89372e1de426198c433ad648f88bf6b38318c6a Mon Sep 17 00:00:00 2001 From: "Markus M. May" Date: Thu, 5 Apr 2018 20:54:48 +0200 Subject: [PATCH 6/6] build flavour full type debug on travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1d620e70b2..54a3e7ca0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ before_install: script: # Unit Test - - ./gradlew -Pcoverage test jacocoTestReport + - ./gradlew -Pcoverage testFullDebugUnitTest jacocoTestFullDebugUnitTestReport after_success: - bash <(curl -s https://codecov.io/bash) \ No newline at end of file