diff = computeDiff(date, System.currentTimeMillis());
+ if(diff.get(TimeUnit.DAYS)*24 + diff.get(TimeUnit.HOURS) > hours)
+ return true;
+ else
+ return false;
}
public String log() {
@@ -184,7 +193,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
try {
JSONObject object = new JSONObject(json);
if (object.has("notes"))
- return object.getString("notes");
+ return StringUtils.abbreviate(object.getString("notes"), 40);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@@ -253,4 +262,5 @@ public class CareportalEvent implements DataPointWithLabelInterface {
return Color.GRAY;
return Color.GRAY;
}
+
}
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 082f872d20..7174c19ec4 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
@@ -30,12 +30,10 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventRefreshOverview;
@@ -44,17 +42,23 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
-import info.nightscout.androidaps.events.EventTreatmentChange;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
+import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter;
+import info.nightscout.utils.ToastUtils;
+/**
+ * This Helper contains all resource to provide a central DB management functionality. Only methods handling
+ * data-structure (and not the DB content) should be contained in here (meaning DDL and not SQL).
+ *
+ * This class can safely be called from Services, but should not call Services to avoid circular dependencies.
+ * One major issue with this (right now) are the scheduled events, which are put into the service. Therefor all
+ * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
+ */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
@@ -63,23 +67,19 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
- public static final String DATABASE_TREATMENTS = "Treatments";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
- public static final String DATABASE_FOODS = "Foods";
+ public static final String DATABASE_TDDS = "TDDs";
private static final int DATABASE_VERSION = 8;
- private static Long earliestDataChange = null;
+ public static Long earliestDataChange = null;
private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture> scheduledBgPost = null;
- private static final ScheduledExecutorService treatmentsWorker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledTratmentPost = null;
-
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture> scheduledTemBasalsPost = null;
@@ -95,7 +95,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture> scheduledProfileSwitchEventPost = null;
- public FoodHelper foodHelper = new FoodHelper(this);
+ private int oldVersion = 0;
+ private int newVersion = 0;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
@@ -108,7 +109,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try {
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
- TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
@@ -116,7 +116,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
- TableUtils.createTableIfNotExists(connectionSource, Food.class);
+ TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
@@ -126,14 +126,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
+ this.oldVersion = oldVersion;
+ this.newVersion = newVersion;
+
if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8");
- TableUtils.dropTable(connectionSource, Treatment.class, true);
- TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
} else {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
- TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
@@ -141,7 +141,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
- TableUtils.dropTable(connectionSource, Food.class, true);
onCreate(database, connectionSource);
}
} catch (SQLException e) {
@@ -150,6 +149,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
+ public int getOldVersion() {
+ return oldVersion;
+ }
+
+ public int getNewVersion() {
+ return newVersion;
+ }
+
/**
* Close the database connections and clear any cached DAOs.
*/
@@ -158,40 +165,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
super.close();
}
- public void cleanUpDatabases() {
- // TODO: call it somewhere
- log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
- getWritableDatabase().delete(DATABASE_BGREADINGS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
- log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_BGREADINGS));
-
- log.debug("Before TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
- getWritableDatabase().delete(DATABASE_TEMPTARGETS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
- log.debug("After TempTargets size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPTARGETS));
-
- log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
- getWritableDatabase().delete(DATABASE_TREATMENTS, "date" + " < '" + (System.currentTimeMillis() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000L) + "'", null);
- log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TREATMENTS));
-
- log.debug("Before History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
- getWritableDatabase().delete(DATABASE_DANARHISTORY, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
- log.debug("After History size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_DANARHISTORY));
-
- log.debug("Before TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
- getWritableDatabase().delete(DATABASE_TEMPORARYBASALS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
- log.debug("After TemporaryBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_TEMPORARYBASALS));
-
- log.debug("Before ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
- getWritableDatabase().delete(DATABASE_EXTENDEDBOLUSES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
- log.debug("After ExtendedBoluses size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_EXTENDEDBOLUSES));
-
- log.debug("Before CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
- getWritableDatabase().delete(DATABASE_CAREPORTALEVENTS, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
- log.debug("After CareportalEvent size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_CAREPORTALEVENTS));
-
- log.debug("Before ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
- getWritableDatabase().delete(DATABASE_PROFILESWITCHES, "recordDate" + " < '" + (System.currentTimeMillis() - Constants.daysToKeepHistoryInDatabase * 24 * 60 * 60 * 1000L) + "'", null);
- log.debug("After ProfileSwitch size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), DATABASE_PROFILESWITCHES));
- }
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
@@ -202,7 +175,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
- TableUtils.dropTable(connectionSource, Treatment.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
@@ -210,8 +182,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
+ TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
- TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
@@ -219,20 +191,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
- foodHelper.resetFood();
+ TableUtils.createTableIfNotExists(connectionSource, TDD.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.setFakingStatus(true);
- scheduleBgChange(); // trigger refresh
+ scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange();
- scheduleTreatmentChange();
scheduleExtendedBolusChange();
scheduleTemporaryTargetChange();
scheduleCareportalEventChange();
scheduleProfileSwitchChange();
- foodHelper.scheduleFoodChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
@@ -244,17 +214,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
);
}
- public void resetTreatments() {
- try {
- TableUtils.dropTable(connectionSource, Treatment.class, true);
- TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
- updateEarliestDataChange(0);
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- scheduleTreatmentChange();
- }
-
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
@@ -308,16 +267,21 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleProfileSwitchChange();
}
+ public void resetTDDs() {
+ try {
+ TableUtils.dropTable(connectionSource, TDD.class, true);
+ TableUtils.createTableIfNotExists(connectionSource, TDD.class);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ }
+
// ------------------ getDao -------------------------------------------
private Dao getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
- private Dao getDaoTreatments() throws SQLException {
- return getDao(Treatment.class);
- }
-
private Dao getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
@@ -326,6 +290,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(DanaRHistoryRecord.class);
}
+ private Dao getDaoTDD() throws SQLException {
+ return getDao(TDD.class);
+ }
+
private Dao getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
@@ -346,7 +314,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(ProfileSwitch.class);
}
- public long roundDateToSec(long date) {
+ public static long roundDateToSec(long date) {
return date - date % 1000;
}
// ------------------- BgReading handling -----------------------
@@ -358,7 +326,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (old == null) {
getDaoBgReadings().create(bgReading);
log.debug("BG: New record from: " + from + " " + bgReading.toString());
- scheduleBgChange();
+ scheduleBgChange(bgReading);
return true;
}
if (!old.isEqual(bgReading)) {
@@ -366,7 +334,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
- scheduleBgChange();
+ scheduleBgChange(bgReading);
return false;
}
} catch (SQLException e) {
@@ -380,15 +348,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try {
getDaoBgReadings().update(bgReading);
} catch (SQLException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
- private static void scheduleBgChange() {
+ private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventNewBg");
- MainApp.bus().post(new EventNewBG());
+ MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null;
}
}
@@ -403,8 +371,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
/*
- * Return last BgReading from database or null if db is empty
- */
+ * Return last BgReading from database or null if db is empty
+ */
@Nullable
public static BgReading lastBg() {
List bgList = null;
@@ -428,9 +396,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
/*
- * Return bg reading if not old ( <9 min )
- * or null if older
- */
+ * Return bg reading if not old ( <9 min )
+ * or null if older
+ */
@Nullable
public static BgReading actualBg() {
BgReading lastBg = lastBg();
@@ -479,6 +447,33 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
+ // ------------------- TDD handling -----------------------
+ public void createOrUpdateTDD(TDD tdd) {
+ try {
+ Dao dao = getDaoTDD();
+ dao.createOrUpdate(tdd);
+ } catch (SQLException e) {
+ ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
+ log.error("Unhandled exception", e);
+ }
+ }
+
+ public List getTDDs() {
+ List tddList;
+ try {
+ QueryBuilder queryBuilder = getDaoTDD().queryBuilder();
+ queryBuilder.orderBy("date", false);
+ queryBuilder.limit(10L);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ tddList = getDaoTDD().query(preparedQuery);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ tddList = new ArrayList<>();
+ }
+ return tddList;
+ }
+
+
// ------------- DbRequests handling -------------------
public void create(DbRequest dbr) {
@@ -515,7 +510,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
queryBuilder.limit(10L);
PreparedQuery preparedQuery = queryBuilder.prepare();
List dbList = getDaoDbRequest().query(preparedQuery);
- log.error("deleteDbRequestbyMongoId query size: " + dbList.size());
for (DbRequest r : dbList) {
delete(r);
}
@@ -543,146 +537,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// -------------------- TREATMENT HANDLING -------------------
- // return true if new record is created
- public boolean createOrUpdate(Treatment treatment) {
- try {
- Treatment old;
- treatment.date = roundDateToSec(treatment.date);
-
- if (treatment.source == Source.PUMP) {
- // check for changed from pump change in NS
- QueryBuilder queryBuilder = getDaoTreatments().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("pumpId", treatment.pumpId);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoTreatments().query(preparedQuery);
- if (trList.size() > 0) {
- // do nothing, pump history record cannot be changed
- return false;
- }
- getDaoTreatments().create(treatment);
- log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
- updateEarliestDataChange(treatment.date);
- scheduleTreatmentChange();
- return true;
- }
- if (treatment.source == Source.NIGHTSCOUT) {
- old = getDaoTreatments().queryForId(treatment.date);
- if (old != null) {
- if (!old.isEqual(treatment)) {
- boolean historyChange = old.isDataChanging(treatment);
- long oldDate = old.date;
- getDaoTreatments().delete(old); // need to delete/create because date may change too
- old.copyFrom(treatment);
- getDaoTreatments().create(old);
- log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString());
- if (historyChange) {
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- }
- scheduleTreatmentChange();
- return true;
- }
- return false;
- }
- // find by NS _id
- if (treatment._id != null) {
- QueryBuilder queryBuilder = getDaoTreatments().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", treatment._id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoTreatments().query(preparedQuery);
- if (trList.size() > 0) {
- old = trList.get(0);
- if (!old.isEqual(treatment)) {
- boolean historyChange = old.isDataChanging(treatment);
- long oldDate = old.date;
- getDaoTreatments().delete(old); // need to delete/create because date may change too
- old.copyFrom(treatment);
- getDaoTreatments().create(old);
- log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString());
- if (historyChange) {
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- }
- scheduleTreatmentChange();
- return true;
- }
- }
- }
- getDaoTreatments().create(treatment);
- log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
- updateEarliestDataChange(treatment.date);
- scheduleTreatmentChange();
- return true;
- }
- if (treatment.source == Source.USER) {
- getDaoTreatments().create(treatment);
- log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
- updateEarliestDataChange(treatment.date);
- scheduleTreatmentChange();
- return true;
- }
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return false;
- }
-
- public void delete(Treatment treatment) {
- try {
- getDaoTreatments().delete(treatment);
- updateEarliestDataChange(treatment.date);
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- scheduleTreatmentChange();
- }
-
- public void update(Treatment treatment) {
- try {
- getDaoTreatments().update(treatment);
- updateEarliestDataChange(treatment.date);
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- scheduleTreatmentChange();
- }
-
- public void deleteTreatmentById(String _id) {
- Treatment stored = findTreatmentById(_id);
- if (stored != null) {
- log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString());
- delete(stored);
- updateEarliestDataChange(stored.date);
- scheduleTreatmentChange();
- }
- }
-
- @Nullable
- public Treatment findTreatmentById(String _id) {
- try {
- Dao daoTreatments = getDaoTreatments();
- QueryBuilder queryBuilder = daoTreatments.queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", _id);
- queryBuilder.limit(10L);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = daoTreatments.query(preparedQuery);
- if (trList.size() != 1) {
- //log.debug("Treatment findTreatmentById query size: " + trList.size());
- return null;
- } else {
- //log.debug("Treatment findTreatmentById found: " + trList.get(0).log());
- return trList.get(0);
- }
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return null;
- }
-
- private void updateEarliestDataChange(long newDate) {
+ public static void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
return;
@@ -692,73 +547,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
- private static void scheduleTreatmentChange() {
- class PostRunnable implements Runnable {
- public void run() {
- log.debug("Firing EventTreatmentChange");
- MainApp.bus().post(new EventReloadTreatmentData(new EventTreatmentChange()));
- if (earliestDataChange != null)
- MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
- earliestDataChange = null;
- scheduledTratmentPost = null;
- }
- }
- // prepare task for execution in 1 sec
- // cancel waiting task to prevent sending multiple posts
- if (scheduledTratmentPost != null)
- scheduledTratmentPost.cancel(false);
- Runnable task = new PostRunnable();
- final int sec = 1;
- scheduledTratmentPost = treatmentsWorker.schedule(task, sec, TimeUnit.SECONDS);
-
- }
-
- public List getTreatmentDataFromTime(long mills, boolean ascending) {
- try {
- Dao daoTreatments = getDaoTreatments();
- List treatments;
- QueryBuilder queryBuilder = daoTreatments.queryBuilder();
- queryBuilder.orderBy("date", ascending);
- Where where = queryBuilder.where();
- where.ge("date", mills);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- treatments = daoTreatments.query(preparedQuery);
- return treatments;
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return new ArrayList();
- }
-
- public void createTreatmentFromJsonIfNotExists(JSONObject trJson) {
- try {
- Treatment treatment = new Treatment();
- treatment.source = Source.NIGHTSCOUT;
- treatment.date = roundDateToSec(trJson.getLong("mills"));
- treatment.carbs = trJson.has("carbs") ? trJson.getDouble("carbs") : 0;
- treatment.insulin = trJson.has("insulin") ? trJson.getDouble("insulin") : 0d;
- treatment.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
- treatment._id = trJson.getString("_id");
- if (trJson.has("isSMB"))
- treatment.isSMB = trJson.getBoolean("isSMB");
- if (trJson.has("eventType")) {
- treatment.mealBolus = !trJson.get("eventType").equals("Correction Bolus");
- double carbs = treatment.carbs;
- if (trJson.has("boluscalc")) {
- JSONObject boluscalc = trJson.getJSONObject("boluscalc");
- if (boluscalc.has("carbs")) {
- carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
- }
- }
- if (carbs <= 0)
- treatment.mealBolus = false;
- }
- createOrUpdate(treatment);
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
-
// ---------------- TempTargets handling ---------------
public List getTemptargetsDataFromTime(long mills, boolean ascending) {
@@ -876,15 +664,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
- String units = MainApp.getConfigBuilder().getProfileUnits();
- TempTarget tempTarget = new TempTarget();
- tempTarget.date = trJson.getLong("mills");
- tempTarget.durationInMinutes = trJson.getInt("duration");
- tempTarget.low = Profile.toMgdl(trJson.getDouble("targetBottom"), units);
- tempTarget.high = Profile.toMgdl(trJson.getDouble("targetTop"), units);
- tempTarget.reason = trJson.getString("reason");
- tempTarget._id = trJson.getString("_id");
- tempTarget.source = Source.NIGHTSCOUT;
+ String units = JsonHelper.safeGetString(trJson, "units", MainApp.getConfigBuilder().getProfileUnits());
+ TempTarget tempTarget = new TempTarget()
+ .date(trJson.getLong("mills"))
+ .duration(trJson.getInt("duration"))
+ .low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
+ .high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
+ .reason(trJson.getString("reason"))
+ ._id(trJson.getString("_id"))
+ .source(Source.NIGHTSCOUT);
createOrUpdate(tempTarget);
} catch (JSONException e) {
log.error("Unhandled exception", e);
@@ -924,6 +712,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createOrUpdate(DanaRHistoryRecord record) {
try {
getDaoDanaRHistory().createOrUpdate(record);
+
+ //If it is a TDD, store it for stats also.
+ if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) {
+ createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
+ }
+
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
@@ -1153,10 +947,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
createOrUpdate(extendedBolus);
} else {
- TemporaryBasal tempBasal = new TemporaryBasal();
- tempBasal.date = trJson.getLong("mills");
- tempBasal.source = Source.NIGHTSCOUT;
- tempBasal.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
+ TemporaryBasal tempBasal = new TemporaryBasal()
+ .date(trJson.getLong("mills"))
+ .source(Source.NIGHTSCOUT)
+ .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
@@ -1360,37 +1154,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
*/
- public void createExtendedBolusFromJsonIfNotExists(JSONObject trJson) {
- try {
- 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.has("duration") ? trJson.getInt("duration") : 0;
- extendedBolus.insulin = trJson.getDouble("relative");
- extendedBolus._id = trJson.getString("_id");
+ public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
+ ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(json);
+ if (extendedBolus != null)
createOrUpdate(extendedBolus);
- } catch (SQLException | JSONException e) {
- log.error("Unhandled exception", e);
- }
}
private static void scheduleExtendedBolusChange() {
@@ -1436,6 +1203,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleCareportalEventChange();
}
+ public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
+ try {
+ return getDaoCareportalEvents().queryForId(timestamp);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
try {
@@ -1489,7 +1265,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteCareportalEventById(String _id) {
try {
- QueryBuilder queryBuilder = null;
+ QueryBuilder queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
@@ -1512,7 +1288,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
try {
- QueryBuilder queryBuilder = null;
+ QueryBuilder queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
@@ -1569,14 +1345,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
List profileSwitches;
QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
- queryBuilder.limit(20L);
+ queryBuilder.limit(100L);
PreparedQuery preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
- return new ArrayList();
+ return new ArrayList<>();
}
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
@@ -1693,7 +1469,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
else {
- ProfileStore store = ConfigBuilderPlugin.getActiveProfileInterface().getProfile();
+ ProfileStore store = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
@@ -1742,4 +1518,4 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
// ---------------- Food handling ---------------
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
index 4232a2fc86..1123cb58df 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
@@ -9,24 +9,25 @@ import android.graphics.Color;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.Round;
/**
@@ -91,6 +92,16 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
pumpId = t.pumpId;
}
+ public static ExtendedBolus createFromJson(JSONObject json) {
+ ExtendedBolus extendedBolus = new ExtendedBolus();
+ extendedBolus.source = Source.NIGHTSCOUT;
+ extendedBolus.date = JsonHelper.safeGetLong(json, "mills");
+ extendedBolus.durationInMinutes = JsonHelper.safeGetInt(json, "duration");
+ extendedBolus.insulin = JsonHelper.safeGetDouble(json, "relative") / 60 * extendedBolus.durationInMinutes;
+ extendedBolus._id = JsonHelper.safeGetString(json, "_id");
+ extendedBolus.pumpId = JsonHelper.safeGetLong(json, "pumpId");
+ return extendedBolus;
+ }
// -------- Interval interface ---------
Long cuttedEnd = null;
@@ -285,4 +296,5 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
public int getColor() {
return Color.CYAN;
}
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/FoodHelper.java b/app/src/main/java/info/nightscout/androidaps/db/FoodHelper.java
deleted file mode 100644
index a933c2166e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/db/FoodHelper.java
+++ /dev/null
@@ -1,208 +0,0 @@
-package info.nightscout.androidaps.db;
-
-import com.j256.ormlite.android.AndroidConnectionSource;
-import com.j256.ormlite.dao.Dao;
-import com.j256.ormlite.stmt.PreparedQuery;
-import com.j256.ormlite.stmt.QueryBuilder;
-import com.j256.ormlite.stmt.Where;
-import com.j256.ormlite.table.TableUtils;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
-
-/**
- * Created by mike on 24.09.2017.
- */
-
-public class FoodHelper {
- private static Logger log = LoggerFactory.getLogger(FoodHelper.class);
-
- DatabaseHelper databaseHelper;
-
- private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledFoodEventPost = null;
-
- public FoodHelper(DatabaseHelper databaseHelper) {
- this.databaseHelper = databaseHelper;
- }
-
- private Dao getDaoFood() throws SQLException {
- return databaseHelper.getDao(Food.class);
- }
-
- public void resetFood() {
- try {
- TableUtils.dropTable(databaseHelper.getConnectionSource(), Food.class, true);
- TableUtils.createTableIfNotExists(databaseHelper.getConnectionSource(), Food.class);
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- scheduleFoodChange();
- }
-
- public List getFoodData() {
- try {
- Dao daoFood = getDaoFood();
- List foods;
- QueryBuilder queryBuilder = daoFood.queryBuilder();
- PreparedQuery preparedQuery = queryBuilder.prepare();
- foods = daoFood.query(preparedQuery);
- return foods;
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return new ArrayList<>();
- }
-
- public boolean createOrUpdate(Food food) {
- try {
- // find by NS _id
- if (food._id != null && !food._id.equals("")) {
- Food old;
-
- QueryBuilder queryBuilder = getDaoFood().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", food._id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List found = getDaoFood().query(preparedQuery);
- if (found.size() > 0) {
- old = found.get(0);
- if (!old.isEqual(food)) {
- getDaoFood().delete(old); // need to delete/create because date may change too
- old.copyFrom(food);
- getDaoFood().create(old);
- log.debug("FOOD: Updating record by _id: " + old.toString());
- scheduleFoodChange();
- return true;
- } else {
- return false;
- }
- } else {
- getDaoFood().createOrUpdate(food);
- log.debug("FOOD: New record: " + food.toString());
- scheduleFoodChange();
- return true;
- }
- }
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return false;
- }
-
- public void delete(Food food) {
- try {
- getDaoFood().delete(food);
- scheduleFoodChange();
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- }
-
- public static void scheduleFoodChange() {
- class PostRunnable implements Runnable {
- public void run() {
- log.debug("Firing EventFoodChange");
- MainApp.bus().post(new EventFoodDatabaseChanged());
- scheduledFoodEventPost = null;
- }
- }
- // prepare task for execution in 1 sec
- // cancel waiting task to prevent sending multiple posts
- if (scheduledFoodEventPost != null)
- scheduledFoodEventPost.cancel(false);
- Runnable task = new PostRunnable();
- final int sec = 1;
- scheduledFoodEventPost = foodEventWorker.schedule(task, sec, TimeUnit.SECONDS);
-
- }
-
- /*
- {
- "_id": "551ee3ad368e06e80856e6a9",
- "type": "food",
- "category": "Zakladni",
- "subcategory": "Napoje",
- "name": "Mleko",
- "portion": 250,
- "carbs": 12,
- "gi": 1,
- "created_at": "2015-04-14T06:59:16.500Z",
- "unit": "ml"
- }
- */
- public void createFoodFromJsonIfNotExists(JSONObject trJson) {
- try {
- Food food = new Food();
- if (trJson.has("type") && trJson.getString("type").equals("food")) {
- if (trJson.has("_id"))
- food._id = trJson.getString("_id");
- if (trJson.has("category"))
- food.category = trJson.getString("category");
- if (trJson.has("subcategory"))
- food.subcategory = trJson.getString("subcategory");
- if (trJson.has("name"))
- food.name = trJson.getString("name");
- if (trJson.has("unit"))
- food.units = trJson.getString("unit");
- if (trJson.has("portion"))
- food.portion = trJson.getDouble("portion");
- if (trJson.has("carbs"))
- food.carbs = trJson.getInt("carbs");
- if (trJson.has("gi"))
- food.gi = trJson.getInt("gi");
- if (trJson.has("energy"))
- food.energy = trJson.getInt("energy");
- if (trJson.has("protein"))
- food.protein = trJson.getInt("protein");
- if (trJson.has("fat"))
- food.fat = trJson.getInt("fat");
- }
- createOrUpdate(food);
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
-
- public void deleteFoodById(String _id) {
- Food stored = findFoodById(_id);
- if (stored != null) {
- log.debug("FOOD: Removing Food record from database: " + stored.toString());
- delete(stored);
- scheduleFoodChange();
- }
- }
-
- public Food findFoodById(String _id) {
- try {
- QueryBuilder queryBuilder = getDaoFood().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", _id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = getDaoFood().query(preparedQuery);
-
- if (list.size() == 1) {
- return list.get(0);
- } else {
- return null;
- }
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- return null;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ICallback.java b/app/src/main/java/info/nightscout/androidaps/db/ICallback.java
new file mode 100644
index 0000000000..7a9360035f
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/ICallback.java
@@ -0,0 +1,15 @@
+package info.nightscout.androidaps.db;
+
+import java.util.concurrent.ScheduledFuture;
+
+/**
+ * Created by triplem on 05.01.18.
+ */
+
+public interface ICallback {
+
+ void setPost(ScheduledFuture> post);
+
+ ScheduledFuture> getPost();
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
index dcce69639f..40c8e50c6d 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
@@ -61,6 +61,31 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private Profile profile = null;
+ public ProfileSwitch date(long date) {
+ this.date = date;
+ return this;
+ }
+
+ public ProfileSwitch profileName(String profileName) {
+ this.profileName = profileName;
+ return this;
+ }
+
+ public ProfileSwitch profile(Profile profile) {
+ this.profile = profile;
+ return this;
+ }
+
+ public ProfileSwitch source(int source) {
+ this.source = source;
+ return this;
+ }
+
+ public ProfileSwitch duration(int duration) {
+ this.durationInMinutes = duration;
+ return this;
+ }
+
@Nullable
public Profile getProfileObject() {
if (profile == null)
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TDD.java b/app/src/main/java/info/nightscout/androidaps/db/TDD.java
new file mode 100644
index 0000000000..f34c79ff1a
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/TDD.java
@@ -0,0 +1,46 @@
+package info.nightscout.androidaps.db;
+
+import com.j256.ormlite.field.DatabaseField;
+import com.j256.ormlite.table.DatabaseTable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Objects;
+
+/**
+ * Created by mike on 20.09.2017.
+ */
+
+
+@DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS)
+public class TDD {
+ private static Logger log = LoggerFactory.getLogger(TDD.class);
+
+ @DatabaseField(id = true)
+ public long date;
+
+ @DatabaseField
+ public double bolus;
+
+ @DatabaseField
+ public double basal;
+
+ @DatabaseField
+ public double total;
+
+
+ public double getTotal(){
+ return (total > 0d) ? total:(bolus+basal);
+ }
+
+
+ public TDD() { }
+
+ public TDD(long date, double bolus, double basal, double total){
+ this.date = date;
+ this.bolus = bolus;
+ this.basal = basal;
+ this.total = total;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
index c6d0ed18c4..ae016a0f29 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
@@ -41,6 +41,10 @@ public class TempTarget implements Interval {
@DatabaseField
public int durationInMinutes;
+ public double target() {
+ return (low + high) / 2;
+ }
+
public boolean isEqual(TempTarget other) {
if (date != other.date) {
return false;
@@ -67,6 +71,41 @@ public class TempTarget implements Interval {
reason = t.reason;
}
+ public TempTarget date(long date) {
+ this.date = date;
+ return this;
+ }
+
+ public TempTarget low(double low) {
+ this.low = low;
+ return this;
+ }
+
+ public TempTarget high(double high) {
+ this.high = high;
+ return this;
+ }
+
+ public TempTarget duration(int duration) {
+ this.durationInMinutes = duration;
+ return this;
+ }
+
+ public TempTarget reason(String reason) {
+ this.reason = reason;
+ return this;
+ }
+
+ public TempTarget _id(String _id) {
+ this._id = _id;
+ return this;
+ }
+
+ public TempTarget source(int source) {
+ this.source = source;
+ return this;
+ }
+
// -------- Interval interface ---------
Long cuttedEnd = null;
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
index 3feb9c4ad2..733027b188 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
@@ -6,7 +6,6 @@ import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.MainApp;
@@ -17,6 +16,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
@@ -60,8 +60,36 @@ public class TemporaryBasal implements Interval {
public TemporaryBasal() {
}
- public TemporaryBasal(long date) {
+ public TemporaryBasal date(long date) {
this.date = date;
+ return this;
+ }
+
+ public TemporaryBasal duration(int durationInMinutes) {
+ this.durationInMinutes = durationInMinutes;
+ return this;
+ }
+
+ public TemporaryBasal absolute(double absoluteRate) {
+ this.absoluteRate = absoluteRate;
+ this.isAbsolute = true;
+ return this;
+ }
+
+ public TemporaryBasal percent(int percentRate) {
+ this.percentRate = percentRate;
+ this.isAbsolute = false;
+ return this;
+ }
+
+ public TemporaryBasal source(int source) {
+ this.source = source;
+ return this;
+ }
+
+ public TemporaryBasal pumpId(long pumpId) {
+ this.pumpId = pumpId;
+ return this;
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
@@ -189,7 +217,7 @@ public class TemporaryBasal implements Interval {
// -------- Interval interface end ---------
- public IobTotal iobCalc(long time) {
+ public IobTotal iobCalc(long time, Profile profile) {
if(isFakeExtended){
log.error("iobCalc should only be called on Extended boluses separately");
@@ -197,7 +225,6 @@ public class TemporaryBasal implements Interval {
}
IobTotal result = new IobTotal(time);
- Profile profile = MainApp.getConfigBuilder().getProfile(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getActiveInsulin();
int realDuration = getDurationToTime(time);
@@ -262,13 +289,13 @@ public class TemporaryBasal implements Interval {
return (remainingMin < 0) ? 0 : Math.round(remainingMin);
}
- public double tempBasalConvertedToAbsolute(long time) {
+ public double tempBasalConvertedToAbsolute(long time, Profile profile) {
if(isFakeExtended){
- return MainApp.getConfigBuilder().getProfile(time).getBasal(time) + netExtendedRate;
+ return profile.getBasal(time) + netExtendedRate;
} else if (isAbsolute) {
return absoluteRate;
} else {
- return MainApp.getConfigBuilder().getProfile(time).getBasal(time) * percentRate / 100;
+ return profile.getBasal(time) * percentRate / 100;
}
}
@@ -325,13 +352,13 @@ public class TemporaryBasal implements Interval {
if(profile != null) {
double basal = profile.getBasal();
if(basal != 0){
- return Math.round(rate*100d/basal) + "% ";
+ return Math.round(rate*100d/basal) + "%";
}
}
}
- return DecimalFormatter.to2Decimal(rate) + "U/h ";
+ return DecimalFormatter.to2Decimal(rate) + "U/h";
} else { // percent
- return percentRate + "% ";
+ return percentRate + "%";
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java b/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java
new file mode 100644
index 0000000000..bcd9061133
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java
@@ -0,0 +1,13 @@
+package info.nightscout.androidaps.events;
+
+public class EventChargingState {
+
+ public boolean isCharging = false;
+
+ public EventChargingState() {}
+
+ public EventChargingState(boolean isCharging) {
+ this.isCharging = isCharging;
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java
new file mode 100644
index 0000000000..e52761dc58
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by mike on 13.02.2018.
+ */
+
+public class EventCustomCalculationFinished extends Event {
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java b/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java
new file mode 100644
index 0000000000..0d07cd6c61
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java
@@ -0,0 +1,36 @@
+package info.nightscout.androidaps.events;
+
+/**
+ * Created by jamorham on 07/02/2018.
+ *
+ * Event to indicate that an app feature is being used, for example bolus wizard being opened
+ *
+ * The purpose this has been created for is to enable opportunistic connection to the pump
+ * so that it is already connected before the user wishes to enact a pump function
+ *
+ */
+
+public class EventFeatureRunning extends Event {
+
+ private Feature feature = Feature.UNKNOWN;
+
+ public EventFeatureRunning() {
+ }
+
+ public EventFeatureRunning(Feature feature) {
+ this.feature = feature;
+ }
+
+ public Feature getFeature() {
+ return feature;
+ }
+
+ public enum Feature {
+ UNKNOWN,
+ MAIN,
+ WIZARD,
+
+ JUST_ADD_MORE_HERE
+ }
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java
new file mode 100644
index 0000000000..03df71f31b
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java
@@ -0,0 +1,14 @@
+package info.nightscout.androidaps.events;
+
+public class EventNetworkChange extends Event {
+
+ public boolean mobileConnected = false;
+ public boolean wifiConnected = false;
+
+ public String ssid = "";
+ public boolean roaming = false;
+
+ public String getSsid() {
+ return ssid.replace("SSID: ","").replaceAll("\"","");
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java
index 2fb9919b00..dc4d434e0a 100644
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java
@@ -1,7 +1,17 @@
package info.nightscout.androidaps.events;
+import android.support.annotation.Nullable;
+
+import info.nightscout.androidaps.db.BgReading;
+
/**
* Created by mike on 05.06.2016.
*/
public class EventNewBG extends EventLoop {
+ @Nullable
+ public final BgReading bgReading;
+
+ public EventNewBG(BgReading bgReading) {
+ this.bgReading = bgReading;
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java
new file mode 100644
index 0000000000..90b6f5681b
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java
@@ -0,0 +1,35 @@
+package info.nightscout.androidaps.events;
+
+import android.os.Bundle;
+
+/**
+ * Event which is published with data fetched from NightScout specific for the
+ * Food-class.
+ *
+ * Payload is the from NS retrieved JSON-String which should be handled by all
+ * subscriber.
+ */
+
+public class EventNsFood extends Event {
+
+ public static final int ADD = 0;
+ public static final int UPDATE = 1;
+ public static final int REMOVE = 2;
+
+ private final int mode;
+
+ private final Bundle payload;
+
+ public EventNsFood(int mode, Bundle payload) {
+ this.mode = mode;
+ this.payload = payload;
+ }
+
+ public int getMode() {
+ return mode;
+ }
+
+ public Bundle getPayload() {
+ return payload;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java
new file mode 100644
index 0000000000..2c5ba6c9c0
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java
@@ -0,0 +1,36 @@
+package info.nightscout.androidaps.events;
+
+import org.json.JSONObject;
+
+
+/**
+ * Event which is published with data fetched from NightScout specific for the
+ * Treatment-class.
+ *
+ * Payload is the from NS retrieved JSON-String which should be handled by all
+ * subscriber.
+ */
+
+public class EventNsTreatment extends Event {
+
+ public static final int ADD = 0;
+ public static final int UPDATE = 1;
+ public static final int REMOVE = 2;
+
+ private final int mode;
+
+ private final JSONObject payload;
+
+ public EventNsTreatment(int mode, JSONObject payload) {
+ this.mode = mode;
+ this.payload = payload;
+ }
+
+ public int getMode() {
+ return mode;
+ }
+
+ public JSONObject getPayload() {
+ return payload;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java
index f99cb54568..f23d4e802a 100644
--- a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java
@@ -12,11 +12,11 @@ public class EventPreferenceChange extends Event {
}
public EventPreferenceChange(int resourceID) {
- changedKey = MainApp.sResources.getString(resourceID);
+ changedKey = MainApp.gs(resourceID);
}
public boolean isChanged(int id) {
- return changedKey.equals(MainApp.sResources.getString(id));
+ return changedKey.equals(MainApp.gs(id));
}
public boolean isChanged(String id) {
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java
index 52c3183821..7d810702b9 100644
--- a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java
@@ -46,13 +46,13 @@ public class EventPumpStatusChanged extends Event {
public String textStatus() {
if (sStatus == CONNECTING)
- return String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), sSecondsElapsed);
+ return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == CONNECTED)
- return MainApp.sResources.getString(R.string.connected);
+ return MainApp.gs(R.string.connected);
else if (sStatus == PERFORMING)
return sPerfomingAction;
else if (sStatus == DISCONNECTING)
- return MainApp.sResources.getString(R.string.disconnecting);
+ return MainApp.gs(R.string.disconnecting);
else if (sStatus == DISCONNECTED)
return "";
return "";
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java
index 439d9a7124..989b24b7f9 100644
--- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java
@@ -1,7 +1,17 @@
package info.nightscout.androidaps.events;
+import android.support.annotation.Nullable;
+
+import info.nightscout.androidaps.plugins.Treatments.Treatment;
+
/**
* Created by mike on 04.06.2016.
*/
public class EventTreatmentChange extends EventLoop {
+ @Nullable
+ public final Treatment treatment;
+
+ public EventTreatmentChange(Treatment treatment) {
+ this.treatment = treatment;
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
index 11c01112ba..0b965d48af 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
@@ -11,5 +11,5 @@ public interface APSInterface {
public APSResult getLastAPSResult();
public Date getLastAPSRun();
- public void invoke(String initiator);
+ public void invoke(String initiator, boolean tempBasalFallback);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java
index 7ecc89ef66..a45ab083e7 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java
@@ -4,4 +4,5 @@ package info.nightscout.androidaps.interfaces;
* Created by mike on 20.06.2016.
*/
public interface BgSourceInterface {
+ boolean advancedFilteringSupported();
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java
new file mode 100644
index 0000000000..58e6045bd1
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java
@@ -0,0 +1,117 @@
+package info.nightscout.androidaps.interfaces;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by mike on 19.03.2018.
+ */
+
+public class Constraint {
+ private static Logger log = LoggerFactory.getLogger(Constraint.class);
+
+ T value;
+ T originalValue;
+
+ List reasons = new ArrayList<>();
+ List mostLimiting = new ArrayList<>();
+
+ public Constraint(T value) {
+ this.value = value;
+ this.originalValue = value;
+ }
+
+ public T value() {
+ return value;
+ }
+
+ public T originalValue() {
+ return originalValue;
+ }
+
+ public Constraint set(T value) {
+ this.value = value;
+ this.originalValue = value;
+ return this;
+ }
+
+ public Constraint set(T value, String reason, Object from) {
+ this.value = value;
+ addReason(reason, from);
+ addMostLimingReason(reason, from);
+ return this;
+ }
+
+ public Constraint setIfSmaller(T value, String reason, Object from) {
+ if (value.compareTo(this.value) < 0) {
+ this.value = value;
+ mostLimiting.clear();
+ addMostLimingReason(reason, from);
+ }
+ if (value.compareTo(this.originalValue) < 0) {
+ addReason(reason, from);
+ }
+ return this;
+ }
+
+ public Constraint setIfGreater(T value, String reason, Object from) {
+ if (value.compareTo(this.value) > 0) {
+ this.value = value;
+ mostLimiting.clear();
+ addMostLimingReason(reason, from);
+ }
+ if (value.compareTo(this.originalValue) > 0) {
+ addReason(reason, from);
+ }
+ return this;
+ }
+
+ public Constraint addReason(String reason, Object from) {
+ reasons.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason);
+ return this;
+ }
+
+ public Constraint addMostLimingReason(String reason, Object from) {
+ mostLimiting.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason);
+ return this;
+ }
+
+ public String getReasons() {
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
+ for (String r : reasons) {
+ if (count++ != 0) sb.append("\n");
+ sb.append(r);
+ }
+ log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
+ return sb.toString();
+ }
+
+ public List getReasonList() {
+ return reasons;
+ }
+
+ public String getMostLimitedReasons() {
+ StringBuilder sb = new StringBuilder();
+ int count = 0;
+ for (String r : mostLimiting) {
+ if (count++ != 0) sb.append("\n");
+ sb.append(r);
+ }
+ log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
+ return sb.toString();
+ }
+
+ public List getMostLimitedReasonList() {
+ return mostLimiting;
+ }
+
+ public void copyReasons(Constraint> another) {
+ for (String s: another.getReasonList()) {
+ reasons.add(s);
+ }
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
index aac7918bdc..a1daa08a56 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
@@ -1,30 +1,54 @@
package info.nightscout.androidaps.interfaces;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
+import info.nightscout.androidaps.data.Profile;
/**
* Created by mike on 15.06.2016.
*/
public interface ConstraintsInterface {
- boolean isLoopEnabled();
+ default Constraint isLoopInvokationAllowed(Constraint value) {
+ return value;
+ }
- boolean isClosedModeEnabled();
+ default Constraint isClosedLoopAllowed(Constraint value) {
+ return value;
+ }
- boolean isAutosensModeEnabled();
+ default Constraint isAutosensModeEnabled(Constraint value) {
+ return value;
+ }
- boolean isAMAModeEnabled();
+ default Constraint isAMAModeEnabled(Constraint value) {
+ return value;
+ }
- boolean isSMBModeEnabled();
+ default Constraint isSMBModeEnabled(Constraint value) {
+ return value;
+ }
- Double applyBasalConstraints(Double absoluteRate);
+ default Constraint isAdvancedFilteringEnabled(Constraint value) {
+ return value;
+ }
- Integer applyBasalConstraints(Integer percentRate);
+ default Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) {
+ return absoluteRate;
+ }
- Double applyBolusConstraints(Double insulin);
+ default Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) {
+ return percentRate;
+ }
- Integer applyCarbsConstraints(Integer carbs);
+ default Constraint applyBolusConstraints(Constraint insulin) {
+ return insulin;
+ }
- Double applyMaxIOBConstraints(Double maxIob);
+ default Constraint applyCarbsConstraints(Constraint carbs) {
+ return carbs;
+ }
+
+ default Constraint applyMaxIOBConstraints(Constraint maxIob) {
+ return maxIob;
+ };
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
index 48efa587d8..a123554ae8 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
@@ -1,25 +1,23 @@
package info.nightscout.androidaps.interfaces;
-import java.util.Date;
-
import info.nightscout.androidaps.data.Iob;
-import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.plugins.Treatments.Treatment;
/**
* Created by mike on 17.04.2017.
*/
public interface InsulinInterface {
- final int FASTACTINGINSULIN = 0;
- final int FASTACTINGINSULINPROLONGED = 1;
- final int OREF_RAPID_ACTING = 2;
- final int OREF_ULTRA_RAPID_ACTING = 3;
- final int OREF_FREE_PEAK = 4;
+ int FASTACTINGINSULIN = 0;
+ int FASTACTINGINSULINPROLONGED = 1;
+ int OREF_RAPID_ACTING = 2;
+ int OREF_ULTRA_RAPID_ACTING = 3;
+ int OREF_FREE_PEAK = 4;
int getId();
String getFriendlyName();
String getComment();
double getDia();
- public Iob iobCalcForTreatment(Treatment treatment, long time, double dia);
+ Iob iobCalcForTreatment(Treatment treatment, long time, double dia);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
index 08db6210d4..1173936430 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
@@ -1,34 +1,165 @@
package info.nightscout.androidaps.interfaces;
-import java.util.Date;
+import android.os.SystemClock;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
/**
* Created by mike on 09.06.2016.
*/
-public interface PluginBase {
- int GENERAL = 1;
- int TREATMENT = 2;
- int SENSITIVITY = 3;
- int PROFILE = 4;
- int APS = 5;
- int PUMP = 6;
- int CONSTRAINTS = 7;
- int LOOP = 8;
- int BGSOURCE = 9;
- int INSULIN = 10;
- int LAST = 11; // keep always highest number
+public abstract class PluginBase {
+ private static Logger log = LoggerFactory.getLogger(PluginBase.class);
- int getType();
- String getFragmentClass();
+ public enum State {
+ NOT_INITIALIZED,
+ ENABLED,
+ DISABLED
+ }
- String getName();
- String getNameShort();
- boolean isEnabled(int type);
- boolean isVisibleInTabs(int type);
- boolean canBeHidden(int type);
- boolean hasFragment();
- boolean showInList(int type);
- void setFragmentEnabled(int type, boolean fragmentEnabled);
- void setFragmentVisible(int type, boolean fragmentVisible);
- int getPreferencesId();
+ private State state = State.NOT_INITIALIZED;
+ private boolean isFragmentVisible = false;
+ public PluginDescription pluginDescription;
+
+
+ // Specific plugin with more Interfaces
+ protected boolean isProfileInterfaceEnabled = false;
+
+ public PluginBase(PluginDescription pluginDescription) {
+ this.pluginDescription = pluginDescription;
+ }
+
+// public PluginType getType() {
+// return mainType;
+// }
+
+// public String getFragmentClass() {
+// return fragmentClass;
+// }
+
+ public String getName() {
+ if (pluginDescription.pluginName == -1)
+ return "UKNOWN";
+ else
+ return MainApp.gs(pluginDescription.pluginName);
+ }
+
+ public String getNameShort() {
+ if (pluginDescription.shortName == -1)
+ return getName();
+ String name = MainApp.gs(pluginDescription.shortName);
+ if (!name.trim().isEmpty()) //only if translation exists
+ return name;
+ // use long name as fallback
+ return getName();
+ }
+
+ public PluginType getType() {
+ return pluginDescription.mainType;
+ }
+
+ public int getPreferencesId() {
+ return pluginDescription.preferencesId;
+ }
+
+ public int getAdvancedPreferencesId() {
+ return pluginDescription.advancedPreferencesId;
+ }
+
+ public boolean isEnabled(PluginType type) {
+ if (pluginDescription.alwaysEnabled && type == pluginDescription.mainType)
+ return true;
+ if (pluginDescription.mainType == PluginType.CONSTRAINTS && type == PluginType.CONSTRAINTS)
+ return true;
+ if (type == pluginDescription.mainType)
+ return state == State.ENABLED && specialEnableCondition();
+ if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP))
+ return true;
+ if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP)
+ return isProfileInterfaceEnabled;
+ return false;
+ }
+
+ public boolean hasFragment() {
+ return pluginDescription.fragmentClass != null;
+ }
+
+
+ /**
+ * So far plugin can have it's main type + ConstraintInterface + ProfileInterface
+ * ConstraintInterface is enabled if main plugin is enabled
+ * ProfileInterface can be enabled only if main iterface is enable
+ */
+
+ public void setPluginEnabled(PluginType type, boolean newState) {
+ if (type == pluginDescription.mainType) {
+ if (newState == true) { // enabling plugin
+ if (state != State.ENABLED) {
+ onStateChange(type, state, State.ENABLED);
+ state = State.ENABLED;
+ log.debug("Starting: " + getName());
+ onStart();
+ }
+ } else { // disabling plugin
+ if (state == State.ENABLED) {
+ onStateChange(type, state, State.ENABLED);
+ state = State.DISABLED;
+ onStop();
+ log.debug("Stopping: " + getName());
+ }
+ }
+ } else if (type == PluginType.PROFILE) {
+ isProfileInterfaceEnabled = newState;
+ }
+
+ }
+
+ public void setFragmentVisible(PluginType type, boolean fragmentVisible) {
+ if (type == pluginDescription.mainType) {
+ isFragmentVisible = fragmentVisible && specialEnableCondition();
+ }
+ }
+
+ public boolean isFragmentVisible() {
+ if (pluginDescription.alwayVisible)
+ return true;
+ if (pluginDescription.neverVisible)
+ return false;
+ return isFragmentVisible;
+ }
+
+ public boolean showInList(PluginType type) {
+ if (pluginDescription.mainType == type)
+ return pluginDescription.showInList && specialShowInListCondition();
+
+ if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP)
+ return isEnabled(PluginType.PUMP);
+ return false;
+ }
+
+ public boolean specialEnableCondition() {
+ return true;
+ }
+
+ public boolean specialShowInListCondition() {
+ return true;
+ }
+
+ protected void onStart() {
+ if (getType() == PluginType.PUMP) {
+ new Thread(() -> {
+ SystemClock.sleep(3000);
+ ConfigBuilderPlugin.getCommandQueue().readStatus("Pump driver changed.", null);
+ }).start();
+ }
+ }
+
+ protected void onStop() {
+ }
+
+ protected void onStateChange(PluginType type, State oldState, State newState) {
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java
new file mode 100644
index 0000000000..c86ae639fa
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java
@@ -0,0 +1,84 @@
+package info.nightscout.androidaps.interfaces;
+
+public class PluginDescription {
+ PluginType mainType = PluginType.GENERAL;
+ String fragmentClass = null;
+ public boolean alwayVisible = false;
+ public boolean neverVisible = false;
+ public boolean alwaysEnabled = false;
+ boolean showInList = true;
+ int pluginName = -1;
+ int shortName = -1;
+ int preferencesId = -1;
+ int advancedPreferencesId = -1;
+ public boolean enableByDefault = false;
+ public boolean visibleByDefault = false;
+
+ public PluginDescription mainType(PluginType mainType) {
+ this.mainType = mainType;
+ return this;
+ }
+
+ public PluginDescription fragmentClass(String fragmentClass) {
+ this.fragmentClass = fragmentClass;
+ return this;
+ }
+
+ public PluginDescription alwaysEnabled(boolean alwaysEnabled) {
+ this.alwaysEnabled = alwaysEnabled;
+ return this;
+ }
+
+ public PluginDescription alwayVisible(boolean alwayVisible) {
+ this.alwayVisible = alwayVisible;
+ return this;
+ }
+
+ public PluginDescription neverVisible(boolean neverVisible) {
+ this.neverVisible = neverVisible;
+ return this;
+ }
+
+ public PluginDescription showInList(boolean showInList) {
+ this.showInList = showInList;
+ return this;
+ }
+
+ public PluginDescription pluginName(int pluginName) {
+ this.pluginName = pluginName;
+ return this;
+ }
+
+ public PluginDescription shortName(int shortName) {
+ this.shortName = shortName;
+ return this;
+ }
+
+ public PluginDescription preferencesId(int preferencesId) {
+ this.preferencesId = preferencesId;
+ return this;
+ }
+
+ public PluginDescription advancedPreferencesId(int advancedPreferencesId) {
+ this.advancedPreferencesId = advancedPreferencesId;
+ return this;
+ }
+
+ public PluginDescription enableByDefault(boolean enableByDefault) {
+ this.enableByDefault = enableByDefault;
+ return this;
+ }
+
+ public PluginDescription visibleByDefault(boolean visibleByDefault) {
+ this.visibleByDefault = visibleByDefault;
+ return this;
+ }
+
+ public String getFragmentClass() {
+ return fragmentClass;
+ }
+
+ public PluginType getType() {
+ return mainType;
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginType.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginType.java
new file mode 100644
index 0000000000..1e5685f2ac
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginType.java
@@ -0,0 +1,14 @@
+package info.nightscout.androidaps.interfaces;
+
+public enum PluginType {
+ GENERAL,
+ TREATMENT,
+ SENSITIVITY,
+ PROFILE,
+ APS,
+ PUMP,
+ CONSTRAINTS,
+ LOOP,
+ BGSOURCE,
+ INSULIN
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
index 701b226031..ec6976a2c7 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
@@ -27,6 +27,8 @@ public class PumpDescription {
public double tempAbsoluteStep = 0.05d;
public int tempDurationStep = 60;
+ public boolean tempDurationStep15mAllowed = false;
+ public boolean tempDurationStep30mAllowed = false;
public int tempMaxDuration = 12 * 60;
@@ -37,4 +39,9 @@ public class PumpDescription {
public boolean isRefillingCapable = false;
public boolean storesCarbInfo = true;
+
+ public boolean is30minBasalRatesCapable = false;
+
+ public boolean supportsTDDs = false;
+ public boolean needsManualTDDLoad = true;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
index 087a1dd0bd..65911f82c6 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
@@ -5,8 +5,8 @@ import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.data.PumpEnactResult;
/**
* Created by mike on 04.06.2016.
@@ -35,8 +35,8 @@ public interface PumpInterface {
PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
void stopBolusDelivering();
- PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean enforceNew);
- PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew);
+ PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew);
+ PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew);
PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes);
//some pumps might set a very short temp close to 100% as cancelling a temp can be noisy
//when the cancel request is requested by the user (forced), the pump should always do a real cancel
@@ -44,7 +44,7 @@ public interface PumpInterface {
PumpEnactResult cancelExtendedBolus();
// Status to be passed to NS
- JSONObject getJSONStatus();
+ JSONObject getJSONStatus(Profile profile, String profileName);
String deviceID();
// Pump capabilities
@@ -54,4 +54,7 @@ public interface PumpInterface {
String shortStatus(boolean veryShort);
boolean isFakingTempsByExtendedBoluses();
+
+ PumpEnactResult loadTDDs();
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
index 044b259ac9..27a6a0846b 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
@@ -5,11 +5,12 @@ import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.db.Treatment;
+import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.ProfileIntervals;
@@ -24,12 +25,13 @@ public interface TreatmentsInterface {
IobTotal getLastCalculationTreatments();
IobTotal getCalculationToTimeTreatments(long time);
IobTotal getLastCalculationTempBasals();
- IobTotal getCalculationToTimeTempBasals(long time);
+ IobTotal getCalculationToTimeTempBasals(long time, Profile profile);
MealData getMealData();
List getTreatmentsFromHistory();
List getTreatments5MinBackFromHistory(long time);
+ long getLastBolusTime();
// real basals (not faked by extended bolus)
boolean isInHistoryRealTempBasalInProgress();
@@ -40,8 +42,6 @@ public interface TreatmentsInterface {
// basal that can be faked by extended boluses
boolean isTempBasalInProgress();
TemporaryBasal getTempBasalFromHistory(long time);
- double getTempBasalAbsoluteRateHistory();
- double getTempBasalRemainingMinutesFromHistory();
Intervals getTemporaryBasalsFromHistory();
boolean isInHistoryExtendedBoluslInProgress();
@@ -55,6 +55,7 @@ public interface TreatmentsInterface {
TempTarget getTempTargetFromHistory();
TempTarget getTempTargetFromHistory(long time);
Intervals getTempTargetsFromHistory();
+ void addToHistoryTempTarget(TempTarget tempTarget);
ProfileSwitch getProfileSwitchFromHistory(long time);
ProfileIntervals getProfileSwitchesFromHistory();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
index d6f56e501b..84086d6117 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
@@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.Actions;
import android.app.Activity;
+import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
@@ -9,14 +10,14 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import com.crashlytics.android.Crashlytics;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.Config;
+import info.nightscout.androidaps.HistoryBrowseActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.TDDStatsActivity;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
@@ -32,6 +33,8 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
+import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SingleClickButton;
/**
@@ -52,6 +55,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
SingleClickButton tempBasal;
SingleClickButton tempBasalCancel;
SingleClickButton fill;
+ SingleClickButton tddStats;
+ SingleClickButton history;
public ActionsFragment() {
super();
@@ -71,6 +76,8 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal);
tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal);
fill = (SingleClickButton) view.findViewById(R.id.actions_fill);
+ tddStats = view.findViewById(R.id.actions_tddstats);
+ history = view.findViewById(R.id.actions_historybrowser);
profileSwitch.setOnClickListener(this);
tempTarget.setOnClickListener(this);
@@ -79,11 +86,13 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal.setOnClickListener(this);
tempBasalCancel.setOnClickListener(this);
fill.setOnClickListener(this);
+ history.setOnClickListener(this);
+ tddStats.setOnClickListener(this);
updateGUI();
return view;
} catch (Exception e) {
- Crashlytics.logException(e);
+ FabricPrivacy.logException(e);
}
return null;
@@ -116,9 +125,14 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
- if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() == null) {
- tempTarget.setVisibility(View.GONE);
+ if (MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() != null) {
+ profileSwitch.setVisibility(View.VISIBLE);
+ } else {
profileSwitch.setVisibility(View.GONE);
+ }
+
+ if (MainApp.getConfigBuilder().getProfile() == null) {
+ tempTarget.setVisibility(View.GONE);
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE);
tempBasal.setVisibility(View.GONE);
@@ -126,22 +140,25 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
fill.setVisibility(View.GONE);
return;
}
+
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
- if (!pump.getPumpDescription().isSetBasalProfileCapable || !pump.isInitialized() || pump.isSuspended())
+ final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease()
+ && pump.getPumpDescription().isSetBasalProfileCapable;
+
+ if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended())
profileSwitch.setVisibility(View.GONE);
else
profileSwitch.setVisibility(View.VISIBLE);
-
if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE);
} else {
- if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) {
+ ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
+ if (activeExtendedBolus != null) {
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.VISIBLE);
- ExtendedBolus running = MainApp.getConfigBuilder().getExtendedBolusFromHistory(System.currentTimeMillis());
- extendedBolusCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + running.toString());
+ extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
} else {
extendedBolus.setVisibility(View.VISIBLE);
extendedBolusCancel.setVisibility(View.GONE);
@@ -153,11 +170,11 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.GONE);
} else {
- if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
+ final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
+ if (activeTemp != null) {
tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE);
- final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
- tempBasalCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + activeTemp.toStringShort());
+ tempBasalCancel.setText(MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort());
} else {
tempBasal.setVisibility(View.VISIBLE);
tempBasalCancel.setVisibility(View.GONE);
@@ -173,6 +190,9 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempTarget.setVisibility(View.GONE);
else
tempTarget.setVisibility(View.VISIBLE);
+
+ if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().supportsTDDs) tddStats.setVisibility(View.GONE);
+ else tddStats.setVisibility(View.VISIBLE);
}
});
}
@@ -201,15 +221,15 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
newExtendedDialog.show(manager, "NewExtendedDialog");
break;
case R.id.actions_extendedbolus_cancel:
- if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) {
+ if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
ConfigBuilderPlugin.getCommandQueue().cancelExtended(null);
- Answers.getInstance().logCustom(new CustomEvent("CancelExtended"));
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("CancelExtended"));
}
break;
case R.id.actions_canceltempbasal:
- if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
+ if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, null);
- Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("CancelTemp"));
}
break;
case R.id.actions_settempbasal:
@@ -220,6 +240,12 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
FillDialog fillDialog = new FillDialog();
fillDialog.show(manager, "FillDialog");
break;
+ case R.id.actions_historybrowser:
+ startActivity(new Intent(getContext(), HistoryBrowseActivity.class));
+ break;
+ case R.id.actions_tddstats:
+ startActivity(new Intent(getContext(), TDDStatsActivity.class));
+ break;
}
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
index 3c71626e64..2397410693 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
@@ -1,82 +1,22 @@
package info.nightscout.androidaps.plugins.Actions;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.interfaces.PluginDescription;
+import info.nightscout.androidaps.interfaces.PluginType;
/**
* Created by mike on 05.11.2016.
*/
-public class ActionsPlugin implements PluginBase {
+public class ActionsPlugin extends PluginBase {
- private boolean fragmentEnabled = true;
- private boolean fragmentVisible = true;
-
- @Override
- public int getType() {
- return PluginBase.GENERAL;
+ public ActionsPlugin() {
+ super(new PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(ActionsFragment.class.getName())
+ .pluginName(R.string.actions)
+ .shortName(R.string.actions_shortname)
+ );
}
-
- @Override
- public String getFragmentClass() {
- return ActionsFragment.class.getName();
- }
-
- @Override
- public String getName() {
- return MainApp.sResources.getString(R.string.actions);
- }
-
- @Override
- public String getNameShort() {
- String name = MainApp.sResources.getString(R.string.actions_shortname);
- if (!name.trim().isEmpty()){
- //only if translation exists
- return name;
- }
- // use long name as fallback
- return getName();
- }
-
- @Override
- public boolean isEnabled(int type) {
- return type == GENERAL && fragmentEnabled;
- }
-
- @Override
- public boolean isVisibleInTabs(int type) {
- return type == GENERAL && fragmentVisible;
- }
-
- @Override
- public boolean canBeHidden(int type) {
- return true;
- }
-
- @Override
- public boolean hasFragment() {
- return true;
- }
-
- @Override
- public boolean showInList(int type) {
- return true;
- }
-
- @Override
- public void setFragmentEnabled(int type, boolean fragmentEnabled) {
- if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
- }
-
- @Override
- public void setFragmentVisible(int type, boolean fragmentVisible) {
- if (type == GENERAL) this.fragmentVisible = fragmentVisible;
- }
-
- @Override
- public int getPreferencesId() {
- return -1;
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java
index 23fa39066f..828c7dbcc9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java
@@ -1,11 +1,13 @@
package info.nightscout.androidaps.plugins.Actions.dialogs;
import android.content.Context;
-import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
+import android.text.Editable;
+import android.text.Html;
+import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
@@ -13,40 +15,73 @@ import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
+import android.widget.CheckBox;
+import android.widget.EditText;
+import android.widget.LinearLayout;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
+import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.text.DecimalFormat;
+import java.util.LinkedList;
+import java.util.List;
-import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
+import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
+import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.utils.FabricPrivacy;
+import info.nightscout.utils.NSUpload;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
+import info.nightscout.utils.ToastUtils;
+
+import static info.nightscout.utils.DateUtil.now;
public class FillDialog extends DialogFragment implements OnClickListener {
private static Logger log = LoggerFactory.getLogger(FillDialog.class);
- Button deliverButton;
+ private CheckBox pumpSiteChangeCheckbox;
+ private CheckBox insulinCartridgeChangeCheckbox;
+
+ private NumberPicker editInsulin;
double amount1 = 0d;
double amount2 = 0d;
double amount3 = 0d;
- NumberPicker editInsulin;
+ private EditText notesEdit;
- public FillDialog() {
+ final private TextWatcher textWatcher = new TextWatcher() {
+ @Override
+ public void afterTextChanged(Editable s) {
+ validateInputs();
+ }
+
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ }
+ };
+
+ private void validateInputs() {
+ int time = editInsulin.getValue().intValue();
+ if (Math.abs(time) > 12 * 60) {
+ editInsulin.setValue(0d);
+ ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.constraintapllied));
+ }
}
@Override
@@ -54,110 +89,122 @@ public class FillDialog extends DialogFragment implements OnClickListener {
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.actions_fill_dialog, null, false);
- deliverButton = (Button) view.findViewById(R.id.treatments_newtreatment_deliverbutton);
+ view.findViewById(R.id.ok).setOnClickListener(this);
+ view.findViewById(R.id.cancel).setOnClickListener(this);
- deliverButton.setOnClickListener(this);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
- Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
+ pumpSiteChangeCheckbox = view.findViewById(R.id.fill_catheter_change);
+ insulinCartridgeChangeCheckbox = view.findViewById(R.id.fill_cartridge_change);
+
+ Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value();
double bolusstep = ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep;
- editInsulin = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_insulinamount);
- editInsulin.setParams(0d, 0d, maxInsulin, bolusstep, new DecimalFormat("0.00"), false);
+ editInsulin = view.findViewById(R.id.fill_insulinamount);
+ editInsulin.setParams(0d, 0d, maxInsulin, bolusstep, DecimalFormatter.pumpSupportedBolusFormat(), false, textWatcher);
- //setup preset buttons
- Button button1 = (Button) view.findViewById(R.id.fill_preset_button1);
- Button button2 = (Button) view.findViewById(R.id.fill_preset_button2);
- Button button3 = (Button) view.findViewById(R.id.fill_preset_button3);
- View divider = view.findViewById(R.id.fill_preset_divider);
+ Button preset1Button = view.findViewById(R.id.fill_preset_button1);
amount1 = SP.getDouble("fill_button1", 0.3);
- amount2 = SP.getDouble("fill_button2", 0d);
- amount3 = SP.getDouble("fill_button3", 0d);
-
if (amount1 > 0) {
- button1.setVisibility(View.VISIBLE);
- button1.setText(DecimalFormatter.to2Decimal(amount1) + "U");
- button1.setOnClickListener(this);
+ preset1Button.setVisibility(View.VISIBLE);
+ preset1Button.setText(DecimalFormatter.toPumpSupportedBolus(amount1)); // + "U");
+ preset1Button.setOnClickListener(this);
} else {
- button1.setVisibility(View.GONE);
+ preset1Button.setVisibility(View.GONE);
}
+ Button preset2Button = view.findViewById(R.id.fill_preset_button2);
+ amount2 = SP.getDouble("fill_button2", 0d);
if (amount2 > 0) {
- button2.setVisibility(View.VISIBLE);
- button2.setText(DecimalFormatter.to2Decimal(amount2) + "U");
- button2.setOnClickListener(this);
+ preset2Button.setVisibility(View.VISIBLE);
+ preset2Button.setText(DecimalFormatter.toPumpSupportedBolus(amount2)); // + "U");
+ preset2Button.setOnClickListener(this);
} else {
- button2.setVisibility(View.GONE);
+ preset2Button.setVisibility(View.GONE);
}
+ Button preset3Button = view.findViewById(R.id.fill_preset_button3);
+ amount3 = SP.getDouble("fill_button3", 0d);
if (amount3 > 0) {
- button3.setVisibility(View.VISIBLE);
- button3.setText(DecimalFormatter.to2Decimal(amount3) + "U");
- button3.setOnClickListener(this);
+ preset3Button.setVisibility(View.VISIBLE);
+ preset3Button.setText(DecimalFormatter.toPumpSupportedBolus(amount3)); // + "U");
+ preset3Button.setOnClickListener(this);
} else {
- button3.setVisibility(View.GONE);
+ preset3Button.setVisibility(View.GONE);
}
- if (button1.getVisibility() == View.GONE && button2.getVisibility() == View.GONE && button3.getVisibility() == View.GONE) {
- divider.setVisibility(View.GONE);
- }
+ LinearLayout notesLayout = view.findViewById(R.id.fill_notes_layout);
+ notesLayout.setVisibility(SP.getBoolean(R.string.key_show_notes_entry_dialogs, false) ? View.VISIBLE : View.GONE);
+ notesEdit = view.findViewById(R.id.fill_notes);
setCancelable(true);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
- @Override
- public void onResume() {
- super.onResume();
- if (getDialog() != null)
- getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- }
-
@Override
public void onClick(View view) {
switch (view.getId()) {
- case R.id.treatments_newtreatment_deliverbutton:
- Double insulin = SafeParse.stringToDouble(editInsulin.getText().toString());
- confirmAndDeliver(insulin);
+ case R.id.ok:
+ confirmAndDeliver();
+ break;
+ case R.id.cancel:
+ dismiss();
break;
case R.id.fill_preset_button1:
- confirmAndDeliver(amount1);
+ editInsulin.setValue(amount1);
break;
case R.id.fill_preset_button2:
- confirmAndDeliver(amount2);
+ editInsulin.setValue(amount2);
break;
case R.id.fill_preset_button3:
- confirmAndDeliver(amount3);
+ editInsulin.setValue(amount3);
break;
}
}
- private void confirmAndDeliver(Double insulin) {
+ private void confirmAndDeliver() {
try {
+ Double insulin = SafeParse.stringToDouble(editInsulin.getText());
- String confirmMessage = getString(R.string.fillwarning) + "\n";
+ List confirmMessage = new LinkedList<>();
- Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(insulin);
- confirmMessage += getString(R.string.bolus) + ": " + insulinAfterConstraints + "U";
- if (insulinAfterConstraints - insulin != 0)
- confirmMessage += "\n" + getString(R.string.constraintapllied);
+ Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value();
+ if (insulinAfterConstraints > 0) {
+ confirmMessage.add(MainApp.gs(R.string.fillwarning));
+ confirmMessage.add("");
+ confirmMessage.add(MainApp.gs(R.string.bolus) + ": " + "" + insulinAfterConstraints + "U" + "");
+ if (!insulinAfterConstraints.equals(insulin))
+ confirmMessage.add("" + MainApp.gs(R.string.bolusconstraintapplied) + "");
+ }
+
+ if (pumpSiteChangeCheckbox.isChecked())
+ confirmMessage.add("" + "" + MainApp.gs(R.string.record_pump_site_change) + "");
+
+ if (insulinCartridgeChangeCheckbox.isChecked())
+ confirmMessage.add("" + "" + MainApp.gs(R.string.record_insulin_cartridge_change) + "");
+
+ final String notes = notesEdit.getText().toString();
+ if (!notes.isEmpty()) {
+ confirmMessage.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes);
+ }
final Double finalInsulinAfterConstraints = insulinAfterConstraints;
final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(this.getContext().getString(R.string.confirmation));
- builder.setMessage(confirmMessage);
- builder.setPositiveButton(getString(R.string.primefill), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
+ builder.setTitle(MainApp.gs(R.string.confirmation));
+ if (insulinAfterConstraints > 0 || pumpSiteChangeCheckbox.isChecked() || insulinCartridgeChangeCheckbox.isChecked()) {
+ builder.setMessage(Html.fromHtml(Joiner.on("
").join(confirmMessage)));
+ builder.setPositiveButton(MainApp.gs(R.string.primefill), (dialog, id) -> {
if (finalInsulinAfterConstraints > 0) {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.insulin = finalInsulinAfterConstraints;
detailedBolusInfo.context = context;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.isValid = false; // do not count it in IOB (for pump history)
+ detailedBolusInfo.notes = notes;
ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
@@ -165,17 +212,23 @@ public class FillDialog extends DialogFragment implements OnClickListener {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
+ i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
- Answers.getInstance().logCustom(new CustomEvent("Fill"));
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("Fill"));
}
- }
- });
- builder.setNegativeButton(getString(R.string.cancel), null);
+ if (pumpSiteChangeCheckbox.isChecked())
+ NSUpload.uploadEvent(CareportalEvent.SITECHANGE, now(), notes);
+ if (insulinCartridgeChangeCheckbox.isChecked())
+ NSUpload.uploadEvent(CareportalEvent.INSULINCHANGE, now() + 1000, notes);
+ });
+ } else {
+ builder.setMessage(MainApp.gs(R.string.no_action_selected));
+ }
+ builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
dismiss();
} catch (RuntimeException e) {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
index dc6a356f1d..45b6460392 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java
@@ -10,20 +10,21 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
+import org.mozilla.javascript.tools.jsc.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
-import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
+import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse;
@@ -39,11 +40,11 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- getDialog().setTitle(getString(R.string.overview_extendedbolus_button));
+ getDialog().setTitle(MainApp.gs(R.string.overview_extendedbolus_button));
View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false);
- Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
+ Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value();
editInsulin = (NumberPicker) view.findViewById(R.id.overview_newextendedbolus_insulin);
editInsulin.setParams(0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false);
@@ -68,13 +69,13 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
Double insulin = SafeParse.stringToDouble(editInsulin.getText());
int durationInMinutes = SafeParse.stringToInt(editDuration.getText());
- String confirmMessage = getString(R.string.setextendedbolusquestion);
+ String confirmMessage = MainApp.gs(R.string.setextendedbolusquestion);
- Double insulinAfterConstraint = MainApp.getConfigBuilder().applyBolusConstraints(insulin);
+ Double insulinAfterConstraint = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value();
confirmMessage += " " + insulinAfterConstraint + " U ";
- confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?";
+ confirmMessage += MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (insulinAfterConstraint - insulin != 0d)
- confirmMessage += "\n" + getString(R.string.constraintapllied);
+ confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
insulin = insulinAfterConstraint;
final Double finalInsulin = insulin;
@@ -82,9 +83,9 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(context.getString(R.string.confirmation));
+ builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage);
- builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
+ builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ConfigBuilderPlugin.getCommandQueue().extendedBolus(finalInsulin, finalDurationInMinutes, new Callback() {
@Override
@@ -93,16 +94,16 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
+ i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
});
- Answers.getInstance().logCustom(new CustomEvent("ExtendedBolus"));
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("ExtendedBolus"));
}
});
- builder.setNegativeButton(getString(R.string.cancel), null);
+ builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
dismiss();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java
index ce3d45fc71..7a03887cf6 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java
@@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.Actions.dialogs;
-import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
@@ -13,7 +12,6 @@ import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import org.slf4j.Logger;
@@ -24,10 +22,12 @@ import java.text.DecimalFormat;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
+import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
+import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse;
@@ -52,7 +52,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- getDialog().setTitle(getString(R.string.overview_tempbasal_button));
+ getDialog().setTitle(MainApp.gs(R.string.overview_tempbasal_button));
View view = inflater.inflate(R.layout.overview_newtempbasal_dialog, container, false);
@@ -118,21 +118,25 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final boolean setAsPercent = percentRadio.isChecked();
int durationInMinutes = SafeParse.stringToInt(duration.getText());
- String confirmMessage = getString(R.string.setbasalquestion);
+ Profile profile = MainApp.getConfigBuilder().getProfile();
+ if (profile == null)
+ return;
+
+ String confirmMessage = MainApp.gs(R.string.setbasalquestion);
if (setAsPercent) {
int basalPercentInput = SafeParse.stringToInt(basalPercent.getText());
- percent = MainApp.getConfigBuilder().applyBasalConstraints(basalPercentInput);
+ percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(basalPercentInput), profile).value();
confirmMessage += "\n" + percent + "% ";
- confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?";
+ confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (percent != basalPercentInput)
- confirmMessage += "\n" + getString(R.string.constraintapllied);
+ confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
} else {
Double basalAbsoluteInput = SafeParse.stringToDouble(basalAbsolute.getText());
- absolute = MainApp.getConfigBuilder().applyBasalConstraints(basalAbsoluteInput);
+ absolute = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(basalAbsoluteInput), profile).value();
confirmMessage += "\n" + absolute + " U/h ";
- confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?";
+ confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (absolute - basalAbsoluteInput != 0d)
- confirmMessage += "\n" + getString(R.string.constraintapllied);
+ confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
}
final int finalBasalPercent = percent;
@@ -140,9 +144,9 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final int finalDurationInMinutes = durationInMinutes;
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
- builder.setTitle(this.getContext().getString(R.string.confirmation));
+ builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage);
- builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
+ builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Callback callback = new Callback() {
@Override
@@ -151,21 +155,21 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
+ i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
}
};
if (setAsPercent) {
- ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(finalBasalPercent, finalDurationInMinutes, true, callback);
+ ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(finalBasalPercent, finalDurationInMinutes, true, profile, callback);
} else {
- ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(finalBasal, finalDurationInMinutes, true, callback);
+ ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(finalBasal, finalDurationInMinutes, true, profile, callback);
}
- Answers.getInstance().logCustom(new CustomEvent("TempBasal"));
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("TempBasal"));
}
});
- builder.setNegativeButton(getString(R.string.cancel), null);
+ builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
dismiss();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
index 4070bc880f..ac018e3101 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalFragment.java
@@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.Careportal;
import android.app.Activity;
+import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
@@ -10,10 +11,11 @@ import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
-import com.crashlytics.android.Crashlytics;
import com.squareup.otto.Subscribe;
-import info.nightscout.androidaps.BuildConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -22,10 +24,12 @@ import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
+import info.nightscout.utils.FabricPrivacy;
public class CareportalFragment extends SubscriberFragment implements View.OnClickListener {
+ private static Logger log = LoggerFactory.getLogger(CareportalFragment.class);
TextView iage;
TextView cage;
@@ -96,7 +100,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
noProfileView = view.findViewById(R.id.profileview_noprofile);
butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons);
- ProfileStore profileStore = ConfigBuilderPlugin.getActiveProfileInterface().getProfile();
+ ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profileStore == null) {
noProfileView.setVisibility(View.VISIBLE);
butonsLayout.setVisibility(View.GONE);
@@ -111,7 +115,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
updateGUI();
return view;
} catch (Exception e) {
- Crashlytics.logException(e);
+ FabricPrivacy.logException(e);
}
return null;
@@ -208,26 +212,54 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
public static void updateAge(Activity activity, final TextView sage, final TextView iage, final TextView cage, final TextView pbage) {
if (activity != null) {
activity.runOnUiThread(
- new Runnable() {
- @Override
- public void run() {
- CareportalEvent careportalEvent;
- String notavailable = OverviewFragment.shorttextmode ? "-" : MainApp.sResources.getString(R.string.notavailable);
- if (sage != null) {
- careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
- sage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
+ () -> {
+ CareportalEvent careportalEvent;
+ NSSettingsStatus nsSettings = new NSSettingsStatus().getInstance();
+
+ double iageUrgent = nsSettings.getExtendedWarnValue("iage", "urgent", 96);
+ double iageWarn = nsSettings.getExtendedWarnValue("iage", "warn", 72);
+ double cageUrgent = nsSettings.getExtendedWarnValue("cage", "urgent", 72);
+ double cageWarn = nsSettings.getExtendedWarnValue("cage", "warn", 48);
+ double sageUrgent = nsSettings.getExtendedWarnValue("sage", "urgent", 166);
+ double sageWarn = nsSettings.getExtendedWarnValue("sage", "warn", 164);
+ double pbageUrgent = nsSettings.getExtendedWarnValue("pgage", "urgent", 360);
+ double pbageWarn = nsSettings.getExtendedWarnValue("pgage", "warn", 240);
+
+ String notavailable = OverviewFragment.shorttextmode ? "-" : MainApp.gs(R.string.notavailable);
+ if (sage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
+ if (careportalEvent != null) {
+ sage.setTextColor(CareportalFragment.determineTextColor(careportalEvent, sageWarn, sageUrgent));
+ sage.setText(careportalEvent.age());
+ } else {
+ sage.setText(notavailable);
}
- if (iage != null) {
- careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
- iage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
+ }
+ if (iage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.INSULINCHANGE);
+ if (careportalEvent != null) {
+ iage.setTextColor(CareportalFragment.determineTextColor(careportalEvent, iageWarn, iageUrgent));
+ iage.setText(careportalEvent.age());
+ } else {
+ iage.setText(notavailable);
}
- if (cage != null) {
- careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
- cage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
+ }
+ if (cage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SITECHANGE);
+ if (careportalEvent != null) {
+ cage.setTextColor(CareportalFragment.determineTextColor(careportalEvent, cageWarn, cageUrgent));
+ cage.setText(careportalEvent.age());
+ } else {
+ cage.setText(notavailable);
}
- if (pbage != null) {
- careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.PUMPBATTERYCHANGE);
- pbage.setText(careportalEvent != null ? careportalEvent.age() : notavailable);
+ }
+ if (pbage != null) {
+ careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.PUMPBATTERYCHANGE);
+ if (careportalEvent != null) {
+ pbage.setTextColor(CareportalFragment.determineTextColor(careportalEvent, pbageWarn, pbageUrgent));
+ pbage.setText(careportalEvent.age());
+ } else {
+ pbage.setText(notavailable);
}
}
}
@@ -235,4 +267,15 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
}
}
+ public static int determineTextColor(CareportalEvent careportalEvent, double warnThreshold, double urgentThreshold) {
+ if (careportalEvent.isOlderThan(urgentThreshold)) {
+ return MainApp.sResources.getColor(R.color.low);
+ } else if (careportalEvent.isOlderThan(warnThreshold)) {
+ return MainApp.sResources.getColor(R.color.high);
+ } else {
+ return Color.WHITE;
+ }
+
+ }
}
+
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
index a72fc200ea..1428880a81 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/CareportalPlugin.java
@@ -1,14 +1,12 @@
package info.nightscout.androidaps.plugins.Careportal;
import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.interfaces.PluginDescription;
+import info.nightscout.androidaps.interfaces.PluginType;
-public class CareportalPlugin implements PluginBase {
-
- private boolean fragmentEnabled = true;
- private boolean fragmentVisible = true;
+public class CareportalPlugin extends PluginBase {
static CareportalPlugin careportalPlugin;
@@ -19,70 +17,13 @@ public class CareportalPlugin implements PluginBase {
return careportalPlugin;
}
- @Override
- public int getType() {
- return PluginBase.GENERAL;
- }
-
- @Override
- public String getFragmentClass() {
- return CareportalFragment.class.getName();
- }
-
- @Override
- public String getName() {
- return MainApp.sResources.getString(R.string.careportal);
- }
-
- @Override
- public String getNameShort() {
- String name = MainApp.sResources.getString(R.string.careportal_shortname);
- if (!name.trim().isEmpty()){
- //only if translation exists
- return name;
- }
- // use long name as fallback
- return getName();
- }
-
- @Override
- public boolean isEnabled(int type) {
- return type == GENERAL && fragmentEnabled;
- }
-
- @Override
- public boolean isVisibleInTabs(int type) {
- return type == GENERAL && fragmentVisible;
- }
-
- @Override
- public boolean canBeHidden(int type) {
- return true;
- }
-
- @Override
- public boolean hasFragment() {
- return true;
- }
-
- @Override
- public boolean showInList(int type) {
- return !Config.NSCLIENT && !Config.G5UPLOADER;
- }
-
- @Override
- public void setFragmentEnabled(int type, boolean fragmentEnabled) {
- if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
- }
-
- @Override
- public void setFragmentVisible(int type, boolean fragmentVisible) {
- if (type == GENERAL) this.fragmentVisible = fragmentVisible;
- }
-
- @Override
- public int getPreferencesId() {
- return R.xml.pref_careportal;
+ public CareportalPlugin() {
+ super(new PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(CareportalFragment.class.getName())
+ .pluginName(R.string.careportal)
+ .shortName(R.string.careportal_shortname)
+ );
}
}
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 58d0603301..46c1e3666d 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
@@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.Careportal.Dialogs;
import android.app.Activity;
-import android.content.DialogInterface;
-import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
@@ -16,15 +14,14 @@ import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
-import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
+import com.google.common.collect.Lists;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
@@ -38,6 +35,7 @@ import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
+import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@@ -45,16 +43,18 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
+import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
-import info.nightscout.androidaps.queue.Callback;
+import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
+import info.nightscout.utils.DefaultValueHelper;
+import info.nightscout.utils.FabricPrivacy;
+import info.nightscout.utils.HardLimits;
+import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP;
@@ -70,8 +70,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
private static String event;
Profile profile;
- ProfileStore profileStore;
- String units;
+ public ProfileStore profileStore;
+ String units = Constants.MGDL;
TextView eventTypeText;
LinearLayout layoutPercent;
@@ -105,13 +105,19 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
Date eventTime;
+ private static Integer seconds = null;
+
public void setOptions(OptionsToShow options, int event) {
this.options = options;
- this.event = MainApp.sResources.getString(event);
+ this.event = MainApp.gs(event);
}
public NewNSTreatmentDialog() {
super();
+
+ if (seconds == null) {
+ seconds = Double.valueOf(Math.random() * 59).intValue();
+ }
}
@Override
@@ -130,7 +136,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (options == null) return null;
- getDialog().setTitle(getString(options.eventName));
+ getDialog().setTitle(MainApp.gs(options.eventName));
setStyle(DialogFragment.STYLE_NORMAL, getTheme());
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
@@ -166,52 +172,61 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
// profile
profile = MainApp.getConfigBuilder().getProfile();
- profileStore = ConfigBuilderPlugin.getActiveProfileInterface().getProfile();
- ArrayList profileList;
- units = profile != null ? profile.getUnits() : Constants.MGDL;
- profileList = profileStore.getProfileList();
- ArrayAdapter adapter = new ArrayAdapter(getContext(),
- R.layout.spinner_centered, profileList);
- profileSpinner.setAdapter(adapter);
- // set selected to actual profile
- for (int p = 0; p < profileList.size(); p++) {
- if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName(false)))
- profileSpinner.setSelection(p);
+ profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
+ if (profileStore == null) {
+ if (options.eventType == R.id.careportal_profileswitch) {
+ log.error("Profile switch called but plugin doesn't contain valid profile");
+ }
+ } else {
+ ArrayList profileList;
+ units = profile != null ? profile.getUnits() : Constants.MGDL;
+ profileList = profileStore.getProfileList();
+ ArrayAdapter adapter = new ArrayAdapter<>(getContext(),
+ R.layout.spinner_centered, profileList);
+ profileSpinner.setAdapter(adapter);
+ // set selected to actual profile
+ for (int p = 0; p < profileList.size(); p++) {
+ if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName(false)))
+ profileSpinner.setSelection(p);
+ }
}
-
- final Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
+ final Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, units);
// temp target
- final ArrayList reasonList = new ArrayList();
- reasonList.add(MainApp.sResources.getString(R.string.manual));
- reasonList.add(MainApp.sResources.getString(R.string.eatingsoon));
- reasonList.add(MainApp.sResources.getString(R.string.activity));
- ArrayAdapter adapterReason = new ArrayAdapter(getContext(),
+ final List reasonList = Lists.newArrayList(
+ MainApp.gs(R.string.manual),
+ MainApp.gs(R.string.eatingsoon),
+ MainApp.gs(R.string.activity),
+ MainApp.gs(R.string.hypo));
+ ArrayAdapter adapterReason = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, reasonList);
reasonSpinner.setAdapter(adapterReason);
reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- double defaultDuration = 0;
+ double defaultDuration;
double defaultTarget = 0;
if (profile != null) {
- defaultTarget = bg.doubleValue();
+ defaultTarget = bg;
}
boolean erase = false;
- if (MainApp.sResources.getString(R.string.eatingsoon).equals(reasonList.get(position))) {
- defaultDuration = SP.getDouble(R.string.key_eatingsoon_duration, 0d);
- defaultTarget = SP.getDouble(R.string.key_eatingsoon_target, 0d);
- ;
- } else if (MainApp.sResources.getString(R.string.activity).equals(reasonList.get(position))) {
- defaultDuration = SP.getDouble(R.string.key_activity_duration, 0d);
- ;
- defaultTarget = SP.getDouble(R.string.key_activity_target, 0d);
- ;
+ String units = MainApp.getConfigBuilder().getProfileUnits();
+ DefaultValueHelper helper = new DefaultValueHelper();
+ if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) {
+ defaultDuration = helper.determineEatingSoonTTDuration();
+ defaultTarget = helper.determineEatingSoonTT(units);
+ } else if (MainApp.gs(R.string.activity).equals(reasonList.get(position))) {
+ defaultDuration = helper.determineActivityTTDuration();
+ defaultTarget = helper.determineActivityTT(units);
+ } else if (MainApp.gs(R.string.hypo).equals(reasonList.get(position))) {
+ defaultDuration = helper.determineHypoTTDuration();
+ defaultTarget = helper.determineHypoTT(units);
} else {
defaultDuration = 0;
erase = true;
}
+
if (defaultTarget != 0 || erase) {
editTemptarget.setValue(defaultTarget);
}
@@ -256,19 +271,16 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
}
- sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
- editBg.setValue(bg);
- }
+ sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
+ Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits());
+ editBg.setValue(bg1);
});
- Integer maxCarbs = MainApp.getConfigBuilder().applyCarbsConstraints(Constants.carbsOnlyForCheckLimit);
+ Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value();
editCarbs = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_carbsinput);
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false);
- Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
+ Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value();
editInsulin = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_insulininput);
editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false);
@@ -295,7 +307,9 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
}
};
- Integer maxPercent = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalPercentOnlyForCheckLimit);
+ Integer maxPercent = 200;
+ if (profile != null)
+ maxPercent = MainApp.getConstraintChecker().getMaxBasalPercentAllowed(profile).value();
editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput);
editPercent.setParams(0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true, percentTextWatcher);
@@ -317,7 +331,9 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
}
};
- Double maxAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalAbsoluteOnlyForCheckLimit);
+ Double maxAbsolute = HardLimits.maxBasal();
+ if (profile != null)
+ maxAbsolute = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value();
editAbsolute = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_absoluteinput);
editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, absoluteTextWatcher);
@@ -330,19 +346,19 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editTimeshift = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_timeshift);
editTimeshift.setParams(0d, (double) Constants.CPP_MIN_TIMESHIFT, (double) Constants.CPP_MAX_TIMESHIFT, 1d, new DecimalFormat("0"), false);
- ProfileSwitch ps = MainApp.getConfigBuilder().getProfileSwitchFromHistory(System.currentTimeMillis());
+ ProfileSwitch ps = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now());
if (ps != null && ps.isCPP) {
final int percentage = ps.percentage;
final int timeshift = ps.timeshift;
reuseButton.setText(reuseButton.getText() + " " + percentage + "% " + timeshift + "h");
- reuseButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- editPercentage.setValue((double) percentage);
- editTimeshift.setValue((double) timeshift);
- }
+ reuseButton.setOnClickListener(v -> {
+ editPercentage.setValue((double) percentage);
+ editTimeshift.setValue((double) timeshift);
});
}
+ if (ps == null) {
+ options.duration = false;
+ }
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_eventtime_layout), options.date);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_bg_layout), options.bg);
@@ -393,7 +409,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
tpd.show(context.getFragmentManager(), "Timepickerdialog");
break;
case R.id.ok:
- createNSTreatment();
+ confirmNSTreatmentCreation();
dismiss();
break;
case R.id.cancel:
@@ -407,20 +423,32 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
else layout.setVisibility(View.GONE);
}
+ private void updateBGforDateTime() {
+ long millis = eventTime.getTime() - (150 * 1000L); // 2,5 * 60 * 1000
+ List data = MainApp.getDbHelper().getBgreadingsDataFromTime(millis, true);
+ if ((data.size() > 0) &&
+ (data.get(0).date > millis - 7 * 60 * 1000L) &&
+ (data.get(0).date < millis + 7 * 60 * 1000L)) {
+ editBg.setValue(Profile.fromMgdlToUnits(data.get(0).value, profile != null ? profile.getUnits() : Constants.MGDL));
+ }
+ }
+
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
eventTime.setYear(year - 1900);
eventTime.setMonth(monthOfYear);
eventTime.setDate(dayOfMonth);
dateButton.setText(DateUtil.dateString(eventTime));
+ updateBGforDateTime();
}
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
eventTime.setHours(hourOfDay);
eventTime.setMinutes(minute);
- eventTime.setSeconds(second);
+ eventTime.setSeconds(this.seconds++); // randomize seconds to prevent creating record of the same time, if user choose time manually
timeButton.setText(DateUtil.timeString(eventTime));
+ updateBGforDateTime();
}
@@ -545,221 +573,200 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
String buildConfirmText(JSONObject data) {
String ret = "";
- try {
- if (data.has("eventType")) {
- ret += getString(R.string.careportal_newnstreatment_eventtype);
- ret += ": ";
- ret += Translator.translate(data.getString("eventType"));
- ret += "\n";
- }
- if (data.has("glucose")) {
- ret += getString(R.string.treatments_wizard_bg_label);
- ret += ": ";
- ret += data.get("glucose");
- ret += " " + units + "\n";
- }
- if (data.has("glucoseType")) {
- ret += getString(R.string.careportal_newnstreatment_glucosetype);
- ret += ": ";
- ret += Translator.translate(data.getString("glucoseType"));
- ret += "\n";
- }
- if (data.has("carbs")) {
- ret += getString(R.string.careportal_newnstreatment_carbs_label);
- ret += ": ";
- ret += data.get("carbs");
- ret += " g\n";
- }
- if (data.has("insulin")) {
- ret += getString(R.string.careportal_newnstreatment_insulin_label);
- ret += ": ";
- ret += data.get("insulin");
- ret += " U\n";
- }
- if (data.has("duration")) {
- ret += getString(R.string.careportal_newnstreatment_duration_label);
- ret += ": ";
- ret += data.get("duration");
- ret += " min\n";
- }
- if (data.has("percent")) {
- ret += getString(R.string.careportal_newnstreatment_percent_label);
- ret += ": ";
- ret += data.get("percent");
- ret += " %\n";
- }
- if (data.has("absolute")) {
- ret += getString(R.string.careportal_newnstreatment_absolute_label);
- ret += ": ";
- ret += data.get("absolute");
- ret += " U/h\n";
- }
- if (data.has("preBolus")) {
- ret += getString(R.string.careportal_newnstreatment_carbtime_label);
- ret += ": ";
- ret += data.get("preBolus");
- ret += " min\n";
- }
- if (data.has("notes")) {
- ret += getString(R.string.careportal_newnstreatment_notes_label);
- ret += ": ";
- ret += data.get("notes");
- ret += "\n";
- }
- if (data.has("profile")) {
- ret += getString(R.string.careportal_newnstreatment_profile_label);
- ret += ": ";
- ret += data.get("profile");
- ret += "\n";
- }
- if (data.has("percentage")) {
- ret += getString(R.string.careportal_newnstreatment_percentage_label);
- ret += ": ";
- ret += data.get("percentage");
- ret += " %\n";
- }
- if (data.has("timeshift")) {
- ret += getString(R.string.careportal_newnstreatment_timeshift_label);
- ret += ": ";
- ret += data.get("timeshift");
- ret += " h\n";
- }
- if (data.has("targetBottom") && data.has("targetTop")) {
- ret += getString(R.string.target_range);
- ret += " ";
- ret += data.get("targetBottom");
- ret += " - ";
- ret += data.get("targetTop");
- ret += "\n";
- }
- if (data.has("created_at")) {
- ret += getString(R.string.careportal_newnstreatment_eventtime_label);
- ret += ": ";
- ret += eventTime.toLocaleString();
- ret += "\n";
- }
- if (data.has("enteredBy")) {
- ret += getString(R.string.careportal_newnstreatment_enteredby_title);
- ret += ": ";
- ret += data.get("enteredBy");
- ret += "\n";
- }
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
+ if (data.has("eventType")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_eventtype);
+ ret += ": ";
+ ret += Translator.translate(JsonHelper.safeGetString(data, "eventType", ""));
+ ret += "\n";
+ }
+ if (data.has("glucose")) {
+ ret += MainApp.gs(R.string.treatments_wizard_bg_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "glucose", "");
+ ret += " " + units + "\n";
+ }
+ if (data.has("glucoseType")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_glucosetype);
+ ret += ": ";
+ ret += Translator.translate(JsonHelper.safeGetString(data, "glucoseType", ""));
+ ret += "\n";
+ }
+ if (data.has("carbs")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_carbs_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "carbs", "");
+ ret += " g\n";
+ }
+ if (data.has("insulin")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_insulin_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "insulin", "");
+ ret += " U\n";
+ }
+ if (data.has("duration")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_duration_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "duration", "");
+ ret += " min\n";
+ }
+ if (data.has("percent")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_percent_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "percent", "");
+ ret += " %\n";
+ }
+ if (data.has("absolute")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_absolute_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "absolute", "");
+ ret += " U/h\n";
+ }
+ if (data.has("preBolus")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_carbtime_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "preBolus", "");
+ ret += " min\n";
+ }
+ if (data.has("notes")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_notes_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "notes", "");
+ ret += "\n";
+ }
+ if (data.has("profile")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_profile_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "profile", "");
+ ret += "\n";
+ }
+ if (data.has("percentage")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_percentage_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "percentage", "");
+ ret += " %\n";
+ }
+ if (data.has("timeshift")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_timeshift_label);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "timeshift", "");
+ ret += " h\n";
+ }
+ if (data.has("targetBottom") && data.has("targetTop")) {
+ ret += MainApp.gs(R.string.target_range);
+ ret += " ";
+ ret += JsonHelper.safeGetObject(data, "targetBottom", "");
+ ret += " - ";
+ ret += JsonHelper.safeGetObject(data, "targetTop", "");
+ ret += "\n";
+ }
+ if (data.has("created_at")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_eventtime_label);
+ ret += ": ";
+ ret += eventTime.toLocaleString();
+ ret += "\n";
+ }
+ if (data.has("enteredBy")) {
+ ret += MainApp.gs(R.string.careportal_newnstreatment_enteredby_title);
+ ret += ": ";
+ ret += JsonHelper.safeGetObject(data, "enteredBy", "");
+ ret += "\n";
}
return ret;
}
- void createNSTreatment() {
- final JSONObject data = gatherData();
- String confirmText = buildConfirmText(data);
- AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
- builder.setTitle(getContext().getString(R.string.confirmation));
- builder.setMessage(confirmText);
- builder.setPositiveButton(getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- if (options.executeProfileSwitch) {
- if (data.has("profile")) {
- try {
- doProfileSwitch(profileStore, data.getString("profile"), data.getInt("duration"), data.getInt("percentage"), data.getInt("timeshift"));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
- } else if (options.executeTempTarget) {
- try {
- if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration") && data.getInt("duration") == 0)) {
- TempTarget tempTarget = new TempTarget();
- tempTarget.date = eventTime.getTime();
- tempTarget.durationInMinutes = data.getInt("duration");
- tempTarget.reason = data.getString("reason");
- tempTarget.source = Source.USER;
- if (tempTarget.durationInMinutes != 0) {
- tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits());
- tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits());
- } else {
- tempTarget.low = 0;
- tempTarget.high = 0;
- }
- log.debug("Creating new TempTarget db record: " + tempTarget.toString());
- MainApp.getDbHelper().createOrUpdate(tempTarget);
- NSUpload.uploadCareportalEntryToNS(data);
- Answers.getInstance().logCustom(new CustomEvent("TempTarget"));
- }
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- } else {
- NSUpload.uploadCareportalEntryToNS(data);
- Answers.getInstance().logCustom(new CustomEvent("NSTreatment"));
- }
- }
- });
- builder.setNegativeButton(getContext().getString(R.string.cancel), null);
- builder.show();
+ void confirmNSTreatmentCreation() {
+ if (context != null) {
+ final JSONObject data = gatherData();
+ final String confirmText = buildConfirmText(data);
+ AlertDialog.Builder builder = new AlertDialog.Builder(context);
+ builder.setTitle(MainApp.gs(R.string.confirmation));
+ builder.setMessage(confirmText);
+ builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> createNSTreatment(data));
+ builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
+ builder.show();
+ }
}
- public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
+
+ public void createNSTreatment(JSONObject data) {
+ if (options.executeProfileSwitch) {
+ if (data.has("profile")) {
+ doProfileSwitch(profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), JsonHelper.safeGetInt(data, "percentage"), JsonHelper.safeGetInt(data, "timeshift"));
+ }
+ } else if (options.executeTempTarget) {
+ final int duration = JsonHelper.safeGetInt(data, "duration");
+ final double targetBottom = JsonHelper.safeGetDouble(data, "targetBottom");
+ final double targetTop = JsonHelper.safeGetDouble(data, "targetTop");
+ final String reason = JsonHelper.safeGetString(data, "reason", "");
+ if ((targetBottom != 0d && targetTop != 0d) || duration == 0) {
+ TempTarget tempTarget = new TempTarget()
+ .date(eventTime.getTime())
+ .duration(duration)
+ .reason(reason)
+ .source(Source.USER);
+ if (tempTarget.durationInMinutes != 0) {
+ tempTarget.low(Profile.toMgdl(targetBottom, profile.getUnits()))
+ .high(Profile.toMgdl(targetTop, profile.getUnits()));
+ } else {
+ tempTarget.low(0).high(0);
+ }
+ TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget);
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("TempTarget"));
+ }
+ } else {
+ if (JsonHelper.safeGetString(data, "eventType").equals(CareportalEvent.PROFILESWITCH)) {
+ ProfileSwitch profileSwitch = prepareProfileSwitch(
+ profileStore,
+ JsonHelper.safeGetString(data, "profile"),
+ JsonHelper.safeGetInt(data, "duration"),
+ JsonHelper.safeGetInt(data, "percentage"),
+ JsonHelper.safeGetInt(data, "timeshift"),
+ eventTime.getTime()
+ );
+ NSUpload.uploadProfileSwitch(profileSwitch);
+ } else {
+ NSUpload.uploadCareportalEntryToNS(data);
+ }
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("NSTreatment"));
+ }
+ }
+
+ public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) {
ProfileSwitch profileSwitch = new ProfileSwitch();
- profileSwitch.date = System.currentTimeMillis();
+ profileSwitch.date = date;
profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
- profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName();
+ profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
- MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
+ return profileSwitch;
+ }
- ConfigBuilderPlugin.getCommandQueue().setProfile(profileSwitch.getProfileObject(), new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
- i.putExtra("soundid", R.raw.boluserror);
- i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.sResources.getString(R.string.failedupdatebasalprofile));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
- }
- MainApp.bus().post(new EventNewBasalProfile());
- }
- });
- Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
+ public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
+ ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, System.currentTimeMillis());
+ TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch);
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
}
public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) {
- ProfileSwitch profileSwitch = MainApp.getConfigBuilder().getProfileSwitchFromHistory(System.currentTimeMillis());
+ ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis());
if (profileSwitch != null) {
profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
profileSwitch.profileName = MainApp.getConfigBuilder().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = MainApp.getConfigBuilder().getProfile().getData().toString();
- profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName();
+ profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
- MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
-
- ConfigBuilderPlugin.getCommandQueue().setProfile(profileSwitch.getProfileObject(), new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
- i.putExtra("soundid", R.raw.boluserror);
- i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.sResources.getString(R.string.failedupdatebasalprofile));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
- }
- MainApp.bus().post(new EventNewBasalProfile());
- }
- });
- Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
+ TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch);
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} else {
log.error("No profile switch existing");
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
index 2e620eab70..829a0fa4ad 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
@@ -4,7 +4,7 @@ package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
-import android.support.v4.app.Fragment;
+import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -17,12 +17,14 @@ import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
-import com.crashlytics.android.Crashlytics;
-import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import java.util.ArrayList;
+import butterknife.BindView;
+import butterknife.ButterKnife;
+import butterknife.OnClick;
+import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.PreferencesActivity;
import info.nightscout.androidaps.R;
@@ -33,43 +35,59 @@ import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
-import info.nightscout.androidaps.plugins.Insulin.InsulinFastactingPlugin;
+import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
+import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.PasswordProtection;
-public class ConfigBuilderFragment extends Fragment {
-
- static ConfigBuilderPlugin configBuilderPlugin = new ConfigBuilderPlugin();
-
- static public ConfigBuilderPlugin getPlugin() {
- return configBuilderPlugin;
- }
+public class ConfigBuilderFragment extends SubscriberFragment {
+ @BindView(R.id.configbuilder_insulinlistview)
ListView insulinListView;
+ @BindView(R.id.configbuilder_sensitivitylistview)
ListView sensitivityListView;
+ @BindView(R.id.configbuilder_bgsourcelistview)
ListView bgsourceListView;
+ @BindView(R.id.configbuilder_bgsourcelabel)
TextView bgsourceLabel;
+ @BindView(R.id.configbuilder_pumplistview)
ListView pumpListView;
+ @BindView(R.id.configbuilder_pumplabel)
TextView pumpLabel;
+ @BindView(R.id.configbuilder_looplistview)
ListView loopListView;
+ @BindView(R.id.configbuilder_looplabel)
TextView loopLabel;
+ @BindView(R.id.configbuilder_treatmentslistview)
ListView treatmentsListView;
+ @BindView(R.id.configbuilder_treatmentslabel)
TextView treatmentsLabel;
+ @BindView(R.id.configbuilder_profilelistview)
ListView profileListView;
+ @BindView(R.id.configbuilder_profilelabel)
TextView profileLabel;
+ @BindView(R.id.configbuilder_apslistview)
ListView apsListView;
+ @BindView(R.id.configbuilder_apslabel)
TextView apsLabel;
+ @BindView(R.id.configbuilder_constraintslistview)
ListView constraintsListView;
+ @BindView(R.id.configbuilder_constraintslabel)
TextView constraintsLabel;
+ @BindView(R.id.configbuilder_generallistview)
ListView generalListView;
+ @BindView(R.id.configbuilder_mainlayout)
LinearLayout mainLayout;
+ @BindView(R.id.configbuilder_unlock)
Button unlock;
PluginCustomAdapter insulinDataAdapter = null;
@@ -84,105 +102,83 @@ public class ConfigBuilderFragment extends Fragment {
PluginCustomAdapter generalDataAdapter = null;
@Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
- insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview);
- sensitivityListView = (ListView) view.findViewById(R.id.configbuilder_sensitivitylistview);
- bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
- bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
- pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
- pumpLabel = (TextView) view.findViewById(R.id.configbuilder_pumplabel);
- loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
- loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
- treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
- treatmentsLabel = (TextView) view.findViewById(R.id.configbuilder_treatmentslabel);
- profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
- profileLabel = (TextView) view.findViewById(R.id.configbuilder_profilelabel);
- apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
- apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
- constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
- constraintsLabel = (TextView) view.findViewById(R.id.configbuilder_constraintslabel);
- generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
+ unbinder = ButterKnife.bind(this, view);
- mainLayout = (LinearLayout) view.findViewById(R.id.configbuilder_mainlayout);
- unlock = (Button) view.findViewById(R.id.configbuilder_unlock);
-
- setViews();
-
- if (PasswordProtection.isLocked("settings_password")) {
+ if (PasswordProtection.isLocked("settings_password"))
mainLayout.setVisibility(View.GONE);
- unlock.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
- @Override
- public void run() {
- mainLayout.setVisibility(View.VISIBLE);
- unlock.setVisibility(View.GONE);
- }
- }, null);
- }
- });
- } else {
+ else
unlock.setVisibility(View.GONE);
- }
return view;
} catch (Exception e) {
- Crashlytics.logException(e);
+ FabricPrivacy.logException(e);
}
return null;
}
- void setViews() {
- insulinDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginBase.INSULIN), PluginBase.INSULIN);
+ @OnClick(R.id.configbuilder_unlock)
+ public void onClickUnlock() {
+ PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", () -> {
+ mainLayout.setVisibility(View.VISIBLE);
+ unlock.setVisibility(View.GONE);
+ }, null);
+ }
+
+
+ @Override
+ protected void updateGUI() {
+
+ insulinDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginType.INSULIN), PluginType.INSULIN);
insulinListView.setAdapter(insulinDataAdapter);
setListViewHeightBasedOnChildren(insulinListView);
- bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginBase.BGSOURCE), PluginBase.BGSOURCE);
+ bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginType.BGSOURCE), PluginType.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.BGSOURCE).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.BGSOURCE).size() == 0)
bgsourceLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(bgsourceListView);
- pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP), PluginBase.PUMP);
+ pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP), PluginType.PUMP);
pumpListView.setAdapter(pumpDataAdapter);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP).size() == 0 || Config.NSCLIENT || Config.G5UPLOADER) {
pumpLabel.setVisibility(View.GONE);
+ pumpListView.setVisibility(View.GONE);
+ }
setListViewHeightBasedOnChildren(pumpListView);
- loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP), PluginBase.LOOP);
+ loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP), PluginType.LOOP);
loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE);
- treatmentDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT), PluginBase.TREATMENT);
+ treatmentDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT), PluginType.TREATMENT);
treatmentsListView.setAdapter(treatmentDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT).size() == 0)
treatmentsLabel.setVisibility(View.GONE);
- profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.PROFILE), PluginBase.PROFILE);
+ profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginType.PROFILE), PluginType.PROFILE);
profileListView.setAdapter(profileDataAdapter);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.PROFILE).size() == 0)
profileLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(profileListView);
- apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.APS), PluginBase.APS);
+ apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginType.APS), PluginType.APS);
apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.APS).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.APS).size() == 0)
apsLabel.setVisibility(View.GONE);
- sensivityDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginBase.SENSITIVITY), PluginBase.SENSITIVITY);
+ sensivityDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginType.SENSITIVITY), PluginType.SENSITIVITY);
sensitivityListView.setAdapter(sensivityDataAdapter);
setListViewHeightBasedOnChildren(sensitivityListView);
- constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.CONSTRAINTS), PluginBase.CONSTRAINTS);
+ constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginType.CONSTRAINTS), PluginType.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView);
- if (MainApp.getSpecificPluginsVisibleInList(PluginBase.CONSTRAINTS).size() == 0)
+ if (MainApp.getSpecificPluginsVisibleInList(PluginType.CONSTRAINTS).size() == 0)
constraintsLabel.setVisibility(View.GONE);
- generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.GENERAL), PluginBase.GENERAL);
+ generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginType.GENERAL), PluginType.GENERAL);
generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView);
-
}
/*
@@ -192,10 +188,10 @@ public class ConfigBuilderFragment extends Fragment {
private class PluginCustomAdapter extends ArrayAdapter {
private ArrayList pluginList;
- final private int type;
+ final private PluginType type;
- public PluginCustomAdapter(Context context, int textViewResourceId,
- ArrayList pluginList, int type) {
+ PluginCustomAdapter(Context context, int textViewResourceId,
+ ArrayList pluginList, PluginType type) {
super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<>();
this.pluginList.addAll(pluginList);
@@ -209,10 +205,11 @@ public class ConfigBuilderFragment extends Fragment {
ImageView settings;
}
+ @NonNull
@Override
- public View getView(int position, View view, ViewGroup parent) {
+ public View getView(int position, View view, @NonNull ViewGroup parent) {
- PluginViewHolder holder = null;
+ PluginViewHolder holder;
PluginBase plugin = pluginList.get(position);
if (view == null) {
@@ -231,60 +228,45 @@ public class ConfigBuilderFragment extends Fragment {
view.setTag(holder);
- holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- CheckBox cb = (CheckBox) v;
- PluginBase plugin = (PluginBase) cb.getTag();
- plugin.setFragmentEnabled(type, cb.isChecked());
- plugin.setFragmentVisible(type, cb.isChecked());
- onEnabledCategoryChanged(plugin, type);
- configBuilderPlugin.storeSettings();
- MainApp.bus().post(new EventRefreshGui());
- MainApp.bus().post(new EventConfigBuilderChange());
- getPlugin().logPluginStatus();
- Answers.getInstance().logCustom(new CustomEvent("ConfigurationChange"));
- }
+ holder.checkboxEnabled.setOnClickListener(v -> {
+ CheckBox cb = (CheckBox) v;
+ PluginBase plugin1 = (PluginBase) cb.getTag();
+ plugin1.setPluginEnabled(type, cb.isChecked());
+ plugin1.setFragmentVisible(type, cb.isChecked());
+ onEnabledCategoryChanged(plugin1, type);
+ ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled");
+ MainApp.bus().post(new EventRefreshGui());
+ MainApp.bus().post(new EventConfigBuilderChange());
+ ConfigBuilderPlugin.getPlugin().logPluginStatus();
+ FabricPrivacy.getInstance().logCustom(new CustomEvent("ConfigurationChange"));
});
- holder.checkboxVisible.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- CheckBox cb = (CheckBox) v;
- PluginBase plugin = (PluginBase) cb.getTag();
- plugin.setFragmentVisible(type, cb.isChecked());
- configBuilderPlugin.storeSettings();
- MainApp.bus().post(new EventRefreshGui());
- getPlugin().logPluginStatus();
- }
+ holder.checkboxVisible.setOnClickListener(v -> {
+ CheckBox cb = (CheckBox) v;
+ PluginBase plugin12 = (PluginBase) cb.getTag();
+ plugin12.setFragmentVisible(type, cb.isChecked());
+ ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxVisible");
+ MainApp.bus().post(new EventRefreshGui());
+ ConfigBuilderPlugin.getPlugin().logPluginStatus();
});
- holder.settings.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- final PluginBase plugin = (PluginBase) v.getTag();
- PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
- @Override
- public void run() {
- Intent i = new Intent(getContext(), PreferencesActivity.class);
- i.putExtra("id", plugin.getPreferencesId());
- startActivity(i);
- }
- }, null);
- }
+ holder.settings.setOnClickListener(v -> {
+ final PluginBase plugin13 = (PluginBase) v.getTag();
+ PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", () -> {
+ Intent i = new Intent(getContext(), PreferencesActivity.class);
+ i.putExtra("id", plugin13.getPreferencesId());
+ startActivity(i);
+ }, null);
});
- holder.name.setOnLongClickListener(new View.OnLongClickListener() {
- @Override
- public boolean onLongClick(View v) {
- final PluginBase plugin = (PluginBase) v.getTag();
- PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
- @Override
- public void run() {
- Intent i = new Intent(getContext(), PreferencesActivity.class);
- i.putExtra("id", plugin.getPreferencesId());
- startActivity(i);
- }
- }, null);
- return false;
- }
+ holder.name.setOnLongClickListener(v -> {
+ final PluginBase plugin14 = (PluginBase) v.getTag();
+ PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", () -> {
+ Intent i = new Intent(getContext(), PreferencesActivity.class);
+ i.putExtra("id", plugin14.getPreferencesId());
+ startActivity(i);
+ }, null);
+ return false;
});
} else {
@@ -293,15 +275,18 @@ public class ConfigBuilderFragment extends Fragment {
holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
- holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
+ holder.checkboxVisible.setChecked(plugin.isFragmentVisible());
holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin);
holder.settings.setTag(plugin);
- if (!plugin.canBeHidden(type)) {
+ if (plugin.pluginDescription.alwaysEnabled) {
+ holder.checkboxEnabled.setEnabled(false);
+ }
+
+ if (plugin.pluginDescription.alwayVisible) {
holder.checkboxEnabled.setEnabled(false);
- holder.checkboxVisible.setEnabled(false);
}
if (!plugin.isEnabled(type)) {
@@ -313,19 +298,19 @@ public class ConfigBuilderFragment extends Fragment {
}
// Hide enabled control and force enabled plugin if there is only one plugin available
- if (type == PluginBase.INSULIN || type == PluginBase.PUMP || type == PluginBase.TREATMENT || type == PluginBase.PROFILE || type == PluginBase.SENSITIVITY)
+ if (type == PluginType.INSULIN || type == PluginType.PUMP || type == PluginType.SENSITIVITY)
if (pluginList.size() < 2) {
holder.checkboxEnabled.setEnabled(false);
- plugin.setFragmentEnabled(type, true);
- getPlugin().storeSettings();
+ plugin.setPluginEnabled(type, true);
+ ConfigBuilderPlugin.getPlugin().storeSettings("ForceEnable");
}
// Constraints cannot be disabled
- if (type == PluginBase.CONSTRAINTS)
+ if (type == PluginType.CONSTRAINTS)
holder.checkboxEnabled.setEnabled(false);
// Hide disabled profiles by default
- if (type == PluginBase.PROFILE) {
+ if (type == PluginType.PROFILE) {
if (!plugin.isEnabled(type)) {
holder.checkboxVisible.setEnabled(false);
holder.checkboxVisible.setChecked(false);
@@ -335,9 +320,9 @@ public class ConfigBuilderFragment extends Fragment {
}
// Disable profile control for pump profiles if pump is not enabled
- if (type == PluginBase.PROFILE) {
+ if (type == PluginType.PROFILE) {
if (PumpInterface.class.isAssignableFrom(plugin.getClass())) {
- if (!plugin.isEnabled(PluginBase.PUMP)) {
+ if (!plugin.isEnabled(PluginType.PUMP)) {
holder.checkboxEnabled.setEnabled(false);
holder.checkboxEnabled.setChecked(false);
}
@@ -354,32 +339,32 @@ public class ConfigBuilderFragment extends Fragment {
}
- void onEnabledCategoryChanged(PluginBase changedPlugin, int type) {
+ void onEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
ArrayList pluginsInCategory = null;
switch (type) {
// Multiple selection allowed
- case PluginBase.GENERAL:
- case PluginBase.CONSTRAINTS:
- case PluginBase.LOOP:
+ case GENERAL:
+ case CONSTRAINTS:
+ case LOOP:
break;
// Single selection allowed
- case PluginBase.INSULIN:
+ case INSULIN:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
break;
- case PluginBase.SENSITIVITY:
+ case SENSITIVITY:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
break;
- case PluginBase.APS:
+ case APS:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
break;
- case PluginBase.PROFILE:
+ case PROFILE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
break;
- case PluginBase.BGSOURCE:
+ case BGSOURCE:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
break;
- case PluginBase.TREATMENT:
- case PluginBase.PUMP:
+ case TREATMENT:
+ case PUMP:
pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class);
break;
}
@@ -390,23 +375,23 @@ public class ConfigBuilderFragment extends Fragment {
if (p.getName().equals(changedPlugin.getName())) {
// this is new selected
} else {
- p.setFragmentEnabled(type, false);
+ p.setPluginEnabled(type, false);
p.setFragmentVisible(type, false);
}
}
} else { // enable first plugin in list
- if (type == PluginBase.PUMP)
- MainApp.getSpecificPlugin(VirtualPumpPlugin.class).setFragmentEnabled(type, true);
- else if (type == PluginBase.INSULIN)
- MainApp.getSpecificPlugin(InsulinFastactingPlugin.class).setFragmentEnabled(type, true);
- else if (type == PluginBase.SENSITIVITY)
- MainApp.getSpecificPlugin(SensitivityOref0Plugin.class).setFragmentEnabled(type, true);
- else if (type == PluginBase.PROFILE)
- MainApp.getSpecificPlugin(NSProfilePlugin.class).setFragmentEnabled(type, true);
+ if (type == PluginType.PUMP)
+ VirtualPumpPlugin.getPlugin().setPluginEnabled(type, true);
+ else if (type == PluginType.INSULIN)
+ InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(type, true);
+ else if (type == PluginType.SENSITIVITY)
+ SensitivityOref0Plugin.getPlugin().setPluginEnabled(type, true);
+ else if (type == PluginType.PROFILE)
+ NSProfilePlugin.getPlugin().setPluginEnabled(type, true);
else
- pluginsInCategory.get(0).setFragmentEnabled(type, true);
+ pluginsInCategory.get(0).setPluginEnabled(type, true);
}
- setViews();
+ updateGUI();
}
}
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 e63924d80a..35130c5209 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
@@ -1,60 +1,71 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
+import android.content.Intent;
import android.support.annotation.Nullable;
-import org.json.JSONException;
-import org.json.JSONObject;
+import com.crashlytics.android.answers.CustomEvent;
+import com.squareup.otto.Subscribe;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
-import java.util.List;
+import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.Intervals;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileIntervals;
+import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.db.ExtendedBolus;
+import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
-import info.nightscout.androidaps.db.TempTarget;
+import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppInitialized;
+import info.nightscout.androidaps.events.EventNewBasalProfile;
+import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
-import info.nightscout.androidaps.interfaces.ConstraintsInterface;
+import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.interfaces.PluginDescription;
+import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
+import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
+import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
+import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
+import info.nightscout.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
-public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, TreatmentsInterface {
+public class ConfigBuilderPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class);
- private static BgSourceInterface activeBgSource;
+ private static ConfigBuilderPlugin configBuilderPlugin;
+
+ static public ConfigBuilderPlugin getPlugin() {
+ if (configBuilderPlugin == null)
+ configBuilderPlugin = new ConfigBuilderPlugin();
+ return configBuilderPlugin;
+ }
+
+ private BgSourceInterface activeBgSource;
private static PumpInterface activePump;
private static ProfileInterface activeProfile;
private static TreatmentsInterface activeTreatments;
@@ -73,131 +84,175 @@ public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, Tr
private static CommandQueue commandQueue = new CommandQueue();
public ConfigBuilderPlugin() {
+ super(new PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(ConfigBuilderFragment.class.getName())
+ .showInList(false)
+ .alwaysEnabled(true)
+ .alwayVisible(true)
+ .pluginName(R.string.configbuilder)
+ .shortName(R.string.configbuilder_shortname)
+ );
+ }
+
+ @Override
+ protected void onStart() {
MainApp.bus().register(this);
+ super.onStart();
}
@Override
- public int getType() {
- return PluginBase.GENERAL;
+ protected void onStop() {
+ super.onStop();
+ MainApp.bus().unregister(this);
}
- @Override
- public String getFragmentClass() {
- return ConfigBuilderFragment.class.getName();
- }
-
- @Override
- public String getName() {
- return MainApp.instance().getString(R.string.configbuilder);
- }
-
- @Override
- public String getNameShort() {
- String name = MainApp.sResources.getString(R.string.configbuilder_shortname);
- if (!name.trim().isEmpty()) {
- //only if translation exists
- return name;
- }
- // use long name as fallback
- return getName();
- }
-
- @Override
- public boolean isEnabled(int type) {
- return type == GENERAL;
- }
-
- @Override
- public boolean isVisibleInTabs(int type) {
- return type == GENERAL;
- }
-
- @Override
- public boolean canBeHidden(int type) {
- return false;
- }
-
- @Override
- public boolean hasFragment() {
- return true;
- }
-
- @Override
- public boolean showInList(int type) {
- return false;
- }
-
- @Override
- public void setFragmentEnabled(int type, boolean fragmentEnabled) {
- // Always enabled
- }
-
- @Override
- public void setFragmentVisible(int type, boolean fragmentVisible) {
- // Always visible
- }
-
- @Override
- public int getPreferencesId() {
- return -1;
- }
public void initialize() {
pluginList = MainApp.getPluginsList();
+ upgradeSettings();
loadSettings();
MainApp.bus().post(new EventAppInitialized());
}
- public void storeSettings() {
+ public void storeSettings(String from) {
if (pluginList != null) {
if (Config.logPrefsChange)
- log.debug("Storing settings");
- SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
- SharedPreferences.Editor editor = settings.edit();
+ log.debug("Storing settings from: " + from);
- for (int type = 1; type < PluginBase.LAST; type++) {
- for (PluginBase p : pluginList) {
- String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
- String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
- editor.putBoolean(settingEnabled, p.isEnabled(type));
- editor.putBoolean(settingVisible, p.isVisibleInTabs(type));
+ for (PluginBase p : pluginList) {
+ PluginType type = p.getType();
+ if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwayVisible)
+ continue;
+ if (p.pluginDescription.alwaysEnabled && p.pluginDescription.neverVisible)
+ continue;
+ savePref(p, type, true);
+ if (type == PluginType.PUMP) {
+ if (p instanceof ProfileInterface) { // Store state of optional Profile interface
+ savePref(p, PluginType.PROFILE, false);
+ }
}
}
- editor.apply();
verifySelectionInCategories();
}
}
+ private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
+ String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
+ SP.putBoolean(settingEnabled, p.isEnabled(type));
+ log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type));
+ if (storeVisible) {
+ String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
+ SP.putBoolean(settingVisible, p.isFragmentVisible());
+ log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible());
+ }
+ }
+
private void loadSettings() {
if (Config.logPrefsChange)
log.debug("Loading stored settings");
- SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
- for (int type = 1; type < PluginBase.LAST; type++) {
- for (PluginBase p : pluginList) {
- try {
- String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
- String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
- if (SP.contains(settingEnabled))
- p.setFragmentEnabled(type, SP.getBoolean(settingEnabled, true));
- if (SP.contains(settingVisible))
- p.setFragmentVisible(type, SP.getBoolean(settingVisible, true) && SP.getBoolean(settingEnabled, true));
- } catch (Exception e) {
- log.error("Unhandled exception", e);
+ for (PluginBase p : pluginList) {
+ PluginType type = p.getType();
+ loadPref(p, type, true);
+ if (p.getType() == PluginType.PUMP) {
+ if (p instanceof ProfileInterface) {
+ loadPref(p, PluginType.PROFILE, false);
}
}
}
verifySelectionInCategories();
}
+ private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
+ String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
+ if (SP.contains(settingEnabled))
+ p.setPluginEnabled(type, SP.getBoolean(settingEnabled, false));
+ else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
+ p.setPluginEnabled(type, true);
+ }
+ log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type));
+ if (loadVisible) {
+ String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
+ if (SP.contains(settingVisible))
+ p.setFragmentVisible(type, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
+ else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
+ p.setFragmentVisible(type, true);
+ }
+ log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible());
+ }
+ }
+
+ // Detect settings prior 1.60
+ private void upgradeSettings() {
+ if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
+ return;
+ if (Config.logPrefsChange)
+ log.debug("Upgrading stored settings");
+ for (PluginBase p : pluginList) {
+ log.debug("Processing " + p.getName());
+ for (int type = 1; type < 11; type++) {
+ PluginType newType;
+ switch (type) {
+ case 1:
+ newType = PluginType.GENERAL;
+ break;
+ case 2:
+ newType = PluginType.TREATMENT;
+ break;
+ case 3:
+ newType = PluginType.SENSITIVITY;
+ break;
+ case 4:
+ newType = PluginType.PROFILE;
+ break;
+ case 5:
+ newType = PluginType.APS;
+ break;
+ case 6:
+ newType = PluginType.PUMP;
+ break;
+ case 7:
+ newType = PluginType.CONSTRAINTS;
+ break;
+ case 8:
+ newType = PluginType.LOOP;
+ break;
+ case 9:
+ newType = PluginType.BGSOURCE;
+ break;
+ case 10:
+ newType = PluginType.INSULIN;
+ break;
+ default:
+ newType = PluginType.GENERAL;
+ break;
+ }
+ String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
+ String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
+ if (SP.contains(settingEnabled))
+ p.setPluginEnabled(newType, SP.getBoolean(settingEnabled, false));
+ if (SP.contains(settingVisible))
+ p.setFragmentVisible(newType, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
+ SP.remove(settingEnabled);
+ SP.remove(settingVisible);
+ if (newType == p.getType()) {
+ savePref(p, newType, true);
+ } else if (p.getType() == PluginType.PUMP && p instanceof ProfileInterface) {
+ savePref(p, PluginType.PROFILE, false);
+ }
+ }
+ }
+ }
+
public static CommandQueue getCommandQueue() {
return commandQueue;
}
- public static BgSourceInterface getActiveBgSource() {
+ public BgSourceInterface getActiveBgSource() {
return activeBgSource;
}
- public static ProfileInterface getActiveProfileInterface() {
+ public ProfileInterface getActiveProfileInterface() {
return activeProfile;
}
@@ -209,10 +264,6 @@ public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, Tr
return activeAPS;
}
- public static LoopPlugin getActiveLoop() {
- return activeLoop;
- }
-
public static PumpInterface getActivePump() {
return activePump;
}
@@ -224,16 +275,16 @@ public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, Tr
void logPluginStatus() {
for (PluginBase p : pluginList) {
log.debug(p.getName() + ":" +
- (p.isEnabled(1) ? " GENERAL" : "") +
- (p.isEnabled(2) ? " TREATMENT" : "") +
- (p.isEnabled(3) ? " SENSITIVITY" : "") +
- (p.isEnabled(4) ? " PROFILE" : "") +
- (p.isEnabled(5) ? " APS" : "") +
- (p.isEnabled(6) ? " PUMP" : "") +
- (p.isEnabled(7) ? " CONSTRAINTS" : "") +
- (p.isEnabled(8) ? " LOOP" : "") +
- (p.isEnabled(9) ? " BGSOURCE" : "") +
- (p.isEnabled(10) ? " INSULIN" : "")
+ (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
+ (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
+ (p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
+ (p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
+ (p.isEnabled(PluginType.APS) ? " APS" : "") +
+ (p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
+ (p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
+ (p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
+ (p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
+ (p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
);
}
}
@@ -241,493 +292,259 @@ public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, Tr
private void verifySelectionInCategories() {
ArrayList pluginsInCategory;
- // PluginBase.APS
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
- activeAPS = (APSInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.APS);
- if (activeAPS != null) {
- if (Config.logConfigBuilder)
- log.debug("Selected APS interface: " + ((PluginBase) activeAPS).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeAPS).getName())) {
- p.setFragmentVisible(PluginBase.APS, false);
- }
- }
+ // PluginType.APS
+ activeAPS = this.determineActivePlugin(APSInterface.class, PluginType.APS);
+
+ // PluginType.INSULIN
+ pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.INSULIN);
+ activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN);
+ if (activeInsulin == null) {
+ activeInsulin = InsulinOrefRapidActingPlugin.getPlugin();
+ InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(PluginType.INSULIN, true);
+ }
+ this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN);
+
+ // PluginType.SENSITIVITY
+ pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.SENSITIVITY);
+ activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY);
+ if (activeSensitivity == null) {
+ activeSensitivity = SensitivityOref0Plugin.getPlugin();
+ SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true);
+ }
+ this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY);
+
+ // PluginType.PROFILE
+ activeProfile = this.determineActivePlugin(ProfileInterface.class, PluginType.PROFILE);
+
+ // PluginType.BGSOURCE
+ activeBgSource = this.determineActivePlugin(BgSourceInterface.class, PluginType.BGSOURCE);
+
+ // PluginType.PUMP
+ pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.PUMP);
+ activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP);
+ if (activePump == null) {
+ activePump = VirtualPumpPlugin.getPlugin();
+ VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
+ }
+ this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
+
+ // PluginType.LOOP
+ activeLoop = this.determineActivePlugin(PluginType.LOOP);
+
+ // PluginType.TREATMENT
+ activeTreatments = this.determineActivePlugin(PluginType.TREATMENT);
+ }
+
+ /**
+ * disables the visibility for all fragments of Plugins with the given PluginType
+ * which are not equally named to the Plugin implementing the given Plugin Interface.
+ *
+ * @param pluginInterface
+ * @param pluginType
+ * @param
+ * @return
+ */
+ private T determineActivePlugin(Class pluginInterface, PluginType pluginType) {
+ ArrayList pluginsInCategory;
+ pluginsInCategory = MainApp.getSpecificPluginsListByInterface(pluginInterface);
+
+ return this.determineActivePlugin(pluginsInCategory, pluginType);
+ }
+
+ private T determineActivePlugin(PluginType pluginType) {
+ ArrayList pluginsInCategory;
+ pluginsInCategory = MainApp.getSpecificPluginsList(pluginType);
+
+ return this.determineActivePlugin(pluginsInCategory, pluginType);
+ }
+
+ /**
+ * disables the visibility for all fragments of Plugins in the given pluginsInCategory
+ * with the given PluginType which are not equally named to the Plugin implementing the
+ * given Plugin Interface.
+ *
+ * TODO we are casting an interface to PluginBase, which seems to be rather odd, since
+ * TODO the interface is not implementing PluginBase (this is just avoiding errors through
+ * TODO conventions.
+ *
+ * @param pluginsInCategory
+ * @param pluginType
+ * @param
+ * @return
+ */
+ private T determineActivePlugin(ArrayList pluginsInCategory,
+ PluginType pluginType) {
+ T activePlugin = (T) getTheOneEnabledInArray(pluginsInCategory, pluginType);
+
+ if (activePlugin != null) {
+ this.setFragmentVisiblities(((PluginBase) activePlugin).getName(),
+ pluginsInCategory, pluginType);
}
- // PluginBase.INSULIN
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
- activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.INSULIN);
+ return activePlugin;
+ }
+
+ private void setFragmentVisiblities(String activePluginName, ArrayList pluginsInCategory,
+ PluginType pluginType) {
if (Config.logConfigBuilder)
- log.debug("Selected insulin interface: " + ((PluginBase) activeInsulin).getName());
+ log.debug("Selected interface: " + activePluginName);
for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeInsulin).getName())) {
- p.setFragmentVisible(PluginBase.INSULIN, false);
- }
- }
-
- // PluginBase.SENSITIVITY
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
- activeSensitivity = (SensitivityInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.SENSITIVITY);
- if (Config.logConfigBuilder)
- log.debug("Selected sensitivity interface: " + ((PluginBase) activeSensitivity).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeSensitivity).getName())) {
- p.setFragmentVisible(PluginBase.SENSITIVITY, false);
- }
- }
-
- // PluginBase.PROFILE
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
- activeProfile = (ProfileInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PROFILE);
- if (Config.logConfigBuilder)
- log.debug("Selected profile interface: " + ((PluginBase) activeProfile).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeProfile).getName())) {
- p.setFragmentVisible(PluginBase.PROFILE, false);
- }
- }
-
- // PluginBase.BGSOURCE
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
- activeBgSource = (BgSourceInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.BGSOURCE);
- if (Config.logConfigBuilder)
- log.debug("Selected bgSource interface: " + ((PluginBase) activeBgSource).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeBgSource).getName())) {
- p.setFragmentVisible(PluginBase.BGSOURCE, false);
- }
- }
-
- // PluginBase.PUMP
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
- activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
- if (activePump == null)
- activePump = VirtualPumpPlugin.getPlugin(); // for NSClient build
- if (Config.logConfigBuilder)
- log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activePump).getName())) {
- p.setFragmentVisible(PluginBase.PUMP, false);
- }
- }
-
- // PluginBase.LOOP
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.LOOP);
- activeLoop = (LoopPlugin) getTheOneEnabledInArray(pluginsInCategory, PluginBase.LOOP);
- if (activeLoop != null) {
- if (Config.logConfigBuilder)
- log.debug("Selected loop interface: " + activeLoop.getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(activeLoop.getName())) {
- p.setFragmentVisible(PluginBase.LOOP, false);
- }
- }
- }
-
- // PluginBase.TREATMENT
- pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.TREATMENT);
- activeTreatments = (TreatmentsInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.TREATMENT);
- if (Config.logConfigBuilder)
- log.debug("Selected treatment interface: " + ((PluginBase) activeTreatments).getName());
- for (PluginBase p : pluginsInCategory) {
- if (!p.getName().equals(((PluginBase) activeTreatments).getName())) {
- p.setFragmentVisible(PluginBase.TREATMENT, false);
+ if (!p.getName().equals(activePluginName)) {
+ p.setFragmentVisible(pluginType, false);
}
}
}
@Nullable
- private PluginBase getTheOneEnabledInArray(ArrayList pluginsInCategory, int type) {
+ private PluginBase getTheOneEnabledInArray(ArrayList pluginsInCategory, PluginType type) {
PluginBase found = null;
for (PluginBase p : pluginsInCategory) {
if (p.isEnabled(type) && found == null) {
found = p;
} else if (p.isEnabled(type)) {
// set others disabled
- p.setFragmentEnabled(type, false);
+ p.setPluginEnabled(type, false);
}
}
// If none enabled, enable first one
- if (found == null && pluginsInCategory.size() > 0)
- found = pluginsInCategory.get(0);
+ //if (found == null && pluginsInCategory.size() > 0)
+ // found = pluginsInCategory.get(0);
return found;
}
- /*
- * Ex Pump interface
- *
- * Config builder return itself as a pump and check constraints before it passes command to pump driver
- */
-
-
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
- *
- * @param request
- * @return
- * true if command is going to be executed
- * false if error
*/
+ public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
+ if (!request.tempBasalRequested) {
+ if (callback != null) {
+ callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
+ }
+ return;
+ }
- public boolean applyAPSRequest(APSResult request, Callback callback) {
PumpInterface pump = getActivePump();
- request.rate = applyBasalConstraints(request.rate);
- PumpEnactResult result;
+
+ request.rateConstraint = new Constraint<>(request.rate);
+ request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value();
if (!pump.isInitialized()) {
- log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpNotInitialized));
+ log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
- return false;
+ return;
}
if (pump.isSuspended()) {
- log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpsuspended));
+ log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
- callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpsuspended)).enacted(false).success(false)).run();
+ callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
- return false;
+ return;
}
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
+
+ long now = System.currentTimeMillis();
+ TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
- if (isTempBasalInProgress()) {
+ if (activeTemp != null) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
getCommandQueue().cancelTempBasal(false, callback);
- return true;
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().absolute(request.rate).duration(0).enacted(false).success(true).comment("Basal set correctly")).run();
+ callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
+ .enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
- return false;
}
- } else if (isTempBasalInProgress()
- && getTempBasalRemainingMinutesFromHistory() > 5
- && Math.abs(request.rate - getTempBasalAbsoluteRateHistory()) < pump.getPumpDescription().basalStep) {
+ } else if (activeTemp != null
+ && activeTemp.getPlannedRemainingMinutes() > 5
+ && request.duration - activeTemp.getPlannedRemainingMinutes() < 30
+ && Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
- callback.result(new PumpEnactResult().absolute(getTempBasalAbsoluteRateHistory()).duration(getTempBasalFromHistory(System.currentTimeMillis()).getPlannedRemainingMinutes()).enacted(false).success(true).comment("Temp basal set correctly")).run();
+ callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
+ .enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
+ .comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
- return false;
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
- getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, callback);
- return true;
+ getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
-
- /**
- * Constraints interface
- **/
- @Override
- public boolean isLoopEnabled() {
- boolean result = true;
-
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- result = result && constrain.isLoopEnabled();
+ public void applySMBRequest(APSResult request, Callback callback) {
+ if (!request.bolusRequested) {
+ return;
}
- return result;
- }
- @Override
- public boolean isClosedModeEnabled() {
- boolean result = true;
-
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- result = result && constrain.isClosedModeEnabled();
+ long lastBolusTime = activeTreatments.getLastBolusTime();
+ if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
+ log.debug("SMB requested but still in 3 min interval");
+ if (callback != null) {
+ callback.result(new PumpEnactResult()
+ .comment(MainApp.gs(R.string.smb_frequency_exceeded))
+ .enacted(false).success(false)).run();
+ }
+ return;
}
- return result;
- }
- @Override
- public boolean isAutosensModeEnabled() {
- boolean result = true;
+ PumpInterface pump = getActivePump();
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- result = result && constrain.isAutosensModeEnabled();
+ if (!pump.isInitialized()) {
+ log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
+ if (callback != null) {
+ callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
+ }
+ return;
}
- return result;
- }
- @Override
- public boolean isAMAModeEnabled() {
- boolean result = SP.getBoolean("openapsama_useautosens", false);
-
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- result = result && constrain.isAMAModeEnabled();
+ if (pump.isSuspended()) {
+ log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
+ if (callback != null) {
+ callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
+ }
+ return;
}
- return result;
+
+ if (Config.logCongigBuilderActions)
+ log.debug("applySMBRequest: " + request.toString());
+
+ // deliver SMB
+ DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
+ detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
+ detailedBolusInfo.insulin = request.smb;
+ detailedBolusInfo.isSMB = true;
+ detailedBolusInfo.source = Source.USER;
+ detailedBolusInfo.deliverAt = request.deliverAt;
+ if (Config.logCongigBuilderActions)
+ log.debug("applyAPSRequest: bolus()");
+ getCommandQueue().bolus(detailedBolusInfo, callback);
}
- @Override
- public boolean isSMBModeEnabled() {
- boolean result = true; // TODO update for SMB // SP.getBoolean("openapsama_useautosens", false);
-
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- result = result && constrain.isSMBModeEnabled();
- }
- return result;
- }
-
- @Override
- public Double applyBasalConstraints(Double absoluteRate) {
- Double rateAfterConstrain = absoluteRate;
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- rateAfterConstrain = Math.min(constrain.applyBasalConstraints(absoluteRate), rateAfterConstrain);
- }
- return rateAfterConstrain;
- }
-
- @Override
- public Integer applyBasalConstraints(Integer percentRate) {
- Integer rateAfterConstrain = percentRate;
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- rateAfterConstrain = Math.min(constrain.applyBasalConstraints(percentRate), rateAfterConstrain);
- }
- return rateAfterConstrain;
- }
-
- @Override
- public Double applyBolusConstraints(Double insulin) {
- Double insulinAfterConstrain = insulin;
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- insulinAfterConstrain = Math.min(constrain.applyBolusConstraints(insulin), insulinAfterConstrain);
- }
- return insulinAfterConstrain;
- }
-
- @Override
- public Integer applyCarbsConstraints(Integer carbs) {
- Integer carbsAfterConstrain = carbs;
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- carbsAfterConstrain = Math.min(constrain.applyCarbsConstraints(carbs), carbsAfterConstrain);
- }
- return carbsAfterConstrain;
- }
-
- @Override
- public Double applyMaxIOBConstraints(Double maxIob) {
- Double maxIobAfterConstrain = maxIob;
- ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
- for (PluginBase p : constraintsPlugins) {
- ConstraintsInterface constrain = (ConstraintsInterface) p;
- if (!p.isEnabled(PluginBase.CONSTRAINTS)) continue;
- maxIobAfterConstrain = Math.min(constrain.applyMaxIOBConstraints(maxIob), maxIobAfterConstrain);
- }
- return maxIobAfterConstrain;
- }
-
- // ****** Treatments interface *****
- @Override
- public void updateTotalIOBTreatments() {
- activeTreatments.updateTotalIOBTreatments();
- }
-
- @Override
- public void updateTotalIOBTempBasals() {
- activeTreatments.updateTotalIOBTempBasals();
- }
-
- @Override
- public IobTotal getLastCalculationTreatments() {
- return activeTreatments.getLastCalculationTreatments();
- }
-
- @Override
- public IobTotal getCalculationToTimeTreatments(long time) {
- return activeTreatments.getCalculationToTimeTreatments(time);
- }
-
- @Override
- public IobTotal getLastCalculationTempBasals() {
- return activeTreatments.getLastCalculationTempBasals();
- }
-
- @Override
- public IobTotal getCalculationToTimeTempBasals(long time) {
- return activeTreatments.getCalculationToTimeTempBasals(time);
- }
-
- @Override
- public MealData getMealData() {
- return activeTreatments.getMealData();
- }
-
- @Override
- public List getTreatmentsFromHistory() {
- return activeTreatments.getTreatmentsFromHistory();
- }
-
- @Override
- public List getTreatments5MinBackFromHistory(long time) {
- return activeTreatments.getTreatments5MinBackFromHistory(time);
- }
-
- @Override
- public boolean isInHistoryRealTempBasalInProgress() {
- return activeTreatments.isInHistoryRealTempBasalInProgress();
- }
-
- @Override
- @Nullable
- public TemporaryBasal getRealTempBasalFromHistory(long time) {
- return activeTreatments.getRealTempBasalFromHistory(time);
- }
-
- @Override
- public boolean isTempBasalInProgress() {
- return activeTreatments != null && activeTreatments.isTempBasalInProgress();
- }
-
- @Override
- @Nullable
- public TemporaryBasal getTempBasalFromHistory(long time) {
- return activeTreatments != null ? activeTreatments.getTempBasalFromHistory(time) : null;
- }
-
- @Override
- public double getTempBasalAbsoluteRateHistory() {
- return activeTreatments.getTempBasalAbsoluteRateHistory();
- }
-
- @Override
- public double getTempBasalRemainingMinutesFromHistory() {
- return activeTreatments.getTempBasalRemainingMinutesFromHistory();
- }
-
- @Override
- public Intervals getTemporaryBasalsFromHistory() {
- return activeTreatments.getTemporaryBasalsFromHistory();
- }
-
- @Override
- public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) {
- boolean newRecordCreated = activeTreatments.addToHistoryTempBasal(tempBasal);
- if (newRecordCreated) {
- if (tempBasal.durationInMinutes == 0)
- NSUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId);
- else if (tempBasal.isAbsolute)
- NSUpload.uploadTempBasalStartAbsolute(tempBasal, null);
- else
- NSUpload.uploadTempBasalStartPercent(tempBasal);
- }
- return newRecordCreated;
- }
-
- @Override
- public boolean isInHistoryExtendedBoluslInProgress() {
- return activeTreatments.isInHistoryExtendedBoluslInProgress();
- }
-
- @Override
- @Nullable
- public ExtendedBolus getExtendedBolusFromHistory(long time) {
- return activeTreatments.getExtendedBolusFromHistory(time);
- }
-
- @Override
- public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) {
- boolean newRecordCreated = activeTreatments.addToHistoryExtendedBolus(extendedBolus);
- if (newRecordCreated) {
- if (extendedBolus.durationInMinutes == 0) {
- if (activePump.isFakingTempsByExtendedBoluses())
- NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId);
- else
- NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId);
- } else if (activePump.isFakingTempsByExtendedBoluses())
- NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin);
- else
- NSUpload.uploadExtendedBolus(extendedBolus);
- }
- return newRecordCreated;
- }
-
- @Override
- public Intervals getExtendedBolusesFromHistory() {
- return activeTreatments.getExtendedBolusesFromHistory();
- }
-
- @Override
- // return true if new record is created
- public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo) {
- boolean newRecordCreated = activeTreatments.addToHistoryTreatment(detailedBolusInfo);
- if (newRecordCreated && detailedBolusInfo.isValid)
- NSUpload.uploadBolusWizardRecord(detailedBolusInfo);
- return newRecordCreated;
- }
-
- @Override
- @Nullable
- public TempTarget getTempTargetFromHistory() {
- return activeTreatments.getTempTargetFromHistory(System.currentTimeMillis());
- }
-
- @Override
- @Nullable
- public TempTarget getTempTargetFromHistory(long time) {
- return activeTreatments.getTempTargetFromHistory(time);
- }
-
- @Override
- public Intervals getTempTargetsFromHistory() {
- return activeTreatments.getTempTargetsFromHistory();
- }
-
- @Override
- @Nullable
- public ProfileSwitch getProfileSwitchFromHistory(long time) {
- return activeTreatments.getProfileSwitchFromHistory(time);
- }
-
- @Override
- public ProfileIntervals