diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 7de867c70c..49d9835d85 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -60,8 +60,9 @@ + android:exported="false" /> + \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java index 8c45e9936f..20dd4a77bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/Config.java +++ b/app/src/main/java/info/nightscout/androidaps/Config.java @@ -4,6 +4,13 @@ package info.nightscout.androidaps; * Created by mike on 07.06.2016. */ public class Config { + // MAIN FUCTIONALITY + public static final boolean APS = true; + // PLUGINS + public static final boolean LOWSUSPEDENABLED = APS && true; + public static final boolean OPENAPSMAENABLED = APS && true; + public static final boolean LOOPENABLED = APS && true; + public static final boolean detailedLog = true; public static final boolean logFunctionCalls = true; public static final boolean logIncommingBG = true; diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 6964cef195..8cfc357768 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps; +import android.content.Intent; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; @@ -59,10 +60,13 @@ public class MainActivity extends AppCompatActivity { pluginsList = new ArrayList(); // Register all tabs in app here pluginsList.add(OverviewFragment.newInstance()); - pluginsList.add(LoopFragment.newInstance()); pluginsList.add(VirtualPumpFragment.newInstance()); - pluginsList.add(LowSuspendFragment.newInstance()); - pluginsList.add(OpenAPSMAFragment.newInstance()); + if (Config.LOOPENABLED) + pluginsList.add(LoopFragment.newInstance()); + if (Config.LOWSUSPEDENABLED) + pluginsList.add(LowSuspendFragment.newInstance()); + if (Config.OPENAPSMAENABLED) + pluginsList.add(OpenAPSMAFragment.newInstance()); pluginsList.add(NSProfileViewerFragment.newInstance()); pluginsList.add(SimpleProfileFragment.newInstance()); pluginsList.add(TreatmentsFragment.newInstance()); @@ -108,6 +112,11 @@ public class MainActivity extends AppCompatActivity { public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { + case R.id.nav_preferences: { + Intent i = new Intent(getApplicationContext(), PreferencesActivity.class); + startActivity(i); + break; + } case R.id.nav_resetdb: MainApp.getDbHelper().resetDatabases(); break; diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java new file mode 100644 index 0000000000..d8d638af92 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java @@ -0,0 +1,37 @@ +package info.nightscout.androidaps; + +import android.content.SharedPreferences; +import android.preference.PreferenceActivity; +import android.preference.PreferenceFragment; +import android.preference.PreferenceManager; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; + +import info.nightscout.androidaps.events.EventPreferenceChange; + +public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit(); + PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + MainApp.bus().post(new EventPreferenceChange()); + } + + public static class MyPreferenceFragment extends PreferenceFragment { + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.pref_treatments); + if (Config.OPENAPSMAENABLED) + addPreferencesFromResource(R.xml.pref_openapsma); + if (Config.LOWSUSPEDENABLED) + addPreferencesFromResource(R.xml.pref_lowsuspend); + + } + } +} \ No newline at end of file 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 d39cf7eae4..421775f78f 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -182,6 +182,7 @@ public class DataService extends IntentService { stored._id = _id; MainApp.getDbHelper().getDaoTreatments().update(stored); } + MainApp.bus().post(new EventTreatmentChange()); return; } else { if (Config.logIncommingData) @@ -196,10 +197,10 @@ public class DataService extends IntentService { MainApp.getDbHelper().getDaoTreatments().create(treatment); if (Config.logIncommingData) log.debug("ADD: Stored treatment: " + treatment.log()); - MainApp.bus().post(new EventTreatmentChange()); } catch (SQLException e) { e.printStackTrace(); } + MainApp.bus().post(new EventTreatmentChange()); } } catch (JSONException e) { @@ -255,10 +256,10 @@ public class DataService extends IntentService { MainApp.getDbHelper().getDaoTreatments().create(treatment); if (Config.logIncommingData) log.debug("CHANGE: Stored treatment: " + treatment.log()); - MainApp.bus().post(new EventTreatmentChange()); } catch (SQLException e) { e.printStackTrace(); } + MainApp.bus().post(new EventTreatmentChange()); } } catch (JSONException e) { 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 f971096845..28661890fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Result.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Result.java @@ -18,7 +18,13 @@ public class Result extends Object implements Parcelable{ } public String toString() { - return "Success: " + success + "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + "\nAbsolute: " + absolute; + String ret = "Success: " + success; + if (enacted) { + ret += "\nEnacted: " + enacted + "\nComment: " + comment + "\nDuration: " + duration + " min\nAbsolute: " + absolute + " U/h"; + } else { + ret += "\nComment: " + comment; + } + return ret; } @Override 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 071f1b28af..fd1426149a 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempBasal.java @@ -6,6 +6,9 @@ import com.j256.ormlite.table.DatabaseTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; @@ -183,8 +186,7 @@ public class TempBasal { return (remainingMin < 0) ? 0 : (int) remainingMin; } - @Override - public String toString() { + public String log() { return "TempBasal{" + "timeIndex=" + timeIndex + ", timeStart=" + timeStart + @@ -196,4 +198,20 @@ public class TempBasal { ", isExtended=" + isExtended + '}'; } + + public String toString() { + DateFormat formatDateToJustTime = new SimpleDateFormat("HH:mm"); + DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00"); + + if (isAbsolute) { + return formatNumber2decimalplaces.format(absolute) + "U/h @" + + formatDateToJustTime.format(timeStart) + + " " + getRealDuration() + "/" + duration + "min"; + } else { // percent + return percent + "% @" + + formatDateToJustTime.format(timeStart) + + " " + getRealDuration() + "/" + duration + "min"; + } + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java new file mode 100644 index 0000000000..b4b430bb1e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.events; + +/** + * Created by mike on 19.06.2016. + */ +public class EventPreferenceChange { +} 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 96cbf43570..e64241a1cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.interfaces; import org.json.JSONObject; import info.nightscout.androidaps.data.Result; +import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.client.data.NSProfile; @@ -23,6 +24,7 @@ public interface PumpInterface { double getBaseBasalRate(); // base basal rate, not temp basal double getTempBasalAbsoluteRate(); double getTempBasalRemainingMinutes(); + TempBasal getTempBasal(); Result deliverTreatment(Double insulin, Double carbs); Result setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes); 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 303a30d1a6..f3de63c552 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 @@ -2,8 +2,11 @@ package info.nightscout.androidaps.plugins.ConfigBuilder; import android.content.Context; +import android.content.Intent; import android.content.SharedPreferences; +import android.content.pm.ResolveInfo; import android.os.Bundle; +import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; @@ -22,15 +25,21 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; +import java.util.List; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.db.TempBasal; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventRefreshGui; +import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.ConstrainsInterface; import info.nightscout.androidaps.interfaces.PluginBase; @@ -42,6 +51,7 @@ import info.nightscout.androidaps.plugins.APSResult; import info.nightscout.androidaps.plugins.TempBasals.TempBasalsFragment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment; import info.nightscout.client.data.NSProfile; +import info.nightscout.utils.DateUtil; public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpInterface, ConstrainsInterface { private static Logger log = LoggerFactory.getLogger(ConfigBuilderFragment.class); @@ -237,10 +247,40 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI return activePump.getTempBasalRemainingMinutes(); } + @Override + public TempBasal getTempBasal() { + return activePump.getTempBasal(); + } + @Override public Result deliverTreatment(Double insulin, Double carbs) { - // TODO: constrains here - return activePump.deliverTreatment(insulin, carbs); + SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + Double maxbolus = Double.parseDouble(SP.getString("treatmentssafety_maxbolus", "3")); + Double maxcarbs = Double.parseDouble(SP.getString("treatmentssafety_maxcarbs", "48")); + + if (insulin > maxbolus || carbs > maxcarbs) { + Result failResult = new Result(); + failResult.success = false; + failResult.comment = MainApp.instance().getString(R.string.constrains_violation); + return failResult; + } + Result result = activePump.deliverTreatment(insulin, carbs); + + if (result.success) { + Treatment t = new Treatment(); + t.insulin = result.bolusDelivered; + t.carbs = carbs; + t.created_at = new Date(); + try { + MainApp.instance().getDbHelper().getDaoTreatments().create(t); + } catch (SQLException e) { + e.printStackTrace(); + } + t.setTimeIndex(t.getTimeIndex()); + t.sendToNSClient(); + MainApp.bus().post(new EventTreatmentChange()); + } + return result; } @Override @@ -263,7 +303,10 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI @Override public Result cancelTempBasal() { - return activePump.cancelTempBasal(); + Result result = activePump.cancelTempBasal(); + if (result.enacted) + uploadTempBasalEnd(); + return result; } @Override @@ -273,7 +316,10 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI @Override public Result applyAPSRequest(APSResult request) { - return activePump.applyAPSRequest(request); + Result result = activePump.applyAPSRequest(request); + if (result.enacted) + uploadTempBasalStart(result.absolute, result.duration); + return result; } @Override @@ -568,7 +614,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI boolean result = true; ArrayList constrainsPlugins = MainActivity.getSpecificPluginsList(PluginBase.CONSTRAINS); - for(PluginBase p: constrainsPlugins) { + for (PluginBase p : constrainsPlugins) { ConstrainsInterface constrain = (ConstrainsInterface) p; if (!p.isEnabled()) continue; result = result && constrain.isAutomaticProcessingEnabled(); @@ -581,7 +627,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI boolean result = false; ArrayList constrainsPlugins = MainActivity.getSpecificPluginsList(PluginBase.CONSTRAINS); - for(PluginBase p: constrainsPlugins) { + for (PluginBase p : constrainsPlugins) { ConstrainsInterface constrain = (ConstrainsInterface) p; if (!p.isEnabled()) continue; result = result || constrain.manualConfirmationNeeded(); @@ -592,7 +638,7 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI @Override public APSResult applyBasalConstrains(APSResult result) { ArrayList constrainsPlugins = MainActivity.getSpecificPluginsList(PluginBase.CONSTRAINS); - for(PluginBase p: constrainsPlugins) { + for (PluginBase p : constrainsPlugins) { ConstrainsInterface constrain = (ConstrainsInterface) p; if (!p.isEnabled()) continue; constrain.applyBasalConstrains(result); @@ -600,4 +646,58 @@ public class ConfigBuilderFragment extends Fragment implements PluginBase, PumpI return result; } + public static void uploadTempBasalStart(Double absolute, double durationInMinutes) { + try { + //SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + //boolean useAbsoluteForUpload = sp.getBoolean("ns_sync_use_absolute", false); + + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", "Temp Basal"); + data.put("duration", durationInMinutes); + //if (useAbsoluteForUpload && absolute != null) + data.put("absolute", absolute); + //else + // data.put("percent", percent - 100); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List q = context.getPackageManager().queryBroadcastReceivers(intent, 0); + if (q.size() < 1) { + log.error("DBADD No receivers"); + } else log.debug("DBADD dbAdd " + q.size() + " receivers " + data.toString()); + } catch (JSONException e) { + } + } + + public static void uploadTempBasalEnd() { + try { + Context context = MainApp.instance().getApplicationContext(); + JSONObject data = new JSONObject(); + data.put("eventType", "Temp Basal"); + data.put("created_at", DateUtil.toISOString(new Date())); + data.put("enteredBy", MainApp.instance().getString(R.string.app_name)); + Bundle bundle = new Bundle(); + bundle.putString("action", "dbAdd"); + bundle.putString("collection", "treatments"); + bundle.putString("data", data.toString()); + Intent intent = new Intent(Intents.ACTION_DATABASE); + intent.putExtras(bundle); + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); + context.sendBroadcast(intent); + List q = context.getPackageManager().queryBroadcastReceivers(intent, 0); + if (q.size() < 1) { + log.error("DBADD No receivers"); + } else log.debug("DBADD dbAdd " + q.size() + " receivers " + data.toString()); + } catch (JSONException e) { + } + } + } 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 e5a277ed6f..5ab9eb5501 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 @@ -7,7 +7,6 @@ import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.Fragment; -import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -223,7 +222,7 @@ public class LoopFragment extends Fragment implements View.OnClickListener, Plug PumpInterface pumpInterface = MainActivity.getConfigBuilder().getActivePump(); APSResult result = null; - if (constrainsInterface == null || pumpInterface == null) + if (constrainsInterface == null || pumpInterface == null || !isEnabled()) return; APSInterface usedAPS = null; 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 c8d08a2dd8..2f920d84e2 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 @@ -32,15 +32,14 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.client.data.NSProfile; /** - * LOW SUSPEND ALGORITHM - * - * Define projection as BG + 6 * avgdelta (estimated BG in 30 min) - * - * If BG is bellow low threshold and projection too: set basal rate to 0 U/h if low temp is not running - * else if projection is bellow low threshold: set basal rate to 0 U/h if low temp is not running - * else if exists low temp: cancel it - * else no change - * + * LOW SUSPEND ALGORITHM + *

+ * Define projection as BG + 6 * avgdelta (estimated BG in 30 min) + *

+ * If BG is bellow low threshold and projection too: set basal rate to 0 U/h if low temp is not running + * else if projection is bellow low threshold: set basal rate to 0 U/h if low temp is not running + * else if exists low temp: cancel it + * else no change */ public class LowSuspendFragment extends Fragment implements View.OnClickListener, PluginBase, APSInterface { @@ -224,21 +223,31 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + if (!isEnabled()) { + updateResultGUI(MainApp.instance().getString(R.string.openapsma_disabled)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_disabled)); + return; + } + if (glucoseStatus == null) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_noglucosedata)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); return; } if (profile == null) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_noprofile)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_noprofile)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_noprofile)); return; } if (pump == null) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_nopump)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_nopump)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_nopump)); return; } @@ -247,7 +256,7 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener minBgDefault = "5"; } - double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("min_bg", minBgDefault).replace(",", ".")), profile.getUnits()); + double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("lowsuspend_lowthreshold", minBgDefault).replace(",", ".")), profile.getUnits()); boolean lowProjected = (glucoseStatus.glucose + 6.0 * glucoseStatus.avgdelta) < minBg; boolean low = glucoseStatus.glucose < minBg; @@ -325,16 +334,12 @@ public class LowSuspendFragment extends Fragment implements View.OnClickListener activity.runOnUiThread(new Runnable() { @Override public void run() { - if (lastRun != null) { - resultView.setText(text); - glucoseStatusView.setText(""); - minBgView.setText(""); - requestView.setText(""); - lastRunView.setText(""); - } + resultView.setText(text); + glucoseStatusView.setText(""); + minBgView.setText(""); + requestView.setText(""); + lastRunView.setText(""); } }); - else - log.debug("EventNewBG: Activity is null"); } } 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 60cc70d9f1..bdae0f057c 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 @@ -218,21 +218,31 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + if (!isEnabled()) { + updateResultGUI(MainApp.instance().getString(R.string.openapsma_disabled)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_disabled)); + return; + } + if (glucoseStatus == null) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_noglucosedata)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); return; } if (profile == null) { updateResultGUI(MainApp.instance().getString(R.string.openapsma_noprofile)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_noprofile)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_noprofile)); return; } if (pump == null) { updateResultGUI(getString(R.string.openapsma_nopump)); - if (Config.logAPSResult) log.debug(MainApp.instance().getString(R.string.openapsma_nopump)); + if (Config.logAPSResult) + log.debug(MainApp.instance().getString(R.string.openapsma_nopump)); return; } @@ -248,12 +258,10 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, Date now = new Date(); - // TODO: objectives limits - double maxIob = Double.parseDouble(SP.getString("max_iob", "1.5").replace(",", ".")); - double maxBasal = Double.parseDouble(SP.getString("max_basal", "1").replace(",", ".")); - // TODO: min_bg, max_bg in prefs - double minBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("min_bg", minBgDefault).replace(",", ".")), units); - double maxBg = NSProfile.toMgdl(Double.parseDouble(SP.getString("max_bg", maxBgDefault).replace(",", ".")), units); + 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); TreatmentsInterface treatments = MainActivity.getConfigBuilder().getActiveTreatments(); TempBasalsInterface tempBasals = MainActivity.getConfigBuilder().getActiveTempBasals(); @@ -306,8 +314,6 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, } } }); - else - log.debug("EventNewBG: Activity is null"); } void updateResultGUI(final String text) { @@ -316,19 +322,15 @@ public class OpenAPSMAFragment extends Fragment implements View.OnClickListener, activity.runOnUiThread(new Runnable() { @Override public void run() { - if (lastRun != null) { - resultView.setText(text); - glucoseStatusView.setText(""); - currentTempView.setText(""); - iobDataView.setText(""); - profileView.setText(""); - mealDataView.setText(""); - requestView.setText(""); - lastRunView.setText(""); - } + resultView.setText(text); + glucoseStatusView.setText(""); + currentTempView.setText(""); + iobDataView.setText(""); + profileView.setText(""); + mealDataView.setText(""); + requestView.setText(""); + lastRunView.setText(""); } }); - else - log.debug("EventNewBG: Activity is null"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/NewTreatmentDialogFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialogFragment.java similarity index 71% rename from app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/NewTreatmentDialogFragment.java rename to app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialogFragment.java index ac5bbb336d..23439b4c42 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/NewTreatmentDialogFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialogFragment.java @@ -1,10 +1,12 @@ -package info.nightscout.androidaps.plugins.Treatments.Dialogs; +package info.nightscout.androidaps.plugins.Overview.Dialogs; -import android.app.Activity; -import android.app.DialogFragment; +import android.content.DialogInterface; +import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; +import android.support.v4.app.DialogFragment; +import android.support.v7.app.AlertDialog; import android.view.*; import android.view.View.OnClickListener; import android.widget.Button; @@ -13,6 +15,8 @@ import android.widget.TextView; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.data.Result; public class NewTreatmentDialogFragment extends DialogFragment implements OnClickListener { @@ -41,8 +45,8 @@ public class NewTreatmentDialogFragment extends DialogFragment implements OnClic switch (view.getId()) { case R.id.treatments_newtreatment_deliverbutton: SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxbolus = Double.parseDouble(SP.getString("safety_maxbolus", "3")); - Double maxcarbs = Double.parseDouble(SP.getString("safety_maxcarbs", "48")); + Double maxbolus = Double.parseDouble(SP.getString("treatmentssafety_maxbolus", "3")); + Double maxcarbs = Double.parseDouble(SP.getString("treatmentssafety_maxcarbs", "48")); String insulinText = this.insulin.getText().toString().replace(",", "."); @@ -55,7 +59,15 @@ public class NewTreatmentDialogFragment extends DialogFragment implements OnClic this.carbs.setText(""); } else if (insulin > 0d || carbs > 0d) { dismiss(); - MainActivity.getConfigBuilder().getActivePump().deliverTreatment(insulin, carbs); + Result result = MainActivity.getConfigBuilder().getActivePump().deliverTreatment(insulin, carbs); + if (!result.success) { + AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext()); + builder.setTitle(this.getContext().getString(R.string.bolusdeliveryerror)); + builder.setMessage(result.comment); + builder.setPositiveButton(this.getContext().getString(R.string.ok), null); + builder.show(); + + } } break; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/WizardDialogFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialogFragment.java similarity index 92% rename from app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/WizardDialogFragment.java rename to app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialogFragment.java index 58f251176c..6188808545 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Dialogs/WizardDialogFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialogFragment.java @@ -1,10 +1,9 @@ -package info.nightscout.androidaps.plugins.Treatments.Dialogs; +package info.nightscout.androidaps.plugins.Overview.Dialogs; -import android.app.Activity; -import android.app.DialogFragment; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; +import android.support.v4.app.DialogFragment; import android.text.Editable; import android.text.TextWatcher; import android.view.*; @@ -15,19 +14,15 @@ import android.widget.CompoundButton; import android.widget.TextView; import java.text.DecimalFormat; -import java.util.Date; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.TempBasalsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.OpenAPSMA.IobTotal; -import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment; import info.nightscout.client.data.NSProfile; import info.nightscout.utils.*; @@ -123,8 +118,6 @@ public class WizardDialogFragment extends DialogFragment implements OnClickListe } private void initDialog() { - SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - String units = SP.getString("ns_units", Constants.MGDL); NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); if (profile == null) { @@ -133,6 +126,7 @@ public class WizardDialogFragment extends DialogFragment implements OnClickListe return; } + String units = profile.getUnits(); bgUnits.setText(units); // Set BG if not old @@ -177,9 +171,8 @@ public class WizardDialogFragment extends DialogFragment implements OnClickListe private void calculateInsulin() { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - Double maxbolus = Double.parseDouble(SP.getString("safety_maxbolus", "3")); - Double maxcarbs = Double.parseDouble(SP.getString("safety_maxcarbs", "48")); - String units = SP.getString("ns_units", Constants.MGDL); + Double maxbolus = Double.parseDouble(SP.getString("treatmentssafety_maxbolus", "3")); + Double maxcarbs = Double.parseDouble(SP.getString("treatmentssafety_maxcarbs", "48")); NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); @@ -268,11 +261,6 @@ public class WizardDialogFragment extends DialogFragment implements OnClickListe } } - private double fromMgdl(Double value, String units) { - if (units.equals(Constants.MGDL)) return value; - else return value / 18; - } - private Double roundTo(Double x, Double step) { if (x != 0d) { return Math.round(x / step) * step; 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 11388091a0..b090788f0d 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 @@ -6,9 +6,12 @@ import android.graphics.Paint; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.Button; +import android.widget.LinearLayout; import android.widget.TextView; import com.jjoe64.graphview.GraphView; @@ -32,9 +35,13 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialogFragment; +import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialogFragment; import info.nightscout.client.data.NSProfile; @@ -46,6 +53,10 @@ public class OverviewFragment extends Fragment implements PluginBase { TextView deltaView; GraphView bgGraph; + Button cancelTempButton; + Button treatmentButton; + Button wizardButton; + boolean visibleNow = false; Handler loopHandler = new Handler(); Runnable refreshLoop = null; @@ -108,7 +119,7 @@ public class OverviewFragment extends Fragment implements PluginBase { activity.runOnUiThread(new Runnable() { @Override public void run() { - updateData(); + updateGUI(); } }); } @@ -127,8 +138,39 @@ public class OverviewFragment extends Fragment implements PluginBase { timeAgoView = (TextView) view.findViewById(R.id.overview_timeago); deltaView = (TextView) view.findViewById(R.id.overview_delta); bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); + cancelTempButton = (Button) view.findViewById(R.id.overview_canceltemp); + treatmentButton = (Button) view.findViewById(R.id.overview_treatment); + wizardButton = (Button) view.findViewById(R.id.overview_wizard); - updateData(); + treatmentButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + FragmentManager manager = getFragmentManager(); + NewTreatmentDialogFragment treatmentDialogFragment = new NewTreatmentDialogFragment(); + treatmentDialogFragment.show(manager, "TreatmentDialog"); + } + }); + + wizardButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + FragmentManager manager = getFragmentManager(); + WizardDialogFragment wizardDialogFragment = new WizardDialogFragment(); + wizardDialogFragment.show(manager, "WizardDialog"); + } + }); + + cancelTempButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + if (pump.isTempBasalInProgress()) { + pump.cancelTempBasal(); + MainApp.bus().post(new EventTempBasalChange()); + } + } + }); + updateGUI(); return view; } @@ -141,7 +183,47 @@ public class OverviewFragment extends Fragment implements PluginBase { MainApp.bus().register(this); } - public void updateData() { + @Subscribe + public void onStatusEvent(final EventTempBasalChange ev) { + Activity activity = getActivity(); + if (activity != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + updateGUI(); + } + }); + else + log.debug("EventTempBasalChange: Activity is null"); + } + + @Subscribe + public void onStatusEvent(final EventNewBG ev) { + Activity activity = getActivity(); + if (activity != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + updateGUI(); + } + }); + else + log.debug("EventNewBG: Activity is null"); + } + + @Override + public void setUserVisibleHint(boolean isVisibleToUser) { + super.setUserVisibleHint(isVisibleToUser); + + if (isVisibleToUser) { + updateGUI(); + visibleNow = true; + } else { + visibleNow = false; + } + } + + 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 @@ -156,6 +238,17 @@ public class OverviewFragment extends Fragment implements PluginBase { if (bgGraph == null) return; + // **** Temp button **** + PumpInterface pump = MainActivity.getConfigBuilder().getActivePump(); + + if (pump.isTempBasalInProgress()) { + TempBasal activeTemp = pump.getTempBasal(); + cancelTempButton.setVisibility(View.VISIBLE); + cancelTempButton.setText(MainApp.instance().getString(R.string.cancel) + ": " + activeTemp.toString()); + } else { + cancelTempButton.setVisibility(View.INVISIBLE); + } + // **** BG value **** if (profile != null && lastBG != null && bgView != null) { bgView.setText(lastBG.valueToUnitsToString(profile.getUnits())); @@ -260,44 +353,4 @@ public class OverviewFragment extends Fragment implements PluginBase { bgGraph.getGridLabelRenderer().setNumVerticalLabels(11); } - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - updateData(); - } - }); - else - log.debug("EventTempBasalChange: Activity is null"); - } - - @Subscribe - public void onStatusEvent(final EventNewBG ev) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - updateData(); - } - }); - else - log.debug("EventNewBG: Activity is null"); - } - - @Override - public void setUserVisibleHint(boolean isVisibleToUser) { - super.setUserVisibleHint(isVisibleToUser); - - if (isVisibleToUser) { - updateData(); - visibleNow = true; - } else { - visibleNow = false; - } - } - } 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 7632c77ab7..70ec045682 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 @@ -4,6 +4,7 @@ package info.nightscout.androidaps.plugins.SafetyFragment; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceFragment; +import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; @@ -29,24 +30,6 @@ import info.nightscout.client.data.NSProfile; public class SafetyFragment extends Fragment implements PluginBase, ConstrainsInterface { private static Logger log = LoggerFactory.getLogger(SafetyFragment.class); - private static final String PREFS_NAME = "Safety"; - - EditText maxBolusEdit; - EditText maxCarbsEdit; - EditText maxBasalEdit; - EditText maxBasalIOBEdit; - - Double maxBolus; - Double maxCarbs; - Double maxBasal; - Double maxBasalIOB; - - boolean fragmentVisible = true; - - public SafetyFragment() { - super(); - loadSettings(); - } @Override public int getType() { @@ -65,7 +48,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstrainsIn @Override public boolean isVisibleInTabs() { - return fragmentVisible; + return false; } @Override @@ -80,7 +63,6 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstrainsIn @Override public void setFragmentVisible(boolean fragmentVisible) { - this.fragmentVisible = fragmentVisible; } public static SafetyFragment newInstance() { @@ -88,72 +70,6 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstrainsIn return fragment; } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.safety_fragment, container, false); - maxBolusEdit = (EditText) layout.findViewById(R.id.safety_maxbolus); - maxCarbsEdit = (EditText) layout.findViewById(R.id.safety_maxcarbs); - maxBasalEdit = (EditText) layout.findViewById(R.id.safety_maxbasal); - maxBasalIOBEdit = (EditText) layout.findViewById(R.id.safety_maxiob); - - maxBolusEdit.setText(maxBolus.toString()); - maxCarbsEdit.setText(maxCarbs.toString()); - maxBasalEdit.setText(maxBasal.toString()); - maxBasalIOBEdit.setText(maxBasalIOB.toString()); - - TextWatcher textWatch = new TextWatcher() { - - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - try { maxBolus = Double.parseDouble(maxBolusEdit.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { maxCarbs = Double.parseDouble(maxCarbsEdit.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { maxBasal = Double.parseDouble(maxBasalEdit.getText().toString().replace(",", ".")); } catch (Exception e) {}; - try { maxBasalIOB = Double.parseDouble(maxBasalIOBEdit.getText().toString().replace(",", ".")); } catch (Exception e) {}; - storeSettings(); - } - }; - maxBolusEdit.addTextChangedListener(textWatch); - maxCarbsEdit.addTextChangedListener(textWatch); - maxBasalEdit.addTextChangedListener(textWatch); - maxBasalIOBEdit.addTextChangedListener(textWatch); - - return layout; - } - - private void storeSettings() { - if (Config.logPrefsChange) - log.debug("Storing settings"); - SharedPreferences settings = MainApp.instance().getApplicationContext().getSharedPreferences(PREFS_NAME, 0); - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("maxBolus", new Float(maxBolus)); - editor.putFloat("maxCarbs", new Float(maxCarbs)); - editor.putFloat("maxBasal", new Float(maxBasal)); - editor.putFloat("maxBasalIOB", new Float(maxBasalIOB)); - editor.commit(); - } - - private void loadSettings() { - if (Config.logPrefsChange) - log.debug("Loading stored settings"); - SharedPreferences settings = MainApp.instance().getApplicationContext().getSharedPreferences(PREFS_NAME, 0); - - if (settings.contains("maxBolus")) maxBolus = (double) settings.getFloat("maxBolus", 3); else maxBolus = 3d; - if (settings.contains("maxCarbs")) maxCarbs = (double) settings.getFloat("maxCarbs", 48); else maxCarbs = 48d; - if (settings.contains("maxBasal")) maxBasal = (double) settings.getFloat("maxBasal", 1); else maxBasal = 1d; - if (settings.contains("maxBasalIOB")) maxBasalIOB = (double) settings.getFloat("maxBasalIOB", 1); else maxBasalIOB = 1d; - } - /** * Constrains interface **/ @@ -169,6 +85,9 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstrainsIn @Override public APSResult applyBasalConstrains(APSResult result) { + SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); + Double maxBasal = Double.parseDouble(SP.getString("openapsma_max_basal", "1").replace(",", ".")); + NSProfile profile = MainActivity.getConfigBuilder().getActiveProfile().getProfile(); if (result.rate < 0) result.rate = 0; @@ -179,7 +98,7 @@ public class SafetyFragment extends Fragment implements PluginBase, ConstrainsIn if (result.rate > maxBasal) { result.rate = maxBasal; if (Config.logConstrainsChnages) - log.debug("Limiting rate " + origRate + " by maxBasal to " + result.rate + "U/h"); + log.debug("Limiting rate " + origRate + " by maxBasal preference to " + result.rate + "U/h"); } if (result.rate > maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight())) { result.rate = Math.floor(maxBasalMult * profile.getBasal(NSProfile.secondsFromMidnight()) * 100) / 100; 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 04274d11cf..8f43380ac4 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 @@ -326,6 +326,7 @@ public class TreatmentsFragment extends Fragment implements View.OnClickListener @Subscribe public void onStatusEvent(final EventTreatmentChange ev) { initializeData(); + updateGUI(); } public void updateGUI() { 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 8d3ae3c9db..04e8dc0dc8 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 @@ -3,6 +3,8 @@ package info.nightscout.androidaps.plugins.VirtualPump; import android.app.Activity; import android.os.Bundle; +import android.os.Handler; +import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; @@ -24,6 +26,7 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.data.Result; import info.nightscout.androidaps.db.TempBasal; @@ -49,6 +52,9 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt TextView batteryView; TextView reservoirView; + Handler loopHandler = new Handler(); + Runnable refreshLoop = null; + boolean fragmentEnabled = true; boolean fragmentVisible = true; boolean visibleNow = false; @@ -92,6 +98,21 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt return fragment; } + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (refreshLoop == null) { + refreshLoop = new Runnable() { + @Override + public void run() { + updateGUI(); + loopHandler.postDelayed(refreshLoop, 60 * 1000l); + } + }; + loopHandler.postDelayed(refreshLoop, 60 * 1000l); + } + } + @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -121,6 +142,7 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt if (Config.logPumpComm) log.debug("Canceling expired temp: " + tempBasal); tempBasal = null; + MainApp.bus().post(new EventTreatmentChange()); } } if (isExtendedBoluslInProgress()) { @@ -189,6 +211,11 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt } } + @Override + public TempBasal getTempBasal() { + return tempBasal; + } + @Override public double getTempBasalRemainingMinutes() { if (!isTempBasalInProgress()) @@ -203,19 +230,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt result.bolusDelivered = insulin; result.comment = getString(R.string.virtualpump_resultok); - Treatment t = new Treatment(); - t.insulin = insulin; - t.carbs = carbs; - t.created_at = new Date(); - try { - MainApp.instance().getDbHelper().getDaoTreatments().create(t); - } catch (SQLException e) { - e.printStackTrace(); - result.success = false; - result.comment = getString(R.string.virtualpump_sqlerror); - } if (Config.logPumpComm) - log.debug("Delivering treatment: " + t + " " + result); + log.debug("Delivering treatment insulin: " + insulin + "U carbs: " + carbs + "g " + result); updateGUI(); return result; } @@ -233,6 +249,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt tempBasal.duration = durationInMinutes; result.success = true; result.enacted = true; + result.absolute = absoluteRate; + result.duration = durationInMinutes; result.comment = getString(R.string.virtualpump_resultok); try { MainApp.instance().getDbHelper().getDaoTempBasals().create(tempBasal); @@ -263,6 +281,8 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt tempBasal.duration = durationInMinutes; result.success = true; result.enacted = true; + result.percent = percent; + result.duration = durationInMinutes; result.comment = getString(R.string.virtualpump_resultok); try { MainApp.instance().getDbHelper().getDaoTempBasals().create(tempBasal); @@ -308,19 +328,20 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt public Result cancelTempBasal() { checkForExpiredTempsAndExtended(); Result result = new Result(); + result.success = true; + result.comment = getString(R.string.virtualpump_resultok); if (isTempBasalInProgress()) { + result.enacted = true; tempBasal.timeEnd = new Date(); try { MainApp.instance().getDbHelper().getDaoTempBasals().update(tempBasal); } catch (SQLException e) { e.printStackTrace(); result.success = false; + result.enacted = false; result.comment = getString(R.string.virtualpump_sqlerror); } } - result.success = true; - result.enacted = true; - result.comment = getString(R.string.virtualpump_resultok); tempBasal = null; if (Config.logPumpComm) log.debug("Canceling temp basal: " + result); @@ -421,28 +442,15 @@ public class VirtualPumpFragment extends Fragment implements PluginBase, PumpInt activity.runOnUiThread(new Runnable() { @Override public void run() { - DateFormat formatDateToJustTime = new SimpleDateFormat("HH:mm"); - DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00"); - basaBasalRateView.setText(getBaseBasalRate() + "U"); if (isTempBasalInProgress()) { - if (tempBasal.isAbsolute) { - tempBasalView.setText(formatNumber2decimalplaces.format(tempBasal.absolute) + "U/h @" + - formatDateToJustTime.format(tempBasal.timeStart) + - " " + tempBasal.getRemainingMinutes() + "/" + tempBasal.duration + "min"); - } else { // percent - tempBasalView.setText(tempBasal.percent + "% @" + - formatDateToJustTime.format(tempBasal.timeStart) + - " " + tempBasal.getRemainingMinutes() + "/" + tempBasal.duration + "min"); - } + tempBasalView.setText(tempBasal.toString()); } else { tempBasalView.setText(""); } if (isExtendedBoluslInProgress()) { - extendedBolusView.setText(formatNumber2decimalplaces.format(extendedBolus.absolute) + "U/h @" + - formatDateToJustTime.format(extendedBolus.timeStart) + - " " + extendedBolus.getRemainingMinutes() + "/" + extendedBolus.duration + "min"); + extendedBolusView.setText(extendedBolus.toString()); } else { extendedBolusView.setText(""); } diff --git a/app/src/main/res/layout/openapsma_fragment.xml b/app/src/main/res/layout/openapsma_fragment.xml index 4c4c88ff59..411d887b74 100644 --- a/app/src/main/res/layout/openapsma_fragment.xml +++ b/app/src/main/res/layout/openapsma_fragment.xml @@ -14,11 +14,18 @@ android:layout_height="match_parent" android:orientation="vertical"> -