diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 015bad2651..1e49b03d73 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -48,6 +48,7 @@ import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Fragment; import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService; import info.nightscout.androidaps.plugins.PumpMDI.MDIFragment; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpFragment; +import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorFragment; import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpFragment; import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gFragment; @@ -102,7 +103,7 @@ public class MainApp extends Application { if (Config.DANARv2) pluginsList.add(DanaRv2Fragment.getPlugin()); pluginsList.add(CareportalFragment.getPlugin()); if (Config.MDI) pluginsList.add(MDIFragment.getPlugin()); - if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpFragment.getPlugin()); + if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance()); if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin()); if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin()); if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSAMAFragment.getPlugin()); 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 d5b1713848..def268bd35 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -463,24 +463,18 @@ public class DataService extends IntentService { public void handleAddChangeTempTargetRecord(JSONObject trJson) throws JSONException { if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPORARYTARGET)) { - if (Config.logIncommingData) - log.debug("Processing TempTarget record: " + trJson.toString()); MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(trJson); } } public void handleAddChangeTempBasalRecord(JSONObject trJson) throws JSONException { if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.TEMPBASAL)) { - if (Config.logIncommingData) - log.debug("Processing TempBasal record: " + trJson.toString()); MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(trJson); } } public void handleAddChangeExtendedBolusRecord(JSONObject trJson) throws JSONException { if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.COMBOBOLUS)) { - if (Config.logIncommingData) - log.debug("Processing Extended Bolus record: " + trJson.toString()); MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(trJson); } } @@ -503,8 +497,6 @@ public class DataService extends IntentService { trJson.getString("eventType").equals(CareportalEvent.OPENAPSOFFLINE) || trJson.getString("eventType").equals(CareportalEvent.PUMPBATTERYCHANGE) )) { - if (Config.logIncommingData) - log.debug("Processing CareportalEvent record: " + trJson.toString()); MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(trJson); } @@ -520,8 +512,6 @@ public class DataService extends IntentService { public void handleAddChangeProfileSwitchRecord(JSONObject trJson) throws JSONException { if (trJson.has("eventType") && trJson.getString("eventType").equals(CareportalEvent.PROFILESWITCH)) { - if (Config.logIncommingData) - log.debug("Processing ProfileSwitch record: " + trJson.toString()); MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson); } } diff --git a/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java index 1992825c26..f560ad0282 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java +++ b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java @@ -28,6 +28,5 @@ public class DetailedBolusInfo { public JSONObject boluscalc = null; // additional bolus wizard info public Context context = null; // context for progress dialog public boolean addToTreatments = true; - public boolean recordFromHistory = false; // true if record is comming from pump history (not a newly created treatment) public long pumpId = 0; // id of record if comming from pump history (not a newly created treatment) } 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 5704add8e5..cd216ef8e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -87,6 +87,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); onCreate(getWritableDatabase(), getConnectionSource()); + //onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1); } @Override @@ -528,8 +529,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (historyChange) { updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); - scheduleTreatmentChange(); } + scheduleTreatmentChange(); return true; } return false; @@ -553,8 +554,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (historyChange) { updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); - scheduleTreatmentChange(); } + scheduleTreatmentChange(); return true; } } @@ -673,7 +674,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { 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; @@ -717,14 +717,58 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } - public void createOrUpdate(TempTarget tempTarget) { - tempTarget.date = tempTarget.date - tempTarget.date % 1000; + public boolean createOrUpdate(TempTarget tempTarget) { try { - getDaoTempTargets().createOrUpdate(tempTarget); - scheduleTemporaryTargetChange(); + TempTarget old; + tempTarget.date = roundDateToSec(tempTarget.date); + + if (tempTarget.source == Source.NIGHTSCOUT) { + old = getDaoTempTargets().queryForId(tempTarget.date); + if (old != null) { + if (!old.isEqual(tempTarget)) { + getDaoTempTargets().delete(old); // need to delete/create because date may change too + old.copyFrom(tempTarget); + getDaoTempTargets().create(old); + log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); + scheduleTemporaryTargetChange(); + return true; + } + return false; + } + // find by NS _id + if (tempTarget._id != null) { + QueryBuilder queryBuilder = getDaoTempTargets().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", tempTarget._id); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoTempTargets().query(preparedQuery); + if (trList.size() > 0) { + old = trList.get(0); + if (!old.isEqual(tempTarget)) { + getDaoTempTargets().delete(old); // need to delete/create because date may change too + old.copyFrom(tempTarget); + getDaoTempTargets().create(old); + log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); + scheduleTemporaryTargetChange(); + return true; + } + } + } + getDaoTempTargets().create(tempTarget); + log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + scheduleTemporaryTargetChange(); + return true; + } + if (tempTarget.source == Source.USER) { + getDaoTempTargets().create(tempTarget); + log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + scheduleTemporaryTargetChange(); + return true; + } } catch (SQLException e) { e.printStackTrace(); } + return false; } public void delete(TempTarget tempTarget) { @@ -771,41 +815,32 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTemptargetFromJsonIfNotExists(JSONObject trJson) { try { - QueryBuilder queryBuilder = null; - queryBuilder = getDaoTempTargets().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoTempTargets().query(preparedQuery); Profile profile = MainApp.getConfigBuilder().getProfile(); String units = profile.getUnits(); - TempTarget tempTarget; - if (list.size() == 0) { - tempTarget = new TempTarget(); - if (Config.logIncommingData) - log.debug("Adding TempTarget record to database: " + trJson.toString()); - // Record does not exists. add - } else if (list.size() == 1) { - tempTarget = list.get(0); - if (Config.logIncommingData) - log.debug("Updating TempTarget record in database: " + trJson.toString()); - } else { - log.error("Something went wrong"); - return; - } + TempTarget tempTarget = new TempTarget(); tempTarget.date = trJson.getLong("mills"); tempTarget.durationInMinutes = trJson.getInt("duration"); tempTarget.low = Profile.toMgdl(trJson.getDouble("targetBottom"), units); tempTarget.high = Profile.toMgdl(trJson.getDouble("targetTop"), units); tempTarget.reason = trJson.getString("reason"); tempTarget._id = trJson.getString("_id"); + tempTarget.source = Source.NIGHTSCOUT; createOrUpdate(tempTarget); - } catch (SQLException | JSONException e) { + } catch (JSONException e) { e.printStackTrace(); } } public void deleteTempTargetById(String _id) { + TempTarget stored = findTempTargetById(_id); + if (stored != null) { + log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString()); + delete(stored); + scheduleTemporaryTargetChange(); + } + } + + public TempTarget findTempTargetById(String _id) { try { QueryBuilder queryBuilder = getDaoTempTargets().queryBuilder(); Where where = queryBuilder.where(); @@ -814,17 +849,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoTempTargets().query(preparedQuery); if (list.size() == 1) { - TempTarget record = list.get(0); - if (Config.logIncommingData) - log.debug("Removing TempTarget record from database: " + record.log()); - delete(record); + return list.get(0); } else { - if (Config.logIncommingData) - log.debug("TempTarget not found database: " + _id); + return null; } } catch (SQLException e) { e.printStackTrace(); } + return null; } // ----------------- DanaRHistory handling -------------------- @@ -881,15 +913,85 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // ------------ TemporaryBasal handling --------------- - public void createOrUpdate(TemporaryBasal tempBasal) { - tempBasal.date = tempBasal.date - tempBasal.date % 1000; + //return true if new record was created + public boolean createOrUpdate(TemporaryBasal tempBasal) { try { - getDaoTemporaryBasal().createOrUpdate(tempBasal); - updateEarliestDataChange(tempBasal.date); + TemporaryBasal old; + tempBasal.date = roundDateToSec(tempBasal.date); + + if (tempBasal.source == Source.PUMP) { + // check for changed from pump change in NS + QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("pumpId", tempBasal.pumpId); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoTemporaryBasal().query(preparedQuery); + if (trList.size() > 0) { + // do nothing, pump history record cannot be changed + log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + return false; + } + getDaoTemporaryBasal().create(tempBasal); + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + updateEarliestDataChange(tempBasal.date); + scheduleTemporaryBasalChange(); + return true; + } + if (tempBasal.source == Source.NIGHTSCOUT) { + old = getDaoTemporaryBasal().queryForId(tempBasal.date); + if (old != null) { + if (!old.isEqual(tempBasal)) { + long oldDate = old.date; + getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too + old.copyFrom(tempBasal); + getDaoTemporaryBasal().create(old); + log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); + updateEarliestDataChange(oldDate); + updateEarliestDataChange(old.date); + scheduleTemporaryBasalChange(); + return true; + } + return false; + } + // find by NS _id + if (tempBasal._id != null) { + QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", tempBasal._id); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoTemporaryBasal().query(preparedQuery); + if (trList.size() > 0) { + old = trList.get(0); + if (!old.isEqual(tempBasal)) { + long oldDate = old.date; + getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too + old.copyFrom(tempBasal); + getDaoTemporaryBasal().create(old); + log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); + updateEarliestDataChange(oldDate); + updateEarliestDataChange(old.date); + scheduleTemporaryBasalChange(); + return true; + } + } + } + getDaoTemporaryBasal().create(tempBasal); + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + updateEarliestDataChange(tempBasal.date); + scheduleTemporaryBasalChange(); + return true; + } + if (tempBasal.source == Source.USER) { + getDaoTemporaryBasal().create(tempBasal); + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + updateEarliestDataChange(tempBasal.date); + scheduleTemporaryBasalChange(); + return true; + } } catch (SQLException e) { e.printStackTrace(); } - scheduleTemporaryBasalChange(); + return false; } public void delete(TemporaryBasal tempBasal) { @@ -918,30 +1020,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } - @Nullable - public TemporaryBasal findTempBasalByTime(Long timeIndex) { - try { - QueryBuilder qb = null; - Dao daoTemporaryBasal = getDaoTemporaryBasal(); - QueryBuilder queryBuilder = daoTemporaryBasal.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("date", timeIndex); - queryBuilder.limit(10L); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = daoTemporaryBasal.query(preparedQuery); - if (trList.size() != 1) { - //log.debug("TemporaryBasal findTempBasalByTime query size: " + trList.size()); - return null; - } else { - //log.debug("TemporaryBasal findTempBasalByTime found: " + trList.get(0).log()); - return trList.get(0); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - private static void scheduleTemporaryBasalChange() { class PostRunnable implements Runnable { public void run() { @@ -983,82 +1061,28 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { try { if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal - QueryBuilder queryBuilder = null; - queryBuilder = getDaoExtendedBolus().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoExtendedBolus().query(preparedQuery); - ExtendedBolus extendedBolus; - if (list.size() == 0) { - extendedBolus = new ExtendedBolus(); - extendedBolus.source = Source.NIGHTSCOUT; - if (Config.logIncommingData) - log.debug("Adding ExtendedBolus record to database: " + trJson.toString()); - // Record does not exists. add - } else if (list.size() == 1) { - extendedBolus = list.get(0); - if (Config.logIncommingData) - log.debug("Updating ExtendedBolus record in database: " + trJson.toString()); - } else { - log.error("Something went wrong"); - return; - } + ExtendedBolus extendedBolus = new ExtendedBolus(); + extendedBolus.source = Source.NIGHTSCOUT; extendedBolus.date = trJson.getLong("mills"); + extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; extendedBolus.durationInMinutes = trJson.getInt("duration"); extendedBolus.insulin = trJson.getDouble("originalExtendedAmount"); extendedBolus._id = trJson.getString("_id"); createOrUpdate(extendedBolus); } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end - QueryBuilder queryBuilder = null; - queryBuilder = getDaoExtendedBolus().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoExtendedBolus().query(preparedQuery); - ExtendedBolus extendedBolus; - if (list.size() == 0) { - extendedBolus = new ExtendedBolus(); - extendedBolus.source = Source.NIGHTSCOUT; - if (Config.logIncommingData) - log.debug("Adding ExtendedBolus record to database: " + trJson.toString()); - // Record does not exists. add - } else if (list.size() == 1) { - extendedBolus = list.get(0); - if (Config.logIncommingData) - log.debug("Updating ExtendedBolus record in database: " + trJson.toString()); - } else { - log.error("Something went wrong"); - return; - } + ExtendedBolus extendedBolus = new ExtendedBolus(); + extendedBolus.source = Source.NIGHTSCOUT; extendedBolus.date = trJson.getLong("mills"); + extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; extendedBolus.durationInMinutes = 0; extendedBolus.insulin = 0; extendedBolus._id = trJson.getString("_id"); createOrUpdate(extendedBolus); } else { - QueryBuilder queryBuilder = null; - queryBuilder = getDaoTemporaryBasal().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoTemporaryBasal().query(preparedQuery); - TemporaryBasal tempBasal; - if (list.size() == 0) { - tempBasal = new TemporaryBasal(); - tempBasal.source = Source.NIGHTSCOUT; - if (Config.logIncommingData) - log.debug("Adding TemporaryBasal record to database: " + trJson.toString()); - // Record does not exists. add - } else if (list.size() == 1) { - tempBasal = list.get(0); - if (Config.logIncommingData) - log.debug("Updating TemporaryBasal record in database: " + trJson.toString()); - } else { - log.error("Something went wrong"); - return; - } + TemporaryBasal tempBasal = new TemporaryBasal(); tempBasal.date = trJson.getLong("mills"); + tempBasal.source = Source.NIGHTSCOUT; + tempBasal.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; if (trJson.has("duration")) { tempBasal.durationInMinutes = trJson.getInt("duration"); } @@ -1073,12 +1097,22 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempBasal._id = trJson.getString("_id"); createOrUpdate(tempBasal); } - } catch (SQLException | JSONException e) { + } catch (JSONException e) { e.printStackTrace(); } } public void deleteTempBasalById(String _id) { + TemporaryBasal stored = findTempBasalById(_id); + if (stored != null) { + log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); + delete(stored); + updateEarliestDataChange(stored.date); + scheduleTemporaryBasalChange(); + } + } + + public TemporaryBasal findTempBasalById(String _id) { try { QueryBuilder queryBuilder = null; queryBuilder = getDaoTemporaryBasal().queryBuilder(); @@ -1087,31 +1121,96 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); List list = getDaoTemporaryBasal().query(preparedQuery); - if (list.size() == 1) { - TemporaryBasal record = list.get(0); - if (Config.logIncommingData) - log.debug("Removing TempBasal record from database: " + record.log()); - delete(record); + if (list.size() != 1) { + return null; } else { - if (Config.logIncommingData) - log.debug("TempBasal not found database: " + _id); + return list.get(0); } } catch (SQLException e) { e.printStackTrace(); } + return null; } // ------------ ExtendedBolus handling --------------- - public void createOrUpdate(ExtendedBolus extendedBolus) { - extendedBolus.date = extendedBolus.date - extendedBolus.date % 1000; + public boolean createOrUpdate(ExtendedBolus extendedBolus) { try { - getDaoExtendedBolus().createOrUpdate(extendedBolus); - updateEarliestDataChange(extendedBolus.date); + ExtendedBolus old; + extendedBolus.date = roundDateToSec(extendedBolus.date); + + if (extendedBolus.source == Source.PUMP) { + // check for changed from pump change in NS + QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("pumpId", extendedBolus.pumpId); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoExtendedBolus().query(preparedQuery); + if (trList.size() > 0) { + // do nothing, pump history record cannot be changed + return false; + } + getDaoExtendedBolus().create(extendedBolus); + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + updateEarliestDataChange(extendedBolus.date); + scheduleTreatmentChange(); + return true; + } + if (extendedBolus.source == Source.NIGHTSCOUT) { + old = getDaoExtendedBolus().queryForId(extendedBolus.date); + if (old != null) { + if (!old.isEqual(extendedBolus)) { + long oldDate = old.date; + getDaoExtendedBolus().delete(old); // need to delete/create because date may change too + old.copyFrom(extendedBolus); + getDaoExtendedBolus().create(old); + log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString()); + updateEarliestDataChange(oldDate); + updateEarliestDataChange(old.date); + scheduleTreatmentChange(); + return true; + } + return false; + } + // find by NS _id + if (extendedBolus._id != null) { + QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", extendedBolus._id); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoExtendedBolus().query(preparedQuery); + if (trList.size() > 0) { + old = trList.get(0); + if (!old.isEqual(extendedBolus)) { + long oldDate = old.date; + getDaoExtendedBolus().delete(old); // need to delete/create because date may change too + old.copyFrom(extendedBolus); + getDaoExtendedBolus().create(old); + log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString()); + updateEarliestDataChange(oldDate); + updateEarliestDataChange(old.date); + scheduleTreatmentChange(); + return true; + } + } + } + getDaoExtendedBolus().create(extendedBolus); + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + updateEarliestDataChange(extendedBolus.date); + scheduleTreatmentChange(); + return true; + } + if (extendedBolus.source == Source.USER) { + getDaoExtendedBolus().create(extendedBolus); + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + updateEarliestDataChange(extendedBolus.date); + scheduleTreatmentChange(); + return true; + } } catch (SQLException e) { e.printStackTrace(); } - scheduleExtendedBolusChange(); + return false; } public void delete(ExtendedBolus extendedBolus) { @@ -1140,31 +1239,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } - @Nullable - public ExtendedBolus findExtendedBolusByTime(Long timeIndex) { - try { - QueryBuilder qb = null; - Dao daoExtendedBolus = getDaoExtendedBolus(); - QueryBuilder queryBuilder = daoExtendedBolus.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("date", timeIndex); - queryBuilder.limit(10L); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = daoExtendedBolus.query(preparedQuery); - if (trList.size() != 1) { - //log.debug("ExtendedBolus findExtendedBolusByTime query size: " + trList.size()); - return null; - } else { - //log.debug("ExtendedBolus findExtendedBolusByTime found: " + trList.get(0).log()); - return trList.get(0); - } - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - public void deleteExtendedBolusById(String _id) { + ExtendedBolus stored = findExtendedBolusById(_id); + if (stored != null) { + log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); + delete(stored); + updateEarliestDataChange(stored.date); + scheduleExtendedBolusChange(); + } + } + public ExtendedBolus findExtendedBolusById(String _id) { try { QueryBuilder queryBuilder = null; queryBuilder = getDaoExtendedBolus().queryBuilder(); @@ -1174,17 +1258,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoExtendedBolus().query(preparedQuery); if (list.size() == 1) { - ExtendedBolus record = list.get(0); - if (Config.logIncommingData) - log.debug("Removing ExtendedBolus record from database: " + record.log()); - delete(record); + return list.get(0); } else { - if (Config.logIncommingData) - log.debug("ExtendedBolus not found database: " + _id); + return null; } } catch (SQLException e) { e.printStackTrace(); } + return null; } /* @@ -1410,14 +1491,58 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } - public void createOrUpdate(ProfileSwitch profileSwitch) { - profileSwitch.date = profileSwitch.date - profileSwitch.date % 1000; + public boolean createOrUpdate(ProfileSwitch profileSwitch) { try { - getDaoProfileSwitch().createOrUpdate(profileSwitch); - scheduleProfileSwitchChange(); + ProfileSwitch old; + profileSwitch.date = roundDateToSec(profileSwitch.date); + + if (profileSwitch.source == Source.NIGHTSCOUT) { + old = getDaoProfileSwitch().queryForId(profileSwitch.date); + if (old != null) { + if (!old.isEqual(profileSwitch)) { + getDaoProfileSwitch().delete(old); // need to delete/create because date may change too + old.copyFrom(profileSwitch); + getDaoProfileSwitch().create(old); + log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + scheduleTemporaryTargetChange(); + return true; + } + return false; + } + // find by NS _id + if (profileSwitch._id != null) { + QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder(); + Where where = queryBuilder.where(); + where.eq("_id", profileSwitch._id); + PreparedQuery preparedQuery = queryBuilder.prepare(); + List trList = getDaoProfileSwitch().query(preparedQuery); + if (trList.size() > 0) { + old = trList.get(0); + if (!old.isEqual(profileSwitch)) { + getDaoProfileSwitch().delete(old); // need to delete/create because date may change too + old.copyFrom(profileSwitch); + getDaoProfileSwitch().create(old); + log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + scheduleTemporaryTargetChange(); + return true; + } + } + } + getDaoProfileSwitch().create(profileSwitch); + log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + scheduleTemporaryTargetChange(); + return true; + } + if (profileSwitch.source == Source.USER) { + getDaoProfileSwitch().create(profileSwitch); + log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + scheduleTemporaryTargetChange(); + return true; + } } catch (SQLException e) { e.printStackTrace(); } + return false; } public void delete(ProfileSwitch profileSwitch) { @@ -1461,32 +1586,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) { try { - QueryBuilder queryBuilder = null; - queryBuilder = getDaoProfileSwitch().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills")); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List list = getDaoProfileSwitch().query(preparedQuery); - ProfileSwitch profileSwitch; - if (list.size() == 0) { - profileSwitch = new ProfileSwitch(); - if (Config.logIncommingData) - log.debug("Adding ProfileSwitch record to database: " + trJson.toString()); - // Record does not exists. add - } else if (list.size() == 1) { - profileSwitch = list.get(0); - if (Config.logIncommingData) - log.debug("Updating ProfileSwitch record in database: " + trJson.toString()); - } else { - log.error("Something went wrong"); - return; - } + ProfileSwitch profileSwitch = new ProfileSwitch(); profileSwitch.date = trJson.getLong("mills"); if (trJson.has("duration")) profileSwitch.durationInMinutes = trJson.getInt("duration"); profileSwitch._id = trJson.getString("_id"); profileSwitch.profileName = trJson.getString("profile"); profileSwitch.isCPP = trJson.has("CircadianPercentageProfile"); + profileSwitch.source = Source.NIGHTSCOUT; if (trJson.has("timeshift")) profileSwitch.timeshift = trJson.getInt("timeshift"); if (trJson.has("percentage")) @@ -1496,12 +1603,21 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (trJson.has("profilePlugin")) profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); - } catch (SQLException | JSONException e) { + } catch (JSONException e) { e.printStackTrace(); } } public void deleteProfileSwitchById(String _id) { + ProfileSwitch stored = findProfileSwitchById(_id); + if (stored != null) { + log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); + delete(stored); + scheduleTemporaryTargetChange(); + } + } + + public ProfileSwitch findProfileSwitchById(String _id) { try { QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder(); Where where = queryBuilder.where(); @@ -1510,17 +1626,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoProfileSwitch().query(preparedQuery); if (list.size() == 1) { - ProfileSwitch record = list.get(0); - if (Config.logIncommingData) - log.debug("Removing ProfileSwitch record from database: " + record.log()); - delete(record); + return list.get(0); } else { - if (Config.logIncommingData) - log.debug("ProfileSwitch not found database: " + _id); + return null; } } catch (SQLException e) { e.printStackTrace(); } + return null; } } \ No newline at end of file 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 083ca76eeb..d422a94211 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -13,15 +13,16 @@ 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.data.Profile; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.utils.DateUtil; @@ -42,6 +43,9 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { @DatabaseField public boolean isValid = true; + @DatabaseField(index = true) + public long pumpId = 0; + @DatabaseField public int source = Source.NONE; @DatabaseField @@ -57,6 +61,35 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { @DatabaseField public double dia = Constants.defaultDIA; + public ExtendedBolus() { + } + + public ExtendedBolus(long date) { + this.date = date; + } + + public boolean isEqual(ExtendedBolus other) { + if (date != other.date) { + return false; + } + if (durationInMinutes != other.durationInMinutes) + return false; + if (insulin != other.insulin) + return false; + if (pumpId != other.pumpId) + return false; + if (!Objects.equals(_id, other._id)) + return false; + return true; + } + + public void copyFrom(ExtendedBolus t) { + date = t.date; + _id = t._id; + durationInMinutes = t.durationInMinutes; + insulin = t.insulin; + pumpId = t.pumpId; + } // -------- Interval interface --------- @@ -122,6 +155,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { ", date= " + DateUtil.dateAndTimeString(date) + ", isValid=" + isValid + ", _id= " + _id + + ", pumpId= " + pumpId + ", insulin= " + insulin + ", durationInMinutes= " + durationInMinutes + "}"; diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index 7806cd298f..448f6cdd51 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -9,6 +9,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; +import java.util.Objects; import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; @@ -49,6 +50,41 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface { @DatabaseField public int durationInMinutes = 0; + public boolean isEqual(ProfileSwitch other) { + if (date != other.date) { + return false; + } + if (durationInMinutes != other.durationInMinutes) + return false; + if (percentage != other.percentage) + return false; + if (timeshift != other.timeshift) + return false; + if (isCPP != other.isCPP) + return false; + if (!Objects.equals(_id, other._id)) + return false; + if (!Objects.equals(profilePlugin, other.profilePlugin)) + return false; + if (!Objects.equals(profileJson, other.profileJson)) + return false; + if (!Objects.equals(profileName, other.profileName)) + return false; + return true; + } + + public void copyFrom(ProfileSwitch t) { + date = t.date; + _id = t._id; + durationInMinutes = t.durationInMinutes; + percentage = t.percentage; + timeshift = t.timeshift; + isCPP = t.isCPP; + profilePlugin = t.profilePlugin; + profileJson = t.profileJson; + profileName = t.profileName; + } + // -------- Interval interface --------- Long cuttedEnd = null; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java index 60d53b96f8..7afe994437 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java @@ -7,6 +7,7 @@ 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.interfaces.Interval; @@ -40,6 +41,32 @@ public class TempTarget implements Interval { @DatabaseField public int durationInMinutes; + public boolean isEqual(TempTarget other) { + if (date != other.date) { + return false; + } + if (durationInMinutes != other.durationInMinutes) + return false; + if (low != other.low) + return false; + if (high != other.high) + return false; + if (reason != other.reason) + return false; + if (!Objects.equals(_id, other._id)) + return false; + return true; + } + + public void copyFrom(TempTarget t) { + date = t.date; + _id = t._id; + durationInMinutes = t.durationInMinutes; + low = t.low; + high = t.high; + reason = t.reason; + } + // -------- Interval interface --------- Long cuttedEnd = null; @@ -108,7 +135,7 @@ public class TempTarget implements Interval { else return DecimalFormatter.to1Decimal(low * Constants.MGDL_TO_MMOLL); } - public String log() { + public String toString() { return "TemporaryTarget{" + "date=" + date + "date=" + DateUtil.dateAndTimeString(date) + 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 45271cf753..4bf668411d 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -7,14 +7,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; +import java.util.Objects; 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.data.Profile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; @@ -32,6 +33,9 @@ public class TemporaryBasal implements Interval { @DatabaseField public boolean isValid = true; + @DatabaseField(index = true) + public long pumpId = 0; + @DatabaseField public int source = Source.NONE; @DatabaseField @@ -49,6 +53,10 @@ public class TemporaryBasal implements Interval { public TemporaryBasal() { } + public TemporaryBasal(long date) { + this.date = date; + } + public TemporaryBasal(ExtendedBolus extendedBolus) { double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date); this.date = extendedBolus.date; @@ -66,6 +74,7 @@ public class TemporaryBasal implements Interval { t.isValid = isValid; t.source = source; t._id = _id; + t.pumpId = pumpId; t.durationInMinutes = durationInMinutes; t.isAbsolute = isAbsolute; t.percentRate = percentRate; @@ -73,6 +82,35 @@ public class TemporaryBasal implements Interval { return t; } + public boolean isEqual(TemporaryBasal other) { + if (date != other.date) { + return false; + } + if (durationInMinutes != other.durationInMinutes) + return false; + if (isAbsolute != other.isAbsolute) + return false; + if (percentRate != other.percentRate) + return false; + if (absoluteRate != other.absoluteRate) + return false; + if (pumpId != other.pumpId) + return false; + if (!Objects.equals(_id, other._id)) + return false; + return true; + } + + public void copyFrom(TemporaryBasal t) { + date = t.date; + _id = t._id; + durationInMinutes = t.durationInMinutes; + isAbsolute = t.isAbsolute; + percentRate = t.percentRate; + absoluteRate = t.absoluteRate; + pumpId = t.pumpId; + } + // -------- Interval interface --------- Long cuttedEnd = null; @@ -205,11 +243,12 @@ public class TemporaryBasal implements Interval { } } - public String log() { + public String toString() { return "TemporaryBasal{" + "date=" + date + ", date=" + DateUtil.dateAndTimeString(date) + ", isValid=" + isValid + + ", pumpId=" + pumpId + ", _id=" + _id + ", percentRate=" + percentRate + ", absoluteRate=" + absoluteRate + @@ -218,7 +257,7 @@ public class TemporaryBasal implements Interval { '}'; } - public String toString() { + public String toStringFull() { if (isAbsolute) { return DecimalFormatter.to2Decimal(absoluteRate) + "U/h @" + DateUtil.timeString(date) + diff --git a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java index bcf68f9b7d..e386a195b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -56,6 +56,10 @@ public class Treatment implements DataPointWithLabelInterface { public Treatment() { } + public Treatment(long date) { + this.date = date; + } + public Treatment(InsulinInterface insulin) { insulinInterfaceID = insulin.getId(); dia = insulin.getDia(); 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 9fbfc15ca4..d9e3742c70 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -35,8 +35,7 @@ public interface TreatmentsInterface { boolean isInHistoryRealTempBasalInProgress(); TemporaryBasal getRealTempBasalFromHistory(long time); - void addToHistoryTempBasalStart(TemporaryBasal tempBasal); - void addToHistoryTempBasalStop(long time); + boolean addToHistoryTempBasal(TemporaryBasal tempBasal); // basal that can be faked by extended boluses boolean isTempBasalInProgress(); @@ -47,10 +46,10 @@ public interface TreatmentsInterface { boolean isInHistoryExtendedBoluslInProgress(); ExtendedBolus getExtendedBolusFromHistory(long time); - void addToHistoryExtendedBolusStart(ExtendedBolus extendedBolus); - void addToHistoryExtendedBolusStop(long time); OverlappingIntervals getExtendedBolusesFromHistory(); + boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus); + boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo); TempTarget getTempTargetFromHistory(long time); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index 23527e2a05..f1e5f09ebd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -658,6 +658,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick tempTarget.date = eventTime.getTime(); tempTarget.durationInMinutes = data.getInt("duration"); tempTarget.reason = data.getString("reason"); + tempTarget.source = Source.USER; if (tempTarget.durationInMinutes != 0) { tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits()); tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits()); @@ -665,7 +666,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick tempTarget.low = 0; tempTarget.high = 0; } - log.debug("Creating new TempTarget db record: " + tempTarget.log()); + log.debug("Creating new TempTarget db record: " + tempTarget.toString()); MainApp.getDbHelper().createOrUpdate(tempTarget); NSUpload.uploadCareportalEntryToNS(data); Answers.getInstance().logCustom(new CustomEvent("TempTarget")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java index dce0a48a61..b476577d06 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderPlugin.java @@ -48,6 +48,7 @@ import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.utils.NSUpload; /** @@ -56,22 +57,22 @@ import info.nightscout.utils.NSUpload; public class ConfigBuilderPlugin implements PluginBase, PumpInterface, ConstraintsInterface, TreatmentsInterface { private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class); - static BgSourceInterface activeBgSource; - static PumpInterface activePump; - static ProfileInterface activeProfile; - static TreatmentsInterface activeTreatments; - static APSInterface activeAPS; - static LoopPlugin activeLoop; - static InsulinInterface activeInsulin; + private static BgSourceInterface activeBgSource; + private static PumpInterface activePump; + private static ProfileInterface activeProfile; + private static TreatmentsInterface activeTreatments; + private static APSInterface activeAPS; + private static LoopPlugin activeLoop; + private static InsulinInterface activeInsulin; static public String nightscoutVersionName = ""; static public Integer nightscoutVersionCode = 0; static public String nsClientVersionName = ""; static public Integer nsClientVersionCode = 0; - static ArrayList pluginList; + private static ArrayList pluginList; - PowerManager.WakeLock mWakeLock; + private PowerManager.WakeLock mWakeLock; public ConfigBuilderPlugin() { MainApp.bus().register(this); @@ -108,12 +109,12 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain @Override public boolean isEnabled(int type) { - return type == GENERAL && true; + return type == GENERAL; } @Override public boolean isVisibleInTabs(int type) { - return type == GENERAL && true; + return type == GENERAL; } @Override @@ -207,7 +208,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain return activeLoop; } - public void logPluginStatus() { + void logPluginStatus() { for (PluginBase p : pluginList) { log.debug(p.getName() + ":" + (p.isEnabled(1) ? " GENERAL" : "") + @@ -275,7 +276,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain // PluginBase.PUMP pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP); activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP); - if (Config.logConfigBuilder && activePump != null) + if (activePump == null) + activePump = VirtualPumpPlugin.getInstance(); // for NSClient build + if (Config.logConfigBuilder) log.debug("Selected pump interface: " + ((PluginBase) activePump).getName()); for (PluginBase p : pluginsInCategory) { if (!p.getName().equals(((PluginBase) activePump).getName())) { @@ -402,43 +405,44 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain else return 0d; } -/* - public PumpEnactResult deliverTreatmentFromBolusWizard(InsulinInterface insulinType, Context context, Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) { - mWakeLock.acquire(); - PumpEnactResult result; - insulin = applyBolusConstraints(insulin); - carbs = applyCarbsConstraints(carbs); - BolusProgressDialog bolusProgressDialog = null; - if (context != null) { - bolusProgressDialog = new BolusProgressDialog(); - bolusProgressDialog.setInsulin(insulin); - bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); + /* + public PumpEnactResult deliverTreatmentFromBolusWizard(InsulinInterface insulinType, Context context, Double insulin, Integer carbs, Double glucose, String glucoseType, int carbTime, JSONObject boluscalc) { + mWakeLock.acquire(); + PumpEnactResult result; + insulin = applyBolusConstraints(insulin); + carbs = applyCarbsConstraints(carbs); + + BolusProgressDialog bolusProgressDialog = null; + if (context != null) { + bolusProgressDialog = new BolusProgressDialog(); + bolusProgressDialog.setInsulin(insulin); + bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); + } + + MainApp.bus().post(new EventBolusRequested(insulin)); + + result = activePump.deliverTreatment(insulinType, insulin, carbs, context); + + BolusProgressDialog.bolusEnded = true; + + MainApp.bus().post(new EventDismissBolusprogressIfRunning(result)); + + if (result.success) { + Treatment t = new Treatment(insulinType); + t.insulin = result.bolusDelivered; + if (carbTime == 0) + t.carbs = (double) result.carbsDelivered; // with different carbTime record will come back from nightscout + t.date = new Date().getTime(); + t.mealBolus = result.carbsDelivered > 0; + addToHistoryTreatment(t); + t.carbs = (double) result.carbsDelivered; + NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc); + } + mWakeLock.release(); + return result; } - - MainApp.bus().post(new EventBolusRequested(insulin)); - - result = activePump.deliverTreatment(insulinType, insulin, carbs, context); - - BolusProgressDialog.bolusEnded = true; - - MainApp.bus().post(new EventDismissBolusprogressIfRunning(result)); - - if (result.success) { - Treatment t = new Treatment(insulinType); - t.insulin = result.bolusDelivered; - if (carbTime == 0) - t.carbs = (double) result.carbsDelivered; // with different carbTime record will come back from nightscout - t.date = new Date().getTime(); - t.mealBolus = result.carbsDelivered > 0; - addToHistoryTreatment(t); - t.carbs = (double) result.carbsDelivered; - NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc); - } - mWakeLock.release(); - return result; - } -*/ + */ @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { mWakeLock.acquire(); @@ -463,56 +467,57 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain mWakeLock.release(); return result; } -/* - @Override - public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context) { - return deliverTreatment(insulinType, insulin, carbs, context, true); - } - public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context, boolean createTreatment) { - mWakeLock.acquire(); - PumpEnactResult result; - insulin = applyBolusConstraints(insulin); - carbs = applyCarbsConstraints(carbs); - - BolusProgressDialog bolusProgressDialog = null; - if (context != null) { - bolusProgressDialog = new BolusProgressDialog(); - bolusProgressDialog.setInsulin(insulin); - bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); - } else { - Intent i = new Intent(); - i.putExtra("insulin", insulin.doubleValue()); - i.setClass(MainApp.instance(), BolusProgressHelperActivity.class); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); + /* + @Override + public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context) { + return deliverTreatment(insulinType, insulin, carbs, context, true); } - MainApp.bus().post(new EventBolusRequested(insulin)); + public PumpEnactResult deliverTreatment(InsulinInterface insulinType, Double insulin, Integer carbs, Context context, boolean createTreatment) { + mWakeLock.acquire(); + PumpEnactResult result; + insulin = applyBolusConstraints(insulin); + carbs = applyCarbsConstraints(carbs); - result = activePump.deliverTreatment(insulinType, insulin, carbs, context); + BolusProgressDialog bolusProgressDialog = null; + if (context != null) { + bolusProgressDialog = new BolusProgressDialog(); + bolusProgressDialog.setInsulin(insulin); + bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); + } else { + Intent i = new Intent(); + i.putExtra("insulin", insulin.doubleValue()); + i.setClass(MainApp.instance(), BolusProgressHelperActivity.class); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + MainApp.instance().startActivity(i); + } - BolusProgressDialog.bolusEnded = true; + MainApp.bus().post(new EventBolusRequested(insulin)); - MainApp.bus().post(new EventDismissBolusprogressIfRunning(result)); + result = activePump.deliverTreatment(insulinType, insulin, carbs, context); - if (Config.logCongigBuilderActions) - log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered); + BolusProgressDialog.bolusEnded = true; - if (result.success && createTreatment) { - Treatment t = new Treatment(insulinType); - t.insulin = result.bolusDelivered; - t.carbs = (double) result.carbsDelivered; - t.date = new Date().getTime(); - t.mealBolus = t.carbs > 0; - addToHistoryTreatment(t); - NSUpload.uploadTreatment(t); + MainApp.bus().post(new EventDismissBolusprogressIfRunning(result)); + + if (Config.logCongigBuilderActions) + log.debug("deliverTreatment insulin: " + insulin + " carbs: " + carbs + " success: " + result.success + " enacted: " + result.enacted + " bolusDelivered: " + result.bolusDelivered); + + if (result.success && createTreatment) { + Treatment t = new Treatment(insulinType); + t.insulin = result.bolusDelivered; + t.carbs = (double) result.carbsDelivered; + t.date = new Date().getTime(); + t.mealBolus = t.carbs > 0; + addToHistoryTreatment(t); + NSUpload.uploadTreatment(t); + } + mWakeLock.release(); + return result; } - mWakeLock.release(); - return result; - } -*/ + */ @Override public void stopBolusDelivering() { activePump.stopBolusDelivering(); @@ -884,19 +889,17 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override - public void addToHistoryTempBasalStart(TemporaryBasal tempBasal) { - activeTreatments.addToHistoryTempBasalStart(tempBasal); - if (tempBasal.isAbsolute) - NSUpload.uploadTempBasalStartAbsolute(tempBasal, null); - else - NSUpload.uploadTempBasalStartPercent(tempBasal); - - } - - @Override - public void addToHistoryTempBasalStop(long time) { - activeTreatments.addToHistoryTempBasalStop(time); - NSUpload.uploadTempBasalEnd(time, false); + public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) { + boolean newRecordCreated = activeTreatments.addToHistoryTempBasal(tempBasal); + if (newRecordCreated) { + if (tempBasal.durationInMinutes == 0) + NSUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); + else if (tempBasal.isAbsolute) + NSUpload.uploadTempBasalStartAbsolute(tempBasal, null); + else + NSUpload.uploadTempBasalStartPercent(tempBasal); + } + return newRecordCreated; } @Override @@ -911,21 +914,20 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain } @Override - public void addToHistoryExtendedBolusStart(ExtendedBolus extendedBolus) { - activeTreatments.addToHistoryExtendedBolusStart(extendedBolus); - if (activePump.isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); - else - NSUpload.uploadExtendedBolus(extendedBolus); - } - - @Override - public void addToHistoryExtendedBolusStop(long time) { - activeTreatments.addToHistoryExtendedBolusStop(time); - if (activePump.isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalEnd(time, true); - else - NSUpload.uploadExtendedBolusEnd(time); + public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) { + boolean newRecordCreated = activeTreatments.addToHistoryExtendedBolus(extendedBolus); + if (newRecordCreated) { + if (extendedBolus.durationInMinutes == 0) { + if (activePump.isFakingTempsByExtendedBoluses()) + NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); + else + NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); + } else if (activePump.isFakingTempsByExtendedBoluses()) + NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); + else + NSUpload.uploadExtendedBolus(extendedBolus); + } + return newRecordCreated; } @Override @@ -980,6 +982,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain public String getProfileName() { return getProfileName(new Date().getTime()); } + public String getProfileName(long time) { ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time); if (profileSwitch != null) { @@ -996,12 +999,13 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain if (defaultProfile != null) return defaultProfile; // If default from plugin fails .... create empty - return "Default"; + return "Default"; } public Profile getProfile() { return getProfile(new Date().getTime()); } + public Profile getProfile(long time) { //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time); 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 2c919c9fe8..427ca5d531 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 @@ -12,7 +12,7 @@ public class AutosensData { public double deviation = 0d; boolean calculateWithDeviation = false; double absorbed = 0d; - double carbsFromBolus = 0d; + public double carbsFromBolus = 0d; public double cob = 0; public double bgi = 0d; public double delta = 0d; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 6c10a1e8d7..f308b1dfb6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -949,11 +949,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits())); else tempTargetView.setText(Profile.toUnitsString(tempTarget.low, Profile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + Profile.toUnitsString(tempTarget.high, Profile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits())); - } - if (Config.NSCLIENT) { - tempTargetView.setVisibility(View.GONE); } else { - Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; if (!profile.getUnits().equals(Constants.MGDL)) { @@ -965,6 +961,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, tempTargetView.setText(SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault)); tempTargetView.setVisibility(View.VISIBLE); } + if (Config.NSCLIENT && tempTarget == null) { + tempTargetView.setVisibility(View.GONE); + } // **** Temp button **** boolean showAcceptButton = !MainApp.getConfigBuilder().isClosedModeEnabled(); // Open mode needed @@ -996,7 +995,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, String basalText = ""; if (activeTemp != null) { - basalText = activeTemp.toString() + " "; + basalText = activeTemp.toStringFull() + " "; } if (Config.NSCLIENT) basalText += "( " + DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + " U/h )"; @@ -1297,17 +1296,30 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, List iobArray = new ArrayList<>(); List cobArray = new ArrayList<>(); List devArray = new ArrayList<>(); + double lastIob = 0; + int lastCob = 0; for (long time = fromTime; time <= now; time += 5 * 60 * 1000L) { if (showIobView.isChecked()) { - IobTotal iob = IobCobCalculatorPlugin.calulateFromTreatmentsAndTemps(time); - iobArray.add(new DataPoint(time, iob.iob)); - maxIobValueFound = Math.max(maxIobValueFound, Math.abs(iob.iob)); + double iob = IobCobCalculatorPlugin.calulateFromTreatmentsAndTemps(time).iob; + if (Math.abs(lastIob - iob) > 0.02) { + if (Math.abs(lastIob - iob) > 0.2) + iobArray.add(new DataPoint(time, lastIob)); + iobArray.add(new DataPoint(time, iob)); + maxIobValueFound = Math.max(maxIobValueFound, Math.abs(iob)); + lastIob = iob; + } } if (showCobView.isChecked() || showDeviationsView.isChecked()) { AutosensData autosensData = IobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null && showCobView.isChecked()) { - cobArray.add(new DataPoint(time, autosensData.cob)); - maxCobValueFound = Math.max(maxCobValueFound, autosensData.cob); + int cob = (int) autosensData.cob; + if (cob != lastCob) { + if (autosensData.carbsFromBolus > 0) + cobArray.add(new DataPoint(time, lastCob)); + cobArray.add(new DataPoint(time, cob)); + maxCobValueFound = Math.max(maxCobValueFound, cob); + lastCob = cob; + } } if (autosensData != null && showDeviationsView.isChecked()) { int color = Color.BLACK; // "=" @@ -1489,7 +1501,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, DataPointWithLabelInterface[] treatmentsArray = new DataPointWithLabelInterface[filteredTreatments.size()]; treatmentsArray = filteredTreatments.toArray(treatmentsArray); if (treatmentsArray.length > 0) { - bgGraph.addSeries(new PointsWithLabelGraphSeries<>(treatmentsArray)); + addSeriesWithoutInvalidate(new PointsWithLabelGraphSeries<>(treatmentsArray), bgGraph); } // set manual y bounds to have nice steps @@ -1530,7 +1542,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, new DataPoint(now, 0), new DataPoint(now, maxIobValueFound) }; - iobGraph.addSeries(seriesNow2 = new LineGraphSeries<>(nowPoints2)); + addSeriesWithoutInvalidate(seriesNow2 = new LineGraphSeries<>(nowPoints2), iobGraph); seriesNow2.setDrawDataPoints(false); //seriesNow.setThickness(1); // custom paint to make a dotted line @@ -1541,6 +1553,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, paint.setColor(Color.WHITE); seriesNow.setCustomPaint(paint); seriesNow2.setCustomPaint(paint); + bgGraph.onDataChanged(false, false); + iobGraph.onDataChanged(false, false); if (updating != null) updating.setVisibility(View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java index 95032fc052..20c8843a31 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java @@ -230,7 +230,7 @@ public class DanaRFragment extends Fragment { SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d); basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(getPlugin().getBaseBasalRate()) + " U/h"); if (MainApp.getConfigBuilder().isInHistoryRealTempBasalInProgress()) { - tempBasalView.setText(MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toString()); + tempBasalView.setText(MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toStringFull()); } else { tempBasalView.setText(""); } 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 b672d80f24..6d337048d7 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 @@ -805,7 +805,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; } if (MainApp.getConfigBuilder().isInHistoryRealTempBasalInProgress()) { - ret += "Temp: " + MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toString() + "\n"; + ret += "Temp: " + MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toStringFull() + "\n"; } if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) { ret += "Extended: " + MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime()).toString() + "\n"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusBolusExtended.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusBolusExtended.java index db30dcbdaa..9d9ccde307 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusBolusExtended.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusBolusExtended.java @@ -10,6 +10,7 @@ import java.util.Date; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.ExtendedBolus; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; @@ -73,26 +74,32 @@ public class MsgStatusBolusExtended extends MessageBase { if (pump.isExtendedInProgress) { if (extendedBolus.absoluteRate() != pump.extendedBolusAbsoluteRate) { // Close current extended - treatmentsInterface.addToHistoryExtendedBolusStop(now - 1000); + ExtendedBolus exStop = new ExtendedBolus(pump.extendedBolusStart.getTime() - 1000); + exStop.source = Source.USER; + treatmentsInterface.addToHistoryExtendedBolus(exStop); // Create new ExtendedBolus newExtended = new ExtendedBolus(); - newExtended.date = new Date(now).getTime(); + newExtended.date = pump.extendedBolusStart.getTime(); newExtended.insulin = pump.extendedBolusAmount; newExtended.durationInMinutes = pump.extendedBolusMinutes; - treatmentsInterface.addToHistoryExtendedBolusStart(newExtended); + newExtended.source = Source.USER; + treatmentsInterface.addToHistoryExtendedBolus(newExtended); } } else { // Close curent temp basal - treatmentsInterface.addToHistoryExtendedBolusStop(now); + ExtendedBolus exStop = new ExtendedBolus(now); + exStop.source = Source.USER; + treatmentsInterface.addToHistoryExtendedBolus(exStop); } } else { if (pump.isExtendedInProgress) { // Create new ExtendedBolus newExtended = new ExtendedBolus(); - newExtended.date = new Date(now).getTime(); + newExtended.date = pump.extendedBolusStart.getTime(); newExtended.insulin = pump.extendedBolusAmount; newExtended.durationInMinutes = pump.extendedBolusMinutes; - treatmentsInterface.addToHistoryExtendedBolusStart(newExtended); + newExtended.source = Source.USER; + treatmentsInterface.addToHistoryExtendedBolus(newExtended); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusTempBasal.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusTempBasal.java index 565243c2b3..bcfd56a8fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusTempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgStatusTempBasal.java @@ -9,6 +9,7 @@ import java.util.Date; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; @@ -67,28 +68,34 @@ public class MsgStatusTempBasal extends MessageBase { if (danaRPump.isTempBasalInProgress) { if (tempBasal.percentRate != danaRPump.tempBasalPercent) { // Close current temp basal - treatmentsInterface.addToHistoryTempBasalStop(now - 1000); + TemporaryBasal tempStop = new TemporaryBasal(danaRPump.tempBasalStart.getTime() - 1000); + tempStop.source = Source.USER; + treatmentsInterface.addToHistoryTempBasal(tempStop); // Create new TemporaryBasal newTempBasal = new TemporaryBasal(); - newTempBasal.date = new Date(now).getTime(); + newTempBasal.date = danaRPump.tempBasalStart.getTime(); newTempBasal.percentRate = danaRPump.tempBasalPercent; newTempBasal.isAbsolute = false; newTempBasal.durationInMinutes = danaRPump.tempBasalTotalSec / 60; - treatmentsInterface.addToHistoryTempBasalStart(newTempBasal); + newTempBasal.source = Source.USER; + treatmentsInterface.addToHistoryTempBasal(newTempBasal); } } else { // Close current temp basal - treatmentsInterface.addToHistoryTempBasalStop(now); + TemporaryBasal tempStop = new TemporaryBasal(now); + tempStop.source = Source.USER; + treatmentsInterface.addToHistoryTempBasal(tempStop); } } else { if (danaRPump.isTempBasalInProgress) { // Create new TemporaryBasal newTempBasal = new TemporaryBasal(); - newTempBasal.date = new Date(now).getTime(); + newTempBasal.date = danaRPump.tempBasalStart.getTime(); newTempBasal.percentRate = danaRPump.tempBasalPercent; newTempBasal.isAbsolute = false; newTempBasal.durationInMinutes = danaRPump.tempBasalTotalSec / 60; - treatmentsInterface.addToHistoryTempBasalStart(newTempBasal); + newTempBasal.source = Source.USER; + treatmentsInterface.addToHistoryTempBasal(newTempBasal); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanFragment.java index f61892d9ca..5a3a5a4f36 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanFragment.java @@ -229,7 +229,7 @@ public class DanaRKoreanFragment extends Fragment { SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d); basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(danaRKoreanPlugin.getBaseBasalRate()) + " U/h"); if (MainApp.getConfigBuilder().isInHistoryRealTempBasalInProgress()) { - tempBasalView.setText(MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toString()); + tempBasalView.setText(MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toStringFull()); } else { tempBasalView.setText(""); } 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 adc513d034..45330dc6d7 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 @@ -809,7 +809,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; } if (MainApp.getConfigBuilder().isInHistoryRealTempBasalInProgress()) { - ret += "Temp: " + MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toString() + "\n"; + ret += "Temp: " + MainApp.getConfigBuilder().getRealTempBasalFromHistory(new Date().getTime()).toStringFull() + "\n"; } if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) { ret += "Extended: " + MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime()).toString() + "\n"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Fragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Fragment.java index 246a6af91d..a0480685ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Fragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Fragment.java @@ -227,7 +227,7 @@ public class DanaRv2Fragment extends Fragment { SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d); basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(getPlugin().getBaseBasalRate()) + " U/h"); if (MainApp.getConfigBuilder().isTempBasalInProgress()) { - tempBasalView.setText(MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toString()); + tempBasalView.setText(MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toStringFull()); } else { tempBasalView.setText(""); } 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 f9612891f3..cf2cad1527 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 @@ -723,7 +723,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, ConstraintsInte ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; } if (MainApp.getConfigBuilder().isTempBasalInProgress()) { - ret += "Temp: " + MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toString() + "\n"; + ret += "Temp: " + MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toStringFull() + "\n"; } if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) { ret += "Extended: " + MainApp.getConfigBuilder().getExtendedBolusFromHistory(new Date().getTime()).toString() + "\n"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java index 626b339d59..fa3cff5c39 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java @@ -11,7 +11,6 @@ import info.nightscout.androidaps.data.DetailedBolusInfo; 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.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; @@ -53,76 +52,62 @@ public class MsgHistoryEvents_v2 extends MessageBase { int param1 = intFromBuff(bytes, 7, 2); int param2 = intFromBuff(bytes, 9, 2); - TemporaryBasal temporaryBasal = MainApp.getDbHelper().findTempBasalByTime(datetime.getTime()); - if (temporaryBasal != null) { - log.debug("EVENT (" + recordCode + ") " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); - log.debug("Existing temporaryBasal found. Skipping ..."); - if (datetime.getTime() > lastEventTimeLoaded) - lastEventTimeLoaded = datetime.getTime(); - return; - } - temporaryBasal = new TemporaryBasal(); + TemporaryBasal temporaryBasal = new TemporaryBasal(); + temporaryBasal.date = datetime.getTime(); + temporaryBasal.source = Source.PUMP; + temporaryBasal.pumpId = datetime.getTime(); - ExtendedBolus extendedBolus = MainApp.getDbHelper().findExtendedBolusByTime(datetime.getTime()); - if (extendedBolus != null) { - log.debug("EVENT (" + recordCode + ") " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); - log.debug("Existing extendedBolus found. Skipping ..."); - if (datetime.getTime() > lastEventTimeLoaded) - lastEventTimeLoaded = datetime.getTime(); - return; - } - extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(); + extendedBolus.date = datetime.getTime(); + extendedBolus.source = Source.PUMP; + extendedBolus.pumpId = datetime.getTime(); DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.recordFromHistory = true; + detailedBolusInfo.date = datetime.getTime(); + detailedBolusInfo.source = Source.PUMP; detailedBolusInfo.pumpId = datetime.getTime(); detailedBolusInfo.source = Source.PUMP; switch (recordCode) { case DanaRPump.TEMPSTART: log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); - temporaryBasal.date = datetime.getTime(); temporaryBasal.percentRate = param1; temporaryBasal.durationInMinutes = param2; - MainApp.getConfigBuilder().addToHistoryTempBasalStart(temporaryBasal); + MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal); break; case DanaRPump.TEMPSTOP: log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); - MainApp.getConfigBuilder().addToHistoryTempBasalStop(datetime.getTime()); + MainApp.getConfigBuilder().addToHistoryTempBasal(temporaryBasal); break; case DanaRPump.EXTENDEDSTART: log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); - extendedBolus.date = datetime.getTime(); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; - MainApp.getConfigBuilder().addToHistoryExtendedBolusStart(extendedBolus); + MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus); break; case DanaRPump.EXTENDEDSTOP: log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); - MainApp.getConfigBuilder().addToHistoryExtendedBolusStop(datetime.getTime()); + MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus); break; case DanaRPump.BOLUS: log.debug("EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); - detailedBolusInfo.date = datetime.getTime(); detailedBolusInfo.insulin = param1 / 100d; MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo); break; case DanaRPump.DUALBOLUS: log.debug("EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); - detailedBolusInfo.date = datetime.getTime(); detailedBolusInfo.insulin = param1 / 100d; MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo); break; case DanaRPump.DUALEXTENDEDSTART: log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); - extendedBolus.date = datetime.getTime(); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; - MainApp.getConfigBuilder().addToHistoryExtendedBolusStart(extendedBolus); + MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus); break; case DanaRPump.DUALEXTENDEDSTOP: log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); - MainApp.getConfigBuilder().addToHistoryExtendedBolusStop(datetime.getTime()); + MainApp.getConfigBuilder().addToHistoryExtendedBolus(extendedBolus); break; case DanaRPump.SUSPENDON: log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); @@ -141,7 +126,6 @@ public class MsgHistoryEvents_v2 extends MessageBase { break; case DanaRPump.CARBS: log.debug("EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); - detailedBolusInfo.date = datetime.getTime(); detailedBolusInfo.carbs = param1; MainApp.getConfigBuilder().addToHistoryTreatment(detailedBolusInfo); break; @@ -153,6 +137,5 @@ public class MsgHistoryEvents_v2 extends MessageBase { if (datetime.getTime() > lastEventTimeLoaded) lastEventTimeLoaded = datetime.getTime(); - return; } } 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 b32465cb73..57e3607504 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 @@ -401,26 +401,28 @@ public class DanaRv2ExecutionService extends Service { mSerialIOThread.sendMessage(msg); MsgSetHistoryEntry_v2 msgSetHistoryEntry_v2 = new MsgSetHistoryEntry_v2(DanaRPump.CARBS, carbtime, carbs, 0); mSerialIOThread.sendMessage(msgSetHistoryEntry_v2); - lastHistoryFetched = carbtime - 1000; + lastHistoryFetched = carbtime - 60000; } - MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables - MainApp.bus().post(new EventDanaRBolusStart()); + if (amount > 0) { + MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables + MainApp.bus().post(new EventDanaRBolusStart()); - if (!stop.stopped) { - mSerialIOThread.sendMessage(start); - } else { - t.insulin = 0d; - return false; - } - while (!stop.stopped && !start.failed) { - waitMsec(100); - if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm - stop.stopped = true; - stop.forced = true; - log.debug("Communication stopped"); + if (!stop.stopped) { + mSerialIOThread.sendMessage(start); + } else { + t.insulin = 0d; + return false; + } + while (!stop.stopped && !start.failed) { + waitMsec(100); + if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm + stop.stopped = true; + stop.forced = true; + log.debug("Communication stopped"); + } } } - waitMsec(1000); + waitMsec(3000); bolusingTreatment = null; loadEvents(); return true; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java index ef9efe4464..c2a0b6780b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java @@ -25,12 +25,6 @@ import info.nightscout.androidaps.plugins.PumpVirtual.events.EventVirtualPumpUpd public class VirtualPumpFragment extends Fragment { private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class); - private static VirtualPumpPlugin virtualPumpPlugin = new VirtualPumpPlugin(); - - public static VirtualPumpPlugin getPlugin() { - return virtualPumpPlugin; - } - TextView basaBasalRateView; TextView tempBasalView; TextView extendedBolusView; @@ -93,9 +87,9 @@ public class VirtualPumpFragment extends Fragment { @Override public void run() { - basaBasalRateView.setText(virtualPumpPlugin.getBaseBasalRate() + "U"); + basaBasalRateView.setText(VirtualPumpPlugin.getInstance().getBaseBasalRate() + "U"); if (MainApp.getConfigBuilder().isTempBasalInProgress()) { - tempBasalView.setText(MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toString()); + tempBasalView.setText(MainApp.getConfigBuilder().getTempBasalFromHistory(new Date().getTime()).toStringFull()); } else { tempBasalView.setText(""); } @@ -104,8 +98,8 @@ public class VirtualPumpFragment extends Fragment { } else { extendedBolusView.setText(""); } - batteryView.setText(VirtualPumpPlugin.batteryPercent + "%"); - reservoirView.setText(VirtualPumpPlugin.reservoirInUnits + "U"); + batteryView.setText(VirtualPumpPlugin.getInstance().batteryPercent + "%"); + reservoirView.setText(VirtualPumpPlugin.getInstance().reservoirInUnits + "U"); } }); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java index 309c031803..39dfcf7873 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; 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.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PumpDescription; @@ -46,6 +47,13 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { PumpDescription pumpDescription = new PumpDescription(); + static VirtualPumpPlugin instance = null; + public static VirtualPumpPlugin getInstance() { + if (instance == null) + instance = new VirtualPumpPlugin(); + return instance; + } + public VirtualPumpPlugin() { pumpDescription.isBolusCapable = true; pumpDescription.bolusStep = 0.1d; @@ -235,6 +243,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { tempBasal.isAbsolute = true; tempBasal.absoluteRate = absoluteRate; tempBasal.durationInMinutes = durationInMinutes; + tempBasal.source = Source.USER; PumpEnactResult result = new PumpEnactResult(); result.success = true; result.enacted = true; @@ -242,7 +251,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { result.absolute = absoluteRate; result.duration = durationInMinutes; result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); - treatmentsInterface.addToHistoryTempBasalStart(tempBasal); + treatmentsInterface.addToHistoryTempBasal(tempBasal); if (Config.logPumpComm) log.debug("Setting temp basal absolute: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); @@ -264,6 +273,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { tempBasal.isAbsolute = false; tempBasal.percentRate = percent; tempBasal.durationInMinutes = durationInMinutes; + tempBasal.source = Source.USER; result.success = true; result.enacted = true; result.percent = percent; @@ -271,7 +281,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { result.isTempCancel = false; result.duration = durationInMinutes; result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); - treatmentsInterface.addToHistoryTempBasalStart(tempBasal); + treatmentsInterface.addToHistoryTempBasal(tempBasal); if (Config.logPumpComm) log.debug("Settings temp basal percent: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); @@ -289,13 +299,14 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { extendedBolus.date = new Date().getTime(); extendedBolus.insulin = insulin; extendedBolus.durationInMinutes = durationInMinutes; + extendedBolus.source = Source.USER; result.success = true; result.enacted = true; result.bolusDelivered = insulin; result.isTempCancel = false; result.duration = durationInMinutes; result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); - treatmentsInterface.addToHistoryExtendedBolusStart(extendedBolus); + treatmentsInterface.addToHistoryExtendedBolus(extendedBolus); if (Config.logPumpComm) log.debug("Setting extended bolus: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); @@ -312,7 +323,9 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (treatmentsInterface.isTempBasalInProgress()) { result.enacted = true; - treatmentsInterface.addToHistoryTempBasalStop(new Date().getTime()); + TemporaryBasal tempStop = new TemporaryBasal(new Date().getTime()); + tempStop.source = Source.USER; + treatmentsInterface.addToHistoryTempBasal(tempStop); //tempBasal = null; if (Config.logPumpComm) log.debug("Canceling temp basal: " + result); @@ -327,7 +340,9 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder(); PumpEnactResult result = new PumpEnactResult(); if (treatmentsInterface.isInHistoryExtendedBoluslInProgress()) { - treatmentsInterface.addToHistoryExtendedBolusStop(new Date().getTime()); + ExtendedBolus exStop = new ExtendedBolus(new Date().getTime()); + exStop.source = Source.USER; + treatmentsInterface.addToHistoryExtendedBolus(exStop); } result.success = true; result.enacted = true; 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 a618feed7b..50bb0c7892 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 @@ -342,18 +342,9 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { } @Override - public void addToHistoryExtendedBolusStart(ExtendedBolus extendedBolus) { - log.debug("Adding new ExtentedBolus record" + extendedBolus.log()); - MainApp.getDbHelper().createOrUpdate(extendedBolus); - } - - @Override - public void addToHistoryExtendedBolusStop(long time) { - ExtendedBolus extendedBolus = new ExtendedBolus(); - extendedBolus.date = time; - extendedBolus.durationInMinutes = 0; - log.debug("Adding new ExtentedBolus stop record" + extendedBolus.log()); - MainApp.getDbHelper().createOrUpdate(extendedBolus); + public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) { + //log.debug("Adding new ExtentedBolus record" + extendedBolus.log()); + return MainApp.getDbHelper().createOrUpdate(extendedBolus); } @Override @@ -391,44 +382,33 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { } @Override - public void addToHistoryTempBasalStart(TemporaryBasal tempBasal) { - log.debug("Adding new TemporaryBasal record" + tempBasal.log()); - MainApp.getDbHelper().createOrUpdate(tempBasal); - } - - @Override - public void addToHistoryTempBasalStop(long time) { - TemporaryBasal temporaryBasal = new TemporaryBasal(); - temporaryBasal.date = time; - temporaryBasal.durationInMinutes = 0; - log.debug("Adding new TemporaryBasal stop record" + temporaryBasal.log()); - MainApp.getDbHelper().createOrUpdate(temporaryBasal); + public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) { + //log.debug("Adding new TemporaryBasal record" + tempBasal.toString()); + return MainApp.getDbHelper().createOrUpdate(tempBasal); } @Override public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo) { Treatment treatment = new Treatment(detailedBolusInfo.insulinInterface); treatment.date = detailedBolusInfo.date; - treatment.source = detailedBolusInfo.recordFromHistory ? Source.PUMP : Source.USER; - if (detailedBolusInfo.recordFromHistory) - treatment.pumpId = treatment.date; + treatment.source = detailedBolusInfo.source; + treatment.pumpId = detailedBolusInfo.pumpId; treatment.insulin = detailedBolusInfo.insulin; if (detailedBolusInfo.carbTime == 0) treatment.carbs = detailedBolusInfo.carbs; treatment.source = detailedBolusInfo.source; treatment.mealBolus = treatment.carbs > 0; boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(treatment); - log.debug("Adding new Treatment record" + treatment.toString()); + //log.debug("Adding new Treatment record" + treatment.toString()); if (detailedBolusInfo.carbTime != 0) { Treatment carbsTreatment = new Treatment(detailedBolusInfo.insulinInterface); - carbsTreatment.source = detailedBolusInfo.recordFromHistory ? Source.PUMP : Source.USER; - if (detailedBolusInfo.recordFromHistory) - carbsTreatment.pumpId = treatment.date; + carbsTreatment.source = detailedBolusInfo.source; + carbsTreatment.pumpId = detailedBolusInfo.pumpId; // but this should never happen 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); - log.debug("Adding new Treatment record" + carbsTreatment); + //log.debug("Adding new Treatment record" + carbsTreatment); } return newRecordCreated; } @@ -481,7 +461,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { @Override public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) { - log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); + //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); MainApp.getDbHelper().createOrUpdate(profileSwitch); } 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 c2bbd123e3..5f6ff02950 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 @@ -32,6 +32,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.Iob; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTreatmentChange; @@ -73,18 +74,21 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) return; - holder.date.setText(DateUtil.dateAndTimeString(treatments.get(position).date)); - holder.insulin.setText(DecimalFormatter.to2Decimal(treatments.get(position).insulin) + " U"); - holder.carbs.setText(DecimalFormatter.to0Decimal(treatments.get(position).carbs) + " g"); - Iob iob = treatments.get(position).iobCalc(new Date().getTime(), profile.getDia()); + Treatment t = treatments.get(position); + holder.date.setText(DateUtil.dateAndTimeString(t.date)); + holder.insulin.setText(DecimalFormatter.to2Decimal(t.insulin) + " U"); + holder.carbs.setText(DecimalFormatter.to0Decimal(t.carbs) + " g"); + Iob iob = t.iobCalc(new Date().getTime(), profile.getDia()); holder.iob.setText(DecimalFormatter.to2Decimal(iob.iobContrib) + " U"); holder.activity.setText(DecimalFormatter.to3Decimal(iob.activityContrib) + " U"); - holder.mealOrCorrection.setText(treatments.get(position).mealBolus ? MainApp.sResources.getString(R.string.mealbolus) : MainApp.sResources.getString(R.string.correctionbous)); + holder.mealOrCorrection.setText(t.mealBolus ? MainApp.sResources.getString(R.string.mealbolus) : MainApp.sResources.getString(R.string.correctionbous)); + holder.ph.setVisibility(t.source == Source.PUMP ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(t._id != null ? View.VISIBLE : View.GONE); if (iob.iobContrib != 0) holder.iob.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive)); else holder.iob.setTextColor(holder.carbs.getCurrentTextColor()); - holder.remove.setTag(treatments.get(position)); + holder.remove.setTag(t); } @Override @@ -106,6 +110,8 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis TextView activity; TextView mealOrCorrection; TextView remove; + TextView ph; + TextView ns; TreatmentsViewHolder(View itemView) { super(itemView); @@ -116,6 +122,8 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis iob = (TextView) itemView.findViewById(R.id.treatments_iob); activity = (TextView) itemView.findViewById(R.id.treatments_activity); mealOrCorrection = (TextView) itemView.findViewById(R.id.treatments_mealorcorrection); + ph = (TextView) itemView.findViewById(R.id.pump_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); remove = (TextView) itemView.findViewById(R.id.treatments_remove); remove.setOnClickListener(this); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java index 96842aafbe..fcd691cf68 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.ExtendedBolus; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.utils.DateUtil; @@ -62,6 +63,8 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { @Override public void onBindViewHolder(ExtendedBolusesViewHolder holder, int position) { ExtendedBolus extendedBolus = extendedBolusList.getReversed(position); + holder.ph.setVisibility(extendedBolus.source == Source.PUMP ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(extendedBolus._id != null ? View.VISIBLE : View.GONE); if (extendedBolus.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(extendedBolus.date)); holder.duration.setText(MainApp.sResources.getString(R.string.cancel)); @@ -115,6 +118,8 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { TextView insulinSoFar; TextView iob; TextView remove; + TextView ph; + TextView ns; ExtendedBolusesViewHolder(View itemView) { super(itemView); @@ -126,6 +131,8 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { ratio = (TextView) itemView.findViewById(R.id.extendedboluses_ratio); insulinSoFar = (TextView) itemView.findViewById(R.id.extendedboluses_netinsulin); iob = (TextView) itemView.findViewById(R.id.extendedboluses_iob); + ph = (TextView) itemView.findViewById(R.id.pump_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); remove = (TextView) itemView.findViewById(R.id.extendedboluses_remove); remove.setOnClickListener(this); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java index 01955ba937..344abd8346 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -26,6 +26,7 @@ import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventTempTargetChange; @@ -67,6 +68,8 @@ public class TreatmentsProfileSwitchFragment extends Fragment implements View.On Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) return; ProfileSwitch profileSwitch = profileSwitchList.getReversed(position); + holder.ph.setVisibility(profileSwitch.source == Source.PUMP ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(profileSwitch._id != null ? View.VISIBLE : View.GONE); holder.date.setText(DateUtil.dateAndTimeString(profileSwitch.date)); if (!profileSwitch.isEndingEvent()) { @@ -98,6 +101,8 @@ public class TreatmentsProfileSwitchFragment extends Fragment implements View.On TextView duration; TextView name; TextView remove; + TextView ph; + TextView ns; ProfileSwitchViewHolder(View itemView) { super(itemView); @@ -105,6 +110,8 @@ public class TreatmentsProfileSwitchFragment extends Fragment implements View.On date = (TextView) itemView.findViewById(R.id.profileswitch_date); duration = (TextView) itemView.findViewById(R.id.profileswitch_duration); name = (TextView) itemView.findViewById(R.id.profileswitch_name); + ph = (TextView) itemView.findViewById(R.id.pump_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); remove = (TextView) itemView.findViewById(R.id.profileswitch_remove); remove.setOnClickListener(this); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index d8a84b0e1c..9b2603ef4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -23,6 +23,7 @@ import com.squareup.otto.Subscribe; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.data.Profile; @@ -64,6 +65,8 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null) return; TempTarget tempTarget = tempTargetList.getReversed(position); + holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(tempTarget._id != null ? View.VISIBLE : View.GONE); if (!tempTarget.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date) + " - " + DateUtil.timeString(tempTarget.originalEnd())); holder.duration.setText(DecimalFormatter.to0Decimal(tempTarget.durationInMinutes) + " min"); @@ -106,6 +109,8 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli TextView reasonLabel; TextView reasonColon; TextView remove; + TextView ph; + TextView ns; TempTargetsViewHolder(View itemView) { super(itemView); @@ -117,6 +122,8 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli reason = (TextView) itemView.findViewById(R.id.temptargetrange_reason); reasonLabel = (TextView) itemView.findViewById(R.id.temptargetrange_reason_label); reasonColon = (TextView) itemView.findViewById(R.id.temptargetrange_reason_colon); + ph = (TextView) itemView.findViewById(R.id.pump_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); remove = (TextView) itemView.findViewById(R.id.temptargetrange_remove); remove.setOnClickListener(this); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java index ce2558683b..61c93abd96 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -28,6 +28,7 @@ import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; @@ -64,6 +65,8 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { @Override public void onBindViewHolder(TempBasalsViewHolder holder, int position) { TemporaryBasal tempBasal = tempBasalList.getReversed(position); + holder.ph.setVisibility(tempBasal.source == Source.PUMP ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(tempBasal._id != null ? View.VISIBLE : View.GONE); if (tempBasal.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(tempBasal.date)); holder.duration.setText(MainApp.sResources.getString(R.string.cancel)); @@ -130,6 +133,8 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { TextView iob; TextView extendedFlag; TextView remove; + TextView ph; + TextView ns; TempBasalsViewHolder(View itemView) { super(itemView); @@ -143,6 +148,8 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { netInsulin = (TextView) itemView.findViewById(R.id.tempbasals_netinsulin); iob = (TextView) itemView.findViewById(R.id.tempbasals_iob); extendedFlag = (TextView) itemView.findViewById(R.id.tempbasals_extendedflag); + ph = (TextView) itemView.findViewById(R.id.pump_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); remove = (TextView) itemView.findViewById(R.id.tempbasals_remove); remove.setOnClickListener(this); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); @@ -219,7 +226,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { public void updateGUI() { Activity activity = getActivity(); - if (activity != null && recyclerView != null) + if (activity != null) activity.runOnUiThread(new Runnable() { @Override public void run() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java index fe14560019..8fc7e9f868 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java @@ -350,6 +350,7 @@ public class ActionStringHandler { tempTarget.date = new Date().getTime(); tempTarget.durationInMinutes = duration; tempTarget.reason = "WearPlugin"; + tempTarget.source = Source.USER; if (tempTarget.durationInMinutes != 0) { tempTarget.low = low; tempTarget.high = high; diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/utils/NSUpload.java index d25c276d23..86d15dc9b7 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -44,6 +44,8 @@ public class NSUpload { data.put("eventType", CareportalEvent.TEMPBASAL); data.put("duration", temporaryBasal.durationInMinutes); data.put("absolute", temporaryBasal.absoluteRate); + if (temporaryBasal.pumpId != 0) + data.put("pumpId", temporaryBasal.pumpId); data.put("created_at", DateUtil.toISOString(temporaryBasal.date)); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + temporaryBasal.absoluteRate + "u/h " + temporaryBasal.durationInMinutes + " min"); // ECOR @@ -81,6 +83,8 @@ public class NSUpload { data.put("eventType", CareportalEvent.TEMPBASAL); data.put("duration", temporaryBasal.durationInMinutes); data.put("percent", temporaryBasal.percentRate - 100); + if (temporaryBasal.pumpId != 0) + data.put("pumpId", temporaryBasal.pumpId); data.put("created_at", DateUtil.toISOString(temporaryBasal.date)); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + temporaryBasal.percentRate + "% " + temporaryBasal.durationInMinutes + " min"); // ECOR @@ -99,7 +103,7 @@ public class NSUpload { } } - public static void uploadTempBasalEnd(long time, boolean isFakedTempBasal) { + public static void uploadTempBasalEnd(long time, boolean isFakedTempBasal, long pumpId) { try { Context context = MainApp.instance().getApplicationContext(); JSONObject data = new JSONObject(); @@ -109,6 +113,8 @@ public class NSUpload { data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalendnote)); // ECOR if (isFakedTempBasal) data.put("isFakedTempBasal", isFakedTempBasal); + if (pumpId != 0) + data.put("pumpId", pumpId); Bundle bundle = new Bundle(); bundle.putString("action", "dbAdd"); bundle.putString("collection", "treatments"); @@ -133,6 +139,8 @@ public class NSUpload { data.put("splitExt", 100); data.put("enteredinsulin", extendedBolus.insulin); data.put("relative", extendedBolus.insulin); + if (extendedBolus.pumpId != 0) + data.put("pumpId", extendedBolus.pumpId); data.put("created_at", DateUtil.toISOString(extendedBolus.date)); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); Bundle bundle = new Bundle(); @@ -149,7 +157,7 @@ public class NSUpload { } } - public static void uploadExtendedBolusEnd(long time) { + public static void uploadExtendedBolusEnd(long time, long pumpId) { try { Context context = MainApp.instance().getApplicationContext(); JSONObject data = new JSONObject(); @@ -161,6 +169,8 @@ public class NSUpload { data.put("relative", 0); data.put("created_at", DateUtil.toISOString(time)); data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + if (pumpId != 0) + data.put("pumpId", pumpId); Bundle bundle = new Bundle(); bundle.putString("action", "dbAdd"); bundle.putString("collection", "treatments"); diff --git a/app/src/main/res/layout/treatments_bolus_item.xml b/app/src/main/res/layout/treatments_bolus_item.xml index d2a30aa0aa..a7189f7dc7 100644 --- a/app/src/main/res/layout/treatments_bolus_item.xml +++ b/app/src/main/res/layout/treatments_bolus_item.xml @@ -82,6 +82,30 @@ android:layout_gravity="center_vertical" android:layout_marginRight="30dp" android:textStyle="bold" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +