Merge pull request #1360 from MilosKozak/insightfix

WIP Insightfix
This commit is contained in:
Milos Kozak 2018-09-14 14:06:18 +02:00 committed by GitHub
commit cc804ac36f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 193 additions and 112 deletions

View file

@ -961,13 +961,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try { try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.source = Source.NIGHTSCOUT; .source(Source.NIGHTSCOUT)
extendedBolus.date = trJson.getLong("mills"); .date(trJson.getLong("mills"))
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
extendedBolus.durationInMinutes = trJson.getInt("duration"); .durationInMinutes(trJson.getInt("duration"))
extendedBolus.insulin = trJson.getDouble("originalExtendedAmount"); .insulin(trJson.getDouble("originalExtendedAmount"))
extendedBolus._id = trJson.getString("_id"); ._id(trJson.getString("_id"));
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) { if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true); VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0); updateEarliestDataChange(0);
@ -982,6 +983,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
extendedBolus.durationInMinutes = 0; extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0; extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id"); extendedBolus._id = trJson.getString("_id");
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) { if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true); VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0); updateEarliestDataChange(0);
@ -1047,23 +1049,33 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public boolean createOrUpdate(ExtendedBolus extendedBolus) { public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try { try {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
ExtendedBolus old; ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date); extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) { if (extendedBolus.source == Source.PUMP) {
// check for changed from pump change in NS // if pumpId == 0 do not check for existing pumpId
// used with pumps without history
// and insight where record as added first without pumpId
// and then is record updated with pumpId
if (extendedBolus.pumpId == 0) {
getDaoExtendedBolus().createOrUpdate(extendedBolus);
} else {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder(); QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where(); Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId); where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare(); PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery); List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) { if (trList.size() > 1) {
// do nothing, pump history record cannot be changed log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
return false; return false;
} }
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().createOrUpdate(extendedBolus);
}
if (L.isEnabled(L.DATABASE)) if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1077,7 +1089,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE)) if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString()); log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1100,7 +1112,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE)) if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString()); log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate); updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1110,7 +1122,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE)) if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1118,7 +1130,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (extendedBolus.source == Source.USER) { if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus); getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE)) if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;

View file

@ -70,6 +70,36 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
this.date = date; this.date = date;
} }
public ExtendedBolus date(long date) {
this.date = date;
return this;
}
public ExtendedBolus insulin(double insulin) {
this.insulin = insulin;
return this;
}
public ExtendedBolus pumpId(long pumpId) {
this.pumpId = pumpId;
return this;
}
public ExtendedBolus source(int source) {
this.source = source;
return this;
}
public ExtendedBolus durationInMinutes(int durationInMinutes) {
this.durationInMinutes = durationInMinutes;
return this;
}
public ExtendedBolus _id(String _id) {
this._id = _id;
return this;
}
public boolean isEqual(ExtendedBolus other) { public boolean isEqual(ExtendedBolus other) {
if (date != other.date) { if (date != other.date) {
return false; return false;
@ -94,13 +124,13 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
} }
public static ExtendedBolus createFromJson(JSONObject json) { public static ExtendedBolus createFromJson(JSONObject json) {
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.source = Source.NIGHTSCOUT; .source(Source.NIGHTSCOUT)
extendedBolus.date = JsonHelper.safeGetLong(json, "mills"); .date(JsonHelper.safeGetLong(json, "mills"))
extendedBolus.durationInMinutes = JsonHelper.safeGetInt(json, "duration"); .durationInMinutes(JsonHelper.safeGetInt(json, "duration"))
extendedBolus.insulin = JsonHelper.safeGetDouble(json, "relative") / 60 * extendedBolus.durationInMinutes; .insulin(JsonHelper.safeGetDouble(json, "relative") / 60 * JsonHelper.safeGetInt(json, "duration"))
extendedBolus._id = JsonHelper.safeGetString(json, "_id"); ._id(JsonHelper.safeGetString(json, "_id"))
extendedBolus.pumpId = JsonHelper.safeGetLong(json, "pumpId"); .pumpId(JsonHelper.safeGetLong(json, "pumpId"));
return extendedBolus; return extendedBolus;
} }
// -------- Interval interface --------- // -------- Interval interface ---------
@ -167,7 +197,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
// -------- Interval interface end --------- // -------- Interval interface end ---------
public String log() { public String log() {
return "Bolus{" + return "ExtendedBolus{" +
"date= " + date + "date= " + date +
", date= " + DateUtil.dateAndTimeString(date) + ", date= " + DateUtil.dateAndTimeString(date) +
", isValid=" + isValid + ", isValid=" + isValid +

View file

@ -105,6 +105,7 @@ public class TemporaryBasal implements Interval {
this.isFakeExtended = true; this.isFakeExtended = true;
this.netExtendedRate = extendedBolus.absoluteRate(); this.netExtendedRate = extendedBolus.absoluteRate();
this.absoluteRate = basal + extendedBolus.absoluteRate(); this.absoluteRate = basal + extendedBolus.absoluteRate();
this.pumpId = extendedBolus.pumpId;
} }
public TemporaryBasal clone() { public TemporaryBasal clone() {

View file

@ -39,7 +39,7 @@ public class DBAccessReceiver extends BroadcastReceiver {
if (!bundles.containsKey("action")) return; if (!bundles.containsKey("action")) return;
if (L.isEnabled(L.NSCLIENT)) if (L.isEnabled(L.NSCLIENT))
BundleLogger.log(bundles); log.debug(BundleLogger.log(bundles));
String collection = null; String collection = null;
String _id = null; String _id = null;
@ -49,16 +49,21 @@ public class DBAccessReceiver extends BroadcastReceiver {
collection = bundles.getString("collection"); collection = bundles.getString("collection");
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
return;
} }
try { try {
if (!action.equals("dbAdd"))
_id = bundles.getString("_id"); _id = bundles.getString("_id");
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
return;
} }
try { try {
if (!action.equals("dbRemove"))
data = new JSONObject(bundles.getString("data")); data = new JSONObject(bundles.getString("data"));
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
return;
} }
if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) { if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) {

View file

@ -79,27 +79,27 @@ public class MsgStatusBolusExtended extends MessageBase {
exStop.source = Source.USER; exStop.source = Source.USER;
treatmentsInterface.addToHistoryExtendedBolus(exStop); treatmentsInterface.addToHistoryExtendedBolus(exStop);
// Create new // Create new
ExtendedBolus newExtended = new ExtendedBolus(); ExtendedBolus newExtended = new ExtendedBolus()
newExtended.date = pump.extendedBolusStart; .date(pump.extendedBolusStart)
newExtended.insulin = pump.extendedBolusAmount; .insulin(pump.extendedBolusAmount)
newExtended.durationInMinutes = pump.extendedBolusMinutes; .durationInMinutes(pump.extendedBolusMinutes)
newExtended.source = Source.USER; .source(Source.USER);
treatmentsInterface.addToHistoryExtendedBolus(newExtended); treatmentsInterface.addToHistoryExtendedBolus(newExtended);
} }
} else { } else {
// Close curent temp basal // Close curent temp basal
ExtendedBolus exStop = new ExtendedBolus(now); ExtendedBolus exStop = new ExtendedBolus(now)
exStop.source = Source.USER; .source(Source.USER);
treatmentsInterface.addToHistoryExtendedBolus(exStop); treatmentsInterface.addToHistoryExtendedBolus(exStop);
} }
} else { } else {
if (pump.isExtendedInProgress) { if (pump.isExtendedInProgress) {
// Create new // Create new
ExtendedBolus newExtended = new ExtendedBolus(); ExtendedBolus newExtended = new ExtendedBolus()
newExtended.date = pump.extendedBolusStart; .date(pump.extendedBolusStart)
newExtended.insulin = pump.extendedBolusAmount; .insulin(pump.extendedBolusAmount)
newExtended.durationInMinutes = pump.extendedBolusMinutes; .durationInMinutes(pump.extendedBolusMinutes)
newExtended.source = Source.USER; .source(Source.USER);
treatmentsInterface.addToHistoryExtendedBolus(newExtended); treatmentsInterface.addToHistoryExtendedBolus(newExtended);
} }
} }

