diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index c659e6fd33..1ecc1a7f7b 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -57,6 +57,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment; import info.nightscout.androidaps.plugins.Wear.WearFragment; import info.nightscout.androidaps.plugins.XDripStatusline.StatuslineFragment; import info.nightscout.androidaps.receivers.KeepAliveReceiver; +import info.nightscout.utils.NSUpload; import io.fabric.sdk.android.Fabric; @@ -128,7 +129,7 @@ public class MainApp extends Application { MainApp.getConfigBuilder().initialize(); } - MainApp.getConfigBuilder().uploadAppStart(); + NSUpload.uploadAppStart(); startKeepAliveService(); diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index a2a5b91870..732c8ff07f 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -27,6 +27,9 @@ public class PumpEnactResult extends Object { public Double bolusDelivered = 0d; // real value of delivered insulin public Integer carbsDelivered = 0; // real value of delivered carbs + public Double originalExtendedAmount = null; // amount of extended bolus insulin if uploading as temp basal + public Boolean isFakedTempBasal = null; // true if canceling extended bolus but uploading as temp basal + public boolean queued = false; public String log() { 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 097c70e53b..d0573654ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -867,42 +867,100 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { try { - 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()); + 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.date = trJson.getLong("mills"); + extendedBolus.durationInMinutes = trJson.getInt("duration"); + extendedBolus.insulin = trJson.getDouble("originalExtendedAmount"); + extendedBolus._id = trJson.getString("_id"); + createOrUpdate(extendedBolus); + scheduleExtendedBolusChange(); + } 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.date = trJson.getLong("mills"); + extendedBolus.durationInMinutes = 0; + extendedBolus.insulin = 0; + extendedBolus._id = trJson.getString("_id"); + createOrUpdate(extendedBolus); + scheduleExtendedBolusChange(); } else { - log.error("Something went wrong"); - return; + 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; + } + tempBasal.date = trJson.getLong("mills"); + if (trJson.has("duration")) { + tempBasal.durationInMinutes = trJson.getInt("duration"); + } + if (trJson.has("percent")) { + tempBasal.percentRate = trJson.getInt("percent") + 100; + tempBasal.isAbsolute = false; + } + if (trJson.has("absolute")) { + tempBasal.absoluteRate = trJson.getDouble("absolute"); + tempBasal.isAbsolute = true; + } + tempBasal._id = trJson.getString("_id"); + createOrUpdate(tempBasal); + scheduleTemporaryBasalChange(); } - tempBasal.date = trJson.getLong("mills"); - if (trJson.has("duration")) { - tempBasal.durationInMinutes = trJson.getInt("duration"); - } - if (trJson.has("percent")) { - tempBasal.percentRate = trJson.getInt("percent") + 100; - tempBasal.isAbsolute = false; - } - if (trJson.has("absolute")) { - tempBasal.absoluteRate = trJson.getDouble("absolute"); - tempBasal.isAbsolute = true; - } - tempBasal._id = trJson.getString("_id"); - createOrUpdate(tempBasal); - scheduleTemporaryBasalChange(); } catch (SQLException e) { e.printStackTrace(); } catch (JSONException e) { 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 ac749c7e35..6e5ba4978d 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -45,7 +45,7 @@ public class ExtendedBolus implements Interval { @DatabaseField public double insulin = 0d; @DatabaseField - public int durationInMinutes = 0; // duration == 0 means end of temp basal + public int durationInMinutes = 0; // duration == 0 means end of extended bolus @DatabaseField public int insulinInterfaceID = InsulinInterface.FASTACTINGINSULIN; 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 5b86b1f483..e44413de15 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWith import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TREATMENTS) public class Treatment implements DataPointWithLabelInterface { @@ -118,23 +119,6 @@ public class Treatment implements DataPointWithLabelInterface { // ----------------- DataPointInterface end -------------------- - public void sendToNSClient() { - JSONObject data = new JSONObject(); - try { - if (mealBolus) - data.put("eventType", "Meal Bolus"); - else - data.put("eventType", "Correction Bolus"); - if (insulin != 0d) data.put("insulin", insulin); - if (carbs != 0d) data.put("carbs", carbs.intValue()); - data.put("created_at", DateUtil.toISOString(date)); - data.put("timeIndex", date); - } catch (JSONException e) { - e.printStackTrace(); - } - ConfigBuilderPlugin.uploadCareportalEntryToNS(data); - } - public Iob iobCalc(long time, double dia) { InsulinInterface insulinInterface = MainApp.getInsulinIterfaceById(insulinInterfaceID); if (insulinInterface == null) 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 2e97e6cf4f..2702f7ac96 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 @@ -53,6 +53,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin; import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; @@ -631,7 +632,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick data.put("timeshift", cpp.timeshift); data.put("percentage", cpp.percentage); } - ConfigBuilderPlugin.uploadCareportalEntryToNS(data); + NSUpload.uploadCareportalEntryToNS(data); Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch")); } catch (JSONException e) { e.printStackTrace(); @@ -659,7 +660,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } log.debug("Creating new TempTarget db record: " + tempTarget.log()); MainApp.getDbHelper().createOrUpdate(tempTarget); - ConfigBuilderPlugin.uploadCareportalEntryToNS(data); + NSUpload.uploadCareportalEntryToNS(data); Answers.getInstance().logCustom(new CustomEvent("TempTarget")); } catch (JSONException e) { e.printStackTrace(); @@ -671,7 +672,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick e.printStackTrace(); } } else { - ConfigBuilderPlugin.uploadCareportalEntryToNS(data); + NSUpload.uploadCareportalEntryToNS(data); Answers.getInstance().logCustom(new CustomEvent("NSTreatment")); } } 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 d67dda593a..67d40627f2 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 @@ -3,13 +3,11 @@ package info.nightscout.androidaps.plugins.ConfigBuilder; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; -import android.os.Bundle; import android.os.PowerManager; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; -import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,11 +19,9 @@ import java.util.List; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; @@ -42,23 +38,16 @@ import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.Loop.APSResult; -import info.nightscout.androidaps.plugins.Loop.DeviceStatus; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; -import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; -import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA; -import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResultMA; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperActivity; 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.PumpDanaR.comm.MsgError; -import info.nightscout.utils.BatteryLevel; -import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.OverlappingIntervals; -import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. @@ -445,7 +434,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain t.mealBolus = result.carbsDelivered > 0; MainApp.getDbHelper().create(t); t.carbs = (double) result.carbsDelivered; - uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc); + NSUpload.uploadBolusWizardRecord(t, glucose, glucoseType, carbTime, boluscalc); } } else { if (Config.logCongigBuilderActions) @@ -456,7 +445,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain t.date = new Date().getDate(); t.mealBolus = t.carbs > 0; MainApp.getDbHelper().create(t); - t.sendToNSClient(); + NSUpload.uploadTreatment(t); result = new PumpEnactResult(); result.success = true; result.bolusDelivered = insulin; @@ -509,7 +498,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain t.date = new Date().getTime(); t.mealBolus = t.carbs > 0; MainApp.getDbHelper().create(t); - t.sendToNSClient(); + NSUpload.uploadTreatment(t); } } else { log.error("activePump==null"); @@ -541,9 +530,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted); if (result.enacted && result.success) { if (result.isPercent) { - uploadTempBasalStartPercent(result.percent, result.duration); + NSUpload.uploadTempBasalStartPercent(result.percent, result.duration); } else { - uploadTempBasalStartAbsolute(result.absolute, result.duration); + NSUpload.uploadTempBasalStartAbsolute(result.absolute, result.duration, result.originalExtendedAmount); } } return result; @@ -563,7 +552,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain if (Config.logCongigBuilderActions) log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted); if (result.enacted && result.success) { - uploadTempBasalStartPercent(result.percent, result.duration); + NSUpload.uploadTempBasalStartPercent(result.percent, result.duration); } return result; } @@ -575,7 +564,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain if (Config.logCongigBuilderActions) log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted); if (result.enacted && result.success) { - uploadExtendedBolus(result.bolusDelivered, result.duration); + NSUpload.uploadExtendedBolus(result.bolusDelivered, result.duration); MainApp.bus().post(new EventTreatmentChange()); } return result; @@ -587,7 +576,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain if (Config.logCongigBuilderActions) log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted); if (result.enacted && result.success) { - uploadTempBasalEnd(); + NSUpload.uploadTempBasalEnd(result.isFakedTempBasal); } return result; } @@ -597,6 +586,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain PumpEnactResult result = activePump.cancelExtendedBolus(); if (Config.logCongigBuilderActions) log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted); + if (result.enacted && result.success) { + NSUpload.uploadExtendedBolusEnd(); + } return result; } @@ -606,6 +598,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain * @param request * @return */ + public PumpEnactResult applyAPSRequest(APSResult request) { request.rate = applyBasalConstraints(request.rate); PumpEnactResult result; @@ -831,296 +824,6 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain return maxIobAfterConstrain; } - public void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes) { - try { - Context context = MainApp.instance().getApplicationContext(); - JSONObject data = new JSONObject(); - data.put("eventType", CareportalEvent.TEMPBASAL); - data.put("duration", durationInMinutes); - data.put("absolute", absolute); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + absolute + "u/h " + durationInMinutes + " min"); // ECOR - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public static void uploadOpenAPSOffline(double durationInMinutes) { - try { - Context context = MainApp.instance().getApplicationContext(); - JSONObject data = new JSONObject(); - data.put("eventType", "OpenAPS Offline"); - data.put("duration", durationInMinutes); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) { - try { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false); - if (useAbsolute) { - double absolute = getBaseBasalRate() * percent / 100d; - uploadTempBasalStartAbsolute(absolute, durationInMinutes); - } else { - Context context = MainApp.instance().getApplicationContext(); - JSONObject data = new JSONObject(); - data.put("eventType", CareportalEvent.TEMPBASAL); - data.put("duration", durationInMinutes); - data.put("percent", percent - 100); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + percent + "% " + durationInMinutes + " min"); // ECOR - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public void uploadTempBasalEnd() { - try { - Context context = MainApp.instance().getApplicationContext(); - JSONObject data = new JSONObject(); - data.put("eventType", CareportalEvent.TEMPBASAL); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalendnote)); // ECOR - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public void uploadExtendedBolus(Double insulin, double durationInMinutes) { - try { - Context context = MainApp.instance().getApplicationContext(); - JSONObject data = new JSONObject(); - data.put("eventType", CareportalEvent.COMBOBOLUS); - data.put("duration", durationInMinutes); - data.put("splitNow", 0); - data.put("splitExt", 100); - data.put("enteredinsulin", insulin); - data.put("relative", insulin); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public void uploadDeviceStatus() { - DeviceStatus deviceStatus = new DeviceStatus(); - try { - LoopPlugin.LastRun lastRun = LoopPlugin.lastRun; - if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 300 * 1000L) { - // do not send if result is older than 1 min - APSResult apsResult = lastRun.request; - apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun)); - deviceStatus.suggested = apsResult.json(); - - if (lastRun.request instanceof DetermineBasalResultMA) { - DetermineBasalResultMA result = (DetermineBasalResultMA) lastRun.request; - deviceStatus.iob = result.iob.json(); - deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun)); - } - - if (lastRun.request instanceof DetermineBasalResultAMA) { - DetermineBasalResultAMA result = (DetermineBasalResultAMA) lastRun.request; - deviceStatus.iob = result.iob.json(); - deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun)); - } - - if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted - deviceStatus.enacted = lastRun.request.json(); - deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate")); - deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration")); - deviceStatus.enacted.put("recieved", true); - JSONObject requested = new JSONObject(); - requested.put("duration", lastRun.request.duration); - requested.put("rate", lastRun.request.rate); - requested.put("temp", "absolute"); - deviceStatus.enacted.put("requested", requested); - } - } else { - log.debug("OpenAPS data too old to upload"); - } - if (activePump != null) { - deviceStatus.device = "openaps://" + deviceID(); - JSONObject pumpstatus = getJSONStatus(); - if (pumpstatus != null) { - deviceStatus.pump = pumpstatus; - } - } - - int batteryLevel = BatteryLevel.getBatteryLevel(); - deviceStatus.uploaderBattery = batteryLevel; - - deviceStatus.created_at = DateUtil.toISOString(new Date()); - deviceStatus.sendToNSClient(); - } catch (JSONException e) { - e.printStackTrace(); - } - } - - public void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) { - JSONObject data = new JSONObject(); - try { - data.put("eventType", "Bolus Wizard"); - if (t.insulin != 0d) data.put("insulin", t.insulin); - if (t.carbs != 0d) data.put("carbs", t.carbs.intValue()); - data.put("created_at", DateUtil.toISOString(t.date)); - data.put("date", t.date); - if (glucose != 0d) data.put("glucose", glucose); - data.put("glucoseType", glucoseType); - data.put("boluscalc", boluscalc); - if (carbTime != 0) data.put("preBolus", carbTime); - } catch (JSONException e) { - e.printStackTrace(); - } - uploadCareportalEntryToNS(data); - } - - public static void uploadCareportalEntryToNS(JSONObject data) { - try { - if (data.has("preBolus") && data.has("carbs")) { - JSONObject prebolus = new JSONObject(); - prebolus.put("carbs", data.get("carbs")); - data.remove("carbs"); - prebolus.put("eventType", data.get("eventType")); - if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy")); - if (data.has("notes")) prebolus.put("notes", data.get("notes")); - long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime(); - Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L); - prebolus.put("created_at", DateUtil.toISOString(preBolusDate)); - uploadCareportalEntryToNS(prebolus); - } - Context context = MainApp.instance().getApplicationContext(); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public static void removeCareportalEntryFromNS(String _id) { - try { - Context context = MainApp.instance().getApplicationContext(); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbRemove"); - bundle.putString("collection", "treatments"); - bundle.putString("_id", _id); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbRemove(intent, _id, ConfigBuilderPlugin.class); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - public void uploadError(String error) { - Context context = MainApp.instance().getApplicationContext(); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - JSONObject data = new JSONObject(); - try { - data.put("eventType", "Announcement"); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("notes", error); - data.put("isAnnouncement", true); - } catch (JSONException e) { - e.printStackTrace(); - } - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), MsgError.class); - } - - public void uploadAppStart() { - if (SP.getBoolean(R.string.key_ns_logappstartedevent, true)) { - Context context = MainApp.instance().getApplicationContext(); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "treatments"); - JSONObject data = new JSONObject(); - try { - data.put("eventType", "Note"); - data.put("created_at", DateUtil.toISOString(new Date())); - data.put("notes", MainApp.sResources.getString(R.string.androidaps_start)); - } catch (JSONException e) { - e.printStackTrace(); - } - bundle.putString("data", data.toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, data.toString(), ConfigBuilderPlugin.class); - } - } - // ****** Treatments interface ***** @Override public void updateTotalIOBTreatments() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java index 0d72464b73..3080717773 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java @@ -402,16 +402,4 @@ public class DeviceStatus { return record; } - public void sendToNSClient() { - Context context = MainApp.instance().getApplicationContext(); - Bundle bundle = new Bundle(); - bundle.putString("action", "dbAdd"); - bundle.putString("collection", "devicestatus"); - bundle.putString("data", mongoRecord().toString()); - Intent intent = new Intent(Intents.ACTION_DATABASE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - DbLogger.dbAdd(intent, mongoRecord().toString(), DeviceStatus.class); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java index f6d319dd7f..b7e4aef717 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java @@ -32,6 +32,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; /** @@ -316,7 +317,7 @@ public class LoopPlugin implements PluginBase { } MainApp.bus().post(new EventLoopUpdateGui()); - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); } finally { if (Config.logFunctionCalls) log.debug("invoke end"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java index 70d8e9e336..79a66186fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java @@ -17,8 +17,9 @@ import info.nightscout.utils.ToastUtils; * Created by mike on 02.07.2016. */ public class DbLogger { - public static void dbAdd(Intent intent, String data, Class sender) { - Logger log = LoggerFactory.getLogger(sender); + private static Logger log = LoggerFactory.getLogger(DbLogger.class); + + public static void dbAdd(Intent intent, String data) { List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); if (q.size() < 1) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled)); @@ -27,8 +28,7 @@ public class DbLogger { log.debug("DBADD dbAdd " + q.size() + " receivers " + data); } - public static void dbRemove(Intent intent, String data, Class sender) { - Logger log = LoggerFactory.getLogger(sender); + public static void dbRemove(Intent intent, String data) { List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); if (q.size() < 1) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java index dac0a2b5f8..45f1768ad6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java @@ -26,6 +26,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.Profiler; import info.nightscout.utils.Round; import info.nightscout.utils.SP; @@ -287,7 +288,7 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface { msg += ".\n"; msg += String.format(MainApp.sResources.getString(R.string.openapsma_valuelimitedto), value, newvalue); log.error(msg); - MainApp.getConfigBuilder().uploadError(msg); + NSUpload.uploadError(msg); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error); } return newvalue; 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 8fcd3323d0..95c99f8d25 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 @@ -108,6 +108,7 @@ import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.utils.BolusWizard; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.Round; import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; @@ -363,14 +364,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(60); // upload 60 min, we don;t know real duration + NSUpload.uploadOpenAPSOffline(60); // upload 60 min, we don;t know real duration return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.enableloop))) { activeloop.setFragmentEnabled(PluginBase.LOOP, true); activeloop.setFragmentVisible(PluginBase.LOOP, true); MainApp.getConfigBuilder().storeSettings(); scheduleUpdateGUI("suspendmenu"); - ConfigBuilderPlugin.uploadOpenAPSOffline(0); + NSUpload.uploadOpenAPSOffline(0); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.resume))) { activeloop.suspendTo(0L); @@ -384,7 +385,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(0); + NSUpload.uploadOpenAPSOffline(0); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor1h))) { activeloop.suspendTo(new Date().getTime() + 60L * 60 * 1000); @@ -398,7 +399,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(60); + NSUpload.uploadOpenAPSOffline(60); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor2h))) { activeloop.suspendTo(new Date().getTime() + 2 * 60L * 60 * 1000); @@ -412,7 +413,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(120); + NSUpload.uploadOpenAPSOffline(120); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor3h))) { activeloop.suspendTo(new Date().getTime() + 3 * 60L * 60 * 1000); @@ -426,7 +427,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(180); + NSUpload.uploadOpenAPSOffline(180); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.suspendloopfor10h))) { activeloop.suspendTo(new Date().getTime() + 10 * 60L * 60 * 1000); @@ -440,7 +441,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(600); + NSUpload.uploadOpenAPSOffline(600); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor30m))) { activeloop.suspendTo(new Date().getTime() + 30L * 60 * 1000); @@ -454,7 +455,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(30); + NSUpload.uploadOpenAPSOffline(30); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor1h))) { activeloop.suspendTo(new Date().getTime() + 1 * 60L * 60 * 1000); @@ -468,7 +469,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(60); + NSUpload.uploadOpenAPSOffline(60); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor2h))) { activeloop.suspendTo(new Date().getTime() + 2 * 60L * 60 * 1000); @@ -482,7 +483,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(120); + NSUpload.uploadOpenAPSOffline(120); return true; } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor3h))) { activeloop.suspendTo(new Date().getTime() + 3 * 60L * 60 * 1000); @@ -496,7 +497,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } }); - ConfigBuilderPlugin.uploadOpenAPSOffline(180); + NSUpload.uploadOpenAPSOffline(180); return true; } @@ -569,7 +570,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, finalLastRun.setByPump = applyResult; finalLastRun.lastEnact = new Date(); finalLastRun.lastOpenModeAccept = new Date(); - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); ObjectivesPlugin objectivesPlugin = (ObjectivesPlugin) MainApp.getSpecificPlugin(ObjectivesPlugin.class); if (objectivesPlugin != null) { objectivesPlugin.manualEnacts++; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java index 5a8813bdf8..dc5fe95190 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.ToastUtils; @@ -217,7 +218,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) { String msg = String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Percentage"); log.error(msg); - MainApp.getConfigBuilder().uploadError(msg); + NSUpload.uploadError(msg); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error); percentage = Math.max(percentage, Constants.CPP_MIN_PERCENTAGE); percentage = Math.min(percentage, Constants.CPP_MAX_PERCENTAGE); 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 b12e771797..46a3251b49 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 @@ -483,6 +483,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf if (Config.logPumpActions) log.debug("setTempBasalAbsolute: Extended bolus set ok"); result.absolute = result.absolute + getBaseBasalRate(); + result.originalExtendedAmount = extendedAmount; return result; } // We should never end here @@ -585,8 +586,11 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf public PumpEnactResult cancelTempBasal() { if (MainApp.getConfigBuilder().isRealTempBasalInProgress()) return cancelRealTempBasal(); - if (MainApp.getConfigBuilder().isExtendedBoluslInProgress() && useExtendedBoluses) - return cancelExtendedBolus(); + if (MainApp.getConfigBuilder().isExtendedBoluslInProgress() && useExtendedBoluses) { + PumpEnactResult cancelEx = cancelExtendedBolus(); + cancelEx.isFakedTempBasal = true; + return cancelEx; + } PumpEnactResult result = new PumpEnactResult(); result.success = true; result.enacted = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java index 9d03f68858..82436cd067 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/History/DanaRNSHistorySync.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.ToastUtils; /** @@ -74,7 +75,7 @@ public class DanaRNSHistorySync { nsrec.put("insulin", record.recordValue); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_sbolus); break; @@ -92,7 +93,7 @@ public class DanaRNSHistorySync { cal.add(Calendar.MINUTE, -1 * record.recordDuration); nsrec.put("created_at", DateUtil.toISOString(cal.getTime())); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_ebolus); } else { @@ -108,7 +109,7 @@ public class DanaRNSHistorySync { nsrec.put("splitExt", 0); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_dsbolus); break; @@ -124,7 +125,7 @@ public class DanaRNSHistorySync { cal.add(Calendar.MINUTE, -1 * record.recordDuration); nsrec.put("created_at", DateUtil.toISOString(cal.getTime())); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_debolus); break; @@ -141,7 +142,7 @@ public class DanaRNSHistorySync { nsrec.put("notes", "Error"); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_error); break; @@ -153,7 +154,7 @@ public class DanaRNSHistorySync { nsrec.put("notes", "Refill " + record.recordValue + "U"); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_refill); break; @@ -166,7 +167,7 @@ public class DanaRNSHistorySync { nsrec.put("duration", 60); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_basalhour); break; @@ -182,7 +183,7 @@ public class DanaRNSHistorySync { nsrec.put("glucoseType", "Finger"); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_glucose); break; @@ -194,7 +195,7 @@ public class DanaRNSHistorySync { nsrec.put("carbs", record.recordValue); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_carbohydrate); break; @@ -206,7 +207,7 @@ public class DanaRNSHistorySync { nsrec.put("notes", "Alarm: " + record.recordAlarm); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", MainApp.sResources.getString(R.string.app_name)); - ConfigBuilderPlugin.uploadCareportalEntryToNS(nsrec); + NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; ev.message += MainApp.sResources.getString(R.string.danar_alarm); break; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java index ec52d533dc..b180d4107b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java @@ -7,6 +7,7 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; +import info.nightscout.utils.NSUpload; public class MsgError extends MessageBase { private static Logger log = LoggerFactory.getLogger(MsgError.class); @@ -48,7 +49,7 @@ public class MsgError extends MessageBase { } if (Config.logDanaMessageDetail) log.debug("Error detected: " + errorString); - MainApp.getConfigBuilder().uploadError(errorString); + NSUpload.uploadError(errorString); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java index c3f0ad6fc1..49099aca5d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java @@ -80,6 +80,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; @@ -338,12 +339,12 @@ public class DanaRExecutionService extends Service { danaRPump.lastConnection = now; MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); - MainApp.getConfigBuilder().uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); + NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); } } catch (Exception e) { e.printStackTrace(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java index 6b65095524..e660968a1f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java @@ -76,6 +76,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgCheckValue_k; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgSettingBasal_k; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgStatusBasic_k; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; @@ -331,12 +332,12 @@ public class DanaRKoreanExecutionService extends Service { danaRPump.lastConnection = now; MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); - MainApp.getConfigBuilder().uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); + NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); } } catch (Exception e) { e.printStackTrace(); 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 97f438ba5f..fb9ca48be6 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 @@ -46,6 +46,7 @@ import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgHistoryEvents_v2; import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgSetAPSTempBasalStart_v2; import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgStatusAPS_v2; import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MsgCheckValue_v2; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; @@ -306,12 +307,12 @@ public class DanaRv2ExecutionService extends Service { danaRPump.lastConnection = now; MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); - MainApp.getConfigBuilder().uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); + NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); } } catch (Exception e) { e.printStackTrace(); 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 5bf251f376..789eee1ba7 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 @@ -29,6 +29,7 @@ import info.nightscout.androidaps.plugins.PumpVirtual.events.EventVirtualPumpUpd import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; /** * Created by mike on 05.08.2016. @@ -181,7 +182,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { @Override public void refreshDataFromPump(String reason) { - MainApp.getConfigBuilder().uploadDeviceStatus(); + NSUpload.uploadDeviceStatus(); lastDataTime = new Date(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index 635134e64e..e10a92205b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -40,6 +40,7 @@ import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.XdripCalibrations; @@ -316,7 +317,7 @@ public class SmsCommunicatorPlugin implements PluginBase { final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop(); activeloop.suspendTo(0); MainApp.bus().post(new EventRefreshGui(false)); - ConfigBuilderPlugin.uploadOpenAPSOffline(0); + NSUpload.uploadOpenAPSOffline(0); reply = MainApp.sResources.getString(R.string.smscommunicator_loopresumed); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); Answers.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume")); @@ -533,7 +534,7 @@ public class SmsCommunicatorPlugin implements PluginBase { final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop(); activeloop.suspendTo(new Date().getTime() + suspendWaitingForConfirmation.duration * 60L * 1000); PumpEnactResult result = MainApp.getConfigBuilder().cancelTempBasal(); - ConfigBuilderPlugin.uploadOpenAPSOffline(suspendWaitingForConfirmation.duration * 60); + NSUpload.uploadOpenAPSOffline(suspendWaitingForConfirmation.duration * 60); MainApp.bus().post(new EventRefreshGui(false)); reply = MainApp.sResources.getString(R.string.smscommunicator_loopsuspended) + " " + MainApp.sResources.getString(result.success?R.string.smscommunicator_tempbasalcanceled:R.string.smscommunicator_tempbasalcancelfailed); 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 6190d2d636..4dd1e712bb 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 @@ -410,7 +410,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface { if (extendedBoluses.size() > 0) oldestTime = Math.min(oldestTime, extendedBoluses.get(0).date); if (treatments.size() > 0) - oldestTime = Math.min(oldestTime, extendedBoluses.get(treatments.size() - 1).date); + oldestTime = Math.min(oldestTime, treatments.get(treatments.size() - 1).date); oldestTime -= 15 * 60 * 1000L; // allow 15 min before return oldestTime; } 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 98d6b5a0dc..1d868b5356 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 @@ -40,6 +40,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; public class TreatmentsBolusFragment extends Fragment implements View.OnClickListener { @@ -135,7 +136,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis public void onClick(DialogInterface dialog, int id) { final String _id = treatment._id; if (_id != null && !_id.equals("")) { - MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id); + NSUpload.removeCareportalEntryFromNS(_id); } MainApp.getDbHelper().delete(treatment); updateGUI(); 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 d1167bd2ac..bd7ecb9f6e 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 @@ -33,6 +33,7 @@ import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.OverlappingIntervals; @@ -142,7 +143,7 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { public void onClick(DialogInterface dialog, int id) { final String _id = extendedBolus._id; if (_id != null && !_id.equals("")) { - MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id); + NSUpload.removeCareportalEntryFromNS(_id); } MainApp.getDbHelper().delete(extendedBolus); Answers.getInstance().logCustom(new CustomEvent("RemoveExtendedBolus")); 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 b806d6079d..8ded729c7d 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 @@ -29,6 +29,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.OverlappingIntervals; import info.nightscout.utils.SP; @@ -135,7 +136,7 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli public void onClick(DialogInterface dialog, int id) { final String _id = tempTarget._id; if (_id != null && !_id.equals("")) { - MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id); + NSUpload.removeCareportalEntryFromNS(_id); } MainApp.getDbHelper().delete(tempTarget); } 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 61f01a94a3..7c3d7f9ed5 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 @@ -33,6 +33,7 @@ import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; +import info.nightscout.utils.NSUpload; import info.nightscout.utils.OverlappingIntervals; @@ -158,7 +159,7 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { public void onClick(DialogInterface dialog, int id) { final String _id = tempBasal._id; if (_id != null && !_id.equals("")) { - MainApp.getConfigBuilder().removeCareportalEntryFromNS(_id); + NSUpload.removeCareportalEntryFromNS(_id); } MainApp.getDbHelper().delete(tempBasal); Answers.getInstance().logCustom(new CustomEvent("RemoveTempBasal")); diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/utils/NSUpload.java new file mode 100644 index 0000000000..4da4fe0a34 --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -0,0 +1,378 @@ +package info.nightscout.utils; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.db.CareportalEvent; +import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.Loop.APSResult; +import info.nightscout.androidaps.plugins.Loop.DeviceStatus; +import info.nightscout.androidaps.plugins.Loop.LoopPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; +import info.nightscout.androidaps.plugins.OpenAPSAMA.DetermineBasalResultAMA; +import info.nightscout.androidaps.plugins.OpenAPSMA.DetermineBasalResultMA; + +/** + * Created by mike on 26.05.2017. + */ + +public class NSUpload { + private static Logger log = LoggerFactory.getLogger(NSUpload.class); + + public static void uploadTempBasalStartAbsolute(Double absolute, double durationInMinutes, Double originalExtendedAmount) { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", CareportalEvent.TEMPBASAL); + data.put("duration", durationInMinutes); + data.put("absolute", absolute); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + absolute + "u/h " + durationInMinutes + " min"); // ECOR + if (originalExtendedAmount != null) + data.put("originalExtendedAmount", originalExtendedAmount); // for back synchronization + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) { + try { + SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + boolean useAbsolute = SP.getBoolean("ns_sync_use_absolute", false); + if (useAbsolute) { + double absolute = MainApp.getConfigBuilder().getBaseBasalRate() * percent / 100d; + uploadTempBasalStartAbsolute(absolute, durationInMinutes, null); + } else { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", CareportalEvent.TEMPBASAL); + data.put("duration", durationInMinutes); + data.put("percent", percent - 100); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalstartnote) + " " + percent + "% " + durationInMinutes + " min"); // ECOR + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadTempBasalEnd(Boolean isFakedTempBasal) { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", CareportalEvent.TEMPBASAL); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + data.put("notes", MainApp.sResources.getString(R.string.androidaps_tempbasalendnote)); // ECOR + if (isFakedTempBasal != null) + data.put("isFakedTempBasal", isFakedTempBasal); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadExtendedBolus(Double insulin, double durationInMinutes) { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", CareportalEvent.COMBOBOLUS); + data.put("duration", durationInMinutes); + data.put("splitNow", 0); + data.put("splitExt", 100); + data.put("enteredinsulin", insulin); + data.put("relative", insulin); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadExtendedBolusEnd() { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", CareportalEvent.COMBOBOLUS); + data.put("duration", 0); + data.put("splitNow", 0); + data.put("splitExt", 100); + data.put("enteredinsulin", 0); + data.put("relative", 0); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadTreatment(Treatment treatment) { + JSONObject data = new JSONObject(); + try { + if (treatment.mealBolus) + data.put("eventType", "Meal Bolus"); + else + data.put("eventType", "Correction Bolus"); + if (treatment.insulin != 0d) data.put("insulin", treatment.insulin); + if (treatment.carbs != 0d) data.put("carbs", treatment.carbs.intValue()); + data.put("created_at", DateUtil.toISOString(treatment.date)); + data.put("timeIndex", treatment.date); + } catch (JSONException e) { + e.printStackTrace(); + } + NSUpload.uploadCareportalEntryToNS(data); + } + + public static void uploadDeviceStatus() { + DeviceStatus deviceStatus = new DeviceStatus(); + try { + LoopPlugin.LastRun lastRun = LoopPlugin.lastRun; + if (lastRun != null && lastRun.lastAPSRun.getTime() > new Date().getTime() - 300 * 1000L) { + // do not send if result is older than 1 min + APSResult apsResult = lastRun.request; + apsResult.json().put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun)); + deviceStatus.suggested = apsResult.json(); + + if (lastRun.request instanceof DetermineBasalResultMA) { + DetermineBasalResultMA result = (DetermineBasalResultMA) lastRun.request; + deviceStatus.iob = result.iob.json(); + deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun)); + } + + if (lastRun.request instanceof DetermineBasalResultAMA) { + DetermineBasalResultAMA result = (DetermineBasalResultAMA) lastRun.request; + deviceStatus.iob = result.iob.json(); + deviceStatus.iob.put("time", DateUtil.toISOString(lastRun.lastAPSRun)); + } + + if (lastRun.setByPump != null && lastRun.setByPump.enacted) { // enacted + deviceStatus.enacted = lastRun.request.json(); + deviceStatus.enacted.put("rate", lastRun.setByPump.json().get("rate")); + deviceStatus.enacted.put("duration", lastRun.setByPump.json().get("duration")); + deviceStatus.enacted.put("recieved", true); + JSONObject requested = new JSONObject(); + requested.put("duration", lastRun.request.duration); + requested.put("rate", lastRun.request.rate); + requested.put("temp", "absolute"); + deviceStatus.enacted.put("requested", requested); + } + } else { + log.debug("OpenAPS data too old to upload"); + } + deviceStatus.device = "openaps://" + MainApp.getConfigBuilder().deviceID(); + JSONObject pumpstatus = MainApp.getConfigBuilder().getJSONStatus(); + if (pumpstatus != null) { + deviceStatus.pump = pumpstatus; + } + + int batteryLevel = BatteryLevel.getBatteryLevel(); + deviceStatus.uploaderBattery = batteryLevel; + + deviceStatus.created_at = DateUtil.toISOString(new Date()); + Context context = MainApp.instance().getApplicationContext(); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "devicestatus"); + bundle.putString("data", deviceStatus.mongoRecord().toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, deviceStatus.mongoRecord().toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadBolusWizardRecord(Treatment t, double glucose, String glucoseType, int carbTime, JSONObject boluscalc) { + JSONObject data = new JSONObject(); + try { + data.put("eventType", "Bolus Wizard"); + if (t.insulin != 0d) data.put("insulin", t.insulin); + if (t.carbs != 0d) data.put("carbs", t.carbs.intValue()); + data.put("created_at", DateUtil.toISOString(t.date)); + data.put("date", t.date); + if (glucose != 0d) data.put("glucose", glucose); + data.put("glucoseType", glucoseType); + data.put("boluscalc", boluscalc); + if (carbTime != 0) data.put("preBolus", carbTime); + } catch (JSONException e) { + e.printStackTrace(); + } + uploadCareportalEntryToNS(data); + } + + public static void uploadCareportalEntryToNS(JSONObject data) { + try { + if (data.has("preBolus") && data.has("carbs")) { + JSONObject prebolus = new JSONObject(); + prebolus.put("carbs", data.get("carbs")); + data.remove("carbs"); + prebolus.put("eventType", data.get("eventType")); + if (data.has("enteredBy")) prebolus.put("enteredBy", data.get("enteredBy")); + if (data.has("notes")) prebolus.put("notes", data.get("notes")); + long mills = DateUtil.fromISODateString(data.getString("created_at")).getTime(); + Date preBolusDate = new Date(mills + data.getInt("preBolus") * 60000L); + prebolus.put("created_at", DateUtil.toISOString(preBolusDate)); + uploadCareportalEntryToNS(prebolus); + } + Context context = MainApp.instance().getApplicationContext(); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public static void removeCareportalEntryFromNS(String _id) { + try { + Context context = MainApp.instance().getApplicationContext(); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbRemove"); + bundle.putString("collection", "treatments"); + bundle.putString("_id", _id); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbRemove(intent, _id); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + public static void uploadOpenAPSOffline(double durationInMinutes) { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", "OpenAPS Offline"); + data.put("duration", durationInMinutes); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public static void uploadError(String error) { + Context context = MainApp.instance().getApplicationContext(); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + JSONObject data = new JSONObject(); + try { + data.put("eventType", "Announcement"); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("notes", error); + data.put("isAnnouncement", true); + } catch (JSONException e) { + e.printStackTrace(); + } + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } + + public static void uploadAppStart() { + if (SP.getBoolean(R.string.key_ns_logappstartedevent, true)) { + Context context = MainApp.instance().getApplicationContext(); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + JSONObject data = new JSONObject(); + try { + data.put("eventType", "Note"); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("notes", MainApp.sResources.getString(R.string.androidaps_start)); + } catch (JSONException e) { + e.printStackTrace(); + } + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + DbLogger.dbAdd(intent, data.toString()); + } + } +}