diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java index d81a8cd4a0..2e5e87c93c 100644 --- a/app/src/main/java/info/nightscout/androidaps/Config.java +++ b/app/src/main/java/info/nightscout/androidaps/Config.java @@ -20,8 +20,9 @@ public class Config { public static final boolean logPrefsChange = true; public static final boolean logConfigBuilder = true; public static final boolean logConstraintsChanges = true; + public static final boolean logTempBasalsCut = true; // Developing mode only - never turn on // TODO: remove fakeGlucoseData - public static final boolean fakeGlucoseData = true; + public static final boolean fakeGlucoseData = false; } diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index bb947f94a0..32ffb61818 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -10,4 +10,5 @@ public class Constants { public static final double MMOLL_TO_MGDL = 18.0182; public static final double MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL; + public static final int hoursToKeepInDatabase = 24; } diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index f95f396499..268ee31ff8 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -47,10 +47,6 @@ public class MainActivity extends AppCompatActivity { private static ConfigBuilderFragment configBuilderFragment; - public static ConfigBuilderFragment getConfigBuilder() { - return configBuilderFragment; - } - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -84,6 +80,7 @@ public class MainActivity extends AppCompatActivity { registerBus(); configBuilderFragment.initialize(); + MainApp.setConfigBuilder(configBuilderFragment); } setUpTabs(false); } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 5b15182e92..0edc28acfc 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -10,6 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; public class MainApp extends Application { @@ -19,6 +20,7 @@ public class MainApp extends Application { private static MainApp sInstance; private static DatabaseHelper databaseHelper = null; + private static ConfigBuilderFragment configBuilder = null; @Override public void onCreate() { @@ -49,6 +51,14 @@ public class MainApp extends Application { } } + public static void setConfigBuilder(ConfigBuilderFragment cb) { + configBuilder = cb; + } + + public static ConfigBuilderFragment getConfigBuilder() { + return configBuilder; + } + @Override public void onTerminate() { super.onTerminate(); diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index e37dfed275..d11838bb85 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -23,6 +23,7 @@ import java.sql.SQLException; import java.util.Date; import java.util.List; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.BgReading; @@ -32,7 +33,11 @@ import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientFragment; +import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripFragment; +import info.nightscout.androidaps.receivers.NSClientDataReceiver; +import info.nightscout.androidaps.receivers.xDripReceiver; import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSSgv; @@ -40,8 +45,8 @@ import info.nightscout.client.data.NSSgv; public class DataService extends IntentService { private static Logger log = LoggerFactory.getLogger(DataService.class); - Handler mHandler; - private HandlerThread mHandlerThread; + boolean xDripEnabled = true; + boolean nsClientEnabled = true; public DataService() { super("DataService"); @@ -52,10 +57,23 @@ public class DataService extends IntentService { if (Config.logFunctionCalls) log.debug("onHandleIntent"); + if (MainApp.getConfigBuilder() != null) { + if (MainApp.getConfigBuilder().getActiveBgSource().getClass().equals(SourceXdripFragment.class)) { + xDripEnabled = true; + nsClientEnabled = false; + } + if (MainApp.getConfigBuilder().getActiveBgSource().getClass().equals(SourceNSClientFragment.class)) { + xDripEnabled = false; + nsClientEnabled = true; + } + } + if (intent != null) { final String action = intent.getAction(); if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { - handleNewDataFromXDrip(intent); + if (xDripEnabled) + handleNewDataFromXDrip(intent); + xDripReceiver.completeWakefulIntent(intent); } else if (Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_TREATMENT.equals(action) || Intents.ACTION_CHANGED_TREATMENT.equals(action) || @@ -63,6 +81,7 @@ public class DataService extends IntentService { Intents.ACTION_NEW_SGV.equals(action) ) { handleNewDataFromNSClient(intent); + NSClientDataReceiver.completeWakefulIntent(intent); } } } @@ -74,17 +93,7 @@ public class DataService extends IntentService { if (Config.logFunctionCalls) log.debug("onStartCommand"); - if (mHandlerThread == null) { - if (Config.detailedLog) - log.debug("Creating handler thread"); - - this.mHandlerThread = new HandlerThread(DataService.class.getSimpleName() + "Handler"); - mHandlerThread.start(); - - this.mHandler = new Handler(mHandlerThread.getLooper()); - - registerBus(); - } + registerBus(); return START_STICKY; } @@ -114,6 +123,12 @@ public class DataService extends IntentService { bgReading.timestamp = bundle.getLong(Intents.EXTRA_TIMESTAMP); bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); + if (bgReading.timestamp < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) { + if (Config.logIncommingBG) + log.debug("Ignoring old XDRIPREC BG " + bgReading.toString()); + return; + } + if (Config.logIncommingBG) log.debug("XDRIPREC BG " + bgReading.toString()); @@ -137,11 +152,11 @@ public class DataService extends IntentService { String profile = bundles.getString("profile"); NSProfile nsProfile = new NSProfile(new JSONObject(profile), activeProfile); EventNewBasalProfile event = new EventNewBasalProfile(nsProfile); - if (MainActivity.getConfigBuilder() == null) { + if (MainApp.getConfigBuilder() == null) { log.error("Config builder not ready on receive profile"); return; } - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (pump != null) { pump.setNewBasalProfile(nsProfile); } else { @@ -298,13 +313,18 @@ public class DataService extends IntentService { } if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) { - if (MainActivity.getConfigBuilder().getActiveBgSource().getClass().equals(SourceNSClientFragment.class)) { + if (nsClientEnabled) { try { if (bundles.containsKey("sgv")) { String sgvstring = bundles.getString("sgv"); JSONObject sgvJson = new JSONObject(sgvstring); NSSgv nsSgv = new NSSgv(sgvJson); BgReading bgReading = new BgReading(nsSgv); + if (bgReading.timestamp < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) { + if (Config.logIncommingData) + log.debug("Ignoring old BG: " + bgReading.toString()); + return; + } MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading); if (Config.logIncommingData) log.debug("ADD: Stored new BG: " + bgReading.toString()); @@ -317,13 +337,16 @@ public class DataService extends IntentService { JSONObject sgvJson = jsonArray.getJSONObject(i); NSSgv nsSgv = new NSSgv(sgvJson); BgReading bgReading = new BgReading(nsSgv); - MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading); - if (Config.logIncommingData) - log.debug("ADD: Stored new BG: " + bgReading.toString()); + if (bgReading.timestamp < new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) { + if (Config.logIncommingData) + log.debug("Ignoring old BG: " + bgReading.toString()); + } else { + MainApp.getDbHelper().getDaoBgReadings().createIfNotExists(bgReading); + if (Config.logIncommingData) + log.debug("ADD: Stored new BG: " + bgReading.toString()); + } } } - MainApp.bus().post(new EventTreatmentChange()); - } catch (JSONException e) { e.printStackTrace(); } catch (Exception e1) { diff --git a/app/src/main/java/info/nightscout/androidaps/data/Result.java b/app/src/main/java/info/nightscout/androidaps/data/Result.java index a079db7d52..92af8f91b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Result.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Result.java @@ -13,6 +13,7 @@ public class Result extends Object implements Parcelable{ public Double absolute = -1d; // absolute rate [U/h] , isPercent = false public Integer percent = -1; // percent of current basal [%] (100% = current basal), isPercent = true public boolean isPercent = false; // if true percent is used, otherwise absolute + public boolean isTempCancel = false; // if true we are caceling temp basal // Result of treatment delivery public Double bolusDelivered = 0d; // real value of delivered insulin public Integer carbsDelivered = 0; // real value of delivered carbs @@ -24,7 +25,10 @@ public class Result extends Object implements Parcelable{ public String toString() { String ret = "Success: " + success; if (enacted) { - if (isPercent) { + if (isTempCancel) { + ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\n" + + "Temp cancel"; + } else if (isPercent) { ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nPercent: " + percent + "%"; } else { ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nAbsolute: " + absolute + " U/h"; 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 47d230bb02..62ec418503 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -7,6 +7,7 @@ import java.util.Date; import java.util.List; import android.content.Context; +import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.os.Parcel; import android.os.Parcelable; @@ -24,6 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventNewBG; @@ -50,7 +52,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, TempBasal.class); TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); - // TODO: add bg support } catch (SQLException e) { log.error(DatabaseHelper.class.getName(), "Can't create database", e); throw new RuntimeException(e); @@ -79,6 +80,21 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { super.close(); } + public void cleanUpDatabases() { + // TODO: call it somewhere + log.debug("Before BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "BgReadings")); + getWritableDatabase().delete("BgReadings", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null); + log.debug("After BgReadings size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "BgReadings")); + + log.debug("Before TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "TempBasals")); + getWritableDatabase().delete("TempBasals", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null); + log.debug("After TempBasals size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "TempBasals")); + + log.debug("Before Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "Treatments")); + getWritableDatabase().delete("Treatments", "timeIndex" + " < '" + Math.ceil((new Date().getTime() - Constants.hoursToKeepInDatabase * 60 * 60 * 1000l) / 60000d) + "'", null); + log.debug("After Treatments size: " + DatabaseUtils.queryNumEntries(getReadableDatabase(), "Treatments")); + } + public void resetDatabases() { try { TableUtils.dropTable(connectionSource, TempBasal.class, true); @@ -114,6 +130,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } public Dao getDaoBgReadings() throws SQLException { + //SQLiteDatabase db = getReadableDatabase(); + //log.debug("BgReadings size: " + DatabaseUtils.queryNumEntries(db, "BgReadings")); return getDao(BgReading.class); } @@ -163,7 +181,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Dao daoBgreadings = getDaoBgReadings(); List bgReadings; QueryBuilder queryBuilder = daoBgreadings.queryBuilder(); - queryBuilder.orderBy("timeIndex", false); + queryBuilder.orderBy("timeIndex", true); Where where = queryBuilder.where(); where.ge("timeIndex", (long) Math.ceil(mills / 60000d)); PreparedQuery preparedQuery = queryBuilder.prepare(); diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java index 852d74bf0a..ba2396fb4b 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java @@ -59,7 +59,7 @@ public class TempBasal { public IobTotal iobCalc(Date time) { IobTotal result = new IobTotal(); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return result; @@ -144,6 +144,31 @@ public class TempBasal { return (remainingMin < 0) ? 0 : (int) remainingMin; } + public boolean isInProgress() { + return isInProgress(new Date()); + } + + public double tempBasalConvertedToAbsolute() { + if (isAbsolute) return absolute; + else { + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); + double absval = profile.getBasal(NSProfile.secondsFromMidnight()) * percent / 100; + return absval; + } + } + + public boolean isInProgress(Date time) { + if (timeStart.getTime() > time.getTime()) return false; // in the future + if (timeEnd == null) { // open end + if (timeStart.getTime() < time.getTime() && getPlannedTimeEnd().getTime() > time.getTime()) + return true; // in interval + return false; + } + // closed end + if (timeStart.getTime() < time.getTime() && timeEnd.getTime() > time.getTime()) return true; // in interval + return false; + } + public String log() { return "TempBasal{" + "timeIndex=" + timeIndex + diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java index d2cceaa78b..158a34f7f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TempBasalsInterface.java @@ -1,5 +1,8 @@ package info.nightscout.androidaps.interfaces; +import java.util.Date; + +import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal; /** @@ -8,4 +11,6 @@ import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal; public interface TempBasalsInterface { void updateTotalIOB(); IobTotal getLastCalculation(); + + TempBasal getTempBasal (Date time); } 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 0f85dcdcad..9a5da2af48 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 @@ -296,7 +296,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI /** * apply constraints, set temp based on percent and expecting result in percent * - * @param percent 0 ... 100 ... + * @param percent 0 ... 100 ... * @param durationInMinutes * @return result */ @@ -338,7 +338,8 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI } /** - * expect absolute request and allow both absolute and percent response based on pump capabilities + * expect absolute request and allow both absolute and percent response based on pump capabilities + * * @param request * @return */ @@ -346,22 +347,40 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI public Result applyAPSRequest(APSResult request) { Double rateAfterConstraints = applyBasalConstraints(request.rate); request.rate = rateAfterConstraints; - Result result = activePump.applyAPSRequest(request); - if (result.enacted) { - if (result.isPercent) { - if (result.percent == 0) { + Result result = null; + + if (request.rate == getBaseBasalRate()) { + if (isTempBasalInProgress()) { + result = cancelTempBasal(); + if (result.enacted) { uploadTempBasalEnd(); - } else { - uploadTempBasalStartPercent(result.percent, result.duration); + MainApp.bus().post(new EventTempBasalChange()); } } else { - if (result.absolute == 0d) { - uploadTempBasalEnd(); + result = new Result(); + result.absolute = request.rate; + result.duration = 0; + result.enacted = false; + result.comment = "Basal set correctly"; + result.success = true; + } + } else if (isTempBasalInProgress() && request.rate == getTempBasalAbsoluteRate()) { + result = new Result(); + result.absolute = request.rate; + result.duration = activePump.getTempBasal().getPlannedRemainingMinutes(); + result.enacted = false; + result.comment = "Temp basal set correctly"; + result.success = true; + } else { + result = setTempBasalAbsolute(request.rate, request.duration); + if (result.enacted) { + if (result.isPercent) { + uploadTempBasalStartPercent(result.percent, result.duration); } else { uploadTempBasalStartAbsolute(result.absolute, result.duration); } + MainApp.bus().post(new EventTempBasalChange()); } - MainApp.bus().post(new EventTempBasalChange()); } return result; } @@ -466,6 +485,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI return convertView; } + } @Nullable @@ -785,7 +805,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI } } - public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) { + public static void uploadTempBasalStartPercent(Integer percent, double durationInMinutes) { try { Context context = MainApp.instance().getApplicationContext(); JSONObject data = new JSONObject(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java index 4774884322..5e0f80f613 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java @@ -194,21 +194,16 @@ public class LoopFragment extends Fragment implements View.OnClickListener, Plug @Subscribe public void onStatusEvent(final EventTreatmentChange ev) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { -// invoke(); - } - }); - else - log.debug("EventTreatmentChange: Activity is null"); + ConstraintsInterface constraintsInterface = MainApp.getConfigBuilder(); + if (constraintsInterface.isAutomaticProcessingEnabled()) { + invoke(); + updateGUI(); + } } @Subscribe public void onStatusEvent(final EventNewBG ev) { - ConstraintsInterface constraintsInterface = MainActivity.getConfigBuilder(); + ConstraintsInterface constraintsInterface = MainApp.getConfigBuilder(); if (constraintsInterface.isAutomaticProcessingEnabled()) { invoke(); updateGUI(); @@ -216,8 +211,8 @@ public class LoopFragment extends Fragment implements View.OnClickListener, Plug } private void invoke() { - ConstraintsInterface constraintsInterface = MainActivity.getConfigBuilder(); - PumpInterface pumpInterface = MainActivity.getConfigBuilder().getActivePump(); + ConstraintsInterface constraintsInterface = MainApp.getConfigBuilder(); + PumpInterface pumpInterface = MainApp.getConfigBuilder().getActivePump(); APSResult result = null; if (constraintsInterface == null || pumpInterface == null || !isEnabled()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/LowSuspend/LowSuspendFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/LowSuspend/LowSuspendFragment.java index 2f920d84e2..a264321ffc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/LowSuspend/LowSuspendFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/LowSuspend/LowSuspendFragment.java @@ -30,6 +30,7 @@ import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.client.data.NSProfile; +import info.nightscout.utils.SafeParse; /** * LOW SUSPEND ALGORITHM @@ -166,11 +167,6 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -184,9 +180,9 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener resultView = (TextView) view.findViewById(R.id.lowsuspend_result); requestView = (TextView) view.findViewById(R.id.lowsuspend_request); - if (savedInstanceState != null) { - lastRun = savedInstanceState.getParcelable("lastrun"); - } +// if (savedInstanceState != null) { +// lastRun = savedInstanceState.getParcelable("lastrun"); +// } updateGUI(); return view; } @@ -220,8 +216,8 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener public void invoke() { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); DatabaseHelper.GlucoseStatus glucoseStatus = MainApp.getDbHelper().getGlucoseStatusData(); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (!isEnabled()) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_disabled)); @@ -256,7 +252,7 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener minBgDefault = "5"; } - double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("lowsuspend_lowthreshold", minBgDefault).replace(",", ".")), profile.getUnits()); + double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("lowsuspend_lowthreshold", minBgDefault)), profile.getUnits()); boolean lowProjected = (glucoseStatus.glucose + 6.0 * glucoseStatus.avgdelta) < minBg; boolean low = glucoseStatus.glucose < minBg; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java index aff370699b..b5fa60adf4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Objectives/ObjectivesFragment.java @@ -318,12 +318,14 @@ public class ObjectivesFragment extends Fragment implements View.OnClickListener **/ @Override public boolean isAutomaticProcessingEnabled() { - return objectives.get(3).started.getTime() > 0; + return true; // TODO: revert back + //return objectives.get(3).started.getTime() > 0; } @Override public boolean manualConfirmationNeeded() { - return objectives.get(3).started.getTime() < 0; + return false; // TODO: revert back + //return objectives.get(3).started.getTime() < 0; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java index 3fb86d4ee7..5c42b18f75 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java @@ -37,6 +37,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment; import info.nightscout.client.data.NSProfile; import info.nightscout.utils.DateUtil; import info.nightscout.utils.Round; +import info.nightscout.utils.SafeParse; public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, PluginBase, APSInterface { private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class); @@ -152,11 +153,6 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, return fragment; } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - } - @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -173,9 +169,9 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, resultView = (TextView) view.findViewById(R.id.openapsma_result); requestView = (TextView) view.findViewById(R.id.openapsma_request); - if (savedInstanceState != null) { - lastRun = savedInstanceState.getParcelable("lastrun"); - } +// if (savedInstanceState != null) { +// lastRun = savedInstanceState.getParcelable("lastrun"); +// } updateGUI(); return view; } @@ -216,8 +212,8 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, } DatabaseHelper.GlucoseStatus glucoseStatus = MainApp.getDbHelper().getGlucoseStatusData(); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (!isEnabled()) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_disabled)); @@ -259,15 +255,15 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, Date now = new Date(); - double maxIob = Double.parseDouble(SP.getString("openapsma_max_iob", "1.5").replace(",", ".")); - double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); - double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("openapsma_min_bg", minBgDefault).replace(",", ".")), units); - double maxBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("openapsma_max_bg", maxBgDefault).replace(",", ".")), units); + double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5")); + double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); + double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units); + double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", minBgDefault)), units); minBg = Round.roundTo(minBg, 1d); maxBg = Round.roundTo(maxBg, 1d); - TreatmentsInterface treatments = MainActivity.getConfigBuilder().getActiveTreatments(); - TempBasalsInterface tempBasals = MainActivity.getConfigBuilder().getActiveTempBasals(); + TreatmentsInterface treatments = MainApp.getConfigBuilder().getActiveTreatments(); + TempBasalsInterface tempBasals = MainApp.getConfigBuilder().getActiveTempBasals(); treatments.updateTotalIOB(); tempBasals.updateTotalIOB(); IobTotal bolusIob = treatments.getLastCalculation(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewExtendedBolusDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewExtendedBolusDialog.java index 8bb831f780..3a32ac68fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewExtendedBolusDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewExtendedBolusDialog.java @@ -12,9 +12,11 @@ import android.widget.EditText; import android.widget.RadioButton; import info.nightscout.androidaps.MainActivity; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.utils.SafeParse; public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener { @@ -47,9 +49,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli switch (view.getId()) { case R.id.overview_newextendedbolus_okbutton: try { - int basalPercent = 100; - String insulinText = insulinEdit.getText().toString().replace(",", "."); - Double insulin = Double.parseDouble(!insulinText.equals("") ? insulinText : "0"); + Double insulin = SafeParse.stringToDouble(insulinEdit.getText().toString()); int durationInMinutes = 30; if (h10Radio.isChecked()) durationInMinutes = 60; if (h20Radio.isChecked()) durationInMinutes = 120; @@ -58,7 +58,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli String confirmMessage = getString(R.string.setextendedbolusquestion); - Double insulinAfterConstraint = MainActivity.getConfigBuilder().applyBolusConstraints(insulin); + Double insulinAfterConstraint = MainApp.getConfigBuilder().applyBolusConstraints(insulin); confirmMessage += " " + insulinAfterConstraint + " U "; confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?"; if (insulinAfterConstraint != insulin) @@ -73,7 +73,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli builder.setMessage(confirmMessage); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); Result result = pump.setExtendedBolus(finalInsulin, finalDurationInMinutes); if (!result.success) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTempBasalDialog.java index 55f955054d..3cc5473495 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTempBasalDialog.java @@ -12,9 +12,11 @@ import android.widget.EditText; import android.widget.RadioButton; import info.nightscout.androidaps.MainActivity; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.utils.SafeParse; public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener { @@ -52,8 +54,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi case R.id.overview_newtempbasal_okbutton: try { int basalPercent = 100; - String basalText = basalEdit.getText().toString().replace(",", "."); - Double basal = Double.parseDouble(!basalText.equals("") ? basalText : "0"); + Double basal = SafeParse.stringToDouble(basalEdit.getText().toString()); final boolean setAsPercent = percentRadio.isChecked(); int durationInMinutes = 30; if (h10Radio.isChecked()) durationInMinutes = 60; @@ -63,13 +64,13 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi String confirmMessage = getString(R.string.setbasalquestion); if (setAsPercent) { - basalPercent = MainActivity.getConfigBuilder().applyBasalConstraints(basal.intValue()); + basalPercent = MainApp.getConfigBuilder().applyBasalConstraints(basal.intValue()); confirmMessage += "\n " + basalPercent + "% "; confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?"; if (basalPercent != basal.intValue()) confirmMessage += "\n" + getString(R.string.constraintapllied); } else { - Double basalAfterConstraint = MainActivity.getConfigBuilder().applyBasalConstraints(basal); + Double basalAfterConstraint = MainApp.getConfigBuilder().applyBasalConstraints(basal); confirmMessage += "\n " + basalAfterConstraint + " U/h "; confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?"; if (basalAfterConstraint != basal) @@ -86,7 +87,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi builder.setMessage(confirmMessage); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); Result result; if (setAsPercent) { result = pump.setTempBasalPercent(finalBasalPercent, finalDurationInMinutes); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java index 5f49018f95..d0bf1fb57d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.utils.SafeParse; public class NewTreatmentDialog extends DialogFragment implements OnClickListener { @@ -46,15 +47,13 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene case R.id.treatments_newtreatment_deliverbutton: try { - String insulinText = this.insulin.getText().toString().replace(",", "."); - String carbsText = this.carbs.getText().toString().replace(",", "."); - Double insulin = Double.parseDouble(!insulinText.equals("") ? insulinText : "0"); - Integer carbs = Integer.parseInt(!carbsText.equals("") ? carbsText : "0"); + Double insulin = SafeParse.stringToDouble(this.insulin.getText().toString()); + Integer carbs = SafeParse.stringToInt(this.carbs.getText().toString()); String confirmMessage = getString(R.string.entertreatmentquestion); - Double insulinAfterConstraints = MainActivity.getConfigBuilder().applyBolusConstraints(insulin); - Integer carbsAfterConstraints = MainActivity.getConfigBuilder().applyCarbsConstraints(carbs); + Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(insulin); + Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(carbs); confirmMessage += getString(R.string.bolus) + ": " + insulinAfterConstraints + "U"; confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; @@ -70,7 +69,7 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) { - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); Result result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints); if (!result.success) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index d6e3e735de..b2010427d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -115,8 +115,8 @@ public class WizardDialog extends DialogFragment implements OnClickListener { DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00"); String confirmMessage = getString(R.string.entertreatmentquestion); - Double insulinAfterConstraints = MainActivity.getConfigBuilder().applyBolusConstraints(calculatedTotalInsulin); - Integer carbsAfterConstraints = MainActivity.getConfigBuilder().applyCarbsConstraints(calculatedCarbs); + Double insulinAfterConstraints = MainApp.getConfigBuilder().applyBolusConstraints(calculatedTotalInsulin); + Integer carbsAfterConstraints = MainApp.getConfigBuilder().applyCarbsConstraints(calculatedCarbs); confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U"; confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; @@ -139,7 +139,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) { - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); Result result = pump.deliverTreatment(finalInsulinAfterConstraints, finalCarbsAfterConstraints); if (!result.success) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); @@ -161,7 +161,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener { } private void initDialog() { - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), "No profile loaded from NS yet"); @@ -197,8 +197,8 @@ public class WizardDialog extends DialogFragment implements OnClickListener { } // IOB calculation - TreatmentsInterface treatments = MainActivity.getConfigBuilder().getActiveTreatments(); - TempBasalsInterface tempBasals = MainActivity.getConfigBuilder().getActiveTempBasals(); + TreatmentsInterface treatments = MainApp.getConfigBuilder().getActiveTreatments(); + TempBasalsInterface tempBasals = MainApp.getConfigBuilder().getActiveTempBasals(); treatments.updateTotalIOB(); tempBasals.updateTotalIOB(); IobTotal bolusIob = treatments.getLastCalculation(); @@ -213,25 +213,18 @@ public class WizardDialog extends DialogFragment implements OnClickListener { } private void calculateInsulin() { - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); // Entered values - String i_bg = this.bgInput.getText().toString().replace("," , "."); - String i_carbs = this.carbsInput.getText().toString().replace(",", "."); - String i_correction = this.correctionInput.getText().toString().replace(",", "."); - Double c_bg = 0d; - try { c_bg = Double.parseDouble(i_bg.equals("") ? "0" : i_bg); } catch (Exception e) {} - Integer c_carbs = 0; - try { c_carbs = Integer.parseInt(i_carbs.equals("") ? "0" : i_carbs); } catch (Exception e) {} - c_carbs = (Integer) Math.round(c_carbs); - Double c_correction = 0d; - try { c_correction = Double.parseDouble(i_correction.equals("") ? "0" : i_correction); } catch (Exception e) {} - if(c_correction != MainActivity.getConfigBuilder().applyBolusConstraints(c_correction)) { + Double c_bg = SafeParse.stringToDouble(this.bgInput.getText().toString()); + Integer c_carbs = SafeParse.stringToInt(this.carbsInput.getText().toString()); + Double c_correction = SafeParse.stringToDouble(this.correctionInput.getText().toString()); + if(c_correction != MainApp.getConfigBuilder().applyBolusConstraints(c_correction)) { this.correctionInput.setText(""); wizardDialogDeliverButton.setVisibility(Button.GONE); return; } - if(c_carbs != MainActivity.getConfigBuilder().applyCarbsConstraints(c_carbs)) { + if(c_carbs != MainApp.getConfigBuilder().applyCarbsConstraints(c_carbs)) { this.carbsInput.setText(""); wizardDialogDeliverButton.setVisibility(Button.GONE); return; @@ -259,8 +252,8 @@ public class WizardDialog extends DialogFragment implements OnClickListener { carbsInsulin.setText(numberFormat.format(insulinFromCarbs) + "U"); // Insulin from IOB - TreatmentsInterface treatments = MainActivity.getConfigBuilder().getActiveTreatments(); - TempBasalsInterface tempBasals = MainActivity.getConfigBuilder().getActiveTempBasals(); + TreatmentsInterface treatments = MainApp.getConfigBuilder().getActiveTreatments(); + TempBasalsInterface tempBasals = MainApp.getConfigBuilder().getActiveTempBasals(); treatments.updateTotalIOB(); tempBasals.updateTotalIOB(); IobTotal bolusIob = treatments.getLastCalculation(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 44eb66bd23..2b4681dcdf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -2,9 +2,11 @@ package info.nightscout.androidaps.plugins.Overview; import android.app.Activity; import android.graphics.Color; +import android.graphics.DashPathEffect; import android.graphics.Paint; import android.os.Bundle; import android.os.Handler; +import android.provider.ContactsContract; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; @@ -15,6 +17,8 @@ import android.widget.LinearLayout; import android.widget.TextView; import com.jjoe64.graphview.GraphView; +import com.jjoe64.graphview.ValueDependentColor; +import com.jjoe64.graphview.series.BarGraphSeries; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.PointsGraphSeries; @@ -175,7 +179,7 @@ public class OverviewFragment extends Fragment implements PluginBase { cancelTempButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (pump.isTempBasalInProgress()) { pump.cancelTempBasal(); MainApp.bus().post(new EventTempBasalChange()); @@ -271,9 +275,9 @@ public class OverviewFragment extends Fragment implements PluginBase { public void updateGUI() { BgReading actualBG = MainApp.getDbHelper().actualBg(); BgReading lastBG = MainApp.getDbHelper().lastBg(); - if (MainActivity.getConfigBuilder() == null || MainActivity.getConfigBuilder().getActiveProfile() == null) // app not initialized yet + if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null) // app not initialized yet return; - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return; @@ -284,7 +288,7 @@ public class OverviewFragment extends Fragment implements PluginBase { return; // **** Temp button **** - PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (pump.isTempBasalInProgress()) { TempBasal activeTemp = pump.getTempBasal(); @@ -317,7 +321,8 @@ public class OverviewFragment extends Fragment implements PluginBase { int agoMin = (int) (agoMsec / 60d / 1000d); timeAgoView.setText(agoMin + " " + getString(R.string.minago)); - // **** BG graph **** + // ****** GRAPH ******* + // allign to hours Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(new Date().getTime()); @@ -333,6 +338,56 @@ public class OverviewFragment extends Fragment implements PluginBase { Double highLine = NSProfile.toUnits(180d, 10d, units); Double maxY = NSProfile.toUnits(400d, 20d, units); // TODO: add some scale support + BarGraphSeries basalsSeries = null; + LineGraphSeries seriesLow = null; + LineGraphSeries seriesHigh = null; + LineGraphSeries seriesNow = null; + PointsGraphSeries seriesInRage = null; + PointsGraphSeries seriesOutOfRange = null; + + bgGraph.removeAllSeries(); + + // **** TEMP BASALS graph **** + class BarDataPoint extends DataPoint { + public BarDataPoint(double x, double y, boolean isTempBasal) { + super(x, y); + this.isTempBasal = isTempBasal; + } + public boolean isTempBasal = false; + } + + Double maxAllowedBasal = MainApp.getConfigBuilder().applyBasalConstraints(1000d); + + long now = new Date().getTime(); + List basalArray = new ArrayList(); + for (long time = fromTime; time < now; time += 5 * 60 * 1000l) { + TempBasal tb = MainApp.getConfigBuilder().getActiveTempBasals().getTempBasal(new Date(time)); + if (tb != null) + basalArray.add(new BarDataPoint(time, tb.tempBasalConvertedToAbsolute(), true)); + else + basalArray.add(new BarDataPoint(time, profile.getBasal(NSProfile.secondsFromMidnight(new Date(time))), false)); + } + BarDataPoint[] basal = new BarDataPoint[basalArray.size()]; + log.debug("Bars: " + basalArray.size()); + basal = basalArray.toArray(basal); + bgGraph.addSeries(basalsSeries = new BarGraphSeries(basal)); + basalsSeries.setValueDependentColor(new ValueDependentColor() { + @Override + public int get(DataPoint data) { + BarDataPoint point = (BarDataPoint) data; + if (point.isTempBasal) return Color.CYAN; + else return Color.BLUE; + } + }); + + // set second scale + bgGraph.getSecondScale().addSeries(basalsSeries); + bgGraph.getSecondScale().setMinY(0); + bgGraph.getSecondScale().setMaxY(maxAllowedBasal * 4); + bgGraph.getGridLabelRenderer().setVerticalLabelsSecondScaleColor(MainApp.instance().getResources().getColor(R.color.background_material_dark)); + + + // **** BG graph **** List bgReadingsArray = MainApp.getDbHelper().getDataFromTime(fromTime); List inRangeArray = new ArrayList(); List outOfRangeArray = new ArrayList(); @@ -354,38 +409,53 @@ public class OverviewFragment extends Fragment implements PluginBase { outOfRange = outOfRangeArray.toArray(outOfRange); - // targets - LineGraphSeries seriesLow = new LineGraphSeries(new DataPoint[]{ - new DataPoint(fromTime, lowLine), - new DataPoint(toTime, lowLine) - }); - seriesLow.setColor(Color.RED); - bgGraph.addSeries(seriesLow); - - LineGraphSeries seriesHigh = new LineGraphSeries(new DataPoint[]{ - new DataPoint(fromTime, highLine), - new DataPoint(toTime, highLine) - }); - seriesHigh.setColor(Color.RED); - bgGraph.addSeries(seriesHigh); - - if (inRange.length > 0) { - PointsGraphSeries seriesInRage = new PointsGraphSeries(inRange); - bgGraph.addSeries(seriesInRage); + bgGraph.addSeries(seriesInRage = new PointsGraphSeries(inRange)); seriesInRage.setShape(PointsGraphSeries.Shape.POINT); seriesInRage.setSize(5); seriesInRage.setColor(Color.GREEN); } if (outOfRange.length > 0) { - PointsGraphSeries seriesOutOfRange = new PointsGraphSeries(outOfRange); - bgGraph.addSeries(seriesOutOfRange); + bgGraph.addSeries(seriesOutOfRange = new PointsGraphSeries(outOfRange)); seriesOutOfRange.setShape(PointsGraphSeries.Shape.POINT); seriesOutOfRange.setSize(5); seriesOutOfRange.setColor(Color.RED); } + + // **** HIGH and LOW targets graph **** + DataPoint[] lowDataPoints = new DataPoint[]{ + new DataPoint(fromTime, lowLine), + new DataPoint(toTime, lowLine) + }; + DataPoint[] highDataPoints = new DataPoint[]{ + new DataPoint(fromTime, highLine), + new DataPoint(toTime, highLine) + }; + bgGraph.addSeries(seriesLow = new LineGraphSeries(lowDataPoints)); + seriesLow.setColor(Color.RED); + bgGraph.addSeries(seriesHigh = new LineGraphSeries(highDataPoints)); + seriesHigh.setColor(Color.RED); + + // **** NOW line **** + DataPoint[] nowPoints = new DataPoint[]{ + new DataPoint(now, 0), + new DataPoint(now, maxY) + }; + bgGraph.addSeries(seriesNow = new LineGraphSeries(nowPoints)); + seriesNow.setColor(Color.GREEN); + seriesNow.setDrawDataPoints(false); + //seriesNow.setThickness(1); + // custom paint to make a dotted line + Paint paint = new Paint(); + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(1); + paint.setPathEffect(new DashPathEffect(new float[]{4, 20}, 0)); + paint.setColor(Color.WHITE); + seriesNow.setCustomPaint(paint); + + // set manual x bounds to have nice steps bgGraph.getViewport().setMaxX(toTime); bgGraph.getViewport().setMinX(fromTime); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java index 9fb5466f34..eab25c57d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SafetyFragment/SafetyFragment.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.client.data.NSProfile; import info.nightscout.utils.Round; +import info.nightscout.utils.SafeParse; public class SafetyFragment extends Fragment implements PluginBase, ConstraintsInterface { private static Logger log = LoggerFactory.getLogger(SafetyFragment.class); @@ -83,9 +84,9 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI @Override public Double applyBasalConstraints(Double absoluteRate) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); + Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (absoluteRate < 0) absoluteRate = 0d; Integer maxBasalMult = 4; @@ -113,9 +114,9 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI @Override public Integer applyBasalConstraints(Integer percentRate) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); + Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); Double currentBasal = profile.getBasal(profile.secondsFromMidnight()); Double absoluteRate = currentBasal * ((double) percentRate / 100); @@ -158,7 +159,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstraintsI public Double applyBolusConstraints(Double insulin) { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); try { - Double maxBolus = Double.parseDouble(SP.getString("treatmentssafety_maxbolus", "3")); + Double maxBolus = SafeParse.stringToDouble(SP.getString("treatmentssafety_maxbolus", "3")); if (insulin < 0) insulin = 0d; if (insulin > maxBolus) insulin = maxBolus; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfileFragment.java index 0ce100b324..5e523bc7a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SimpleProfile/SimpleProfileFragment.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.client.data.NSProfile; +import info.nightscout.utils.SafeParse; public class SimpleProfileFragment extends Fragment implements PluginBase, ProfileInterface { private static Logger log = LoggerFactory.getLogger(SimpleProfileFragment.class); @@ -156,13 +157,13 @@ public class SimpleProfileFragment extends Fragment implements PluginBase, Profi @Override public void onTextChanged(CharSequence s, int start, int before, int count) { - try { dia = Double.parseDouble(diaView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { ic = Double.parseDouble(icView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { isf = Double.parseDouble(isfView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { car = Double.parseDouble(carView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { basal = Double.parseDouble(basalView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { targetLow = Double.parseDouble(targetlowView.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { targetHigh = Double.parseDouble(targethighView.getText().toString().replace(",", ".")); } catch (Exception e) {}; + dia = SafeParse.stringToDouble(diaView.getText().toString()); + ic = SafeParse.stringToDouble(icView.getText().toString()); + isf = SafeParse.stringToDouble(isfView.getText().toString()); + car = SafeParse.stringToDouble(carView.getText().toString()); + basal = SafeParse.stringToDouble(basalView.getText().toString()); + targetLow = SafeParse.stringToDouble(targetlowView.getText().toString()); + targetHigh = SafeParse.stringToDouble(targethighView.getText().toString()); storeSettings(); } }; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/TempBasals/TempBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/TempBasals/TempBasalsFragment.java index 274a18e986..aa1783ccdf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/TempBasals/TempBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/TempBasals/TempBasalsFragment.java @@ -2,13 +2,13 @@ package info.nightscout.androidaps.plugins.TempBasals; import android.app.Activity; import android.os.Bundle; +import android.support.annotation.Nullable; import android.support.v4.app.Fragment; -import android.support.v7.widget.CardView; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.*; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.LinearLayout; import android.widget.TextView; import com.j256.ormlite.dao.Dao; @@ -28,6 +28,7 @@ import java.util.Date; import java.util.List; import java.util.Locale; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.TempBasal; @@ -116,6 +117,40 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa queryBuilder.limit(30l); PreparedQuery preparedQuery = queryBuilder.prepare(); tempBasals = dao.query(preparedQuery); + + // Update ended + long now = new Date().getTime(); + for (int position = tempBasals.size() - 1; position >= 0; position--) { + TempBasal t = tempBasals.get(position); + boolean update = false; + if (t.timeEnd == null && t.getPlannedTimeEnd().getTime() < now) { + t.timeEnd = new Date(t.getPlannedTimeEnd().getTime()); + if (Config.logTempBasalsCut) + log.debug("Add timeEnd to old record"); + update = true; + } + if (position > 0) { + Date startofnewer = tempBasals.get(position - 1).timeStart; + if (t.timeEnd == null) { + t.timeEnd = new Date(Math.min(startofnewer.getTime(), t.getPlannedTimeEnd().getTime())); + if (Config.logTempBasalsCut) + log.debug("Add timeEnd to old record"); + update = true; + } else if (t.timeEnd.getTime() > startofnewer.getTime()) { + t.timeEnd = startofnewer; + update = true; + } + } + if (update) { + dao.update(t); + if (Config.logTempBasalsCut) { + log.debug("Fixing unfinished temp end: " + t.log()); + if (position > 0) + log.debug("Previous: " + tempBasals.get(position - 1).log()); + } + } + + } } catch (SQLException e) { log.debug(e.getMessage(), e); tempBasals = new ArrayList(); @@ -144,13 +179,30 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa TempBasal t = tempBasals.get(pos); total.plus(t.iobCalc(now)); } - if (iobTotal != null) - iobTotal.setText(formatNumber2decimalplaces.format(total.basaliob)); + final IobTotal finalTotal = total; + + Activity activity = getActivity(); + if (visibleNow && activity != null && recyclerView != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (iobTotal != null) + iobTotal.setText(formatNumber2decimalplaces.format(finalTotal.basaliob)); + } + }); lastCalculationTimestamp = new Date().getTime(); lastCalculation = total; } + @Nullable + @Override + public TempBasal getTempBasal(Date time) { + for (TempBasal t: tempBasals) { + if (t.isInProgress(time)) return t; + } + return null; + } public static class RecyclerViewAdapter extends RecyclerView.Adapter { @@ -172,24 +224,33 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa // TODO: implement locales DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, new Locale("cs", "CZ")); DateFormat enddf = DateFormat.getTimeInstance(DateFormat.SHORT, new Locale("cs", "CZ")); - if (tempBasals.get(position).timeEnd != null) { - holder.date.setText(df.format(tempBasals.get(position).timeStart) + " - " + enddf.format(tempBasals.get(position).timeEnd)); + TempBasal tempBasal = tempBasals.get(position); + if (tempBasal.timeEnd != null) { + holder.date.setText(df.format(tempBasal.timeStart) + " - " + enddf.format(tempBasals.get(position).timeEnd)); } else { - holder.date.setText(df.format(tempBasals.get(position).timeStart)); + holder.date.setText(df.format(tempBasal.timeStart)); } - holder.duration.setText(formatNumber0decimalplaces.format(tempBasals.get(position).duration) + " min"); - if (tempBasals.get(position).isAbsolute) { - holder.absolute.setText(formatNumber0decimalplaces.format(tempBasals.get(position).absolute) + " U/h"); + holder.duration.setText(formatNumber0decimalplaces.format(tempBasal.duration) + " min"); + if (tempBasal.isAbsolute) { + holder.absolute.setText(formatNumber0decimalplaces.format(tempBasal.absolute) + " U/h"); holder.percent.setText(""); } else { holder.absolute.setText(""); - holder.percent.setText(formatNumber0decimalplaces.format(tempBasals.get(position).percent) + "%"); + holder.percent.setText(formatNumber0decimalplaces.format(tempBasal.percent) + "%"); } - holder.realDuration.setText(formatNumber0decimalplaces.format(tempBasals.get(position).getRealDuration()) + " min"); - IobTotal iob = tempBasals.get(position).iobCalc(new Date()); + holder.realDuration.setText(formatNumber0decimalplaces.format(tempBasal.getRealDuration()) + " min"); + IobTotal iob = tempBasal.iobCalc(new Date()); holder.iob.setText(formatNumber2decimalplaces.format(iob.basaliob) + " U"); holder.netInsulin.setText(formatNumber2decimalplaces.format(iob.netInsulin) + " U"); holder.netRatio.setText(formatNumber2decimalplaces.format(iob.netRatio) + " U/h"); + if (tempBasal.isInProgress()) + holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.colorInProgress)); + else if (tempBasal.timeEnd == null) + holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.colorNotEnded)); + else if (tempBasal.iobCalc(new Date()).basaliob != 0) + holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.colorAffectingIOB)); + else + holder.dateLinearLayout.setBackgroundColor(MainApp.instance().getResources().getColor(R.color.cardColorBackground)); } @Override @@ -212,6 +273,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa TextView netRatio; TextView netInsulin; TextView iob; + LinearLayout dateLinearLayout; TempBasalsViewHolder(View itemView) { super(itemView); @@ -224,6 +286,7 @@ public class TempBasalsFragment extends Fragment implements PluginBase, TempBasa netRatio = (TextView) itemView.findViewById(R.id.tempbasals_netratio); netInsulin = (TextView) itemView.findViewById(R.id.tempbasals_netinsulin); iob = (TextView) itemView.findViewById(R.id.tempbasals_iob); + dateLinearLayout = (LinearLayout) itemView.findViewById(R.id.tempbasals_datelinearlayout); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java index 8f43380ac4..e83b3aee8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java @@ -134,9 +134,9 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener public void updateTotalIOB() { IobTotal total = new IobTotal(); - if (MainActivity.getConfigBuilder() == null || MainActivity.getConfigBuilder().getActiveProfile() == null) // app not initialized yet + if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null) // app not initialized yet return; - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) { lastCalculation = total; return; @@ -153,10 +153,20 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener Iob bIOB = t.iobCalc(now, dia / 2); total.bolussnooze += bIOB.iobContrib; } - if (iobTotal != null) - iobTotal.setText(formatNumber2decimalplaces.format(total.iob)); - if (activityTotal != null) - activityTotal.setText(formatNumber3decimalplaces.format(total.activity)); + + final IobTotal finalTotal = total; + + Activity activity = getActivity(); + if (visibleNow && activity != null && recyclerView != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + if (iobTotal != null) + iobTotal.setText(formatNumber2decimalplaces.format(finalTotal.iob)); + if (activityTotal != null) + activityTotal.setText(formatNumber3decimalplaces.format(finalTotal.activity)); + } + }); lastCalculationTimestamp = new Date().getTime(); lastCalculation = total; @@ -170,7 +180,7 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener @Override public MealData getMealData() { MealData result = new MealData(); - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return result; @@ -207,9 +217,9 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener @Override public void onBindViewHolder(TreatmentsViewHolder holder, int position) { - if (MainActivity.getConfigBuilder() == null || MainActivity.getConfigBuilder().getActiveProfile() == null) // app not initialized yet + if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null) // app not initialized yet return; - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return; // TODO: implement locales diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpFragment.java index e9388ccb44..bba47b6ea4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/VirtualPump/VirtualPumpFragment.java @@ -18,6 +18,7 @@ import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.Date; +import java.util.concurrent.ExecutionException; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainActivity; @@ -37,7 +38,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt Double defaultBasalValue = 0.2d; - TempBasal tempBasal = null; + //TempBasal tempBasal = null; TempBasal extendedBolus = null; Integer batteryPercent = 50; Integer resevoirInUnits = 50; @@ -126,18 +127,22 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt void checkForExpiredTempsAndExtended() { long now = new Date().getTime(); if (isTempBasalInProgress()) { - long plannedTimeEnd = tempBasal.getPlannedTimeEnd().getTime(); + //long plannedTimeEnd = tempBasal.getPlannedTimeEnd().getTime(); + long plannedTimeEnd = getTempBasal().getPlannedTimeEnd().getTime(); if (plannedTimeEnd < now) { - tempBasal.timeEnd = new Date(plannedTimeEnd); + //tempBasal.timeEnd = new Date(plannedTimeEnd); + getTempBasal().timeEnd = new Date(plannedTimeEnd); try { - MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); + //MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); + MainApp.instance().getDbHelper().getDaoTempBasals().update(getTempBasal()); } catch (SQLException e) { e.printStackTrace(); log.error(e.getMessage()); } if (Config.logPumpComm) - log.debug("Canceling expired temp: " + tempBasal); - tempBasal = null; + //log.debug("Canceling expired temp: " + tempBasal); + log.debug("Canceling expired temp: " + getTempBasal()); + //tempBasal = null; MainApp.bus().post(new EventTreatmentChange()); } } @@ -160,7 +165,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt @Override public boolean isTempBasalInProgress() { - return tempBasal != null; + //return tempBasal != null; + return getTempBasal() != null; } @Override @@ -180,12 +186,12 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt @Override public void setNewBasalProfile(NSProfile profile) { - // Do nothing here. we are using MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + // Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile(); } @Override public double getBaseBasalRate() { - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return defaultBasalValue; return profile.getBasal(profile.secondsFromMidnight()); @@ -195,28 +201,33 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt public double getTempBasalAbsoluteRate() { if (!isTempBasalInProgress()) return 0; - if (tempBasal.isAbsolute) { - return tempBasal.absolute; + //if (tempBasal.isAbsolute) { + if (getTempBasal().isAbsolute) { + //return tempBasal.absolute; + return getTempBasal().absolute; } else { - NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); + NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) return defaultBasalValue; Double baseRate = profile.getBasal(profile.secondsFromMidnight()); - Double tempRate = baseRate * (tempBasal.percent / 100d); + //Double tempRate = baseRate * (tempBasal.percent / 100d); + Double tempRate = baseRate * (getTempBasal().percent / 100d); return baseRate + tempRate; } } @Override public TempBasal getTempBasal() { - return tempBasal; + //return tempBasal; + return MainApp.getConfigBuilder().getActiveTempBasals().getTempBasal(new Date()); } @Override public double getTempBasalRemainingMinutes() { if (!isTempBasalInProgress()) return 0; - return tempBasal.getPlannedRemainingMinutes(); + //return tempBasal.getPlannedRemainingMinutes(); + return getTempBasal().getPlannedRemainingMinutes(); } @Override @@ -225,7 +236,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt result.success = true; result.bolusDelivered = insulin; result.carbsDelivered = carbs; - result.comment = getString(R.string.virtualpump_resultok); + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (Config.logPumpComm) log.debug("Delivering treatment insulin: " + insulin + "U carbs: " + carbs + "g " + result); @@ -239,7 +250,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt Result result = cancelTempBasal(); if (!result.success) return result; - tempBasal = new TempBasal(); + //tempBasal = new TempBasal(); + TempBasal tempBasal = new TempBasal(); tempBasal.timeStart = new Date(); tempBasal.isAbsolute = true; tempBasal.absolute = absoluteRate; @@ -248,13 +260,13 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt result.enacted = true; result.absolute = absoluteRate; result.duration = durationInMinutes; - result.comment = getString(R.string.virtualpump_resultok); + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); try { MainApp.instance().getDbHelper().getDaoTempBasals().create(tempBasal); } catch (SQLException e) { e.printStackTrace(); result.success = false; - result.comment = getString(R.string.virtualpump_sqlerror); + result.comment = MainApp.instance().getString(R.string.virtualpump_sqlerror); } if (Config.logPumpComm) log.debug("Setting temp basal absolute: " + result); @@ -271,7 +283,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt if (!result.success) return result; } - tempBasal = new TempBasal(); + //tempBasal = new TempBasal(); + TempBasal tempBasal = new TempBasal(); tempBasal.timeStart = new Date(); tempBasal.isAbsolute = false; tempBasal.percent = percent; @@ -281,13 +294,13 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt result.percent = percent; result.isPercent = true; result.duration = durationInMinutes; - result.comment = getString(R.string.virtualpump_resultok); + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); try { MainApp.instance().getDbHelper().getDaoTempBasals().create(tempBasal); } catch (SQLException e) { e.printStackTrace(); result.success = false; - result.comment = getString(R.string.virtualpump_sqlerror); + result.comment = MainApp.instance().getString(R.string.virtualpump_sqlerror); } if (Config.logPumpComm) log.debug("Settings temp basal percent: " + result); @@ -311,14 +324,14 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt result.enacted = true; result.bolusDelivered = insulin; result.duration = durationInMinutes; - result.comment = getString(R.string.virtualpump_resultok); + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); try { MainApp.instance().getDbHelper().getDaoTempBasals().create(extendedBolus); } catch (SQLException e) { e.printStackTrace(); result.success = false; result.enacted = false; - result.comment = getString(R.string.virtualpump_sqlerror); + result.comment = MainApp.instance().getString(R.string.virtualpump_sqlerror); } if (Config.logPumpComm) log.debug("Setting extended bolus: " + result); @@ -331,23 +344,25 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt checkForExpiredTempsAndExtended(); Result result = new Result(); result.success = true; - result.comment = getString(R.string.virtualpump_resultok); + result.isTempCancel = true; + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (isTempBasalInProgress()) { result.enacted = true; - tempBasal.timeEnd = new Date(); + //tempBasal.timeEnd = new Date(); + getTempBasal().timeEnd = new Date(); try { - MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); + MainApp.instance().getDbHelper().getDaoTempBasals().update(getTempBasal()); + //tempBasal = null; + if (Config.logPumpComm) + log.debug("Canceling temp basal: " + result); + updateGUI(); } catch (SQLException e) { e.printStackTrace(); result.success = false; result.enacted = false; - result.comment = getString(R.string.virtualpump_sqlerror); + result.comment = MainApp.instance().getString(R.string.virtualpump_sqlerror); } } - tempBasal = null; - if (Config.logPumpComm) - log.debug("Canceling temp basal: " + result); - updateGUI(); return result; } @@ -358,16 +373,16 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt if (isExtendedBoluslInProgress()) { extendedBolus.timeEnd = new Date(); try { - MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); + MainApp.instance().getDbHelper().getDaoTempBasals().update(extendedBolus); } catch (SQLException e) { e.printStackTrace(); result.success = false; - result.comment = getString(R.string.virtualpump_sqlerror); + result.comment = MainApp.instance().getString(R.string.virtualpump_sqlerror); } } result.success = true; result.enacted = true; - result.comment = getString(R.string.virtualpump_resultok); + result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); extendedBolus = null; if (Config.logPumpComm) log.debug("Canceling extended basal: " + result); @@ -377,30 +392,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt @Override public Result applyAPSRequest(APSResult request) { - if (isTempBasalInProgress()) { - if (request.rate == getTempBasalAbsoluteRate()) { - Result noChange = new Result(); - noChange.absolute = request.rate; - noChange.duration = tempBasal.getPlannedRemainingMinutes(); - noChange.enacted = false; - noChange.comment = "Temp basal set correctly"; - noChange.success = true; - return noChange; - } else { - return setTempBasalAbsolute(request.rate, request.duration); - } - } - if (request.rate == getBaseBasalRate()) { - Result noChange = new Result(); - noChange.absolute = request.rate; - noChange.duration = 0; - noChange.enacted = false; - noChange.comment = "Basal set correctly"; - noChange.success = true; - return noChange; - } - - return setTempBasalAbsolute(request.rate, request.duration); + // This should be implemented only on ConfigBuilder + return null; } @Override @@ -411,12 +404,13 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt try { battery.put("percent", batteryPercent); status.put("status", "normal"); - //status.put("lastbolus", last_bolus_amount); - //status.put("lastbolustime", DateUtil.toISOString(last_bolus_time)); if (isTempBasalInProgress()) { - status.put("tempbasalpct", tempBasal.percent); - status.put("tempbasalstart", DateUtil.toISOString(tempBasal.timeStart)); - status.put("tempbasalremainmin", tempBasal.getPlannedRemainingMinutes()); + //status.put("tempbasalpct", tempBasal.percent); + //status.put("tempbasalstart", DateUtil.toISOString(tempBasal.timeStart)); + //status.put("tempbasalremainmin", tempBasal.getPlannedRemainingMinutes()); + status.put("tempbasalpct", getTempBasal().percent); + status.put("tempbasalstart", DateUtil.toISOString(getTempBasal().timeStart)); + status.put("tempbasalremainmin", getTempBasal().getPlannedRemainingMinutes()); } status.put("timestamp", DateUtil.toISOString(new Date())); @@ -451,7 +445,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt basaBasalRateView.setText(getBaseBasalRate() + "U"); if (isTempBasalInProgress()) { - tempBasalView.setText(tempBasal.toString()); + //tempBasalView.setText(tempBasal.toString()); + tempBasalView.setText(getTempBasal().toString()); } else { tempBasalView.setText(""); } diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/xDripReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/xDripReceiver.java index ef006b7400..2c6a9b9237 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/xDripReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/xDripReceiver.java @@ -18,16 +18,10 @@ public class xDripReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - if (MainActivity.getConfigBuilder().getActiveBgSource() == null) { - log.debug("getActiveBgSource is still null"); - return; - } - if (MainActivity.getConfigBuilder().getActiveBgSource().getClass().equals(SourceXdripFragment.class)) { - if (Config.logFunctionCalls) - log.debug("onReceive " + intent); - startWakefulService(context, new Intent(context, DataService.class) - .setAction(intent.getAction()) - .putExtras(intent)); - } + if (Config.logFunctionCalls) + log.debug("onReceive " + intent); + startWakefulService(context, new Intent(context, DataService.class) + .setAction(intent.getAction()) + .putExtras(intent)); } } diff --git a/app/src/main/java/info/nightscout/utils/SafeParse.java b/app/src/main/java/info/nightscout/utils/SafeParse.java new file mode 100644 index 0000000000..5e9b132a1a --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/SafeParse.java @@ -0,0 +1,26 @@ +package info.nightscout.utils; + +/** + * Created by mike on 23.06.2016. + */ +public class SafeParse { + public static Double stringToDouble(String input) { + Double result = 0d; + input = input.replace(",", "."); + try { + result = Double.parseDouble(input); + } catch (Exception e) { + } + return result; + } + + public static Integer stringToInt(String input) { + Integer result = 0; + input = input.replace(",", "."); + try { + result = Integer.parseInt(input); + } catch (Exception e) { + } + return result; + } +} diff --git a/app/src/main/res/layout/tempbasals_item.xml b/app/src/main/res/layout/tempbasals_item.xml index 52f5b6bb79..0c4469c0df 100644 --- a/app/src/main/res/layout/tempbasals_item.xml +++ b/app/src/main/res/layout/tempbasals_item.xml @@ -19,7 +19,8 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="true" - android:orientation="horizontal"> + android:orientation="horizontal" + android:id="@+id/tempbasals_datelinearlayout"> #FF47C8FF #FF478EFF #FFDD7792 + + #c45026 + #830400 + #190084 +