View file

@ -89,10 +89,7 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
TemporaryBasal temporaryBasal = new TemporaryBasal().date(datetime).source(Source.PUMP).pumpId(datetime); TemporaryBasal temporaryBasal = new TemporaryBasal().date(datetime).source(Source.PUMP).pumpId(datetime);
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus().date(datetime).source(Source.PUMP).pumpId(datetime);
extendedBolus.date = datetime;
extendedBolus.source = Source.PUMP;
extendedBolus.pumpId = datetime;
String status; String status;

View file

@ -67,10 +67,10 @@ public class MsgHistoryEvents_v2 extends MessageBase {
.source(Source.PUMP) .source(Source.PUMP)
.pumpId(datetime); .pumpId(datetime);
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.date = datetime; .date(datetime)
extendedBolus.source = Source.PUMP; .source(Source.PUMP)
extendedBolus.pumpId = datetime; .pumpId(datetime);
String status = ""; String status = "";

View file

@ -573,7 +573,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { public PumpEnactResult cancelTempBasal(boolean enforceNew) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Cancel TBR"); log.debug("Cancel TBR called");
try { try {
cancelExtendedBolus(); cancelExtendedBolus();
@ -581,7 +581,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
realTBRCancel(); realTBRCancel();
SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS) SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS)
updateGui(); updateGui();
if (L.isEnabled(L.PUMP)) log.debug("Canceling temp basal");
connector.requestHistorySync(5000); connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).isTempCancel(true); return new PumpEnactResult().success(true).enacted(true).isTempCancel(true);
@ -609,18 +608,16 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
extendedBolusMessage.setAmount(insulin); extendedBolusMessage.setAmount(insulin);
extendedBolusMessage.setDuration(durationInMinutes); extendedBolusMessage.setDuration(durationInMinutes);
BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class); BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class);
final ExtendedBolus extendedBolus = new ExtendedBolus(); final ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.date = System.currentTimeMillis(); .date(System.currentTimeMillis())
extendedBolus.insulin = insulin; .insulin(insulin)
extendedBolus.durationInMinutes = durationInMinutes; .durationInMinutes(durationInMinutes)
extendedBolus.source = Source.USER; .source(Source.USER)
extendedBolus.pumpId = getRecordUniqueID(bolusMessage.getBolusId()); .pumpId(getRecordUniqueID(bolusMessage.getBolusId()));
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
updateGui(); updateGui();
connector.requestHistorySync(30000); connector.requestHistorySync(30000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
if (L.isEnabled(L.PUMP))
log.debug("Setting extended bolus: " + insulin + " mins:" + durationInMinutes);
return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin); return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin);
} catch (Exception e) { } catch (Exception e) {
return pumpEnactFailure(); return pumpEnactFailure();
@ -630,7 +627,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Cancel Extended bolus"); log.debug("Cancel Extended bolus called");
Integer bolusId = null; Integer bolusId = null;
@ -641,7 +638,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
exStop.source = Source.USER; exStop.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop);
} }
if (L.isEnabled(L.PUMP)) log.debug("Cancel extended bolus:");
if (bolusId != null) connector.requestHistorySync(5000); if (bolusId != null) connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
updateGui(); updateGui();

View file

@ -34,8 +34,8 @@ class HistoryIntentAdapter {
private HistoryLogAdapter logAdapter = new HistoryLogAdapter(); private HistoryLogAdapter logAdapter = new HistoryLogAdapter();
private static Date getDateExtra(Intent intent, String name) { private static long getDateExtra(Intent intent, String name) {
return (Date) intent.getSerializableExtra(name); return ((Date) intent.getSerializableExtra(name)).getTime();
} }
static long getRecordUniqueID(long pump_serial_number, long pump_record_id) { static long getRecordUniqueID(long pump_serial_number, long pump_record_id) {
@ -52,8 +52,7 @@ class HistoryIntentAdapter {
pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1); pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
} }
final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER)); final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
final Date event_time = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
final Date start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) { if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) {
log.error("Invalid TBR record!!!"); log.error("Invalid TBR record!!!");
@ -76,8 +75,8 @@ class HistoryIntentAdapter {
pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1); pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
} }
final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER)); final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
final Date event_time = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); final long event_time = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
final Date start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME); final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
final double immediate_amount = intent.getDoubleExtra(HistoryBroadcast.EXTRA_IMMEDIATE_AMOUNT, -1); final double immediate_amount = intent.getDoubleExtra(HistoryBroadcast.EXTRA_IMMEDIATE_AMOUNT, -1);
final double extended_insulin = intent.getDoubleExtra(HistoryBroadcast.EXTRA_EXTENDED_AMOUNT, -1); final double extended_insulin = intent.getDoubleExtra(HistoryBroadcast.EXTRA_EXTENDED_AMOUNT, -1);
final int extended_minutes = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1); final int extended_minutes = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1);
@ -90,7 +89,7 @@ class HistoryIntentAdapter {
log.error("ERROR Standard bolus fails sanity check"); log.error("ERROR Standard bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time);
logAdapter.createStandardBolusRecord(start_time, immediate_amount, record_unique_id); logAdapter.createStandardBolusRecord(start_time, immediate_amount, record_unique_id);
break; break;
@ -99,7 +98,7 @@ class HistoryIntentAdapter {
log.error("ERROR: Extended bolus fails sanity check"); log.error("ERROR: Extended bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id); logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
break; break;
@ -108,7 +107,7 @@ class HistoryIntentAdapter {
log.error("ERROR: Multiwave bolus fails sanity check"); log.error("ERROR: Multiwave bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
logAdapter.createStandardBolusRecord(start_time, immediate_amount, pump_serial_number + pump_record_id); logAdapter.createStandardBolusRecord(start_time, immediate_amount, pump_serial_number + pump_record_id);
logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id); logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
break; break;
@ -118,31 +117,31 @@ class HistoryIntentAdapter {
} }
void processDailyTotalIntent(Intent intent) { void processDailyTotalIntent(Intent intent) {
Date date = getDateExtra(intent, HistoryBroadcast.EXTRA_TOTAL_DATE); long date = getDateExtra(intent, HistoryBroadcast.EXTRA_TOTAL_DATE);
double basal = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BASAL_TOTAL, 0D); double basal = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BASAL_TOTAL, 0D);
double bolus = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BOLUS_TOTAL, 0D); double bolus = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BOLUS_TOTAL, 0D);
TDD tdd = new TDD(date.getTime(), bolus, basal, bolus + basal); TDD tdd = new TDD(date, bolus, basal, bolus + basal);
MainApp.getDbHelper().createOrUpdateTDD(tdd); MainApp.getDbHelper().createOrUpdateTDD(tdd);
} }
void processCannulaFilledIntent(Intent intent) { void processCannulaFilledIntent(Intent intent) {
Date date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.SITECHANGE); uploadCareportalEvent(date, CareportalEvent.SITECHANGE);
} }
void processCartridgeInsertedIntent(Intent intent) { void processCartridgeInsertedIntent(Intent intent) {
Date date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.INSULINCHANGE); uploadCareportalEvent(date, CareportalEvent.INSULINCHANGE);
} }
void processBatteryInsertedIntent(Intent intent) { void processBatteryInsertedIntent(Intent intent) {
Date date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.PUMPBATTERYCHANGE); uploadCareportalEvent(date, CareportalEvent.PUMPBATTERYCHANGE);
} }
private void uploadCareportalEvent(Date date, String event) { private void uploadCareportalEvent(long date, String event) {
if (SP.getBoolean("insight_automatic_careportal_events", false)) { if (SP.getBoolean("insight_automatic_careportal_events", false)) {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return; return;
try { try {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
@ -159,18 +158,18 @@ class HistoryIntentAdapter {
void processOccurenceOfAlertIntent(Intent intent) { void processOccurenceOfAlertIntent(Intent intent) {
if (SP.getBoolean("insight_automatic_careportal_events", false)) { if (SP.getBoolean("insight_automatic_careportal_events", false)) {
Date date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE); String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE);
int alertText = getAlertText(alertType); int alertText = getAlertText(alertType);
if (alertText == 0) return; if (alertText == 0) return;
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return; return;
logNote(date, MainApp.gs(alertText)); logNote(date, MainApp.gs(alertText));
} }
} }
void processPumpStatusChangedIntent(Intent intent) { void processPumpStatusChangedIntent(Intent intent) {
Date newStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME); long newStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
if (SP.getBoolean("insight_automatic_careportal_events", false)) { if (SP.getBoolean("insight_automatic_careportal_events", false)) {
String newStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_NEW_STATUS); String newStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_NEW_STATUS);
switch (newStatus) { switch (newStatus) {
@ -188,8 +187,8 @@ class HistoryIntentAdapter {
if (intent.hasExtra(HistoryBroadcast.EXTRA_OLD_STATUS_TIME)) { if (intent.hasExtra(HistoryBroadcast.EXTRA_OLD_STATUS_TIME)) {
String oldStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_OLD_STATUS); String oldStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_OLD_STATUS);
if (oldStatus.equals("STOPPED")) { if (oldStatus.equals("STOPPED")) {
Date oldStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_OLD_STATUS_TIME); long oldStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_OLD_STATUS_TIME);
int duration = (int) ((newStatusTime.getTime() - oldStatusTime.getTime()) / 60000); int duration = (int) ((newStatusTime - oldStatusTime) / 60000);
long serialNumber = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER)); long serialNumber = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
long recordId = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1); long recordId = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
@ -200,9 +199,9 @@ class HistoryIntentAdapter {
} }
} }
private void logNote(Date date, String note) { private void logNote(long date, String note) {
try { try {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return; return;
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", ""); String enteredBy = SP.getString("careportal_enteredby", "");

View file

@ -3,15 +3,18 @@ package info.nightscout.androidaps.plugins.PumpInsight.history;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.T;
/** /**
* Created by jamorham on 27/01/2018. * Created by jamorham on 27/01/2018.
@ -22,13 +25,13 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
class HistoryLogAdapter { class HistoryLogAdapter {
private Logger log = LoggerFactory.getLogger(L.PUMP); private Logger log = LoggerFactory.getLogger(L.PUMP);
private static final long MAX_TIME_DIFFERENCE = 61000; private static final long MAX_TIME_DIFFERENCE = T.secs(61).msecs();
void createTBRrecord(Date eventDate, int percent, int duration, long record_id) { void createTBRrecord(long eventDate, int percent, int duration, long record_id) {
TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate.getTime()); TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate);
final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate.getTime()); final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate);
if (temporaryBasalFromHistory == null) { if (temporaryBasalFromHistory == null) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -36,12 +39,18 @@ class HistoryLogAdapter {
} else { } else {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Loaded existing TBR record: " + temporaryBasalFromHistory.toString()); log.debug("Loaded existing TBR record: " + temporaryBasalFromHistory.toString());
if (Math.abs(eventDate.getTime() - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) { if (Math.abs(eventDate - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) {
if (temporaryBasalFromHistory.source != Source.PUMP) { if (temporaryBasalFromHistory.source != Source.PUMP) {
if (temporaryBasalFromHistory.percentRate == percent) { if (temporaryBasalFromHistory.percentRate == percent) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Things seem to match: %" + percent); log.debug("Things seem to match: %" + percent);
temporaryBasal = temporaryBasalFromHistory; temporaryBasal = temporaryBasalFromHistory;
String _id = temporaryBasal._id;
if (NSUpload.isIdValid(_id)) {
NSUpload.removeCareportalEntryFromNS(_id);
} else {
UploadQueue.removeID("dbAdd", _id);
}
MainApp.getDbHelper().delete(temporaryBasalFromHistory); MainApp.getDbHelper().delete(temporaryBasalFromHistory);
} else { } else {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -53,7 +62,7 @@ class HistoryLogAdapter {
} }
} else { } else {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Time difference too great! : " + (eventDate.getTime() - temporaryBasalFromHistory.date)); log.debug("Time difference too big! : " + (eventDate - temporaryBasalFromHistory.date));
} }
} }
@ -65,28 +74,60 @@ class HistoryLogAdapter {
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
} }
void createExtendedBolusRecord(Date eventDate, double insulin, int durationInMinutes, long record_id) { void createExtendedBolusRecord(long eventDate, double insulin, int durationInMinutes, long record_id) {
final ExtendedBolus extendedBolusFromHistory = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(eventDate);
if (extendedBolusFromHistory == null) {
if (L.isEnabled(L.PUMP))
log.debug("Create new EB: " + eventDate + " " + insulin + " " + durationInMinutes);
} else {
if (L.isEnabled(L.PUMP))
log.debug("Loaded existing EB record: " + extendedBolusFromHistory.log());
if (Math.abs(eventDate - extendedBolusFromHistory.date) < MAX_TIME_DIFFERENCE) {
if (extendedBolusFromHistory.source != Source.PUMP) {
if (L.isEnabled(L.PUMP))
log.debug("Date seem to match: " + DateUtil.dateAndTimeFullString(eventDate));
String _id = extendedBolusFromHistory._id;
if (NSUpload.isIdValid(_id)) {
NSUpload.removeCareportalEntryFromNS(_id);
} else {
UploadQueue.removeID("dbAdd", _id);
}
MainApp.getDbHelper().delete(extendedBolusFromHistory);
} else {
if (L.isEnabled(L.PUMP))
log.debug("This record is already a pump record!");
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("Time difference too big! : " + (eventDate - extendedBolusFromHistory.date));
}
}
// TODO trap items below minimum period // TODO trap items below minimum period
final ExtendedBolus extendedBolus = new ExtendedBolus(); // TODO (mike) find and remove ending record with Source.USER
extendedBolus.date = eventDate.getTime();
extendedBolus.insulin = insulin;
extendedBolus.durationInMinutes = durationInMinutes;
extendedBolus.source = Source.PUMP;
extendedBolus.pumpId = record_id;
ExtendedBolus extendedBolus = new ExtendedBolus()
.date(eventDate)
.insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.PUMP)
.pumpId(record_id);
if (ProfileFunctions.getInstance().getProfile(extendedBolus.date) != null) // actual basal rate is needed for absolute rate calculation
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
} }
void createStandardBolusRecord(Date eventDate, double insulin, long record_id) { void createStandardBolusRecord(long eventDate, double insulin, long record_id) {
//DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(eventDate.getTime()); //DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(eventDate.getTime());
// TODO do we need to do the same delete + insert that we are doing for temporary basals here too? // TODO do we need to do the same delete + insert that we are doing for temporary basals here too?
final DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); final DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.date = eventDate.getTime(); detailedBolusInfo.date = eventDate;
detailedBolusInfo.source = Source.PUMP; detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = record_id; detailedBolusInfo.pumpId = record_id;
detailedBolusInfo.insulin = insulin; detailedBolusInfo.insulin = insulin;

View file

@ -315,11 +315,11 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (!result.success) if (!result.success)
return result; return result;
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus()
extendedBolus.date = System.currentTimeMillis(); .date(System.currentTimeMillis())
extendedBolus.insulin = insulin; .insulin(insulin)
extendedBolus.durationInMinutes = durationInMinutes; .durationInMinutes(durationInMinutes)
extendedBolus.source = Source.USER; .source(Source.USER);
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
result.bolusDelivered = insulin; result.bolusDelivered = insulin;